en How to create a snake game in Python

How to create a snake game in Python

If you are someone who likes to play Snake games, then this article will surely be of interest to you.

This article shows you how to come up with a simple snake game that is easy to develop even for beginners in Python.

There are many ways to create this game, one of which is to use Python’s PyGame library, which is a Python library used to create games.

Another method is to use the turtle library. This module comes with Python preinstalled and provides a virtual canvas for users to create shapes and images.

Therefore, in this article, we will use the Turtle library to implement a simple snake game that is beginner-friendly, especially for novice Python developers.

In addition to this module, we also use two other modules.

  • Time module – This method allows you to track the number of seconds that have passed since the last time.
  • Random module – Generate random numbers in Python.

Other basic tools you should use include any text editor. This article uses VSCode. Of course, you’ll need to install Python 3 if you don’t already have it installed on your machine. You can also use a compiler.

This should be fun!

How to create a Snake game in Python
How to create a Snake game in Python

Snake game mechanics

The ultimate goal of this game is for the player to control the snake and collect the food shown on the screen to achieve the highest score.

The player controls the snake using four directional keys depending on the snake’s direction of movement. If the snake hits a block or the snake itself, the player loses the game.

Follow these steps to implement this game:

  • Import the preinstalled modules (Turtle, Time, Random) into the program.
  • Create the game’s screen display using the Turtle module.
  • Set the key for the snake’s movement direction on the screen.
  • Gameplay implementation.

Create a snakegame.py file to add your implementation code.

How to create a snake game in Python
How to create a snake game in Python

Importing modules

This piece of code imports the Turtle, Time, and Random modules that come preinstalled by default with Python. Additionally, you set default values ​​for the player’s initial score, the highest score the player achieves, and the delay time the player takes for every move. Here, the time module is used to calculate the delay time.

Add the following code to the snakegame.py file.

 import turtle
import random
import time

player_score = 0
highest_score = 0
delay_time = 0.1 
How to create a Snake game in Python
How to create a Snake game in Python

Create a game screen display

The Turtle module you import here allows you to create a virtual canvas that will serve as your game’s window screen. From here you can create the snake’s body and the food it collects. The screen also displays the player’s tracking score.

Add this code to your Python file.

 # window screen created
wind = turtle.Screen()
wind.title("Snake Maze🐍")
wind.bgcolor("red")

# The screen size
wind.setup(width=600, height=600)


# creating the snake 
snake = turtle.Turtle()
snake.shape("square")
snake.color("black")
snake.penup()
snake.goto(0, 0)
snake.direction = "Stop"

# creating the food
snake_food = turtle.Turtle()
shapes = random.choice('triangle','circle')
snake_food.shape(shapes)
snake_food.color("blue")
snake_food.speed(0)
snake_food.penup()
snake_food.goto(0, 100)

pen = turtle.Turtle()
pen.speed(0)
pen.shape('square')
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Your_score: 0 Highest_Score : 0", align="center", 
font=("Arial", 24, "normal"))
turtle.mainloop()

The above code snippet starts by initializing the turtle screen and passing the title and background color to the screen. After defining the screen window size, draw the snake shape on the virtual canvas.

The penup() method simply picks up the turtle’s pen so that no lines are drawn as the turtle moves. The goto(x,y) method contains a coordinate position to move the turtle to an absolute position.

Next, create the food that the snake has collected. I want to display the player’s score each time the snake collects food, and the highest score the player reached during the game. So to implement this, use the pen.write() method. Hideturtle() hides the turtle icon from the screen in the header section where this text is written.

It is important to add turtle.mainloop() at the end of your code. This allows the screen to appear longer and allows the user to do things on the screen.

When you run the file, you should get the following output:

Snakes and Food displays the player's initial and highest scores.
Snakes and Food displays the player’s initial and highest scores.

Set snake direction keys

Here you set specific keys that will guide the direction the snake will move on the screen. Use “L” for left, “R” for right, “U” for top, and “D” for bottom. We implement these directions using the turtle direction functions we call on the snake.

Add the following code snippet to your code.

 # Assigning directions
def moveleft():
    if snake.direction != "right":
        snake.direction = "left"

def moveright():
    if snake.direction != "left":
        snake.direction = "right"

def moveup():
    if snake.direction != "down":
        snake.direction = "up"

def movedown():
    if snake.direction != "up":
        snake.direction = "down"

def move():
    if snake.direction == "up":
        coord_y = snake.ycor()
        snake.sety(coord_y+20)

    if snake.direction == "down":
        coord_y = snake.ycor()
        snake.sety(coord_y-20)

    if snake.direction == "right":
        coord_x = snake.xcor()
        snake.setx(coord_x+20)

    if snake.direction == "left":
        coord_x = snake.xcor()
        snake.setx(coord_x-20)

wind.listen()
wind.onkeypress(moveleft, 'L')
wind.onkeypress(moveright, 'R')
wind.onkeypress(moveup, 'U')
wind.onkeypress(movedown, 'D')

The move() function above sets the movement of the snake at a defined position within precise coordinate values.

The listen() function is an event listener that calls a method that moves the snake in a specific direction when the player presses a key.

Snake game gameplay implementation

After you have a basic outlook for your snake game, you need to make your game real-time.

This includes:

  • Increase the snake’s length each time it collects food, preferably using a different color.
  • The player’s score increases each time the snake collects food and keeps track of the highest score.
  • Players can control the snake to avoid colliding with walls or their own body.
  • The game will restart when the snake collides.
  • When the game restarts, the player’s score is reset to zero, but the screen retains the player’s highest score.

Add the rest of this code to your Python file.

 segments = []

#Implementing the gameplay
while True:
    wind.update()
    if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290:
        time.sleep(1)
        snake.goto(0, 0)
        snake.direction = "Stop"
        snake.shape("square")
        snake.color("green")

        for segment in segments:
            segment.goto(1000, 1000)
            segments.clear()
            player_score = 0
            delay_time = 0.1
            pen.clear()
            pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))

        if snake.distance(snake_food) < 20:
            coord_x = random.randint(-270, 270)
            coord_y = random.randint(-270, 270)
            snake_food.goto(coord_x, coord_y)

            # Adding segment
            added_segment = turtle.Turtle()
            added_segment.speed(0)
            added_segment.shape("square")
            added_segment.color("white")
            added_segment.penup()
            segments.append(added_segment)
            delay_time -= 0.001
            player_score += 5

            if player_score > highest_score:
                highest_score = player_score
                pen.clear()
                pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))

    # checking for collisions
    for i in range(len(segments)-1, 0, -1):
        coord_x = segments[i-1].xcor()
        coord_y = segments[i-1].ycor()
        segments[i].goto(coord_x, coord_y)

    if len(segments) > 0:
        coord_x = snake.xcor()
        coord_y = snake.ycor()
        segments[0].goto(coord_x, coord_y)
    move()

    for segment in segments:
        if segment.distance(snake) < 20:
            time.sleep(1)
            snake.goto(0, 0)
            snake.direction = "stop"
            snake.color('white')
            snake.shape('square')

            for segment in segments:
                segment.goto(1000, 1000)
                segment.clear()
                player_score = 0
                delay_time = 0.1
                pen.clear()
                pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))

     time.sleep(delay_time)

turtle.mainloop()

The above code snippet sets the random position of the snake food within the screen. Each time the snake collects this food, its body parts increase in different colors. In this case, it is white to distinguish the growth.

After the snake collects the food without colliding, the food is placed at a random location within a 270 coordinate range of the screen size. Each time the snake collects food, the player’s score increases by 5. If the snake collides, the player’s score will be set to 0, but the screen will keep the highest score.

If you now return the Python file, you should see a turtle screen like this:

Conclusion 🐍

As you’ll see in this article, using the Turtle Library is one of the fun and easy ways to create a Snake game. Alternatively, you can implement the same using the PyGame library. Check out the PyGame tutorial here to see how to implement your game differently.

You can also try out the number guessing game in Python or how to get JSON data in Python.
Have fun coding!

How to create a snake game in Python
How to create a snake game in Python