Menu
CoddyTech

Acertar e reiniciar como métodos

Lição 39 de 41 do curso Crie jogos com Pygame da Coddy.

Mais duas tarefas pertencem à bola: rebater em uma raquete e voltar para o meio. Como métodos, o loop principal apresenta as regras do jogo.

def reset(self):
    self.rect.center = (300, 200)
    self.vx = -self.vx

Os dois testes de colisão com as raquetes diferem apenas na direção em que a bola sai: para a direita ao sair da raquete esquerda, para a esquerda ao sair da raquete direita. Passe isso como um número, way, 1 ou -1, e um único método atende aos dois casos:

ball.hit(left, 1)
ball.hit(right, -1)

Dentro dele, self.vx = way * abs(self.vx) envia a bola nessa direção, independentemente de como ela estava se movendo, e o ângulo do arremesso permanece como estava.

challenge icon

Desafio

Difícil

Mova a colisão com a raquete e a redefinição para a classe Ball.

  1. Escreva hit(paddle, way): em uma colisão, self.vx = way * abs(self.vx) e o ângulo do arremesso.
  2. Escreva reset(): centralize em (300, 200) e inverta self.vx.
  3. No loop, chame ball.hit(left, 1), ball.hit(right, -1) e ball.reset() após cada ponto.

Pressione “Jogar”: o jogo continua funcionando da mesma forma. Depois, pressione “Verificar”.

Experimente você mesmo

import pygame


class Ball:
    def __init__(self):
        self.rect = pygame.Rect(293, 193, 14, 14)
        self.vx = 5
        self.vy = 4

    def move(self):
        self.rect.x += self.vx
        self.rect.y += self.vy
        if self.rect.top <= 0 or self.rect.bottom >= 400:
            self.vy = -self.vy

    def draw(self, surface):
        pygame.draw.rect(surface, (255, 196, 0), self.rect)


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

ball = Ball()
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
waiting = False
winner = None

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            if winner is None:
                waiting = 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())

    if not waiting:
        ball.move()
        if ball.rect.colliderect(left):
            ball.vx = abs(ball.vx)
            ball.vy = (ball.rect.centery - left.centery) // 6
        if ball.rect.colliderect(right):
            ball.vx = -abs(ball.vx)
            ball.vy = (ball.rect.centery - right.centery) // 6
        if ball.rect.left > 600:
            left_score += 1
            ball.rect.center = (300, 200)
            ball.vx = -ball.vx
            waiting = True
        if ball.rect.right < 0:
            right_score += 1
            ball.rect.center = (300, 200)
            ball.vx = -ball.vx
            waiting = True
        if left_score == 5:
            winner = "Left player wins!"
        elif right_score == 5:
            winner = "Right player wins!"

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), left)
    pygame.draw.rect(screen, (235, 80, 80), right)
    ball.draw(screen)
    score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
    screen.blit(score, score.get_rect(center=(300, 30)))
    if winner is not None:
        message = font.render(winner, True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(300, 120)))
    elif waiting:
        message = font.render("Press Space to serve", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(300, 360)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Crie jogos com Pygame

Pratique por conta própria: Playground de Pygame