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:

  1. HEAD
    • follows input or block directions
    • creates BODY blocks
  2. BODY
    • represents the body of the snake
  3. TAIL
    • follows block directions
    • changes TAIL to VOID
    • changes BODY to TAIL
  4. FOOD
    • suspends TAIL actions
  5. 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

# Conclusion

These are all the basic rules for implementing the Snake game. The described algorithm is very simple, elegant and interesting. Due to its simplicity, it can be implemented in about 200 lines of code in many dynamic programming languages.

# Implementations

Comments