Design snake game

Aishwarya Shilpi
3 min readJan 30, 2021

With a weekend in hand, here is a fun project that you could take up.

I tried coding a basic version of Snake Game, using the turtle library in python. And here I am writing a code-along for the same.

The turtle library comes inbuilt with python and you can think about it in this way that it helps with the creation of an object which can be manipulated to write on a 2-D screen. The screen object in the same library can help control the screen projection and our interaction with it.

The project could be divided into 7 parts:

Creating a snake body

A turtle instance takes up a 20 x 20 space on the screen. And the body can therefore be created by linking these instances together.

Moving the snake

The important logic to take care of, reversing the movement, so that the last segment moves first, and occupies the position of the second last segment.

Controlling the snake

In the snake object, it could be mapped to the functions which change the snake's direction, which can be easily controlled by assigning options to the snake’s head.

The input can be events on the screen which can be mapped to the functions defined in the snake object. The code which can be found in main.py

Detect collision with food

The food object can be another instance of the turtle class, which will change its position at any given time on a random position on board.

The collision can be detected between the snake object and the food and the snake’s length can be extended at the same time with the position of the food getting updated.

Create a scoreboard

The scoreboard is placed on the screen to display the current score as well as print other relevant information on the screen. The score has to increment every time, for which the text object needs to be replaced by the next one.

And in the case of a collision with the wall, or itself, the scoreboard can be used to display the game over message.

Detect collision with the wall

The screen can be seen as a coordinate place, with the x-axis and the y-axis, if the screen is assumed to be 600 x 600, the x and y coordinates will stretch from -300 to 300, by default the turtle objects are of size 20 x 20, so give or take 10 pixels, -290 to 290 is a good range for the object to detect the walls in the game helping us add the functionality of game over.

Detect collision with tail

If the snake's segments, intersect with any other segment of the body, in mathematical terms is within 10 pixels of it, it points to another collision. This would be our functionality of the snake eating itself.

Finally, this brings us to the core orchestration of our code which is the main file.

The good thing about using object-oriented programming in python is its simplicity in implementing such complex functionality.

--

--