Chunky's Snake
Snake is one of the oldest computer games: a snake wanders across a field, eats whatever lies there and grows longer with every bite – until it runs into the wall or bites its own tail. The idea comes from the 1976 arcade game Blockade; it became famous in 1997 on the Nokia 6110, and soon millions of people carried Snake around in their pocket. In this lesson you build it in five steps. The snake is Chunky, and what he eats is bacon, of course.
A game like this is a grid of cells. show_game draws one below the cell, 20 cells wide and 15 high. The block gets it as g, and you say what lies in which cell:
show_game(width: 20, height: 15) do |g|
g.cell(10, 7, :chunky) # Chunky in the middle
g.cell(15, 7, :bacon) # bacon to his right
g.cell(0, 0, :wall) # a wall at the top left
g.cell(19, 14, :green) # a green cell at the bottom right
endThe cells are counted like the pixels in lesson 82: x from left to right, y from top to bottom, both from 0. The top left cell is 0, 0, the bottom right one 19, 14. A cell shows a picture (:chunky, :bacon, :egg, :wall, :star …), a colour (:green, :red, "#3a8") or any emoji as a String. Without a third argument, g.cell(10, 7) asks what lies there.
So far nothing moves. A game has to do something again and again – but a loop with sleep would freeze the whole page here, because Ruby runs in the same thread as the browser. So the page runs the rounds, and you only tell it what happens in one: g.every(0.15) { … } calls the block every 0.15 seconds. Click the field and Chunky sets off:
show_game(width: 20, height: 15) do |g|
x = 0
step = 1 # +1: to the right, -1: to the left
g.cell(x, 7, :chunky)
g.every(0.15) do
g.clear(x, 7) # empty the old cell
x += step
step = -step if x == 0 || x == 19 # turn round at the edge
g.cell(x, 7, :chunky)
end
endThe page calls the every block long after the cell has finished – and still the block knows x and step. A block takes along the variables that existed where it was written (it is a closure). That is how the game knows from round to round where Chunky is. g.clear(x, 7) empties one cell, g.clear without arguments the whole field.
The game only runs while it has the focus. Esc pauses it, Tab or a click elsewhere leaves it; with the keyboard you get in with Tab and start it with the space bar. That way the arrow keys never end up in the editor by accident – and we need them now. g.on_key(:left) { … } runs when someone presses ←:
show_game(width: 20, height: 15) do |g|
x, y = 10, 7
direction = [1, 0] # [to the right, down]
g.on_key(:left) { direction = [-1, 0] }
g.on_key(:right) { direction = [1, 0] }
g.on_key(:up) { direction = [0, -1] }
g.on_key(:down) { direction = [0, 1] }
g.cell(x, y, :chunky)
g.every(0.15) do
ahead = [x + direction[0], y + direction[1]]
if g.inside?(*ahead) # at the edge Chunky stops
g.clear(x, y)
x, y = ahead
g.cell(x, y, :chunky)
end
end
endThe direction is an array of two numbers: how many cells to the right and how many down. [0, -1] means "none to the right, one up". The keys only change the direction; the timer still does the moving. g.inside?(*ahead) asks whether the next cell is still on the field – the star unpacks the array, so it is the same as g.inside?(ahead[0], ahead[1]). And x, y = ahead hands the two numbers to two variables.
Now Chunky becomes a snake: no longer one cell but an array of cells, head first. Each round a new cell is added at the front (unshift) and one drops off at the back (pop) – that is how the snake moves. When Chunky eats bacon, nothing drops off at the back, and he grows by one cell:
show_game(width: 20, height: 15) do |g|
snake = [[5, 7], [4, 7], [3, 7]] # the head first
direction = [1, 0]
bacon = [12, 7]
score = 0
g.on_key(:left) { direction = [-1, 0] }
g.on_key(:right) { direction = [1, 0] }
g.on_key(:up) { direction = [0, -1] }
g.on_key(:down) { direction = [0, 1] }
g.cell(*bacon, :bacon) # the picture at the start
snake.each { |part| g.cell(*part, :body) }
g.every(0.15) do
x, y = snake.first
head = [x + direction[0], y + direction[1]]
next unless g.inside?(*head) # at the edge: wait
snake.unshift(head) # one cell more at the front
if head == bacon
score += 1
bacon = g.free_cells.sample # new bacon on a free cell
else
snake.pop # one less at the back
end
g.clear
g.cell(*bacon, :bacon)
snake.each { |part| g.cell(*part, :body) }
g.cell(*head, :chunky)
g.status("Bacon: #{score}")
end
endEvery round the game paints everything afresh: g.clear, then the bacon, the body in Chunky's orange (:body) and the head last. That is not slow – afterwards the page only redraws the cells that really changed. g.free_cells is an array of all empty cells, and sample picks one at random: so the new bacon never lands inside Chunky. next ends a round early, and g.status writes a line below the field.
Only the end is missing. If Chunky runs into the wall or bites his own tail, the game is over: g.game_over stops it and shows a message. A click or the space bar starts a new round, and for it the show_game block runs once more from the top.
show_game(width: 20, height: 15) do |g|
snake = [[5, 7], [4, 7], [3, 7]]
direction = [1, 0]
bacon = [12, 7]
score = 0
# no turning straight back: Chunky would bite himself with one key press
g.on_key(:left) { direction = [-1, 0] unless direction == [1, 0] }
g.on_key(:right) { direction = [1, 0] unless direction == [-1, 0] }
g.on_key(:up) { direction = [0, -1] unless direction == [0, 1] }
g.on_key(:down) { direction = [0, 1] unless direction == [0, -1] }
g.cell(*bacon, :bacon)
snake.each { |part| g.cell(*part, :body) }
g.every(0.15) do
x, y = snake.first
head = [x + direction[0], y + direction[1]]
if !g.inside?(*head) || snake.include?(head)
g.game_over("Ouch! Chunky ate #{score} bacon.")
next
end
snake.unshift(head)
if head == bacon
score += 1
bacon = g.free_cells.sample
else
snake.pop
end
g.clear
g.cell(*bacon, :bacon)
snake.each { |part| g.cell(*part, :body) }
g.cell(*head, :chunky)
g.status("Bacon: #{score}")
end
endThat is the whole game, about 35 lines. snake.include?(head) is true when the new cell already belongs to the snake – then Chunky has bitten himself. And since the unless forbids turning straight back, that cannot happen with a single key press.
Two things help while tinkering: what you print with puts in a round appears in a small log below the field. And if a round raises an error, the game stops and shows it with the line number. An endless loop in a round is stopped by the page after a second, so it does not freeze.
show_game only exists on this page. On a computer, games are written with gems like ruby2d or gosu: they open a window of their own and call a block whenever a new picture is due – in ruby2d it is update do … end, and keys come in with on :key_down. The idea is the same as here: your program says what happens in one round, and the library runs the rounds. Lesson 88 shows what that looks like with ruby2d – with programs that run the same here and on your computer.
% computes the remainder of a division, 17 % 16 is 1.# Chunky's Snake without walls: out on the right, back in on the
# left; out at the top, back in at the bottom. Only his own tail
# still ends the game.
show_game(width: 16, height: 12) do |g|
fox = [[4, 6], [3, 6], [2, 6]]
heading = [1, 0]
food = [10, 6]
eaten = 0
g.on_key(:left) { heading = [-1, 0] unless heading == [1, 0] }
g.on_key(:right) { heading = [1, 0] unless heading == [-1, 0] }
g.on_key(:up) { heading = [0, -1] unless heading == [0, 1] }
g.on_key(:down) { heading = [0, 1] unless heading == [0, -1] }
g.cell(*food, :bacon)
fox.each { |part| g.cell(*part, :body) }
g.every(0.15) do
x, y = fox.first
head = [x + heading[0], y + heading[1]]
if !g.inside?(*head) || fox.include?(head)
g.game_over("Ouch! #{eaten} bacon.")
next
end
fox.unshift(head)
if head == food
eaten += 1
food = g.free_cells.sample
else
fox.pop
end
g.clear
g.cell(*food, :bacon)
fox.each { |part| g.cell(*part, :body) }
g.cell(*head, :chunky)
g.status("Bacon: #{eaten}")
end
end