The Snake Game
This time we're going to look at the elegant algorithm behind the classic Snake game.
# Definition
First, we need a 2D grid and some constants to label the blocks, which are described bellow:- HEAD
- follows input or block directions
- creates BODY blocks
- BODY
- represents the body of the snake
- TAIL
- follows block directions
- changes TAIL to VOID
- changes BODY to TAIL
- FOOD
- suspends TAIL actions
- VOID
- represents an empty block
Initially, the grid is created with all the blocks labeled as VOID.
# Illustration
After we have the 2D grid, we need to create the snake itself and the food source. Currently, the snake has no BODY, only the HEAD and the TAIL, both with a left (⬅) direction specified:
FOOD | ||||||
HEAD ⬅ |
TAIL ⬅ |
|||||
After applying the HEAD definition, the HEAD moves to the left by one block and creates a new BODY block in its old position:
FOOD | ||||||
HEAD ⬅ |
BODY ⬅ |
TAIL ⬅ |
||||
Following the TAIL definition, the TAIL moves to the left by one block and replaces the BODY label with TAIL and the old TAIL with VOID:
FOOD | ||||||
HEAD ⬅ |
TAIL ⬅ |
|||||
If we now press the up-arrow key (⬆), the HEAD will move upwards, instead of following the block direction. Also, because the HEAD encountered FOOD this time, the TAIL step is skipped, so the snake grows by one BODY block without it being removed by the TAIL.
The new BODY block always stores the current HEAD direction:
HEAD ⬆ |
||||||
BODY ⬆ |
TAIL ⬅ |
|||||
FOOD | ||||||
In the next step, the HEAD follows its block direction and continues to move upwards, creating a new BODY block in its old place:
HEAD ⬆ |
||||||
BODY ⬆ |
||||||
BODY ⬆ |
TAIL ⬅ |
|||||
FOOD | ||||||
Because no FOOD was encountered this time, the TAIL will follow its block direction and replace BODY with TAIL, but it will never change the block direction:
HEAD ⬆ |
||||||
BODY ⬆ |
||||||
TAIL ⬆ |
||||||
FOOD | ||||||
Comments
Post a Comment