Home โ€บ Curriculum โ€บ Game Development with Pygame
Updated for Python 3.12+ ยท November 2026

๐ŸŽฎ Game Development with Pygame
in Python

Learn Pygame: the game loop, surfaces, events, sprites, rect collisions, sound and a complete small game, with runnable headless demos of timestep and collision maths.

Intermediate 9 lessonsโ‰ˆ 55 min read by Glenn Pansensoy

What this lesson is about

Pygame is a library for making 2D games in Python. It gives you a window to draw in, a way to read the keyboard and mouse, tools for images and sound, and a clock to keep everything running at a steady speed. It is a popular first step into game programming because a small game fits in one file and you can see the result of every change immediately.

Every game, from the simplest to the biggest, is built around one idea: the game loop. Many times per second the program reads input, updates the state of the world, and draws a new picture. Everything else in this lesson, including surfaces, sprites, collisions and sound, plugs into that loop. Once you can read a loop like that, you can read nearly any game's source code.

A game window cannot open inside a web page, so the Pygame code here is marked as run on your computer and I only syntax-checked it, so I will not claim a screenshot I have not seen. The ideas that make a game feel right are mostly maths and logic, though, and those I can run here with the standard library: a headless loop with a fixed timestep, rectangle collision, velocity vectors and score rules. The final section combines everything into a complete small game you can copy and play.

What you will learn

  • โœ“Initialise Pygame, open a window and understand the three-step game loop
  • โœ“Draw with surfaces, rectangles, colours and text, and flip the display
  • โœ“Handle events and held keys, and move things with velocity
  • โœ“Use a Clock and delta time, and understand fixed-timestep updates
  • โœ“Detect collisions with rectangles and explain how AABB checks work
  • โœ“Organise objects with Sprite and Group
  • โœ“Play sound effects and music and know how to fail gracefully without audio
  • โœ“Put it all together in a complete catch-the-falling-items game

Why programmers should learn this

  • โ˜…Games are a very motivating way to practise loops, classes, lists, conditions and maths, because every mistake becomes visible on screen.
  • โ˜…The game loop, delta time and collision detection are the same ideas used by large engines, so Pygame teaches transferable fundamentals.
  • โ˜…Small games make excellent portfolio pieces: people can run them, read the code and see how you structure a larger program.
  • โ˜…Simulations and visualisations, such as a bouncing ball model or a cellular automaton, are easier to build with a live drawing surface.
  • โ˜…You practise separating state, logic and drawing, a habit that makes any program, game or not, easier to change.

Setting up and the game loop

Install Pygame on your own computer with pip install pygame (many people use the maintained pygame-ce fork, which has the same import pygame; check the project pages for current advice). A minimal program calls pygame.init(), creates a window with pygame.display.set_mode((width, height)), and then runs a while running: loop until the player closes the window.

Inside the loop you do three things in order. First, handle events: ask Pygame for everything that happened since the last frame, such as key presses and the window's close button. Second, update: change the state of your game, for instance moving the player. Third, draw: fill the screen, draw your objects and call pygame.display.flip() to show the finished picture. If you do not process events, the operating system decides your window has stopped responding.

Finally the loop must not run as fast as the computer can manage, or it will use a whole CPU core and your game will play at different speeds on different machines. A pygame.time.Clock solves this: clock.tick(60) pauses just long enough to hold the loop at about 60 frames per second and returns the milliseconds since the previous call. The program below opens a window with a bouncing square, built from the three steps.

bounce.pyrun on your computer
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
pygame.display.set_caption("Bouncing square")
clock = pygame.time.Clock()

square = pygame.Rect(50, 50, 40, 40)
vx, vy = 4, 3
running = True

while running:
    # 1. events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 2. update
    square.x += vx
    square.y += vy
    if square.left < 0 or square.right > 640:
        vx = -vx
    if square.top < 0 or square.bottom > 360:
        vy = -vy

    # 3. draw
    screen.fill((20, 24, 40))
    pygame.draw.rect(screen, (240, 180, 60), square)
    pygame.display.flip()

    clock.tick(60)

pygame.quit()

Line by line

  1. 1-6Import, initialise all Pygame modules, open a 640 by 360 window, set its title and create a clock.
  2. 8-10The state of the game: a rectangle for the square, its velocity in pixels per frame, and the flag that keeps the loop alive.
  3. 12-16Step 1, events. event.get() returns everything that happened. Clicking the window's close button creates a QUIT event, so we stop the loop.
  4. 18-24Step 2, update. Move the square by its velocity, and if it touches a wall reverse that component of the velocity so it bounces.
  5. 26-29Step 3, draw. Paint the background, draw the square and flip the display to show the new frame.
  6. 31Wait so the loop runs at about 60 frames per second.
  7. 33Shut down Pygame cleanly after the loop ends.
โš ๏ธ

Never put a while True loop that waits for a key inside an event handler. The only loop in a game should be the main one, otherwise the window stops redrawing and responding.

Surfaces, rectangles, colours and text

Everything you see in Pygame is drawn on a Surface, which is a rectangle of pixels in memory. The window itself is a surface (screen). You can create others, load images into them with pygame.image.load, draw shapes on them and then copy one surface onto another with blit. Drawing an image is always the same thing: screen.blit(image, (x, y)), where the position is the top-left corner.

A Rect stores a position and a size, and it is the most useful class in the library. It keeps x, y, width and height and also computed attributes like left, right, top, bottom, center and midbottom, which you can read and assign. Setting rect.center = (320, 180) moves the rectangle so that its centre is there. Positions are in pixels with the origin at the top left and y increasing downwards, which is the opposite of a maths graph.

Colours are tuples of red, green and blue from 0 to 255, so (255, 0, 0) is red. For text you create a pygame.font.Font (or SysFont), call render(text, True, colour) to get a Surface and blit it like any image. Rendering text every frame is fine for a small game, but if the text rarely changes, render it once and reuse the surface. The example draws shapes, a text label and an off-screen surface that is blitted to the window.

surfaces.pyrun on your computer
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 270))
pygame.display.set_caption("Surfaces and rects")
font = pygame.font.Font(None, 36)          # None means the default font

# an off-screen surface we draw on once and reuse
badge = pygame.Surface((120, 60))
badge.fill((40, 90, 160))
pygame.draw.rect(badge, (255, 255, 255), badge.get_rect(), width=3)

box = pygame.Rect(0, 0, 160, 80)
box.center = screen.get_rect().center       # centre the box in the window

clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((18, 18, 28))
    pygame.draw.rect(screen, (200, 70, 70), box, border_radius=10)
    pygame.draw.circle(screen, (250, 220, 90), (60, 60), 30)
    pygame.draw.line(screen, (150, 150, 170), (0, 200), (480, 200), 2)

    label = font.render("Score: 120", True, (240, 240, 240))
    screen.blit(label, (box.x + 20, box.y + 25))
    screen.blit(badge, (350, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Line by line

  1. 1-6Set up the window as before and create a default-font object, size 36.
  2. 8-11Make a separate 120 by 60 surface, fill it blue and draw a white border using its own get_rect(). It lives off-screen until we blit it.
  3. 13-14A rectangle for a box, moved so that its centre equals the window's centre.
  4. 16-22The usual loop with just the quit event handled.
  5. 24-27Clear the screen, then draw a rounded rectangle, a circle and a line. Each call names the surface to draw on, the colour and the geometry.
  6. 29-31Render text into a new surface and blit it, and also blit the badge into the corner.
  7. 33-37Flip, tick and quit as before.
๐Ÿ’ก

Call convert() or convert_alpha() on images after loading them (once the display exists). It converts them to the screen's pixel format and makes blitting noticeably faster.

Fixed timestep and delta time, headless

Our bouncing square moved a fixed number of pixels per frame. That means on a computer that manages only 30 frames per second it moves at half the speed. There are two standard cures. The first is delta time: measure how many seconds the last frame took (dt = clock.tick(60) / 1000) and move by speed * dt, where speed is in pixels per second. The second is a fixed timestep: always advance the simulation in equal slices, such as 1/60 of a second, and run as many slices as real time has accumulated. The simulation then behaves identically on every computer, which makes physics predictable and games reproducible.

The fixed-timestep loop keeps an accumulator. Each frame you add the real elapsed time to it, then while it holds at least one step you run update(step) and subtract. Draw once afterwards. If the machine is slow you may do several updates per frame and if it is fast you may do none, but the total simulated time always matches the real time. Cap the elapsed time (for example at 0.25 s) so a long pause, such as dragging the window, does not cause a huge burst of updates.

Because the maths does not need a window, I can run it right here. The block below fakes the frame times of a fast machine and a slow one, and shows both reach the same position after one second of simulated time. This is called headless execution, and it is also how automated tests of game logic work.

Headless fixed-timestep loop
def simulate(frame_times, step=1/60, speed=120.0):
    """Move at `speed` px/s using a fixed timestep. Returns (x, updates)."""
    x = 0.0
    accumulator = 0.0
    updates = 0
    for elapsed in frame_times:
        accumulator += min(elapsed, 0.25)     # cap huge pauses
        while accumulator >= step - 1e-9:
            x += speed * step
            accumulator -= step
            updates += 1
    return x, updates

fast = [1/120] * 120          # 120 fps for one second
slow = [1/20] * 20            # 20 fps for one second
uneven = [0.01, 0.03, 0.02, 0.05, 0.9, 0.01] + [1/60] * 50   # includes one long pause

for name, frames in [("fast", fast), ("slow", slow), ("uneven", uneven)]:
    x, n = simulate(frames)
    print(f"{name:7s} real time = {sum(frames):5.2f}s  updates = {n:3d}  x = {x:7.2f}")

# the naive version: a fixed number of pixels per frame
def naive(frames, per_frame=2.0):
    return per_frame * len(frames)

print("naive fast:", naive(fast), " naive slow:", naive(slow))
Expected output
fast    real time =  1.00s  updates =  60  x =  120.00
slow    real time =  1.00s  updates =  60  x =  120.00
uneven  real time =  1.85s  updates =  72  x =  144.00
naive fast: 240.0  naive slow: 40.0

Line by line

  1. 1-4The function simulates a moving object at 120 pixels per second, in steps of one sixtieth of a second.
  2. 5-11For every rendered frame, add the real elapsed time (capped at a quarter second) to the accumulator. While a whole step is available, advance the position by speed * step and count the update. The tiny 1e-9 avoids floating-point rounding leaving a step unused.
  3. 12Return the final position and how many updates ran.
  4. 14-16Three fake machines: one at 120 fps, one at 20 fps and one with uneven frame times including a long 0.9 second hiccup.
  5. 18-20Run each one and print real elapsed time, update count and final position.
  6. 22-26The naive version moves a fixed distance per frame, so its result depends on the frame rate.

Look at the output: the fast and slow machines both finish with 60 updates and the same position, while the naive version differs by a factor of six. The uneven machine does fewer updates than real time would suggest, because the hiccup was capped. That is a deliberate trade-off: after a long pause it is better to skip time than to fast-forward the game.

Events, keyboard input and velocity vectors

Pygame reports input in two ways. Events describe something that happened once: a key went down (KEYDOWN), a key went up (KEYUP), the mouse moved or a button was clicked (MOUSEBUTTONDOWN). Use events for one-off actions, such as jump, fire or pause. Polled state, from pygame.key.get_pressed(), tells you whether a key is currently held, which is the right tool for continuous movement like walking left while the key is down.

Movement is cleanest when you think of a velocity vector: a pair (vx, vy) in pixels per second. Position changes by velocity times time. Keyboard input produces a direction such as (1, 0) or (-1, 1), and a classic bug appears when you press two keys at once: the diagonal (1, 1) has length about 1.41, so the player moves faster diagonally. The fix is to normalise the direction, dividing it by its length so the speed is the same in every direction.

The first block shows the keyboard handling in a window. The second is runnable: it implements direction from a set of pressed key names, normalisation, and a speed-limited update, and prints what happens for a few key combinations. The maths is exactly what goes into your real update method.

movement.pyrun on your computer
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()

player = pygame.Vector2(320, 180)
speed = 220                       # pixels per second
running = True

while running:
    dt = clock.tick(60) / 1000    # seconds since last frame

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False

    keys = pygame.key.get_pressed()
    direction = pygame.Vector2(
        keys[pygame.K_RIGHT] - keys[pygame.K_LEFT],
        keys[pygame.K_DOWN] - keys[pygame.K_UP],
    )
    if direction.length_squared() > 0:
        direction = direction.normalize()
    player += direction * speed * dt

    screen.fill((20, 24, 40))
    pygame.draw.circle(screen, (120, 220, 160), player, 16)
    pygame.display.flip()

pygame.quit()

Line by line

  1. 1-9Set up. The player's position is a Vector2, which supports arithmetic and normalising.
  2. 12tick(60) returns milliseconds, divided by 1000 for seconds, our delta time.
  3. 14-18One-off actions use events: closing the window or pressing Escape ends the game.
  4. 20-24get_pressed() returns whether each key is held. Booleans subtract as 1 and 0, so right minus left gives -1, 0 or 1.
  5. 25-26If any key is pressed, scale the direction to length 1 so diagonals are not faster.
  6. 27Move by direction times speed times time.
  7. 29-32Draw a circle at the player's position and flip.
Velocity vectors and diagonal speed
import math

def direction_from(pressed):
    dx = ("right" in pressed) - ("left" in pressed)
    dy = ("down" in pressed) - ("up" in pressed)
    return dx, dy

def normalise(dx, dy):
    length = math.hypot(dx, dy)
    return (dx / length, dy / length) if length else (0.0, 0.0)

def step(pos, pressed, speed, dt, fix_diagonal=True):
    dx, dy = direction_from(pressed)
    if fix_diagonal:
        dx, dy = normalise(dx, dy)
    return pos[0] + dx * speed * dt, pos[1] + dy * speed * dt

for keys in [{"right"}, {"right", "down"}, {"left", "right"}, set()]:
    plain = step((0, 0), keys, 200, 1.0, fix_diagonal=False)
    fixed = step((0, 0), keys, 200, 1.0)
    d_plain = math.hypot(*plain)
    d_fixed = math.hypot(*fixed)
    label = "+".join(sorted(keys)) or "none"
    print(f"{label:11s} distance in 1s  without fix: {d_plain:6.1f}   with fix: {d_fixed:6.1f}")
Expected output
right       distance in 1s  without fix:  200.0   with fix:  200.0
down+right  distance in 1s  without fix:  282.8   with fix:  200.0
left+right  distance in 1s  without fix:    0.0   with fix:    0.0
none        distance in 1s  without fix:    0.0   with fix:    0.0

Line by line

  1. 3-6Turn a set of held key names into a direction pair. Opposite keys cancel to zero.
  2. 8-10Normalise: divide by the vector's length, using hypot, and return zero when there is no direction at all.
  3. 12-16Move a position by speed times dt, with an option to switch the diagonal fix off to show the bug.
  4. 18-24For four key combinations, compute the distance moved in one second with and without normalising, and print them.

The output makes the diagonal bug concrete: without the fix the player travels about 283 pixels in a second when two keys are held, against 200 pixels in a straight line.

Collision detection with rectangles

Most 2D collision checks use axis-aligned bounding boxes, abbreviated AABB: each object is wrapped in a rectangle whose sides are parallel to the screen edges. Two such rectangles overlap only if they overlap on the x axis and on the y axis. In code, A's left edge must be left of B's right edge, A's right edge right of B's left edge, and the same for top and bottom. If any of the four tests fails, there is a gap, so there is no collision.

Pygame does this for you: rect_a.colliderect(rect_b) returns a boolean, rect.collidepoint((x, y)) tests a point such as the mouse, and rect.collidelist(list) finds the first colliding rectangle in a list. Rectangles are cheap, which is why they are the default. For round objects you can compare the distance between centres with the sum of radii, and for irregular shapes Pygame has pixel-perfect masks, which are slower.

A subtle point: edges that merely touch do not count. A rectangle with right == 100 and another with left == 100 do not overlap in Pygame, because rectangles cover pixels from left up to but not including right. Another is tunnelling: if an object moves so far in one frame that it jumps over a thin wall, no frame ever sees an overlap. Small steps, which the fixed timestep gives you, avoid it. The code below reimplements the AABB test, checks it against random cases using a brute-force count of shared pixels, and also resolves a collision by pushing the player out of a wall.

rect_collisions.pyrun on your computer
import pygame

player = pygame.Rect(100, 100, 40, 40)
wall = pygame.Rect(130, 90, 20, 100)
coins = [pygame.Rect(300, 100, 16, 16), pygame.Rect(120, 120, 16, 16)]

print(player.colliderect(wall))
print(player.collidepoint((110, 110)))
print(player.collidelist(coins))               # index of the first hit, or -1
print([c for c in coins if player.colliderect(c)])

Line by line

  1. 1-5Create a player, a wall and two coins as rectangles. Arguments are (x, y, width, height).
  2. 7Test whether two rectangles overlap.
  3. 8Test whether a point is inside a rectangle, which is how you test mouse clicks.
  4. 9collidelist returns the index of the first rectangle in the list that overlaps, or -1.
  5. 10A list comprehension that collects every coin being touched.
AABB maths and collision response
import random

class Box:
    def __init__(self, x, y, w, h):
        self.x, self.y, self.w, self.h = x, y, w, h
    @property
    def right(self):
        return self.x + self.w
    @property
    def bottom(self):
        return self.y + self.h

def overlaps(a, b):
    return a.x < b.right and a.right > b.x and a.y < b.bottom and a.bottom > b.y

def brute_force(a, b):
    """Count shared pixels the slow way."""
    shared = 0
    for px in range(a.x, a.right):
        for py in range(a.y, a.bottom):
            if b.x <= px < b.right and b.y <= py < b.bottom:
                shared += 1
    return shared

random.seed(7)
mismatches = 0
for _ in range(2000):
    a = Box(random.randint(0, 30), random.randint(0, 30), random.randint(1, 15), random.randint(1, 15))
    b = Box(random.randint(0, 30), random.randint(0, 30), random.randint(1, 15), random.randint(1, 15))
    if overlaps(a, b) != (brute_force(a, b) > 0):
        mismatches += 1
print("random cases checked: 2000, mismatches:", mismatches)

# touching edges do not overlap
print("touching edges overlap?", overlaps(Box(0, 0, 10, 10), Box(10, 0, 10, 10)))

def push_out_x(player, wall, vx):
    """Resolve a horizontal hit by snapping the player to the wall's edge."""
    if overlaps(player, wall):
        player.x = wall.x - player.w if vx > 0 else wall.right
    return player.x

p = Box(95, 100, 20, 20)
w = Box(110, 90, 10, 60)
print("overlap before:", overlaps(p, w), " x after resolving:", push_out_x(p, w, vx=5), " overlap after:", overlaps(p, w))
Expected output
random cases checked: 2000, mismatches: 0
touching edges overlap? False
overlap before: True  x after resolving: 90  overlap after: False

Line by line

  1. 3-10A simple box class with computed right and bottom edges.
  2. 12-13The AABB test written out: overlap on x and overlap on y. Strict inequalities mean touching edges are not collisions.
  3. 15-22A slow, obviously correct check that counts the shared pixel cells, used to verify the fast one.
  4. 24-31With a fixed seed, compare the two methods on 2000 random pairs and count disagreements, which should be zero.
  5. 33-34Confirm that two boxes sharing an edge do not overlap.
  6. 36-39Collision response: if the player moving right overlaps a wall, snap the player's right edge to the wall's left edge (or the left edge to the wall's right edge when moving left).
  7. 41-43Try it with a player that has pushed 5 pixels into a wall and print the before and after states.

Sprites and groups

As games grow, a pile of separate variables becomes unmanageable. Pygame's Sprite class gives you a standard shape for a game object: it has an image (a surface), a rect (position and size) and an update() method you write. A Group is a container of sprites that can update and draw all of them with one call: group.update(dt) and group.draw(screen).

To make your own sprite, subclass pygame.sprite.Sprite, call super().__init__(), set self.image and self.rect, and put your behaviour into update. Groups also help with cleanup: calling sprite.kill() removes the sprite from every group it belongs to. Collision helpers work on groups too. pygame.sprite.spritecollide(player, items, dokill=True) returns the list of items touching the player and removes them in the same call, and groupcollide compares two groups.

Notice the separation that sprites encourage. Each sprite knows how to move itself, the group knows how to draw them, and the main loop only coordinates. The static example creates falling stars and a player that collects them. It is a miniature version of the full game below, so read it as a warm-up. If you do not need full sprite features you can still keep plain classes and lists, which is perfectly fine for small games.

sprites.pyrun on your computer
import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 320))
clock = pygame.time.Clock()


class Star(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((14, 14))
        self.image.fill((255, 230, 90))
        self.rect = self.image.get_rect(midbottom=(random.randint(10, 470), 0))
        self.speed = random.randint(80, 200)       # pixels per second

    def update(self, dt):
        self.rect.y += self.speed * dt
        if self.rect.top > 320:
            self.kill()


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((60, 16))
        self.image.fill((90, 200, 255))
        self.rect = self.image.get_rect(midbottom=(240, 310))

    def update(self, dt):
        x = pygame.mouse.get_pos()[0]
        self.rect.centerx = max(30, min(450, x))


player = Player()
stars = pygame.sprite.Group()
everything = pygame.sprite.Group(player)
score = 0
spawn_timer = 0.0
running = True

while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    spawn_timer += dt
    if spawn_timer > 0.6:
        spawn_timer = 0
        star = Star()
        stars.add(star)
        everything.add(star)

    everything.update(dt)
    score += len(pygame.sprite.spritecollide(player, stars, dokill=True))

    screen.fill((12, 12, 28))
    everything.draw(screen)
    pygame.display.set_caption(f"Stars caught: {score}")
    pygame.display.flip()

pygame.quit()

Line by line

  1. 1-6Imports and standard set-up.
  2. 9-20A Star sprite: a small yellow surface, a random start above the screen and a speed in pixels per second. Its update moves it down and calls kill() when it leaves the bottom.
  3. 23-33A Player sprite: a paddle that follows the mouse horizontally, clamped inside the window.
  4. 36-41One group for stars (for collision tests) and another for everything (for updating and drawing), plus score and a spawn timer.
  5. 43-49Loop: compute dt and handle the quit event.
  6. 51-56Every 0.6 seconds spawn a new star and add it to both groups.
  7. 58-59Update all sprites, then count how many stars touched the player. dokill=True removes them from every group.
  8. 61-65Clear, draw all sprites with one call, show the score in the window title and flip.
โ„น๏ธ

Pygame sprites store rect coordinates as integers, so tiny per-frame movements can be rounded away. For very slow or precise movement, keep a float position of your own and copy it into the rect each frame.

Sound and music

Sound is handled by pygame.mixer. For short effects such as a coin pickup, load a Sound object once with pygame.mixer.Sound('coin.wav') and call .play() whenever you need it. For background music use pygame.mixer.music.load('theme.ogg') followed by pygame.mixer.music.play(-1), where -1 means loop forever. WAV and OGG files are the safest formats. Volume goes from 0.0 to 1.0 through set_volume.

Two practical rules save a lot of trouble. First, initialise the mixer through pygame.init() or pygame.mixer.init() and be prepared for it to fail, since a computer may have no audio device. Wrap the set-up in try/except pygame.error and fall back to a silent stand-in object, so the game still runs. Second, load sounds before the game loop starts. Loading a file in the middle of a frame can cause a visible stutter.

You do not need to hunt for sound files to practise, because a sound is just a list of numbers: samples of a wave. The block below creates a short 440 hertz beep with the standard wave module, writes it to a WAV file in memory, reads the header back and prints facts about it. You can save the same file on your computer and load it with pygame.mixer.Sound. The static block above it shows the safe loading pattern.

sound_setup.pyrun on your computer
import pygame


class SilentSound:
    """Stand-in used when there is no audio device."""
    def play(self):
        pass
    def set_volume(self, volume):
        pass


def load_sound(path):
    try:
        return pygame.mixer.Sound(path)
    except (pygame.error, FileNotFoundError):
        return SilentSound()


pygame.init()
try:
    pygame.mixer.init()
except pygame.error:
    print("No audio device, running without sound")

coin = load_sound("coin.wav")
coin.set_volume(0.6)

try:
    pygame.mixer.music.load("theme.ogg")
    pygame.mixer.music.set_volume(0.3)
    pygame.mixer.music.play(-1)
except pygame.error:
    pass

coin.play()

Line by line

  1. 4-9A do-nothing class with the same methods as a Sound, so the rest of the game never needs to check whether sound exists.
  2. 12-16A loader that returns a real Sound, or the silent stand-in if the file or audio device is missing.
  3. 19-23Initialise Pygame and attempt to start the mixer, printing a message instead of crashing when audio is unavailable.
  4. 25-26Load the effect once, before the game loop, and lower its volume.
  5. 28-33Try to load looping music at low volume. A missing file or device is ignored.
  6. 35Play the effect. In a game this would happen in the collision code.
Making a beep as raw samples
import io
import math
import struct
import wave

RATE = 22050

def make_beep(freq=440.0, seconds=0.25, volume=0.5):
    count = int(RATE * seconds)
    samples = []
    for i in range(count):
        envelope = min(1.0, (count - i) / (RATE * 0.05))        # fade out the last 50 ms
        value = math.sin(2 * math.pi * freq * i / RATE) * volume * envelope
        samples.append(int(value * 32767))
    return samples

samples = make_beep()
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
    wav.setnchannels(1)
    wav.setsampwidth(2)            # 16-bit
    wav.setframerate(RATE)
    wav.writeframes(struct.pack("<" + "h" * len(samples), *samples))

data = buffer.getvalue()
buffer.seek(0)
with wave.open(buffer, "rb") as wav:
    print("channels:", wav.getnchannels())
    print("sample rate:", wav.getframerate())
    print("frames:", wav.getnframes())
    print("duration (s):", round(wav.getnframes() / wav.getframerate(), 3))
print("file size in bytes:", len(data))
print("peak sample:", max(samples), " lowest sample:", min(samples))
print("first five samples:", samples[:5])
Expected output
channels: 1
sample rate: 22050
frames: 5512
duration (s): 0.25
file size in bytes: 11068
peak sample: 16383  lowest sample: -16383
first five samples: [0, 2048, 4065, 6018, 7876]

Line by line

  1. 1-5Only the standard library is needed. 22,050 samples per second is plenty for a simple effect.
  2. 7-14Generate a sine wave at 440 hertz. Each sample is the wave's height at that instant, scaled to the 16-bit range. A short fade at the end stops the click that an abrupt cut would make.
  3. 16-22Write the numbers into a WAV container in memory: one channel, two bytes per sample, and the sample rate, packing the samples as little-endian signed 16-bit integers.
  4. 24-31Read the file back and print its properties: channels, rate, frame count and duration.
  5. 32-34Print the file size and a few samples. In your own project you could write data to beep.wav and load it with pygame.mixer.Sound.

Score logic, lives and game state

A game is more than moving objects. It also has rules: how points are earned, when you lose a life, when the level gets harder and when the game ends. Keep these rules out of the drawing code and out of the event loop where you can. Put them in a small class with plain methods and no Pygame inside. It is then easy to test, easy to tweak, and it is the code you will change most often as you balance the game.

A common structure is a state machine: the game is always in exactly one state, such as menu, playing or game_over, and the loop does different things depending on the state. A string or Enum stored in one variable is enough. This avoids a tangle of boolean flags, like is_paused and has_started, that can disagree with each other.

The following runnable class handles points, combos (consecutive catches earn a multiplier), lives, difficulty that grows with score, and a high score. It prints the result of a scripted play session. The finished game in the next section uses exactly these rules, so you can run this block and tune the numbers before you open a window.

ScoreKeeper: combos, lives and levels
from enum import Enum

class State(Enum):
    PLAYING = "playing"
    GAME_OVER = "game over"

class ScoreKeeper:
    def __init__(self, lives=3, high_score=0):
        self.lives = lives
        self.score = 0
        self.combo = 0
        self.high_score = high_score
        self.state = State.PLAYING

    @property
    def level(self):
        return 1 + self.score // 100

    def fall_speed(self):
        return 120 + 25 * (self.level - 1)      # pixels per second

    def caught(self):
        if self.state is not State.PLAYING:
            return 0
        self.combo += 1
        points = 10 * min(self.combo, 5)       # multiplier caps at 5x
        self.score += points
        self.high_score = max(self.high_score, self.score)
        return points

    def missed(self):
        if self.state is not State.PLAYING:
            return
        self.combo = 0
        self.lives -= 1
        if self.lives <= 0:
            self.state = State.GAME_OVER

keeper = ScoreKeeper(high_score=150)
events = ["c", "c", "c", "m", "c", "c", "c", "c", "c", "c", "c", "c", "m", "m", "c", "m"]
for e in events:
    if e == "c":
        gained = keeper.caught()
        print(f"caught  +{gained:2d}  score={keeper.score:3d}  combo={keeper.combo}  level={keeper.level}  speed={keeper.fall_speed()}")
    else:
        keeper.missed()
        print(f"missed      score={keeper.score:3d}  lives={keeper.lives}  state={keeper.state.value}")

print("high score:", keeper.high_score)
Expected output
caught  +10  score= 10  combo=1  level=1  speed=120
caught  +20  score= 30  combo=2  level=1  speed=120
caught  +30  score= 60  combo=3  level=1  speed=120
missed      score= 60  lives=2  state=playing
caught  +10  score= 70  combo=1  level=1  speed=120
caught  +20  score= 90  combo=2  level=1  speed=120
caught  +30  score=120  combo=3  level=2  speed=145
caught  +40  score=160  combo=4  level=2  speed=145
caught  +50  score=210  combo=5  level=3  speed=170
caught  +50  score=260  combo=6  level=3  speed=170
caught  +50  score=310  combo=7  level=4  speed=195
caught  +50  score=360  combo=8  level=4  speed=195
missed      score=360  lives=1  state=playing
missed      score=360  lives=0  state=game over
caught  + 0  score=360  combo=0  level=4  speed=195
missed      score=360  lives=0  state=game over
high score: 360

Line by line

  1. 1-5A tiny Enum for the two states of the game.
  2. 7-14The keeper holds lives, score, combo, high score and the current state.
  3. 16-21Level and fall speed are computed from the score, so difficulty rises automatically.
  4. 23-30A catch increases the combo and awards ten points times the combo, with the multiplier capped at five. It also updates the high score. After game over, it awards nothing.
  5. 32-38A miss resets the combo and removes a life. At zero lives the state flips to game over.
  6. 40-49Run a scripted session of catches and misses and print each step.
  7. 51Finally print the high score, which was beaten once the session passed 150.
๐Ÿ’ก

Tune difficulty by changing numbers in one class, not by hunting through the game loop. Small, readable rule code is what lets you balance a game quickly.

A complete game: Catch the Apples

Here is a full small game that brings the whole page together. You move a basket left and right with the arrow keys or A and D. Apples fall from the top, and each one you catch earns points with a growing combo. Every apple that reaches the floor costs a life. Speeds increase as the score rises, and when your lives run out a game-over screen offers to restart with the Enter key, remembering the best score for the session.

Look at how the pieces we met fit. The main loop reads events and handles QUIT, Escape and Enter. A fixed timestep accumulates time so the game plays the same on any machine. A Basket and Apple are sprites in groups. Catching is spritecollide with the basket, and a missed apple is detected when it passes the floor line. All scoring goes through ScoreKeeper, which is the class you just ran. The sound is optional and silent if the files are missing, thanks to the loader from the sound section.

To play it, install Pygame, save the code as apples.py and run python apples.py. Put catch.wav and miss.wav next to it if you want sound; the game works without them. Good next steps are adding images instead of coloured rectangles, a pause key, bombs that cost a life if caught, and a high-score file saved with json. Each of those touches one small part of the program, which is the sign of a well-organised game.

apples.pyrun on your computer
import random
from enum import Enum

import pygame

WIDTH, HEIGHT = 480, 640
STEP = 1 / 60
FLOOR = HEIGHT - 10


class State(Enum):
    PLAYING = "playing"
    GAME_OVER = "game over"


class ScoreKeeper:
    def __init__(self, lives=3, high_score=0):
        self.lives = lives
        self.score = 0
        self.combo = 0
        self.high_score = high_score
        self.state = State.PLAYING

    @property
    def level(self):
        return 1 + self.score // 100

    def fall_speed(self):
        return 120 + 25 * (self.level - 1)

    def spawn_delay(self):
        return max(0.35, 1.0 - 0.08 * (self.level - 1))

    def caught(self):
        self.combo += 1
        points = 10 * min(self.combo, 5)
        self.score += points
        self.high_score = max(self.high_score, self.score)

    def missed(self):
        self.combo = 0
        self.lives -= 1
        if self.lives <= 0:
            self.state = State.GAME_OVER


class SilentSound:
    def play(self):
        pass


def load_sound(path):
    try:
        return pygame.mixer.Sound(path)
    except (pygame.error, FileNotFoundError):
        return SilentSound()


class Basket(pygame.sprite.Sprite):
    SPEED = 380

    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((90, 20))
        self.image.fill((90, 170, 255))
        self.rect = self.image.get_rect(midbottom=(WIDTH // 2, HEIGHT - 20))
        self.x = float(self.rect.x)

    def update(self, step, direction):
        self.x += direction * self.SPEED * step
        self.x = max(0, min(WIDTH - self.rect.width, self.x))
        self.rect.x = round(self.x)


class Apple(pygame.sprite.Sprite):
    def __init__(self, speed):
        super().__init__()
        self.image = pygame.Surface((22, 22))
        self.image.fill((230, 60, 60))
        self.rect = self.image.get_rect(midbottom=(random.randint(20, WIDTH - 20), 0))
        self.y = float(self.rect.y)
        self.speed = speed * random.uniform(0.9, 1.2)

    def update(self, step):
        self.y += self.speed * step
        self.rect.y = round(self.y)


def new_game(high_score):
    basket = Basket()
    apples = pygame.sprite.Group()
    return ScoreKeeper(high_score=high_score), basket, apples, 0.0


def main():
    pygame.init()
    try:
        pygame.mixer.init()
    except pygame.error:
        pass
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Catch the Apples")
    clock = pygame.time.Clock()
    font = pygame.font.Font(None, 34)
    big = pygame.font.Font(None, 64)
    catch_sound = load_sound("catch.wav")
    miss_sound = load_sound("miss.wav")

    keeper, basket, apples, spawn_timer = new_game(0)
    accumulator = 0.0
    running = True

    while running:
        accumulator += min(clock.tick(60) / 1000, 0.25)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_RETURN and keeper.state is State.GAME_OVER:
                    keeper, basket, apples, spawn_timer = new_game(keeper.high_score)

        keys = pygame.key.get_pressed()
        direction = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])

        while accumulator >= STEP:
            accumulator -= STEP
            if keeper.state is not State.PLAYING:
                continue

            basket.update(STEP, direction)
            spawn_timer += STEP
            if spawn_timer >= keeper.spawn_delay():
                spawn_timer = 0.0
                apples.add(Apple(keeper.fall_speed()))
            apples.update(STEP)

            for _ in pygame.sprite.spritecollide(basket, apples, dokill=True):
                keeper.caught()
                catch_sound.play()
            for apple in list(apples):
                if apple.rect.top > FLOOR:
                    apple.kill()
                    keeper.missed()
                    miss_sound.play()

        screen.fill((16, 20, 34))
        pygame.draw.line(screen, (60, 70, 100), (0, FLOOR), (WIDTH, FLOOR), 2)
        apples.draw(screen)
        screen.blit(basket.image, basket.rect)

        hud = f"Score {keeper.score}   Lives {keeper.lives}   Level {keeper.level}   Combo x{min(keeper.combo, 5)}"
        screen.blit(font.render(hud, True, (235, 235, 245)), (12, 10))
        screen.blit(font.render(f"Best {keeper.high_score}", True, (250, 210, 90)), (12, 38))

        if keeper.state is State.GAME_OVER:
            text = big.render("Game over", True, (255, 120, 120))
            hint = font.render("Press Enter to play again", True, (235, 235, 245))
            screen.blit(text, text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 20)))
            screen.blit(hint, hint.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30)))

        pygame.display.flip()

    pygame.quit()


if __name__ == "__main__":
    main()

Line by line

  1. 1-9Imports and constants: window size, the fixed step (1/60 s) and the y coordinate of the floor.
  2. 12-47The State enum and ScoreKeeper rules you ran earlier, plus a spawn delay that shrinks as the level rises.
  3. 50-60The silent sound stand-in and a loader that never crashes when files or audio are missing.
  4. 63-76Basket sprite: a blue paddle that keeps a float x position for smooth movement and clamps itself inside the window.
  5. 79-90Apple sprite: spawns above a random column with a slightly random speed and moves by speed times step.
  6. 93-96A helper that returns a fresh keeper, basket, apple group and spawn timer, used at start and on restart.
  7. 99-114Start-up inside main(): initialise Pygame, tolerate a missing mixer, open the window, create fonts and sounds, and start the first game.
  8. 116-118The accumulator collects real time, capped at a quarter second.
  9. 120-128Events: quit and Escape end the program, and Enter restarts only from the game-over state, keeping the best score.
  10. 130-131Polled keys give the direction: right or D is +1, left or A is -1.
  11. 133-155The fixed-step update. Skip logic when the game is over; otherwise move the basket, spawn apples on a timer, move them, award catches with spritecollide, and charge a life for any apple below the floor.
  12. 157-175Draw: background, floor line, apples, basket, a heads-up display with score, lives, level, combo and best score, and a game-over overlay.
  13. 177-181Flip the display, quit cleanly, and the guard that starts the game only when the file is run directly.
โš ๏ธ

I checked this program's syntax but did not run it in a window while writing this page, so I am not showing a screenshot. If a value feels off when you play, such as speed or spawn rate, adjust the numbers in ScoreKeeper; that is exactly what they are there for.

Common mistakes

โŒ Forgetting to process events

If you never call pygame.event.get() (or pump()), the window freezes and the operating system reports it as not responding. Process events once every frame, even in menus and game-over screens.

โŒ Tying speed to frame rate

Moving a fixed number of pixels per frame makes the game faster on fast computers. Use delta time or a fixed timestep with speeds expressed in pixels per second.

โŒ Fast diagonal movement and tunnelling

Adding x and y movement without normalising makes diagonals about 41 percent faster. Moving objects too far in one step lets them skip through thin walls. Normalise directions and keep step sizes small.

โŒ Loading assets inside the loop

Calling image.load or Sound(...) every frame is slow and causes stutters. Load once before the loop and reuse the objects, converting images with convert().

โŒ Mixing game rules into drawing code

When scoring, lives and difficulty are tangled into draw calls they are hard to change or test. Keep rules in a plain class, such as ScoreKeeper, and let the loop draw whatever the state says.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What are the three steps repeated in a typical game loop?

Q2. Why is a fixed timestep useful?

Q3. Two rectangles with a.right == 100 and b.left == 100 are tested with colliderect. What is the result?

Q4. Why normalise the movement direction vector?

Q5. What does pygame.sprite.spritecollide(player, items, True) do?

Q6. How should a game handle a computer with no audio device?

Frequently asked questions

Both give you import pygame and nearly identical code. Pygame-ce is a community-maintained fork. Check each project's current documentation to choose, and install only one of them in a given environment.

A Pygame window needs the operating system's graphics and sound, which a web page does not offer to Python in this runner. The Run buttons on this page use headless versions of the logic, and the full programs are for your own computer.

Use clock.tick(60) to cap the frame rate, and use delta time or a fixed timestep so movement is measured in pixels per second rather than pixels per frame.

No. For small games plain classes in lists work well. Sprites become convenient when you have many objects, group collisions and automatic drawing, but they are optional.

You can send the source and ask them to install Pygame, or bundle it into an executable with a tool such as PyInstaller. Test the bundle on a computer that does not have Python installed, since asset paths often need attention.

Key takeaways

  • โœ“Every game is a loop: handle events, update the state, draw, and wait for the next frame with a Clock.
  • โœ“Surfaces are pixel grids you blit onto each other, and Rect stores position and size with handy edge attributes.
  • โœ“Use delta time or a fixed timestep so speed does not depend on the frame rate, and normalise direction vectors.
  • โœ“AABB collision tests overlap on both axes, and colliderect, spritecollide and groupcollide do the work for you.
  • โœ“Sprites and groups organise objects, and a plain rules class such as ScoreKeeper keeps scoring and difficulty testable.
  • โœ“Load assets once, make sound optional, and keep the game logic separate from the drawing so it is easy to extend.