Menu
CoddyTech

각도 샷

Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 33개 중 18번째.

Pong에서는 공이 패들에 맞는 위치에 따라 공이 향하는 방향이 결정됩니다. 패들의 위쪽 끝에 가까이 맞으면 위로 날아가고, 아래쪽 끝에 가까이 맞으면 아래로 날아가며, 가운데에 맞으면 곧장 가로질러 날아갑니다.

공의 중심과 패들의 중심 사이의 거리를 측정하고, 그 값을 새 vy로 설정합니다:

if ball.colliderect(right):
    vx = -abs(vx)
    vy = (ball.centery - right.centery) // 6

가운데보다 위쪽에서는 차이가 음수이므로 공이 위로 날아가고, 아래쪽에서는 양수입니다. 6으로 나누면 공이 너무 빨라지는 것을 막을 수 있습니다. 패들 끝에 맞으면 vy는 약 7이 됩니다.

이렇게 하면 Pong은 실력 게임이 됩니다. 패들로 공의 방향을 조절하세요.

challenge icon

챌린지

어려움

패들이 공을 원하는 방향으로 보내도록 하세요.

  1. 두 패들 충돌 처리 모두에서 vx를 설정한 다음, vy를 공의 중앙 좌표에서 해당 패들의 중앙 좌표를 뺀 값으로 설정하세요.
  2. 그 값을 //로 6으로 나누세요.

‘플레이’를 누르고 패들 끝으로 공을 맞혀 보세요. 공이 비스듬한 각도로 날아갑니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

import pygame

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 = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
waiting = False

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:
            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.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)
        if ball.left > 600:
            left_score += 1
            ball.center = (300, 200)
            vx = -vx
            waiting = True
        if ball.right < 0:
            right_score += 1
            ball.center = (300, 200)
            vx = -vx
            waiting = True

    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)
    score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
    screen.blit(score, score.get_rect(center=(300, 30)))
    if 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()

프로젝트의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드