Pausa
Lezione 16 di 40 del corso Crea giochi con Pygame di Coddy.
Esistono due modi per leggere la tastiera. pygame.key.get_pressed() indica quali tasti sono premuti in quel momento, a ogni fotogramma: è adatto al movimento. Un evento KEYDOWN arriva una sola volta, nel fotogramma in cui si preme il tasto: è adatto alle azioni che avvengono una sola volta per pressione.
Mettere in pausa è un'azione che avviene una sola volta per pressione. Con get_pressed, tenendo premuto P per un momento, la pausa si attiverebbe e disattiverebbe a ogni fotogramma. Con l'evento, invece, si attiva una sola volta:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
paused = not pausednot paused trasforma True in False e viceversa. Aggiungi la pausa alla condizione che esegue il gioco e mostra Paused mentre è attiva.
Sfida
Medio- Prima del ciclo, imposta
paused = False. - Nel ciclo degli eventi, inverti il valore di
pausedquando il tasto di un evento KEYDOWN èpygame.K_p. - Esegui il gioco solo quando non è in pausa:
if lives > 0 and score < 10 and not paused:. - Quando
pausedè true, mostraPausedal centro di(240, 160).
Provalo tu
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
lives = 3
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if lives > 0 and score < 10:
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)
lives -= 1
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)
score += 1
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
screen.blit(lives_text, (370, 10))
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
elif score == 10:
message = font.render("You win!", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Crea giochi con Pygame
Esercitati da solo: Playground Pygame