Menu
CoddyTech

Sempre più veloce

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

Un gioco diventa più difficile man mano che si procede. Qui i blocchi cadono un po' più velocemente ogni 10 secondi.

pygame.time.set_timer(event_type, ms) genera un evento di quel tipo ogni ms millisecondi. Crea un tuo tipo di evento con pygame.USEREVENT, che è un numero che pygame lascia libero per te:

SPEED_UP = pygame.USEREVENT + 1
pygame.time.set_timer(SPEED_UP, 10000)
fall_speed = 3

for event in pygame.event.get():
    if event.type == SPEED_UP:
        fall_speed += 1

L'evento arriva nel ciclo degli eventi insieme agli altri, una volta ogni 10 secondi. A quel punto il blocco cade con block.y += fall_speed invece che con un valore fisso di 3. Una nuova partita ricomincia lentamente, quindi il riavvio imposta anche fall_speed = 3.

challenge icon

Sfida

Medio

Fai cadere i blocchi più velocemente ogni 10 secondi.

  1. Sotto il carattere, crea SPEED_UP = pygame.USEREVENT + 1 e avvia un timer per questo evento ogni 10000 ms.
  2. Imposta fall_speed = 3 prima del ciclo e usalo per la caduta.
  3. Aggiungi 1 a fall_speed a ogni evento SPEED_UP e reimpostalo a 3 quando R avvia una nuova partita.

Premi «Gioca» e aspetta 10 secondi: i blocchi cadono più velocemente. Poi premi «Verifica».

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
paused = False

running = True
while running:
    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 paused
            elif event.key == pygame.K_r and (lives == 0 or score == 10):
                score = 0
                lives = 3
                basket.x = 200
                block.y = -20
                block.x = random.randint(0, 460)

    if lives > 0 and score < 10 and not paused:
        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)))
    if lives == 0 or score == 10:
        again = font.render("Press R to play again", True, (240, 240, 240))
        screen.blit(again, again.get_rect(center=(240, 200)))
    if paused:
        message = font.render("Paused", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Il game loop

Esercitati da solo: Playground Pygame