The Basket
Lesson 9 of 40 in Coddy's Make Games with Pygame course.
A new game: blocks fall from the top and you catch them in a basket. The basket and the blocks are rectangles, and pygame has a class for those: pygame.Rect.
basket = pygame.Rect(200, 330, 80, 16)A Rect keeps its position and size together, in the same order as before: x, y, width, height. You can read and change basket.x and basket.y, and it knows its edges: basket.left, basket.right, basket.top, basket.bottom and its middle, basket.centerx.
Pass the Rect straight to pygame.draw.rect(screen, color, basket). And it can keep itself inside another Rect: basket.clamp_ip(screen.get_rect()) moves it back inside the window when it goes past an edge. screen.get_rect() is the window's own Rect.
Challenge
Easy- Before the loop, make
basket = pygame.Rect(200, 330, 80, 16). - In the loop, before the fill, move it 8 pixels a frame while Left or Right is held, then keep it inside the window with
basket.clamp_ip(screen.get_rect()). - After the fill, draw it in blue
(80, 160, 255).
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 30, 46))
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