Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 41 ยท Projects and Practice

Project: Build the Snake Game with Pygame

Build Snake in Pygame step by step: grid movement, timed steps, growth, food, collisions, score, game over and restart, with the game logic separated from drawing.

Snake is the classic first complete game: a few rules, a satisfying loop and just enough tricky details (reversing into yourself, growing, speeding up) to teach real game programming. We will build it the way the architecture lessons recommend: a pure logic class that knows nothing about Pygame, and a thin Pygame layer that handles input and drawing.

The logic runs here as a headless simulation, so you can check every rule. The window code is shown read-only and should be run on your own computer with pip install pygame-ce.

The rules

  • The snake lives on a grid, and moves one cell per step in its current direction.
  • Eating food makes the snake one cell longer and adds a point.
  • The game ends when the head hits a wall or its own body.
  • The snake cannot instantly reverse (left while moving right would kill it at once).
flowchart TD
  I["Read input: choose next direction"] --> T{"step timer elapsed?"}
  T -- no --> D["draw"]
  T -- yes --> M["compute new head = head + direction"]
  M --> C{"wall or body?"}
  C -- yes --> G["game over"]
  C -- no --> E{"head on food?"}
  E -- yes --> F["grow, score+1, new food"]
  E -- no --> S["drop the tail cell"]
  F --> D
  S --> D

Movement is a "step", not a per-frame move: the snake advances on a timer while the loop draws at 60 fps.

Step 1: the logic class

Represent the snake as a list of (column, row) cells with the head first. Moving adds a new head and removes the tail; growing simply skips the removal.

Python
import random

class SnakeGame:
    def __init__(self, cols=20, rows=15, seed=None):
        self.cols, self.rows = cols, rows
        self.rng = random.Random(seed)
        self.reset()

    def reset(self):
        cx, cy = self.cols // 2, self.rows // 2
        self.body = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]   # head first
        self.direction = (1, 0)
        self.pending = self.direction       # direction requested by the player
        self.score = 0
        self.alive = True
        self.food = self.place_food()

    def place_food(self):
        free = [(c, r) for c in range(self.cols) for r in range(self.rows)
                if (c, r) not in self.body]
        return self.rng.choice(free) if free else None

    def turn(self, dx, dy):
        # forbid reversing relative to the CURRENT direction
        if (dx, dy) != (-self.direction[0], -self.direction[1]):
            self.pending = (dx, dy)

    def step(self):
        if not self.alive:
            return
        self.direction = self.pending
        hx, hy = self.body[0]
        head = (hx + self.direction[0], hy + self.direction[1])
        grows = head == self.food
        body_to_check = self.body if grows else self.body[:-1]   # the tail will move away
        if not (0 <= head[0] < self.cols and 0 <= head[1] < self.rows) or head in body_to_check:
            self.alive = False
            return
        self.body.insert(0, head)
        if grows:
            self.score += 1
            self.food = self.place_food()
        else:
            self.body.pop()

Three subtle details make the difference between a toy and a correct game:

  1. Food is placed only on free cells. Picking random coordinates and retrying can loop for a long time on a nearly full board.
  2. pending versus direction. If the player presses Up then Left quickly between two steps, comparing with the old direction would allow Left after Right to slip through via Up. Storing a pending direction and applying it once per step, checked against the current one, prevents the instant U-turn bug.
  3. The tail cell is free. Moving into the cell the tail is leaving is legal, because the tail moves away on the same step, unless the snake grows.
Python Play the logic with scripted moves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that D right after U and R right after L are ignored: the game refuses a reversal and the snake keeps its direction.

Python An autopilot proves growth and game over

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The greedy autopilot eats food for a while and may eventually trap itself in its own coil; that is also what happens to humans. Tests like this are how you check game rules without clicking through the window.

Step 2: the Pygame layer

The window code turns the logic into pictures and key presses into turn() calls. A step timer decouples the snake's speed from the frame rate:

Python
import pygame
from snake_logic import SnakeGame

CELL, COLS, ROWS = 32, 20, 15
pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL + 40))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)

game = SnakeGame(COLS, ROWS)
STEP_EVERY = 0.12                     # seconds per move
timer = 0.0
KEYS = {pygame.K_UP: (0, -1), pygame.K_w: (0, -1), pygame.K_DOWN: (0, 1), pygame.K_s: (0, 1),
        pygame.K_LEFT: (-1, 0), pygame.K_a: (-1, 0), pygame.K_RIGHT: (1, 0), pygame.K_d: (1, 0)}

running = True
while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key in KEYS and game.alive:
                game.turn(*KEYS[event.key])
            elif event.key == pygame.K_r and not game.alive:
                game.reset()

    timer += dt
    while timer >= STEP_EVERY:
        timer -= STEP_EVERY
        game.step()

    screen.fill((18, 22, 32))
    for i, (c, r) in enumerate(game.body):
        colour = (120, 230, 140) if i == 0 else (70, 180, 100)
        pygame.draw.rect(screen, colour, (c * CELL + 1, r * CELL + 1, CELL - 2, CELL - 2), border_radius=6)
    if game.food:
        fc, fr = game.food
        pygame.draw.circle(screen, (240, 90, 90), (fc * CELL + CELL // 2, fr * CELL + CELL // 2), CELL // 2 - 4)
    text = f"Score {game.score}" + ("   GAME OVER - press R" if not game.alive else "")
    screen.blit(font.render(text, True, (240, 240, 245)), (8, ROWS * CELL + 8))
    pygame.display.flip()

pygame.quit()

Save the logic class in snake_logic.py and the window code in main.py. Notice that the drawing never changes the game state, and the logic never imports Pygame.

Ideas to extend it

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the snake move on a timer instead of every frame?

    A step timer keeps the snake on grid cells and gives you a speed setting independent of the display rate.
  2. 2. How does the game prevent an instant reversal?

    turn() compares the request with the negative of the current direction and refuses it.
  3. 3. Why is moving onto the cell currently holding the tail not a collision when the snake does not grow?

    The body check excludes the last cell unless the snake grows.
  4. 4. What is the benefit of keeping SnakeGame free of Pygame code?

    Separating rules from rendering allows headless tests and reuse with other front ends.

Summary

  • Snake is a list of grid cells; a step adds a head and removes the tail unless food was eaten.
  • A pending direction plus a reversal check avoids the instant U-turn bug.
  • Place food only on free cells and treat the leaving tail as free space.
  • A step timer separates game speed from frame rate.
  • Keep logic and drawing apart to test the rules headlessly.

Next: Tic Tac Toe Game