Building a Snake game in Python using Turtle

For those of you who have started learning Python, it can be awesome to start a project. Let’s build a game in Python. Remember the good old days when everybody used to play the snake game? We will be building a simple GUI-based Snake game using Python. So, let’s start.

A bit of history

Snake game first appeared in the year of 1976. It was an arcade game known as Blockade.

Blockade — arcade snake game

Later the game became viral and everyone loved it because in the Nokia phone this snake game was pre-installed. In the age of modern technology, that time cell phone was the greatest innovation, and that innovation came with another pre-installed game.

Nowadays almost every platform has the Snake game with some cool interface.

Main module: Turtle

Turtle is a python feature like a drawing board, which lets you command a turtle to draw all over it! You can use functions like turtle.forward(…) and turtle.left(…) which can move the turtle around.

What we will build

Because this is a starter-level project, so we will build it as easier as possible.

Snake Game

I’d recommend using any Python IDE(i,e VSCode, Pycharm, Spyder, etc). You are good to go with Jupyter Notebook also.

You can find resource files on github, go to https://github.com/MdRubelRana/SnakeGame and clone the repository. Let’s jump ahead.

Rules of the game

Before getting our hands dirty by doing code, let’s initialize some rules/logic that the user has to follow in the game.

1. The game screen has a fixed size(i.e width = 600px, height = 600px)

2. In the beginning, the game starts with the initial snake and apple at certain positions.

3. The user has control of the snake by presses specific arrow keys (i,e. ⬅️ = Move to Left, ⬆️ = Move to Upward, ➡️ = Move to Right and ⬇️ = Move to Downward).

4. Once the user presses a key, the snake keeps moving and waiting for the next direction otherwise it will move in the direction that the user has pressed previously.

5. The initial score is zero, and it will increase as the snake grab the apple.

6. Once the snake hits the wall or his own body, the game will be over at that point.

Importing the libraries

At first, we need to import the turtle library into our project which will be used to build our game.

from turtle import *
import time
import random

Turtle: This is a pre-installed python graphical library that enables users to create pictures and shapes by providing them with a virtual canvas. With this library, you can draw and create various types of shapes and images.

Time: This library helps us with time-related functions.

Random: Random helps us to generate randomize position for spawning the apple.

Setting the Graphics

After importing all the libraries we need, let’s get into the code. Let’s initial a screen(window).

root = Screen()
root.title('Snake Game')
root.setup(width=600, height=600)
root.bgcolor('#222f3e')

Now we need some graphical items to visualize the snake body and the apple.

1. head.gif

2. tail.gif

3. apple.gif

I’ve put all the source files in the github repository. You can clone the repository to access them all. We need a GIF(.gif) image for graphical use because another format of the image is unsupported in the turtle. So we must use gif images for avoiding any error.

Defining the variables

Now we will initialize variables that will be used later.

root.addshape('head.gif')
root.addshape('tail.gif')
root.addshape('apple.gif')

At the beginning of the game, the initial score is zero. It will increase when the snake grabs an apple. Now initial the scoring view.

pen.write('Score: 0', align='right', font=('ubuntu', 14, 'bold'))

Controls and Helpers

Once the user presses a key, the snake keeps moving and waiting for the next direction otherwise it will move in the direction that the user has pressed previously.

Let’s write down the code for controls our snake.

def go_down():
    if head.direction != 'up':
        head.direction = 'down'
        head.shape('head.gif')

def go_up():
    if head.direction != 'down':
        head.direction = 'up'
        head.shape('head.gif')

def go_left():
    if head.direction != 'right':
        head.direction = 'left'
        head.shape('head.gif')

def go_right():
    if head.direction != 'left':
        head.direction = 'right'
        head.shape('head.gif')

After all of this, we need a helper function to use all of this code. So here need another function to move our snake. When a user presses the desired control key to control the snake, the snake will move according to the command and reach a new position. The position will change according to the X or the Y coordinate.

def move():
    if head.direction == 'up':
        y = head. or()
        head.set (y + 20)

    if head.direction == 'down':
        y = head.ycor()
        head.sety(y - 20)

    if head.direction == 'right':
        x = head.xcor()
        head.setx(x + 20)

    if head.direction == 'left':
        x = head.xcor()
        head.setx(x - 20)

After moving out snake successfully now we have to spawn the apple. If the snake grabs the current apple, after a minimum of delays there will be another spawn of another apple at another random position. If the snake grabs an apple then the score will be increased. Every apple is counted as a 10 point. When the snake grabs an apple, its size will increase. After eating an apple the snake size will be incremented by tail size and so on.

while True:
    root.update()

    if head.xcor() > 255 or head.xcor() < -260 or head.ycor() > 260 or head.ycor() < -260:
        t = Turtle()
        t.goto(0, 0)
        t.color('orange')
        t.penup()
        t.hideturtle()
        t.write('Game Over\n', align='center', font=('ubuntu', 26, 'bold'))
        t.write('Please wait a while to play again!!',
                align='center', font=('ubuntu', 14, 'bold'))
        time.sleep(3)
        t.clear()

        time.sleep(1)
        head.goto(0, 0)
        head.direction = 'stop'

        for segment in segments:
            segment.goto(1000, 1000)

        segments.clear()

        score = 0
        delay = 0.1

        pen.clear()
        pen.write(f'Score: {score} ', align='right',
                  font=('ubuntu', 14, 'bold'))

    if head.distance(food) < 20:
        x = random.randint(-255, 255)
        y = random.randint(-255, 255)
        food.goto(x, y)
        delay -= 0.003

        new_segment = Turtle()
        new_segment.shape('tail.gif')
        new_segment.color('grey')
        new_segment.penup()
        segments.append(new_segment)

        score = score + 10

        pen.clear()
        pen.write(f'Score: {score}', align='right',
                  font=('ubuntu', 14, 'bold'))

So we have just made the basic python snake game using turtle. But there are some issues. The snake takes input with keys to change its direction accordingly. It doesn’t change its direction to the opposite side. If the snake is moving upward and the user wants to change the direction of the snake downward then he/she can not. He/she can only change the direction either left or right but not downwards. In any case, the user presses the wrong direction and the snake touches its own body, there will be a collision that means GAME OVER.

So, we have completed our snake game. If you need source files for this project, go to https://github.com/MdRubelRana/SnakeGame .

To read the original post on medium, just click Building a Snake game in Python using Turtle.

Thanks, happy coding!

Building a Snake game in Python using Turtle
Scroll to top