pygame — real-time applications

A game, a robot dashboard, a lab simulator and a kiosk quiz are the same architecture: a loop that never ends until the user quits. Each pass: read events (keys, mouse, window close), update state (position, score, cooldown), draw. pygame is the library Indian classrooms actually use for this. The maths is the Intermediate loops you already have, running 60 times a second.

Game loop

Events in, pictures out, sixty times a second.

You will be able to

  • Describe the game loop: events → update → draw
  • Keep physics/rules out of the draw call
  • Know surfaces, clocks and event types at a reading level

The loop is the application

Web apps wait for a request. Games poll. clock.tick(60) aims at 60 frames per second. If your update does a pandas groupby on 100,000 rows inside that loop, the game stutters. Heavy data work belongs in a pipeline that writes a small table the game then reads — or in a loading screen, once.

pygame.QUIT is not optional. Without it, the window’s close button does nothing useful and students force-kill Python. Always handle QUIT and a key for escape.

State is a dict (or a class)

player = {"x": 40, "y": 80, "vx": 3} is enough for a first sprite. Each frame: x = x + vx, bounce when x hits a wall. Classes (pygame.sprite.Sprite) are this dict with methods and a rect for collisions. Learn the dict first so Sprite is not magic.

Collision is geometry: two rectangles overlap. pygame.Rect.colliderect is the helper. The rule “if they overlap, score += 1” is a pure function of two rects if you keep it out of the blit (draw) section.

Draw is the last step, not the program

fill the screen (or you see smears), blit images, flip/update the display. Mixing “load CSV” into the draw section is how a 60 FPS loop becomes a 2 FPS slide show. Load assets once before the loop.

Fonts, sounds and images are files. pathlib belongs here too. A missing .png should raise a clear error at startup, not a black rectangle after the principal sits down.

What pygame is for — and not for

For: 2D games, interactive lab sims, quiz kiosks, simple robot visualisations. Not for: Excel reports (pandas), websites (Flask/Django/FastAPI), numeric HPC (NumPy/SciPy). Real products combine them: a pygame trainer that saves scores to SQLite and a pandas weekly report.

Words that matter

Game loop
Repeated cycle: events, update state, draw.
Frame
One pass of that loop; FPS is frames per second.
Surface
An image buffer you blit onto the window.
Event
A queued input: key, mouse, quit, custom user event.

Common mistakes

Avoid: Loading a CSV or calling pandas inside the 60 FPS loop.

Do this: Load once; the loop only updates and draws.

Avoid: Forgetting pygame.QUIT.

Do this: Handle quit and Escape so the window can close.

On a full Python install — pygame

The usual Python library for 2D real-time apps in schools and indie games. Installs SDL under the hood.

pip install pygame

Minimal loop: quit, move a rect, bounce, draw. Copy this onto a laptop.

Real library code (not run in this browser sandbox)

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
x, vx = 40, 4
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    x = x + vx
    if x > 600 or x < 0:
        vx = -vx
    screen.fill((12, 12, 16))
    pygame.draw.rect(screen, (225, 6, 0), (x, 160, 40, 40))
    pygame.display.flip()
    clock.tick(60)
pygame.quit()

Example program — Eight frames of a bouncing x

The update half of a game loop. pygame draws this 60 times a second.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Move then stop at the wall

Start x = 0, speed = 10. Loop 5 times adding speed. If x >= 40, set speed to 0. Print a line containing 40.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. The three stages of a game loop are…
2. Heavy pandas work should run…

Progress is stored in a browser cookie on this device.