Lecture 42

PyGame

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 42: PyGame

Reminders and announcements:

  • Please complete your course evaluations — response rates are very low at the moment
  • Project 4 autograder is open
  • Project 4 due Friday at 11:59pm
  • Final homework due tomorrow at Noon

Last time

We worked on a new Python project and used it to study version control with git and GitHub.

The project itself (a minimal "game") was mostly ignored!

Workflow

  • Initial setup: git init or git clone URL
  • Work session:
    • git pull
    • Make and test changes
    • git status   (optional)
    • git add file1
    • git add file2
    • git status   (optional)
    • git commit
    • git push

If push ever fails, do a pull, follow instructions, then push again.

PyGame

Python package for making games.

Key features: graphics, sound, user input device support, game mechanics calculations (e.g. collision detection)

Best for 2D sprite-based applications — i.e. a bunch of small images moving around and/or changing

Built with PyGame

and many more

PyGame internals

Based on Simple DirectMedia Layer (SDL), a library written in C to let programs access sound and graphics hardware in an efficient way, uniformly across various OS.

SDL is fast, widely used, and well-tested.

Why?

Provides practice with event-based programming, where the main job is to respond to events that arrive from an external source.

Event-based pseudocode


        while True:
            evt = wait_for_event()
            if evt.type == "alpha":
                handle_alpha(evt)
            elif:
                ...
            elif:
                ...

    

Events in a game

  • It's time to update what's shown on the screen (e.g. 60 times per second)
  • A key has been pressed
  • A key has been released
  • The mouse moved
  • A mouse button was pressed
  • A timer we set before has expired
  • The sound hardware is running out of data in its playback buffer
  • etc.

Draw-handle loop


    while True:
        redraw_window()

        for evt in event_queue:
            handle(evt)

        wait_for_redraw_time()

Prioritizes scheduled redraw to keep graphics responsive and smooth.

Key PyGame concepts

  • Surface - A thing you can draw on (e.g. an image, the screen, ...)
  • Rect - A rectangular region in a surface (with lots of utility methods)
  • Sprite - A visible object that is part of the game (has a location, behavior, draw process)

Project

Let's analyze the hello world example from last time, then build it out to an actual game.

References

Revision history

  • 2024-04-22 Initial publication