Classic Snake Game with Python Turtle Graphics

Python Turtle Graphics is awesome! It can be used to learn and teach Python programming and Computer Science from elementary to advanced level. There is a post on this blog about the Turtle Graphics demos which come with IDLE (the development environment that ships with Python) – check them out to get an idea of some of the fun stuff you can do!

Below is an embedded version of the Classic Snake Game on repl.it

Click on the Turtle window to enable keyboard control using the arrow keys.

Please note this is a `tkinter repl.it`. The Python Turtle module is built on Tkinter and some commands are not available in the standard Turtle repl.it

Python Snake Game Program Explained

Snake Representation

We represent our snake as a list of pairs of coordinates:

`snake = [[0, 0], [20, 0], [40, 0]]`

We could use `sn` to notate the nth segment:

`[s1, s2, s3]`

How does the snake move?

There are several ways to approach programming the Classic Snake Game in Python (or other languages for that matter). The main challenge is how to get the snake to move.

Here are two ways to conceptualize what is basically the same effect:

1. Chop off the last segment, and add it to the front of the snake each time the snake “moves”.
1. Create a copy of the head, add it to the front of the snake and then chop off the last segment.

These are the steps for the second version:

NB For this demonstration, consider the leftmost list item to be the tail and the rightmost to be the head.

• create a new list item for the new head position:

`new_head = snake[-1].copy() # snake[-1] means the rightmost item. Must be copied or original would be modified by next step.`

That is,

or

• Increment the `x` coordinate of `new_head`, giving `[60, 0]`.

• Append new head to the snake:

`snake.append(new_head)`

snake = [[0, 0], [20, 0], [40, 0], [60, 0]] now.

or

snake = [s1, s2, s3, H]

• Finally, remove the leftmost item (`s1`, or `[0, 0]`), using `snake.pop(0)`.

Ta da the snake has moved forward one position!

Moving the Snake with Python Turtle Graphics

The basic movement of the snake can be implemented in a simple program as shown here:

For info on using the super-handy `stamp()` function of Python Turtle Graphics, check out my video on Youtube

Python Classic Snake Game Code Listing

The listing for our Snake Game is below. Depending on your level of experiece, you may be able to understand exactly how it works or maybe just some of it. That’s all fine.

Whatever your level, you should experiment with the code, play with it. For example you could change some colours, or the speed of the snake, or the controls etc.

For more experienced programmers, why not improve upon the basic idea by adding scoring and other features?

Happy coding,

Robin Andrews