Il cestino
Fa parte della sezione Il game loop del percorso Pygame di Coddy. Lezione 26 di 35.
Un nuovo gioco: i blocchi cadono dall’alto e tu li prendi in un cestino. Il cestino e i blocchi sono rettangoli, quindi sono pygame.Rect, come la gemma e la cassa in Gem Hunt.
basket = pygame.Rect(200, 330, 80, 16)Oltre a basket.x e basket.y, un Rect conosce i suoi bordi: basket.left, basket.right, basket.top, basket.bottom e il suo centro, basket.centerx.
Passa il Rect direttamente a pygame.draw.rect(screen, color, basket). E può mantenersi all’interno di un altro Rect: basket.clamp_ip(screen.get_rect()) lo sposta nuovamente all’interno della finestra quando supera un bordo. screen.get_rect() è il Rect della finestra stessa.
Sfida
FacileCrea il cestino per Catch the Blocks.
- Prima del ciclo, crea
basket = pygame.Rect(200, 330, 80, 16). - Prima del riempimento, spostalo di 8 pixel per fotogramma mentre tieni premuto Sinistra o Destra, poi
basket.clamp_ip(screen.get_rect()). - Dopo il riempimento, disegnalo in blu
(80, 160, 255).
Premi «Gioca» e tieni premuto Sinistra o Destra: il cestino si ferma ai bordi. Poi premi «Verifica».
Provalo tu
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()
Tutte le lezioni di Il game loop
Esercitati da solo: Playground Pygame