Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 149 ยท Data and the Web

Games with pygame

Learn pygame basics in Python. Build the game loop, handle keyboard and quit events, draw shapes, use Rect and Sprite classes, detect collisions and keep logic testable.

Few things make programming feel as rewarding as seeing your own game move on the screen. pygame is the most popular Python library for 2D games. It gives you a window, drawing functions, keyboard and mouse input, sound and a steady clock, and it leaves the design of the game to you. Plenty of first games, game-jam entries and teaching projects are written with it.

There is one catch for this site: a pygame window needs a real desktop to open in, so the pygame code in this lesson is read-only. You'll run it on your own computer. The good news is that the ideas behind a game (a loop, state that changes, events, rectangles that overlap) are plain Python, and we can run those right here. We'll do both: read the real pygame code, then run the same logic in the editor without a window.

Installing and the smallest program

Install pygame in a virtual environment with pip install pygame (see packages and pip). There is also a community fork called pygame-ce that installs the same pygame module name; don't install both in one environment. A program that opens a window and waits to be closed looks like this:

Python
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))   # width, height in pixels
pygame.display.set_caption("My first pygame window")
clock = pygame.time.Clock()

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

    screen.fill((30, 30, 46))                  # 2. draw the frame
    pygame.draw.circle(screen, (255, 200, 0), (320, 180), 40)
    pygame.display.flip()                      # show what we drew

    clock.tick(60)                             # 3. wait: at most 60 frames per second

pygame.quit()

Colors are (red, green, blue) tuples with values from 0 to 255. The screen's top-left corner is (0, 0), x grows to the right and, unlike in math class, y grows downward. That detail causes more first-game confusion than any other.

The game loop

Every game, from this tiny window to a huge commercial title, is built around the same cycle, repeated many times per second. One pass is one frame:

flowchart LR
    A["Handle events<br/>(keys, mouse, quit)"] --> B["Update state<br/>(positions, score)"]
    B --> C["Draw the frame"]
    C --> D["Wait for the clock<br/>(about 60 FPS)"]
    D --> A

A game is a loop: read input, change the world a little, draw it, wait, and repeat.

Keeping the three jobs apart pays off quickly. Events only record what the player did. Update changes your variables. Draw only reads them and paints pixels. If you draw inside your update code, or move things inside your drawing code, the game gets hard to change.

clock.tick(60) does two things: it pauses long enough to hold the loop at 60 frames per second, and it returns how many milliseconds the last frame took. That second value lets you move things by speed times time instead of "this many pixels per frame", so the game runs at the same speed on a slow or a fast computer:

Python
dt = clock.tick(60) / 1000        # seconds since the previous frame
ball_x += ball_speed * dt         # speed is in pixels per second

Moving with delta time, without a window

Here is that idea as plain Python. A ball bounces between two walls. We call update with a fixed dt of one sixtieth of a second, exactly like a 60 FPS game, and print where the ball is every 30 frames:

Python A bouncing ball: update logic only

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.

Notice that the ball class knows nothing about pygame. That is the most useful habit in this lesson: keep the rules of your game in ordinary classes, and let the pygame code only feed them input and draw their state. Such classes are easy to test and to reuse.

Drawing

All drawing happens on a Surface. The window itself (screen) is a surface, and so is every image you load. The functions you'll use most are:

Call What it does
screen.fill(color) paint the whole surface one color (do this at the start of each frame)
pygame.draw.rect(screen, color, rect) filled rectangle (add a width to get an outline)
pygame.draw.circle(screen, color, center, radius) circle
pygame.draw.line(screen, color, start, end, width) line
font.render(text, True, color) returns a new surface with text on it
screen.blit(surface, position) copy one surface onto another
pygame.display.flip() show everything drawn this frame

Pygame draws into an off-screen buffer, and nothing becomes visible until flip(). Because the whole frame is redrawn every time, you need to fill first; otherwise last frame's picture stays under the new one.

Text takes two steps: create a Font once (outside the loop), then render it into a surface and blit that:

Python
font = pygame.font.Font(None, 36)             # None = built-in default font, 36 px high
text = font.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(text, (10, 10))

Events and keyboard input

pygame.event.get() returns a list of everything that happened since the last call. Each event has a type and extra attributes. The ones you'll meet first:

Event type When it happens Useful attributes
pygame.QUIT the player closes the window none
pygame.KEYDOWN / KEYUP a key is pressed / released event.key (such as pygame.K_SPACE)
pygame.MOUSEBUTTONDOWN a mouse button is pressed event.pos, event.button
pygame.MOUSEMOTION the mouse moves event.pos, event.rel

Use events for things that happen once (jump, shoot, pause). For things that continue while a key is held (walking), ask for the current state of the keyboard each frame with pygame.key.get_pressed():

Python
while running:
    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()
    if keys[pygame.K_LEFT]:
        player.x -= player.speed * dt
    if keys[pygame.K_RIGHT]:
        player.x += player.speed * dt

If your loop never calls event.get() (or event.pump()), the operating system decides the program has frozen. That's why even a screensaver-style program needs the for event in ... loop.

Rectangles and collisions

Most 2D games treat things as rectangles. pygame.Rect(x, y, width, height) stores one and gives you handy attributes (left, right, top, bottom, center, width, height) plus methods such as colliderect(other), collidepoint(pos) and move(dx, dy). Two rectangles overlap when each one starts before the other ends, on both axes. This tiny version of Rect shows exactly what colliderect checks, and drives a little "collect the coins" scene with scripted key events instead of a real keyboard:

Python Events, rectangles and collisions with no window

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.

The structure matches a real pygame program line for line: loop over frames, loop over that frame's events, update, then draw (here, print). To turn it into a real game you would replace the scripted frames with pygame.event.get() and replace print with pygame.draw.rect calls. That is also how you'd write automated tests for game rules.

Sprites and groups

Once a game has many things on screen, repeating "update this, draw that" gets tedious. pygame.sprite.Sprite is a base class for game objects, and pygame.sprite.Group is a container that updates and draws all its sprites at once. A sprite needs two attributes, image (a surface) and rect (its position), and usually an update method:

Python
import pygame

class Coin(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((16, 16))
        self.image.fill((255, 200, 0))
        self.rect = self.image.get_rect(topleft=(x, y))

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((32, 32))
        self.image.fill((80, 160, 255))
        self.rect = self.image.get_rect(center=(320, 180))
        self.speed = 240                         # pixels per second

    def update(self, dt, keys):
        self.rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * self.speed * dt
        self.rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * self.speed * dt

player = Player()
coins = pygame.sprite.Group(Coin(100, 100), Coin(300, 220), Coin(500, 80))
everything = pygame.sprite.Group(player, *coins)

# inside the game loop:
player.update(dt, pygame.key.get_pressed())
hits = pygame.sprite.spritecollide(player, coins, dokill=True)   # touching coins vanish
score += len(hits)

screen.fill((30, 30, 46))
everything.draw(screen)                          # blits every sprite's image at its rect
pygame.display.flip()

spritecollide(sprite, group, dokill) returns a list of the sprites in group that overlap sprite; with dokill=True it also removes them from every group, so collected coins disappear. This code uses only classes and the loop you already know: classes, inheritance and super().

Note that rect stores whole pixels. Moving by a tiny speed * dt each frame may round to zero. When the movement is slow or precise, keep the true position in a pygame.Vector2 (or two floats) and copy it into rect for drawing.

Putting it together

A complete, small game follows the same layout as every pygame project. Read this one on your own machine, then change the numbers and see what happens. The player steers left and right with the arrow keys to catch falling blocks:

Python
import random
import pygame

WIDTH, HEIGHT = 480, 640
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)

player = pygame.Rect(WIDTH // 2 - 30, HEIGHT - 40, 60, 20)
blocks = []                      # list of Rects falling down
score, spawn_timer = 0, 0.0

running = True
while running:
    dt = clock.tick(60) / 1000

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

    keys = pygame.key.get_pressed()
    player.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 360 * dt
    player.clamp_ip(screen.get_rect())            # keep inside the window

    spawn_timer += dt
    if spawn_timer > 0.7:
        spawn_timer = 0
        blocks.append(pygame.Rect(random.randint(0, WIDTH - 24), -24, 24, 24))

    for block in blocks[:]:                       # iterate over a copy while removing
        block.y += 240 * dt
        if block.colliderect(player):
            blocks.remove(block)
            score += 1
        elif block.top > HEIGHT:
            blocks.remove(block)

    screen.fill((20, 20, 30))
    pygame.draw.rect(screen, (80, 160, 255), player)
    for block in blocks:
        pygame.draw.rect(screen, (255, 200, 0), block)
    screen.blit(font.render(f"Score: {score}", True, (255, 255, 255)), (10, 10))
    pygame.display.flip()

pygame.quit()

Look for the three jobs in the loop: events, update (movement, spawning, collisions), draw. Ideas to extend it: lose a life when a block reaches the bottom, speed up as the score grows, load an image with pygame.image.load("player.png").convert_alpha() for the player, or play a sound with pygame.mixer.Sound.

Common mistakes

  • Forgetting flip() (or pygame.display.update()): the window stays black.
  • No event handling: the window "stops responding."
  • Drawing outside the loop: only the last drawing survives, and it is erased by the next fill.
  • Moving a fixed number of pixels per frame: the game speed then depends on the computer. Multiply by dt.
  • Loading files inside the loop: loading an image or font every frame is slow. Load once at the start.
  • Removing from a list while looping over it: loop over a copy (blocks[:]) or build a new list, as in the example above.
  • Forgetting that y points down: "up" means a smaller y.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the three jobs done in every pass of a game loop?

    Each frame reads the player's input, changes the state of the game, and draws the result. Waiting for the clock then keeps the speed steady.
  2. 2. In pygame's coordinate system, what happens to y when an object moves down the screen?

    The origin (0, 0) is the top-left corner, and y grows downward.
  3. 3. Why do games multiply movement by dt (the seconds since the last frame)?

    Speed times elapsed time is the distance moved. Without it, the game runs faster on a computer that draws more frames per second.
  4. 4. Which is the right tool for a continuous action such as walking while an arrow key is held down?

    KEYDOWN fires once when the key goes down. get_pressed() tells you which keys are down right now, so you can keep moving each frame.
  5. 5. What does pygame.sprite.spritecollide(player, coins, True) do?

    The function returns a list of the overlapping sprites. With the third argument (dokill) set to True it also removes them from every group they belong to.

Summary

  • pygame gives Python a window, drawing, input, sound and a clock. It needs a desktop, so run its code locally (pip install pygame).
  • A game is a loop: handle events, update state, draw, wait with clock.tick(60).
  • The screen's origin is the top-left corner and y grows downward.
  • Use dt (seconds per frame) so speed does not depend on frame rate.
  • Use events for one-time actions and key.get_pressed() for held keys.
  • Rect stores position and size; colliderect tests overlaps. Sprite and Group manage many objects.
  • Keep game rules in plain classes, separate from pygame calls, so you can test them like any other Python code.

Next: REST APIs with FastAPI.