Menu
CoddyTech

Rects Feel Unfair

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 22 of 39.

Fly the ship toward the spike ball with the arrow keys. Rect collisions, colliderect, are fast and simple, and for a round ball they lie. The ball's Rect is the square around it, see-through corners and all, and the ship's Rect has empty space beside its nose.

Make the test visible: outline the ball's Rect and colour the outline by what colliderect says.

if ship_rect.colliderect(ball_rect):
    colour = (230, 60, 60)
else:
    colour = (90, 90, 120)
pygame.draw.rect(screen, colour, ball_rect, 2)

Then come at the ball from the bottom right. The outline turns red while a clear gap of sky still lies between the ship and the spikes: the corners of the two Rects overlap, the pictures do not. In a game that is a life lost for nothing, and players notice.

The next lessons test the pictures themselves.

challenge icon

Challenge

Easy

Show when the two Rects collide.

  1. After drawing the ball and the ship, outline ball_rect, 2 pixels wide.
  2. Make it red (230, 60, 60) while ship_rect collides with it, grey (90, 90, 120) otherwise.

Press Play and fly in from the bottom right: the outline turns red before the pictures touch. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Near Miss")
clock = pygame.time.Clock()

ship = pygame.image.load("assets/images/ship.png").convert_alpha()
ship_rect = ship.get_rect(topleft=(420, 320))
ball = pygame.image.load("assets/images/spike_ball.png").convert_alpha()
ball_rect = ball.get_rect(center=(320, 240))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        ship_rect.x -= 4
    if keys[pygame.K_RIGHT]:
        ship_rect.x += 4
    if keys[pygame.K_UP]:
        ship_rect.y -= 4
    if keys[pygame.K_DOWN]:
        ship_rect.y += 4

    screen.fill((20, 22, 40))
    screen.blit(ball, ball_rect)
    screen.blit(ship, ship_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground