Javascript Snake
I made a Javascript version of that ubiquitous snake game. Why? Well certainly not because the world is lacking of Javascript based Snake games. I came across a copious amount of free time at work today and feeling that I had to code something while at work I figure a snake game would be straight forward(ish).
Displaying The Snake:
The basic premise is the following grid (where yellow represents the snake and green represents the snake head):
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
| 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 |
To appear to move the snake you manipulate the head (27) and tail (22) cells by changing its colour. For example to move up colour cells 17, 22, and 27 green, white, and yellow respectively. I’m more than sure there’s a name for this kind of ‘illusion’.
Changing the colour is as simple as changing the cell’s background-color property.
Surprisingly the biggest hurdle that I had to overcome was coming up with the HTML to make the grid. I tried using a bunch of <div>s and aligning them with float:right but of course I couldn’t get that to work across browsers. The Designer helpfully suggested that I just use a good old fashioned <table> and lo and behold that worked beautifully!
Moving The Snake:
The snake’s cell numbers are stored internally in a deque. When the snake moves push the new head and pop the old tail.
get new head position
if new head position is the wall or the snake itself
end the game
else
if new head position is food
place food in a new position
grow the snake
update the score
else
remove the tail from the snake deque
add the new head position to the snake deque
Determining The New Head Position:
The new head position is determined by the current direction of the snake. For example in the grid above the new head positions would be 17, 28, and 37 for up, right, and down respectively. Note that left is an invalid direction. The current direction is controlled by whatever arrow the user presses during the game. Of course you want to check if whatever the user presses is a valid direction.
Anyways… play the game. Let me know what you think…
Comments
Leave a Reply