Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
Collision means “did two things touch?”. For rectangles we use rect.colliderect(other_rect). When the player rect hits an obstacle rect, we can end the game, add a point, or trigger a jump — that’s game logic.
Pygame Rects have a method colliderect:
if player_rect.colliderect(obstacle_rect):
print("Collision!")
# do something: game over, score, etc.
It returns True when the two rectangles overlap (even a little), False otherwise. Use it in the game loop, after you’ve updated positions and before or after drawing.
For several obstacles (e.g. many blocks or cacti), keep a list of Rects:
obstacles = [
pygame.Rect(300, 250, 30, 50),
pygame.Rect(500, 240, 30, 60),
]
Each frame, loop over the list and check collision with the player:
for obs in obstacles:
if player_rect.colliderect(obs):
game_over = True
To get a “runner” feel (like Chrome Dino), keep the player mostly in one place and move obstacles left each frame:
for obs in obstacles:
obs.x -= 5
if obs.right < 0:
obs.x = 600 # wrap or remove and add a new one
Then check collision after moving them.
pygame.display.flip().player_rect.colliderect(obstacle_rect), set game_over = True and stop moving or print “Game Over!”.Next: 5.5 Building a runner game — put it all together like Chrome Dino.