0⚑

πŸ’₯

Crash Detection

Right now, the bird flies straight through the pipes like a ghost. That is no fun. We need collision detection: the game needs to know when the bird hits something.

Invisible Boxes

To the computer, your bird and pipes are not pictures. They are rectangles. We call these hitboxes.

When two hitboxes overlap, that is a collision.
πŸ“¦

Rect = Rectangle

Pygame has a built-in tool called pygame.Rect(x, y, width, height) that creates an invisible rectangle. It comes with a method called colliderect() that checks if two rectangles are touching.

The Overlap Test

colliderect() returns True if two rectangles overlap, False if they do not.

collision detection
1# Create hitboxes each frame
2bird_rect = pygame.Rect(50, bird_y, 30, 30)
🐀 Bird hitbox: 30x30 at its current position
3pipe_top_rect = pygame.Rect(pipe_x, 0, 50, gap_y - 75)
🟩 Top pipe hitbox
4pipe_bottom_rect = pygame.Rect(pipe_x, gap_y + 75, 50, 600)
🟩 Bottom pipe hitbox
5
6# Check for collision
7if bird_rect.colliderect(pipe_top_rect):
πŸ’₯ Are the bird and top pipe overlapping?
8 game_active = False
9
10if bird_rect.colliderect(pipe_bottom_rect):
πŸ’₯ Are the bird and bottom pipe overlapping?
11 game_active = False
12
13# Also check floor and ceiling
14if bird_y > 570 or bird_y < 0:
🚧 Did the bird hit the floor or fly off the top?
15 game_active = False

What Happens on Crash?

When we detect a collision, we set game_active = False. Why use a variable instead of immediately quitting?

Your Turn: Detect the Crash

Use Pygame’s collision method to check if the bird hit a pipe.

🎯
🎯

Level Goal

Use colliderect to detect if the bird hits a pipe and end the game.

Logic Lab: python.py
0/3
123456789
def check_collision(bird_rect, pipes): for pipe in pipes: if bird_rect.(pipe): return if bird_rect.top <= 0 or bird_rect.bottom >= 600: return return True

Choose for blank #1