🎓 A1Learner
🔍
0 of 18 lessons completed

Python Snake Game Plan

Snake is a game where a snake of squares crawls around a board and grows as it eats. This course builds that game in Python, and every lesson ends with a working program that grows toward the complete game.

The snake as a list of squares

The list holds one pair for each square. The first pair is the head square.

snake = [(0, 0), (-20, 0), (-40, 0)]
print(snake)

One step to the right

A step adds a new head square 20 to the right. The last square drops off, so the snake keeps its length.

snake = [(0, 0), (-20, 0), (-40, 0)]
head_x, head_y = snake[0]
snake = [(head_x + 20, head_y)] + snake[:-1]
print(snake)

Example

# The whole game in one idea: the snake is a list of squares.
snake = [(0, 0), (-20, 0), (-40, 0)]
print("The snake starts as a list of squares:")
print(snake)

# One step right: a new head square appears, the tail square drops off.
head_x, head_y = snake[0]
snake = [(head_x + 20, head_y)] + snake[:-1]
print("After one step right:")
print(snake)

Key points

  • Turtle graphics is drawing by moving a shape around a window with code
  • Turtle ships with Python, so the course needs no extra install
  • The course builds on the Python skills from Python Beginner
  • Use the arrow keys to steer the snake around the board
  • Eating food makes the snake grow longer and adds to the score
  • Hitting a wall or the snake's own body ends the run

In this example, the program builds the snake as a list of three squares. It prints the starting list. It reads the head square and builds a new head 20 to the right. It keeps the first two old squares and drops the last one. It prints the new list, which shows the same snake one step to the right.

Note

Two challenge lessons at the end change the rules of the game

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens to the snake list after one step right?