The code uses a list to store the snakes body. Each element in the list is itself a two element list with two entries: X and Y. Each update we draw the player's current position to the screen, push it to the front of the list and then pop the last position off and clear it. This makes it looks like the snake is slithering across the screen. The list starts out at one element long and each time we eat some food we push another, extra element to it - making the snake's body a little longer.
We use another list of X/Y pairs, called directions, to tell us how to move from the current position to the next, based on player_direction. The variable player_direction is an index into that list, which is four elements long, so player_direction must be an integer between 0 and 3. We manage this using the modulus (written as '%') operator:
Here is the complete listing:
Note that it's not possible to complete the game - if you're good enough then you'll eventually run out of space, there will be nowhere to generate new food and the game will hang. Maybe you'd like to add the code to handle this case yourself? You'll need to ask yourself some questions:
- What is the maximum possible score?
- What does completing the game mean - is it a certain score, a certain length of snake or is it when the screen is full?
- How do you tell if the player has completed the game?
- What will you do when the game is complete?