Catch It
Lesson 12 of 40 in Coddy's Make Games with Pygame course.
Two rectangles collide when they overlap. a.colliderect(b) is True when Rect a and Rect b overlap, even by one pixel.
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)A caught block goes back to the top, the same way as a missed one. Testing the overlap is safer than testing exact positions: a block moving 3 pixels at a time can skip right over the one y value you test for.
Challenge
EasyAfter the missed-block check, when the block collides with the basket, send it back to the top: block.y = -20 and a random block.x, as for a missed block.
Try it yourself
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
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]:
basket.x -= 8
if keys[pygame.K_RIGHT]:
basket.x += 8
basket.clamp_ip(screen.get_rect())
block.y += 3
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
Practice on your own: Pygame playground