Build Snake Game in Python Using Turtle Module

Recently, I was helping my nephew learn Python programming, and I wanted to create something that would keep him engaged and excited. What better way than creating a classic Snake game? Using Python’s Turtle module, we can easily build this nostalgic game that many of us played on our old Nokia phones.

In this tutorial, I’ll walk you through creating a complete Snake game from scratch using Python’s Turtle module. The game includes all the essential features, a snake that grows when it eats food, score tracking, and game-over conditions.

Let’s get right in!

What is a Turtle in Python?

Turtle is a pre-installed Python library that allows us to create graphics easily. It’s like having a virtual drawing board where we can control a turtle (cursor) to draw various shapes and patterns.

The beauty of Turtle is its simplicity. Even beginners can create impressive graphics with just a few lines of code.

Set Up Our Environment

Before we start coding, make sure you have Python installed on your computer. Turtle comes built-in with Python, so you don’t need to install anything extra.

Let’s start by importing the necessary modules:

import turtle
import time
import random

The turtle module will handle our graphics, time will help us control the game speed, and random will help us place food at random locations.

Read Python Turtle Font

Create the Game Window

First, let’s set up our game window:

# Set up the screen
window = turtle.Screen()
window.title("Snake Game - Python Guides")
window.bgcolor("black")
window.setup(width=600, height=600)
window.tracer(0)  # Turns off screen updates

I’ve chosen a black background to make our game elements stand out better. The tracer(0) function turns off automatic screen updates, which will help our game run smoother.

Create the Snake Head

Now, let’s create our snake:

# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("green")
head.penup()
head.goto(0, 0)  # Start at the center
head.direction = "stop"

I’ve made the snake head green and placed it in the center of our screen. Initially, the snake won’t move until the player presses a direction key.

Create Snake Food

Every snake needs food! Let’s add that:

# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)  # Position the food above the snake initially

The food is represented by a red circle, positioned above our snake to start.

Add a Score Display

A game is more fun when you can track your progress:

# Score display
score = 0
high_score = 0

pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))

This creates a white text display at the top of our screen to show the current score and high score.

Define Movement Functions

Now, let’s define functions to control the snake’s movement:

# Functions to change direction
def go_up():
    if head.direction != "down":
        head.direction = "up"

def go_down():
    if head.direction != "up":
        head.direction = "down"

def go_left():
    if head.direction != "right":
        head.direction = "left"

def go_right():
    if head.direction != "left":
        head.direction = "right"

def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)

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

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

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

Notice how I’ve prevented the snake from immediately reversing direction, which would cause it to run into itself.

Setting Up Keyboard Bindings

Let’s connect our keyboard keys to the movement functions:

# Keyboard bindings
window.listen()
window.onkeypress(go_up, "w")
window.onkeypress(go_down, "s")
window.onkeypress(go_left, "a")
window.onkeypress(go_right, "d")
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")

I’ve included both WASD keys and arrow keys, so players can use whichever they prefer.

Create the Snake Body

When our snake eats food, it needs to grow longer. Let’s prepare for that:

# Snake body segments
segments = []

This list will store all the body segments of our snake.

Main Game Loop

Now, let’s tie everything together with our main game loop:

# Main game loop
while True:
    window.update()

    # Check for collision with border
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = "stop"

        # Hide the segments
        for segment in segments:
            segment.goto(1000, 1000)  # Move off-screen

        # Clear the segments list
        segments.clear()

        # Reset score
        score = 0
        pen.clear()
        pen.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))

    # Check for collision with food
    if head.distance(food) < 20:
        # Move food to random position
        x = random.randint(-290, 290)
        y = random.randint(-290, 290)
        food.goto(x, y)

        # Add a segment
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("light green")
        new_segment.penup()
        segments.append(new_segment)

        # Increase score
        score += 10
        if score > high_score:
            high_score = score

        pen.clear()
        pen.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))

    # Move the end segments first in reverse order
    for index in range(len(segments) - 1, 0, -1):
        x = segments[index - 1].xcor()
        y = segments[index - 1].ycor()
        segments[index].goto(x, y)

    # Move segment 0 to where the head is
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x, y)

    move()

    # Check for collision with body
    for segment in segments:
        if head.distance(segment) < 20:
            time.sleep(1)
            head.goto(0, 0)
            head.direction = "stop"

            # Hide the segments
            for segment in segments:
                segment.goto(1000, 1000)

            # Clear the segments list
            segments.clear()

            # Reset score
            score = 0
            pen.clear()
            pen.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))

    time.sleep(0.1)  # Control game speed

This loop handles everything from moving the snake to checking for collisions and updating the score.

You can see the output in the screenshot below.

turtle snake

Check out Python Turtle Size

Game Customization

You can customize your Snake game further by adding various features:

  1. Different food types: Create special food items that give extra points or temporary speed boosts.
  2. Background music: Add some retro game music using Python’s pygame module.
  3. Level progression: Make the game faster as the player’s score increases.
  4. Custom snake appearance: Let players choose different colors for their snake.

I’ve found that these customizations make the game much more engaging, especially for younger players who are just getting started with programming.

Creating this Snake game is not just fun but also educational. It teaches fundamental programming concepts like loops, conditionals, and event handling in an engaging way. My nephew was thrilled to see his code come to life as a playable game, and it sparked his interest to learn more about Python programming.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.