Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 41 ยท Game Architecture

Organizing Pygame Code: Classes, Modules and Assets

Structure a growing Pygame project: modules, a Game class, entity classes, settings, an asset loader with caching, configuration files and simple event messaging.

A tiny game fits in one file. A game with ten enemies, a menu, levels and sounds does not, and the moment you start scrolling past 500 lines to find the code that moves the player you are paying for a lack of structure. Good organization is not about being fancy; it is about being able to find, change and reuse things.

This lesson shows a project layout, the classes that matter most, an asset loader that caches resources, and a lightweight way to let parts of the game talk without tangling them together. The Pygame snippets are read-only; the structure and caching logic are exercised with runnable stand-ins.

A project layout that scales

TEXT
mygame/
  main.py              # tiny: create Game and run it
  settings.py          # constants: sizes, colours, speeds
  game.py              # Game class: window, loop, state manager
  states/
    menu.py
    play.py
    gameover.py
  entities/
    player.py
    enemy.py
    bullet.py
  assets.py            # loading and caching images, sounds, fonts
  assets/
    images/ sounds/ fonts/ levels/

main.py should stay almost empty:

Python
from game import Game

if __name__ == "__main__":
    Game().run()

The if __name__ == "__main__" guard lets other files import game without starting a window, which matters for tests and tools.

Constants live in settings.py

Python
# settings.py
WIDTH, HEIGHT = 960, 540
FPS = 60
TITLE = "Space Gardeners"

PLAYER_SPEED = 320          # pixels per second
BULLET_SPEED = 700
ENEMY_SPAWN_EVERY = 1.2     # seconds

BG = (14, 18, 30)
WHITE = (240, 240, 245)

Other modules do from settings import * or, better, import settings as cfg and use cfg.FPS. Changing the difficulty then means editing one file, not hunting for magic numbers.

Entity classes

Each thing in the world becomes a class that owns its data and behavior, with the same small interface (update(dt) and draw(surface)). Subclassing pygame.sprite.Sprite gives you groups, collision helpers and automatic image/rect conventions:

Python
import pygame
import settings as cfg

class Bullet(pygame.sprite.Sprite):
    def __init__(self, pos, direction, groups):
        super().__init__(groups)                     # auto-added to the groups
        self.image = pygame.Surface((8, 18))
        self.image.fill((255, 230, 120))
        self.rect = self.image.get_rect(center=pos)
        self.pos = pygame.Vector2(pos)
        self.vel = pygame.Vector2(direction) * cfg.BULLET_SPEED

    def update(self, dt):
        self.pos += self.vel * dt
        self.rect.center = self.pos
        if not pygame.display.get_surface().get_rect().colliderect(self.rect):
            self.kill()                              # removes from every group

Because the sprite adds itself to its groups when created, calling all_sprites.update(dt) and all_sprites.draw(screen) handles everything. Keep creation logic (who shoots) in the owner, and behavior (how it moves) in the entity.

Composition over inheritance

Resist deep class hierarchies such as Enemy -> FlyingEnemy -> FireFlyingEnemy. A flexible pattern is one Enemy class that is configured with data:

Python
ENEMY_TYPES = {
    "grunt":  {"hp": 2, "speed": 80,  "colour": (200, 80, 80)},
    "runner": {"hp": 1, "speed": 220, "colour": (240, 200, 60)},
    "tank":   {"hp": 8, "speed": 40,  "colour": (90, 90, 200)},
}

New enemy kinds are now one dictionary entry, and the same data could come from a JSON file written by a designer.

An asset loader with caching

Loading the same image from many places wastes time and memory. An asset module loads each file once and hands out the same object afterwards:

Python
# assets.py
import pygame
from pathlib import Path

ROOT = Path(__file__).parent / "assets"
_images, _sounds = {}, {}

def image(name, alpha=True):
    if name not in _images:
        surf = pygame.image.load(ROOT / "images" / name)
        _images[name] = surf.convert_alpha() if alpha else surf.convert()
    return _images[name]

def sound(name):
    if name not in _sounds:
        _sounds[name] = pygame.mixer.Sound(ROOT / "sounds" / name)
    return _sounds[name]

Path(__file__).parent makes paths independent of the folder you launch the game from, which prevents the classic "file not found" when someone double-clicks main.py. convert_alpha() needs the display to exist, so first call image(...) after set_mode.

Python A cache that loads each asset once

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.

Six requests cost only three disk reads. The same pattern works for fonts, where pygame.font.Font(path, size) is a costly object to recreate.

Letting parts talk: a tiny event bus

When the player collects a coin, several things should happen: the score rises, a sound plays, particles burst. If the coin code calls all of them directly, the coin knows about everything. An event bus (publish and subscribe) lets the coin say "coin collected" and lets anyone who cares listen:

Python
from collections import defaultdict

class Bus:
    def __init__(self):
        self.handlers = defaultdict(list)

    def on(self, topic, fn):
        self.handlers[topic].append(fn)

    def emit(self, topic, **data):
        for fn in self.handlers[topic]:
            fn(**data)
Python Decoupling with an event bus

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.

Adding a screen shake on enemy_hit is now one bus.on line; no existing code changes. Do not overuse it: for simple games a direct method call is clearer. Reach for a bus when one event has three or more reactions.

Separate logic from drawing

Keep rules (what happens) apart from rendering (how it looks) wherever you can. A Board class for a puzzle that holds a grid and methods like move() and is_solved() needs no Pygame at all, so you can unit test it with pytest and later reuse it with a different display. Several projects in this track, such as Tic Tac Toe and Sudoku, follow this split.

Practical habits

  • One responsibility per file. If a file needs the word "and" to describe it, split it.
  • No globals except constants. Pass game or specific dependencies into constructors.
  • Type hints and short docstrings help your future self.
  • Version control (Git) from day one; commit whenever something works. Add __pycache__/ and your build folders to .gitignore.
  • Virtual environment with a requirements.txt listing pygame-ce (or pygame) so the project installs anywhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use if name == "main": in main.py?

    The guard runs the game only when the file is executed directly, not when another file imports it.
  2. 2. What does an asset cache achieve?

    Repeated requests return the stored object, saving time and memory.
  3. 3. When is an event bus a good idea?

    Publishers do not need to know subscribers, so adding a new reaction touches no existing code.
  4. 4. Why describe enemy kinds in a dictionary of data instead of subclasses?

    Configuring one class with data avoids deep inheritance and allows loading definitions from files.

Summary

  • Split the project into small modules: settings, game, states, entities and assets.
  • Keep main.py tiny and constants in settings.py.
  • Entities own their data and behavior and share an update/draw interface; configure kinds with data.
  • Cache images, sounds and fonts in one asset module, using paths relative to the file.
  • Use an event bus sparingly to decouple reactions, and keep game rules independent from drawing.

Next: Tilemaps and Scrolling Camera