Skip to Content
Course content

90: Building a Simple Snake Game with Turtle

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you've got a handle on the core logic of Python, but I've always found that the best way to solidify those concepts is to build something visual. Today, we're using the turtle module. It's a bit old-school, but it's built right into Python and it's fantastic for understanding coordinate systems and game loops without needing to install heavy libraries like Pygame.

Setting up the Arena

First, we need a window. In turtle, the Screen object acts as our game board. I like to set a fixed window size so the game doesn't jump around when it starts. We'll also set the background to black to give it that classic arcade feel.

import turtle
import time
import random

# Setup the screen
win = turtle.Screen()
win.title("Snake Game")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0) # Turns off screen updates for smoother animation

Defining the Snake and its Movement

I'm treating the snake's head as a separate turtle object. We need to define a move() function that shifts the head forward based on its current heading. To handle the controls, we'll use win.listen() and bind the arrow keys to functions that change the head's direction.

head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0,0)
head.direction = "stop"

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)

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

# ... (similar functions for go_down, go_left, go_right)

win.listen()
win.onkeypress(go_up, "Up")
# Bind other keys here...

Spawning Food and Growing the Body

For the food, we just need another turtle that jumps to a random coordinate whenever the snake "collides" with it. To make the snake grow, I'm using a list to keep track of the body segments. Each time the snake eats, we append a new turtle object to that list.

food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)

segments = []

# Inside the game loop:
if head.distance(food) < 20:
    # Move food to random spot
    x = random.randint(-290, 290)
    y = random.randint(-290, 290)
    food.goto(x, y)

    # Add a segment
    new_segment = turtle.Turtle()
    new_segment.shape("square")
    new_segment.color("grey")
    new_segment.penup()
    segments.append(new_segment)

The "Frozen Screen" Mistake

Here is where I usually trip up the first time I build this. You'll notice I called win.tracer(0) at the start. This tells Python not to animate every single movement of the turtle, which prevents that annoying "stutter" as the snake moves. However, when I first ran my game loop, the screen stayed completely blank. I spent five minutes wondering why my logic was broken, only to realize that when you turn off the tracer, you're responsible for manually refreshing the screen.

If you don't call win.update() inside your while loop, you're essentially drawing on a canvas that's hidden from the user. It's a classic "gotcha."

while True:
    win.update() # This is the missing piece!
    time.sleep(0.1)
    move()
    
    # Move the segments 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)
    
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x, y)

Collision Detection

Finally, we need the game to actually end. I'm checking if the head's x or y coordinates exceed 290 (since our window is 600 wide). I also loop through the segments list; if the head's distance to any segment is too small, it's game over. It's a simple distance check, but it's effective enough for a project like this.




📋 Practical Task

Implementing a Live Scoreboard for the Snake Game

Your task is to add a scoring system to the Snake game we just built. Follow these requirements:

  • Create a new turtle object specifically for the scoreboard.
  • Use the .write() method to display the current score in the top-center of the screen.
  • Ensure the scoreboard is hidden (using .hideturtle()) so only the text is visible.
  • Update the score and refresh the text on the screen every time the snake collides with the food.
  • Reset the score to 0 when the snake hits a wall or its own tail.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.