What you will learn

This first chapter lays the foundation for every Pygame project: the game loop. Without it, no game can function. You will understand how a window appears, how the program listens for your actions, and how it redraws the screen dozens of times per second to create the illusion of movement.

The concept

A video game is not a typical program that waits for input and then displays a result. It is an infinite loop that repeats three actions constantly:

  1. Handle events: did the user press a key, move the mouse, close the window?
  2. Update state: move objects, check collisions, update the score.
  3. Draw: clear the previous screen and redraw everything in its new position.

This loop runs about 60 times per second (60 FPS). Each pass is called a frame. The clock (pygame.time.Clock) ensures the loop does not run too fast: it slows the program down to maintain the desired FPS.

Before the loop, you must initialize Pygame with pygame.init(). This call prepares all subsystems (video, audio, keyboard). Then, you create the window with pygame.display.set_mode() by passing the desired dimensions as a tuple (width, height).

Step by step

1. Initialization

We start by importing Pygame and initializing all its subsystems. We also define our constants: window size, frames per second, and background color.

python
import pygame
import sys

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
BG_COLOR = (20, 20, 40)  # Dark blue background

The color (20, 20, 40) is an RGB tuple: Red=20, Green=20, Blue=40. It is a very dark blue, more pleasant than pure black for a game.

2. Creating the window

set_mode() creates the game window. set_caption() sets the title displayed in the title bar. The clock will be used to regulate speed.

python
# Create the window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Brick Breaker - Chapter 1")

# Clock for controlling frame rate
clock = pygame.time.Clock()

3. The main loop

Here is the heart of the program. pygame.event.get() retrieves all pending events. We check if the user closed the window (QUIT) or pressed Escape. screen.fill() fills the screen with our background color. pygame.display.flip() displays the result on screen. clock.tick(FPS) waits the necessary time to not exceed 60 FPS.

python
running = True
while running:
    # 1. Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # 2. Update game state
    # (nothing to update yet)

    # 3. Draw everything
    screen.fill(BG_COLOR)

    # 4. Flip the display
    pygame.display.flip()

    # 5. Tick the clock
    clock.tick(FPS)

4. Cleanup

When the loop ends, we call pygame.quit() to release resources, then sys.exit() to cleanly exit the program.

python
pygame.quit()
sys.exit()

Key takeaways

Tip: if you forget pygame.event.get() in your loop, your window will appear frozen because the operating system will think the program is not responding.

Common pitfall: do not confuse pygame.display.flip() (updates the entire screen) with pygame.display.update() (can update only a portion). For now, flip() is the right choice.

Pygame functions used:

  • pygame.init(): initializes all modules
  • pygame.display.set_mode(): creates the window
  • pygame.display.set_caption(): sets the window title
  • pygame.event.get(): retrieves events
  • screen.fill(): fills the surface with a color
  • pygame.display.flip(): displays the render
  • clock.tick(): regulates the loop speed

Complete code

python
"""Brick Breaker - Chapter 1: The Game Loop"""
import pygame
import sys

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
BG_COLOR = (20, 20, 40)  # Dark blue background

# Create the window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Brick Breaker - Chapter 1")

# Clock for controlling frame rate
clock = pygame.time.Clock()

# Main game loop
running = True
while running:
    # 1. Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # 2. Update game state
    # (nothing to update yet)

    # 3. Draw everything
    screen.fill(BG_COLOR)

    # 4. Flip the display
    pygame.display.flip()

    # 5. Tick the clock
    clock.tick(FPS)

# Clean up
pygame.quit()
sys.exit()

Telechargement

Telecharger le code source de ce chapitre : brick-breaker-ch01.zip