Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 41 ยท Projects and Practice

Project: A Complete Platformer Game in Pygame

Build a tile-based platformer in Pygame: level from text, player physics with coyote time, coins, spikes, moving enemies, scrolling camera, lives and a win condition.

This capstone project combines most of what you have learned: a level built from tiles, a player with acceleration, gravity and a forgiving jump, collectible coins, hazards, patrolling enemies, a scrolling camera and a win and lose condition. We will structure it the way Organizing Pygame Code recommends and keep the rules testable without a window.

The physics and collision run here as headless simulations driven by scripted inputs. The full program is read-only: copy it into one file and run it on your own computer with pip install pygame-ce. No image files are needed; everything is drawn with rectangles, and you can swap in sprites later.

What we are building

flowchart TD
  L["LEVEL text rows"] --> W["World: tiles, coins, enemies, goal"]
  I["Input (keys)"] --> P["Player.update(dt)"]
  W --> P
  P --> X["collisions: tiles, coins, spikes, enemies, goal"]
  X --> S["state: playing / dead / won"]
  P --> C["Camera follows player"]
  C --> D["draw visible tiles, objects, HUD"]

Input goes to the player; the world answers with collisions; the camera decides what to draw.

The level format uses one character per tile:

Python
LEVEL = [
    "                                                ",
    "                                                ",
    "                                          G     ",
    "                 $$$                   ######   ",
    "                #####         E                 ",
    "       $$                    ####               ",
    "      ####        ^^                    $$      ",
    "P                ######      E         ####     ",
    "##########   ##########################    #####",
    "##########   ##########################    #####",
]

# is solid ground, $ a coin, ^ spikes, E an enemy that patrols, G the goal flag and P the start. The level is wider than the screen, so the camera has something to do. The gaps at the bottom are pits; falling below the map kills the player.

Player physics

We reuse the ideas from Movement and Delta Time and Gravity and Jumping: acceleration with friction horizontally, gravity vertically, axis-separated tile collision, coyote time and jump buffering.

Python
import pygame
from pygame.math import Vector2

TILE = 32
GRAVITY = 2200
MAX_FALL = 900
ACCEL = 2600
FRICTION = 10.0
MAX_SPEED = 260
JUMP_SPEED = -720
COYOTE = 0.10
BUFFER = 0.12

class Player:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 22, 30)
        self.pos = Vector2(self.rect.topleft)
        self.vel = Vector2()
        self.on_ground = False
        self.coyote = 0.0
        self.buffer = 0.0
        self.facing = 1

    def update(self, dt, move, jump_pressed, jump_held, solids):
        # horizontal acceleration and friction
        self.vel.x += move * ACCEL * dt
        self.vel.x -= self.vel.x * min(1.0, FRICTION * dt)
        self.vel.x = max(-MAX_SPEED, min(MAX_SPEED, self.vel.x))
        if move:
            self.facing = 1 if move > 0 else -1

        # jump with coyote time and buffering
        self.coyote = COYOTE if self.on_ground else max(0.0, self.coyote - dt)
        self.buffer = BUFFER if jump_pressed else max(0.0, self.buffer - dt)
        if self.buffer > 0 and self.coyote > 0:
            self.vel.y = JUMP_SPEED
            self.coyote = self.buffer = 0.0
        if not jump_held and self.vel.y < -200:       # variable jump height
            self.vel.y = -200

        self.vel.y = min(self.vel.y + GRAVITY * dt, MAX_FALL)

        # move and collide, one axis at a time
        self.pos.x += self.vel.x * dt
        self.rect.x = round(self.pos.x)
        for s in solids(self.rect):
            if self.rect.colliderect(s):
                if self.vel.x > 0: self.rect.right = s.left
                elif self.vel.x < 0: self.rect.left = s.right
                self.pos.x, self.vel.x = float(self.rect.x), 0.0

        self.pos.y += self.vel.y * dt
        self.rect.y = round(self.pos.y)
        self.on_ground = False
        for s in solids(self.rect):
            if self.rect.colliderect(s):
                if self.vel.y > 0:
                    self.rect.bottom = s.top
                    self.on_ground = True
                elif self.vel.y < 0:
                    self.rect.top = s.bottom
                self.pos.y, self.vel.y = float(self.rect.y), 0.0

solids(rect) returns the solid tiles near a rectangle, using the grid lookup from Tilemaps and Scrolling Camera.

Python Physics with scripted input

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 character starts on the left, accelerates to its top speed, jumps over the gap and keeps running. Edit the script (for example remove the jump) and watch it fall into the pit.

Coins, hazards, enemies and the goal

After moving the player, test the rest of the world:

Python
class World:
    def __init__(self, level):
        self.level = level
        self.rows, self.cols = len(level), len(level[0])
        self.coins, self.spikes, self.enemies, self.goal = [], [], [], None
        self.start = (0, 0)
        for r, line in enumerate(level):
            for c, ch in enumerate(line):
                rect = pygame.Rect(c * TILE, r * TILE, TILE, TILE)
                if ch == "$":
                    self.coins.append(rect.inflate(-12, -12))
                elif ch == "^":
                    self.spikes.append(pygame.Rect(c * TILE + 4, r * TILE + 16, TILE - 8, TILE - 16))
                elif ch == "E":
                    self.enemies.append(Enemy(c * TILE, r * TILE + 6, self))
                elif ch == "G":
                    self.goal = rect
                elif ch == "P":
                    self.start = (c * TILE + 4, r * TILE)

    def is_solid(self, col, row):
        return 0 <= row < self.rows and 0 <= col < self.cols and self.level[row][col] == "#"

    def solids(self, rect):
        for row in range(rect.top // TILE, rect.bottom // TILE + 1):
            for col in range(rect.left // TILE, rect.right // TILE + 1):
                if self.is_solid(col, row):
                    yield pygame.Rect(col * TILE, row * TILE, TILE, TILE)

class Enemy:
    def __init__(self, x, y, world):
        self.rect = pygame.Rect(x + 4, y, 24, 26)
        self.world, self.dir, self.speed = world, -1, 60

    def update(self, dt):
        self.rect.x += round(self.dir * self.speed * dt)
        ahead_x = self.rect.right + 2 if self.dir > 0 else self.rect.left - 2
        col, row_below = ahead_x // TILE, (self.rect.bottom + 2) // TILE
        wall = self.world.is_solid(ahead_x // TILE, self.rect.centery // TILE)
        no_floor = not self.world.is_solid(col, row_below)
        if wall or no_floor:                 # turn around at walls and ledges
            self.dir *= -1

An enemy needs only two checks: is there a wall in front, and is there still floor under the next step? If either answer says "turn", it reverses, which makes patrolling enemies stay on their platform.

Interactions follow a few simple rules:

  • Coins: player.rect.collidelist(coins) finds a touched coin; remove it and add to the score.
  • Spikes and pits: touching a spike rect, or player.rect.top > map_height, costs a life.
  • Enemies: if the player is falling and their feet are above the enemy's middle, it is a stomp: the enemy dies and the player bounces. Otherwise the player is hurt.
  • Goal: touching the flag rect ends the level with a win.
Python Collision rules: stomp or hurt?

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.

Camera, lives and states

Reuse the clamped, eased camera from Tilemaps and Scrolling Camera. The loop keeps three counters, score, lives and state ("play", "dead", "won"), and draws a HUD. When the player dies, wait a moment with a timer, subtract a life and respawn at the start; at zero lives show a "Game Over" overlay. The state handling mirrors Game States and Menus.

The complete program

Python
import pygame
from pygame.math import Vector2
# (put TILE ... constants, LEVEL, World, Enemy and Player from above here)

pygame.init()
W, H = 960, 540
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("Pixel Runner")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)

world = World(LEVEL)
MAP_W, MAP_H = world.cols * TILE, world.rows * TILE

def spawn():
    p = Player(*world.start)
    return p

player, cam = spawn(), Vector2()
score, lives, state, timer = 0, 3, "play", 0.0

running = True
while running:
    dt = min(clock.tick(60) / 1000, 0.05)
    jump_pressed = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP, pygame.K_w):
            jump_pressed = True
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_r and state != "play":
            world = World(LEVEL); player = spawn(); score, lives, state = 0, 3, "play"

    keys = pygame.key.get_pressed()
    move = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
    jump_held = keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]

    if state == "play":
        player.update(dt, move, jump_pressed, jump_held, world.solids)
        for e in world.enemies:
            e.update(dt)
        i = player.rect.collidelist(world.coins)
        if i != -1:
            world.coins.pop(i); score += 10
        hurt = player.rect.collidelist(world.spikes) != -1 or player.rect.top > MAP_H
        for e in world.enemies[:]:
            if player.rect.colliderect(e.rect):
                if player.vel.y > 0 and player.rect.bottom - e.rect.top < e.rect.height * 0.6:
                    world.enemies.remove(e); player.vel.y = -420; score += 50
                else:
                    hurt = True
        if hurt:
            lives -= 1
            state, timer = ("dead" if lives > 0 else "over"), 1.0
        elif world.goal and player.rect.colliderect(world.goal):
            state = "won"
    elif state == "dead":
        timer -= dt
        if timer <= 0:
            player, state = spawn(), "play"

    goal = Vector2(player.rect.center) - (W / 2, H / 2)
    goal.x = max(0, min(goal.x, MAP_W - W)); goal.y = max(0, min(goal.y, max(0, MAP_H - H)))
    cam += (goal - cam) * min(1.0, 8 * dt)
    off = (-round(cam.x), -round(cam.y))

    screen.fill((120, 190, 240))
    for r in range(world.rows):
        for c in range(world.cols):
            if world.level[r][c] == "#":
                pygame.draw.rect(screen, (90, 70, 50), pygame.Rect(c * TILE, r * TILE, TILE, TILE).move(off))
    for coin in world.coins:
        pygame.draw.ellipse(screen, (250, 210, 40), coin.move(off))
    for s in world.spikes:
        pygame.draw.polygon(screen, (200, 200, 210), [(s.left + off[0], s.bottom + off[1]),
                            (s.centerx + off[0], s.top + off[1]), (s.right + off[0], s.bottom + off[1])])
    for e in world.enemies:
        pygame.draw.rect(screen, (200, 60, 70), e.rect.move(off), border_radius=6)
    if world.goal:
        pygame.draw.rect(screen, (60, 200, 100), world.goal.move(off))
    pygame.draw.rect(screen, (250, 250, 250), player.rect.move(off), border_radius=5)

    hud = f"Score {score}   Lives {lives}"
    if state == "won": hud += "   YOU WIN! (R to restart)"
    if state == "over": hud += "   GAME OVER (R to restart)"
    screen.blit(font.render(hud, True, (20, 30, 50)), (12, 10))
    pygame.display.flip()
pygame.quit()

Run it, then tune the constants. A different GRAVITY and JUMP_SPEED changes the whole character of the game.

Where to go next

  • Replace rectangles with sprites and animations; add a walking and jumping cycle.
  • Add sound effects for coins, jumps and defeat.
  • Read levels from files, add several, and a level-select screen.
  • Add moving platforms, springs, keys and doors, and particle bursts when collecting coins (particle effects).
  • Save the best score (saving scores) and package the game for friends.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a patrolling enemy avoid walking off its platform?

    Checking the tile below and ahead lets the enemy reverse at ledges and walls.
  2. 2. Which condition best identifies a stomp?

    A downward velocity with feet near the enemy's top distinguishes a stomp from a side collision.
  3. 3. Why is the horizontal velocity set to 0 after a wall collision?

    Zeroing velocity on the blocked axis prevents hidden speed from accumulating.
  4. 4. What is the point of clamping dt with min(dt, 0.05)?

    A long frame would otherwise produce a big step and tunneling through thin colliders.

Summary

  • A platformer = tile level + player physics + world interactions + camera + state handling.
  • Axis-separated tile collision with coyote time and jump buffering gives responsive controls.
  • Enemies patrol by testing for walls and missing floor; stomps depend on velocity and relative position.
  • Coins, spikes, pits and a goal form the game's rules; counters and states drive the HUD.
  • Tune constants, then replace placeholder shapes with art and sound.

Next: Pygame Practice Exercises