See Think Explore Marvel

UMPSA STEM LAB · Game Development with Python

Build a Snake Game in Python

Learn programming concepts step by step — from variables to machine learning — through a real Pygame project.

📋
Research Study — Complete the Pre-Survey First
Takes ~18 min  ·  70 questions  ·  Saved automatically
Start Pre-Survey →

Welcome

Welcome to the UMPSA STEM Lab Learning Module on Python Programming. In this module, you will learn core programming concepts not through abstract exercises, but by building something real — the classic Snake game.

Along the way, you will also develop Computational Thinking skills — learning how to break problems into parts, spot patterns, and design step-by-step solutions. These are the same skills professional programmers use every day.

The Python foundation you build here will carry directly into your next challenge: applying these skills to Raspberry Pi IoT projects, where your code controls real-world hardware.

The finished game

This is what you will build. The AI snake runs automatically — use arrow keys or click the button to take control. Collect bonus food ⭐ for 3× points!

Score: 0  |  High Score: 0
Regular food — 1 point
Bonus food ⭐ — 3 points, disappears after 4 s
TipArrow keys to play. Click canvas after Game Over to restart. Click "Watch AI" to hand back control.
🗂 CT Activity 1 — Decompose

What are the parts of the Snake game?

Before writing any code, a programmer decomposes the problem — breaks it into smaller, manageable pieces. Click each game component below to discover what Python concept it maps to.

🐍

Snake Head

Where is it on the grid?

Tuple — (col, row)
A pair of integers stored in round brackets. Tuples are fixed — the head position is replaced each move, never modified in place.
🟩

Snake Body

How is the full snake stored?

List of Tuples — [(col,row), …]
A list grows with insert(0, head) and shrinks with pop(). Lists are perfect here because the snake's length changes constantly.
🍎

Regular Food

How does it appear randomly?

Tuple + random — (randint(…), randint(…))
A random column and row are generated with random.randint() and stored as a tuple. Worth 1 point.
⭐

Bonus Food

How does it appear periodically?

List + Timer — [(col, row, timer), …]
A list of bonus items, each with a countdown timer. The modulo operator frame_count % 300 == 0 triggers spawning every 300 frames. Worth 3 points, disappears when timer hits 0.
🏆

Score

What kind of value is it?

Integer variable — score = 0
Starts at 0, increases by 1 for regular food and 3 for bonus food. In later steps stored in a dictionary alongside the high score.
⬛

Grid

How is the game board defined?

Constants — GRID_COLS = 20, GRID_ROWS = 15, CELL_SIZE = 25
Written in UPPER_CASE by convention. Set once at the start, never changed during the game.
➡️

Direction

How does the snake know which way to go?

String — "RIGHT", "LEFT", "UP", "DOWN"
Updated when arrow keys are pressed. In Step 7 replaced by a dictionary: MOVES = {"RIGHT":(1,0), …} — cleaner and faster.
⏱️

Game Clock

How does the game control speed?

Frame counter + interval — frame_count += 1
The game loop runs every ~16 ms (60 fps). Movement only happens every 120 ms. frame_count % N == 0 triggers periodic events like bonus food spawning.

✅ Click all 8 components — then discuss: which components depend on each other?

📋 CT Activity 2 — Algorithm

Describe the flow — put the steps in order

An algorithm is a precise sequence of steps. For each function below, click the steps in the correct order (1 → 2 → 3 …). Then check your answer.

The game loop runs every frame. What order do these steps happen in? Click them 1 → 2 → 3 → 4 → 5 → 6.

?
Check if the snake's head position matches a food position → update score, spawn new food
?
Read keyboard events — if an arrow key is pressed, update the direction variable
?
Wait ~120 ms before the next frame (controls the snake's speed)
?
Draw the grid, snake body, food and score onto the canvas
?
Calculate the new head position: new_head = (head_x + dx, head_y + dy)
?
Check if the new head position overlaps the snake body → Game Over if it does

What exactly happens when the snake eats regular food? Click the steps in order.

?
Do NOT call snake.pop() — the tail stays, making the snake one cell longer
?
Call spawn_food() to place new food at a random empty cell
?
The new head position equals the food's (col, row)
?
Add 1 to score and insert the new head at position 0 of the body list
?
Check if score > high_score — if so, update and save the high score

The bonus food spawns periodically and disappears. Describe its lifecycle in order.

?
A new bonus food tuple (col, row, 240) is appended to the bonus_foods list
?
If the timer reaches 0, remove that bonus food from the list (it "expired")
?
If the snake head hits a bonus food, add 3 to score and remove it from the list
?
frame_count % 300 == 0 evaluates to True — it's time to spawn a new bonus food
?
Every frame, subtract 1 from each bonus food's timer: for bf in bonus_foods: bf[2] -= 1

How does the game detect a self-collision (snake hits its own body)?

?
Loop through every segment in the body list: for segment in snake_body[1:]:
?
Calculate the new head position after moving one step in the current direction
?
Set running = False — the game loop exits on the next frame
?
Apply wrap-around: new_x = new_x % GRID_COLS so the snake crosses the wall instead of dying
?
If segment == new_head, a collision is detected

Your Learning Journey

Ten milestones from zero to a machine-learning snake. Each step builds on the last.

Programming Concept Mapping

Which concept is first introduced at each step — and where it reappears.

★ Introduced (core)
★ Introduced (boundary / modulo)
★ Introduced (OOP / sets)
★ Introduced (ML)
● Applied / reinforced
STEP Variables Tuples Conditionals Loops Lists Functions Classes / OOP Sets Dicts Modulo % File I/O Try / Except f-strings Random numpy / ML
1 · Variables & Setup ★★
2 · Loop & Events ●★●
3 · Direction & Movement ●●★●
4 · Snake Body ⭐ ●●●●★
5 · Bonus Food 🌟 ●●●●●★
6 · Functions ●●●●●★●
7 · Wrap-Around ⭐ ●●●●●●★★●
8 · Save High Score ●●●●●●●●★★★●
9 · OOP Refactor ●●●●●●★★●●●●●●
10 · ML Extension 🤖 ●●●●●●●●●●★

Scroll right to see all concepts. ★ = first time this concept appears.

Before You Start

Make sure your computer is ready.

1

Install Python 3

Download from python.org and run the installer. Tick "Add Python to PATH".

2

Install Pygame

Open a terminal (or Thonny's Shell) and type: pip install pygame

3

Open Thonny

Thonny is a beginner-friendly Python editor. Download from thonny.org if not already installed.

Ready? Once you can run import pygame; print(pygame.version.ver) without errors, you are set!