5.4 Collision and game logic

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

5.4 Collision and game logic

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.

colliderect

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.

Keeping a list of obstacles

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

Moving obstacles (scrolling)

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.

Simple game loop structure

  1. Handle events (quit, key down for jump).
  2. Update: move player (e.g. gravity/jump), move obstacles, check collisions.
  3. Draw: fill screen, draw player, draw obstacles, maybe score text.
  4. pygame.display.flip().

Project: Dodge one block

  1. One player rect (move with arrows or just sit on the left).
  2. One obstacle rect that moves left each frame. When it goes off the left, put it back on the right (or at a random y) so it “comes again”.
  3. If player_rect.colliderect(obstacle_rect), set game_over = True and stop moving or print “Game Over!”.
  4. (Optional: draw “Game Over” on the screen and wait for a key to restart.)

Next: 5.5 Building a runner game — put it all together like Chrome Dino.