Menu
CoddyTech

Vinci o perdi

Fa parte della sezione Il game loop del percorso Pygame di Coddy. Lezione 29 di 32.

La partita finisce. Qui perdi quando le vite arrivano a 0 e vinci quando il punteggio arriva a 10. Finché non si verifica nessuna delle due cose, la partita è in corso.

Metti tutto ciò che si muove sotto un'unica condizione, così si ferma quando la partita finisce:

if lives > 0 and score < 10:
    # tasti, il cestino, il blocco, prese e mancate prese

Il disegno rimane fuori da quell'if: lo schermo continua a mostrare l'ultimo fotogramma, e sopra di esso il risultato.

if lives == 0:
    message = font.render("Game over", True, (240, 240, 240))
    screen.blit(message, message.get_rect(center=(240, 160)))

message.get_rect(center=(240, 160)) è il Rect dell'immagine del testo, posizionata con il centro in (240, 160). Il blit in un Rect usa il suo angolo in alto a sinistra, quindi il testo è centrato.

challenge icon

Sfida

Medio
  1. Indenta tutto ciò che si muove (i tasti, il cesto, il blocco, le prese e i mancati) all'interno di if lives > 0 and score < 10:.
  2. Dopo aver disegnato il punteggio e le vite, mostra Game over quando lives == 0, oppure You win! quando score == 10, centrato in (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

    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))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Tutte le lezioni di Il game loop

Esercitati da solo: Playground Pygame