5.1 Pygame setup and the game loop

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

5.1 Pygame setup and the game loop

We’re moving from text-based programs to a game window. Pygame is a library that gives you a window, shapes, colours, and keyboard input — everything you need for a simple game.

Install Pygame

In the terminal (or your IDE’s terminal):

pip install pygame

If you use Python 3 specifically: pip3 install pygame.

A minimal Pygame program

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("My Game")

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

    screen.fill((0, 0, 0))   # black background
    pygame.display.flip()     # show the new frame

pygame.quit()

Important idea: you can’t “remove” shapes

In Pygame you don’t delete things from the screen. You redraw the whole frame every time. So each loop we:

  1. Clear the screen (e.g. screen.fill(...)).
  2. Draw everything that should be visible (player, obstacles, etc.).
  3. Call pygame.display.flip().

Anything you drew last time is gone after the fill; only what you draw this time appears.

Project: Empty game window

  1. Create a new file and run the minimal program above.
  2. Change the window size and the background colour (try (30, 60, 100) for a blue).
  3. Close the window with the X and confirm the program exits cleanly.

Next: 5.2 Coordinates and drawing — the coordinate system and drawing rectangles.