Menu
CoddyTech

각도 조절 샷

Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 36번째.

Pong에서는 공이 패들 어디에 맞는지에 따라 공이 향하는 방향이 달라집니다. 패들 위쪽 끝에 가까이 맞으면 위로 날아가고, 아래쪽 끝에 가까이 맞으면 아래로 날아가며, 가운데에 맞으면 곧장 가로질러 갑니다.

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

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

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

이렇게 하면 Pong은 실력으로 겨루는 게임이 됩니다. 패들로 공의 방향을 조준합니다.

challenge icon

챌린지

어려움

두 패들과의 충돌 모두에서 vx를 설정한 후, vy를 공의 중앙에서 해당 패들의 중앙을 뺀 값에 //를 사용해 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()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Pygame으로 게임 만들기의 모든 레슨

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