Menu
CoddyTech

Torna al centro

Lezione 33 di 41 del corso Crea giochi con Pygame di Coddy.

Quando un giocatore manca la palla, questa esce dalla finestra dal suo lato. Riportala al centro e mandala verso l'altro lato.

if ball.right < 0 or ball.left > 600:
    ball.center = (300, 200)
    vx = -vx

ball.right < 0 significa che tutta la palla ha oltrepassato il bordo sinistro, mentre ball.left > 600 significa che tutta la palla ha oltrepassato il bordo destro. Impostare ball.center sposta il Rect in modo che il suo centro si trovi in quel punto; le sue dimensioni restano le stesse.

Qui vx = -vx è sicuro: la palla è al centro, lontana da qualsiasi racchetta.

challenge icon

Sfida

Facile

Riporta al centro una palla mancata.

  1. Quando tutta la palla supera il bordo sinistro o destro, imposta il suo center su (300, 200).
  2. Inverti anche vx lì.

Premi «Gioca» e manca la palla: torna indietro e si dirige dall’altra parte. Poi premi «Verifica».

Provalo tu

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()

ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)

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_w]:
        left.y -= 6
    if keys[pygame.K_s]:
        left.y += 6
    if keys[pygame.K_UP]:
        right.y -= 6
    if keys[pygame.K_DOWN]:
        right.y += 6
    left.clamp_ip(screen.get_rect())
    right.clamp_ip(screen.get_rect())

    ball.x += vx
    ball.y += vy
    if ball.top <= 0 or ball.bottom >= 400:
        vy = -vy
    if ball.colliderect(left):
        vx = abs(vx)
    if ball.colliderect(right):
        vx = -abs(vx)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), left)
    pygame.draw.rect(screen, (235, 80, 80), right)
    pygame.draw.rect(screen, (255, 196, 0), ball)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Tutte le lezioni di Crea giochi con Pygame

Esercitati da solo: Playground Pygame