The Basket
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 23 of 32.
A new game: blocks fall from the top and you catch them in a basket. The basket and the blocks are rectangles, so they are pygame.Rects, like the gem and the crate in Gem Hunt.
basket = pygame.Rect(200, 330, 80, 16)Besides basket.x and basket.y, a Rect 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()
All lessons in The Game Loop
Practice on your own: Pygame playground