Dodge the Blocks
Games
- You should already know
- Loops, functions, dictionaries and the local package workflow.
- You'll build
- A game window: move left and right, dodge falling blocks and restart after a collision.
- You'll be able to
- Handle events, update positions over time, draw a frame and detect collisions.
- You need
- Your local setup, any plain-text editor, uv and internet access for installing packages. Python 3.14 is selected for these examples.
Your card game waits for a command before anything changes. A graphical game keeps moving while you decide what to do.
We'll draw a player and falling blocks using pygame-ce, a community edition of Pygame. No artwork or sound files are needed. Your score increases for every block that passes you. A collision ends the round.

Open a Window
From your course folder, make a separate project:
mkdir dodge-game cd dodge-game uv init --bare --vcs none --no-workspace --python 3.14 uv python pin 3.14 uv add pygame-ce
The package is called pygame-ce; its import is pygame. Save this first experiment as dodge.py:
import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill('navy') pygame.display.flip() clock.tick(60) pygame.quit()
Run uv run dodge.py. A navy window should open. Close it with its close button and confirm that the terminal prompt returns.
The loop handles queued events, paints a frame and displays it. clock.tick(60) limits how often it repeats. Without checking events, the window couldn't respond properly to a close request.
Draw Your Player
Keep editing dodge.py. Add this after the clock assignment, before running = True:
player = pygame.FRect(300, 420, 40, 30)
A rectangle records its left position, top position, width and height. Coordinates start at the window's top-left: x grows to the right and y grows downward. This rectangle is 40 pixels wide and 30 high.
Inside the loop, between screen.fill('navy') and pygame.display.flip(), add:
pygame.draw.rect(screen, '#46d9bf', player)
Run again. You should see a green rectangle near the bottom. Change x from 300 to 100 and predict which way it moves. Restore 300 afterward. Drawing must follow fill(): filling afterward would paint over the player.
Compare the player stage if yours differs. Save a comparison as dodge.py in your project to run it with the same command.
Move Left and Right
Before the loop's screen.fill(...) line, insert:
keys = pygame.key.get_pressed() direction = int(keys[pygame.K_RIGHT]) - int(keys[pygame.K_LEFT]) player.x = max(0, min(640 - player.width, player.x + direction * 6))
keys reports held keys. Converting a Boolean to int gives 1 for True and 0 for False. Right alone gives direction 1, left alone gives −1, and both or neither give 0. The player moves six pixels per frame.
The inner min() keeps its left edge at most 640 - player.width. The outer max() keeps it at least zero. That leaves the entire rectangle inside the window.
Run and hold each arrow key. Click the game window first if it doesn't receive input. Check both edges, then hold both arrows: why should the player stay still? Compare the movement stage after trying.
Let One Block Fall
Start with one obstacle before adding a list of them. After the player assignment, add:
block = pygame.FRect(300, -40, 40, 40)
Its top is negative, so it starts just above the window. Inside the loop, after movement and before filling the screen, add:
block.y = block.y + 4 if block.top >= 480: block.y = -40
Then draw it after the player, before flip():
pygame.draw.rect(screen, '#ffb454', block)
Predict how long the block will remain visible, then run. It falls four pixels per frame and returns above the window when its top passes the bottom. There is no collision rule yet: it can pass through the player. Move aside and watch two complete falls. Compare the one-block stage.
Stop on Collision and Restart
Add over = False before running = True. Replace the movement-and-falling section inside the loop with:
if not over: keys = pygame.key.get_pressed() direction = int(keys[pygame.K_RIGHT]) - int(keys[pygame.K_LEFT]) player.x = max(0, min(640 - player.width, player.x + direction * 6)) block.y = block.y + 4 if block.top >= 480: block.y = -40 if player.colliderect(block): over = True
colliderect() checks whether the rectangles overlap. Once over becomes True, future frames skip these updates. Keep filling, drawing and displaying outside that condition so the last positions remain visible.
Inside the event loop, add this branch beside if event.type == pygame.QUIT::
elif event.type == pygame.KEYDOWN and event.key == pygame.K_r: player.x = 300 block.y = -40 over = False
This branch handles a key press once; held arrows are still checked each frame. Stay in the middle until a collision freezes movement. Press R and check that the block returns above the window and the player can move again. Closing the window should work even after a collision. Compare the collision stage.
Count Dodged Blocks
A collision now ends a round. Let's show how many blocks you avoided. Before the main loop, create:
score = 0 font = pygame.font.Font(None, 30)
Inside if block.top >= 480:, add score = score + 1 before resetting the block. Inside the R-key branch, add score = 0 beside the other reset assignments.
After drawing both rectangles and before flip(), add:
label = font.render(f'Dodged: {score}', True, 'white') screen.blit(label, (16, 16)) if over: message = font.render('Game over! R to restart.', True, 'white') screen.blit(message, (100, 220))
font.render() produces a text image. blit() draws that image at the supplied coordinates. Move aside for two falls: the score should reach 2. Let a collision happen: the score should stop changing. Press R: it should return to zero. Compare the scored stage.
You now have a complete one-block game. Keep a copy before continuing.
Give the Game Several Blocks
The final version adds a list of blocks, random starting positions and a timer for creating new ones. It also moves the state into a dictionary and separates three familiar jobs: new_game() creates state, update() changes it, and draw() displays it.
Compare these functions with the code you've just assembled. Start with new_game(): which values did your R-key branch reset? Then find the collision and score rules in update().
The final movement uses elapsed seconds, dt, rather than a fixed number of pixels per frame. Multiplying speed by time helps keep motion consistent when frames take different amounts of time. The next section traces that calculation. Reach a working one-block game before replacing it with this version.
Compare the complete dodge.py
import random import pygame WIDTH = 640 HEIGHT = 480 def new_game(): return { 'player': pygame.FRect(300, 420, 40, 30), 'blocks': [], 'spawn': 0.0, 'score': 0, 'over': False, } def update(game, direction, dt): if game['over']: return player = game['player'] player.x = max(0, min(WIDTH - player.width, player.x + direction * 360 * dt)) game['spawn'] += dt if game['spawn'] >= 0.55: game['spawn'] = 0.0 game['blocks'].append(pygame.FRect(random.randint(0, WIDTH - 40), -40, 40, 40)) remaining = [] for block in game['blocks']: block.y += 220 * dt if block.top >= HEIGHT: game['score'] += 1 else: remaining.append(block) game['blocks'] = remaining for block in game['blocks']: if player.colliderect(block): game['over'] = True def draw(screen, font, game): screen.fill('#14213d') pygame.draw.rect(screen, '#46d9bf', game['player']) for block in game['blocks']: pygame.draw.rect(screen, '#ffb454', block) label = font.render(f"Dodged: {game['score']}", True, 'white') screen.blit(label, (16, 16)) if game['over']: message = font.render('Game over! R to restart; Esc to quit.', True, 'white') screen.blit(message, (50, 220)) def main(): pygame.init() try: screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Dodge the Blocks') font = pygame.font.Font(None, 30) clock = pygame.time.Clock() game = new_game() running = True while running: dt = min(clock.tick(60) / 1000, 0.05) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False elif event.key == pygame.K_r: game = new_game() keys = pygame.key.get_pressed() direction = int(keys[pygame.K_RIGHT]) - int(keys[pygame.K_LEFT]) update(game, direction, dt) draw(screen, font, game) pygame.display.flip() finally: pygame.quit() if __name__ == '__main__': main()
You can also download dodge.py. Save the complete version in your project and run it. Use the left/right arrow keys, R to restart and Esc to quit. Click the game window if it isn't receiving keyboard input.
Follow One Frame
pygame.FRect holds a rectangle with floating-point coordinates. Its x, y, width and height describe a position and size. colliderect() asks whether two rectangles overlap. We use rectangles for both drawing and collision rules.
pygame.key.get_pressed() reports keys held down now. Events such as pressing R happen once; held arrow keys move the player across many frames. Converting each Boolean to int gives a direction of -1, 0 or 1.
dt is the elapsed time in seconds, calculated from the clock's millisecond result. Movement is speed multiplied by elapsed time. The small cap avoids a huge jump after a pause; this simple game slows during a long stall rather than trying to catch up instantly.
The player is clamped between the left and right edges. A timer creates blocks above the window. Blocks move downward, and each one that leaves the bottom adds a point. remaining collects the blocks still on screen; we don't remove items from the list we're iterating over.
A collision sets over to True. Later updates return immediately, freezing the round. Drawing still happens so we can show the restart message. R replaces the state dictionary with a fresh round.
Check a Rule Without Playing
Save as check_game.py beside the full game:
import pygame from dodge import new_game, update first = new_game() second = new_game() first['blocks'].append(first['player'].copy()) update(first, 0, 0) assert first['over'] is True assert second['over'] is False assert second['blocks'] == [] fresh = new_game() fresh['blocks'].append(pygame.FRect(0, 480, 40, 40)) update(fresh, 0, 0) assert fresh['score'] == 1 assert fresh['blocks'] == [] print('Game checks passed.')
Run uv run check_game.py. The fixed rectangles make collision and scoring predictable. The main guard lets this check import the game without opening its window.
Make It Yours
Change the fall speed, spawn interval or player width one at a time. Before each change, predict whether it makes survival easier. Then play long enough to compare.
Add a best score that lasts between rounds. Decide which value must live outside the dictionary replaced by new_game(). Saving it between program runs can reuse the file techniques from Part II.
A larger optional extension is a maze: draw a grid, mark walls and find a route. That adds a search algorithm, so write a tiny maze with a known answer before attempting animation.
In Your Own Words
Explain why a graphical game needs a loop even when the player isn't typing, and which work belongs in update versus draw.
Continue with the pygame-ce documentation. This first draft uses simple rectangle collisions; it doesn't attempt a physics simulation.