The Snake Game

Don't you think that it's only appropriate to discover Python with a snake game?

avatar

Sébastien Boisgérault
Associate Professor, ITN Mines Paris – PSL

Boa constrictor by Jan Kopřiva

Introduction

In this project you will create a program which is a classic video game: the 🐍 snake game! You will use Python and the Pyxel library. What matters is the learning experience: you will discover how to design and implement a complete application, by starting with a simple program and adding features one by one.

By the end of this project, you will have something like this:

🎮

Inside a square arena, you control a 🐍 snake:

Getting started

Let’s start with a message display whose color changes over time.

The code of this application is:

import pyxel

def update():
    if pyxel.btnp(pyxel.KEY_Q):
        pyxel.quit()

def draw():
    pyxel.cls(0)
    color = pyxel.frame_count % 16
    pyxel.text(56, 54, "Hello, Snake!", color)

pyxel.init(160, 120)
pyxel.run(update, draw)

Now we are going to slightly tweak this program until we understand what’s going on. When it’s necessary, search into Pyxel’s user’s guide and reference documentation.

Colors

Let’s tweak the colors a little:

Frame rate

To get a feel of the rythm at which the Pyxel application is running:

The Game Board

Let’s build a game board

To check that everything’s ok, draw a checkerboard pattern like this:

A 30x30 checkerboard

(You may keep this checkerboard in the background as “training wheels” for a while, and remove it when you’re ready.)

The Forbidden Fruit

Display a fruit at a random location on top of the checkerboard. A fruit is a simple 1x1 rectangle (a pixel!). Pick a color you like! When we say “random”, we want the fruit location to be different each time you restart the program.

A fruit at a random location

A Restin’ Snake

In the next step, we will represent the snake, as a sequence of pixels. Let’s snake with the following simple sequence

snake_geometry = [
    [10, 15],
    [11, 15],
    [12, 15],
]

Let’s say that the last list item (here [12, 15]) represents the snake head. Use a dark green color to represent the snake body and a light green for its head.

A resting snake

Events

Modify the program so that when the user presses the arrow keys, the program displays (with the print function) the characters , , or in the terminal.

It’s Aliiiiiiive!

We are finally going to make the snake move!

I am starving!

So far the fruit and the snake don’t interact. Let’s change that! Make sure that:

Epilog

Obviously, there are a couple of things missing here with respect to the initial demo:

Since we are not too cruel, the snake doesn’t die when such a collision occurs. Instead, he loses one segment of it body (by frame), until only the head remains.

Implements these changes!