Menu
CoddyTech

서브

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

점수를 얻은 뒤에는 플레이어가 준비될 때까지 공이 가운데에서 기다려야 합니다. 공이 기다리는지 여부는 플래그로 나타냅니다:

waiting = False

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
    # 패들은 항상 움직인다
    if not waiting:
        # 공이 움직이고 튕기며 득점한다. 득점하면 waiting = True로 설정된다

패들은 if 바깥에 있으므로 공이 기다리는 동안 플레이어는 준비할 수 있습니다. 스페이스 키는 한 번 누를 때마다 한 번 동작하므로 KEYDOWN 이벤트에서 처리합니다.

공이 기다리는 동안 화면 아래쪽에 Press Space to serve를 (300, 360)을 중심으로 표시합니다.

challenge icon

챌린지

중급
  1. 루프 전에 waiting = False로 설정합니다.
  2. 공의 이동, 튕김, 점수 계산을 if not waiting: 아래에 두고, 각 점수를 얻은 후 waiting = True로 설정합니다.
  3. pygame.K_SPACE에 대한 KEYDOWN 이벤트는 waiting = False로 설정합니다.
  4. 대기하는 동안 Press Space to serve를 (300, 360)의 중앙에 표시합니다.

직접 해보기

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

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)
    if ball.left > 600:
        left_score += 1
        ball.center = (300, 200)
        vx = -vx
    if ball.right < 0:
        right_score += 1
        ball.center = (300, 200)
        vx = -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)
    score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
    screen.blit(score, score.get_rect(center=(300, 30)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

프로젝트의 모든 레슨

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