5점 먼저 얻기
Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 37번째.
먼저 5점을 얻는 플레이어가 승리합니다. 아직 아무도 승리하지 않은 상태를 나타내는 Python의 값인 None으로 시작하는 변수에 승자의 이름을 저장하세요:
winner = None
if left_score == 5:
winner = "Left player wins!"
elif right_score == 5:
winner = "Right player wins!"winner is None 또는 winner is not None으로 테스트하세요. 누군가 승리한 뒤에는 공이 계속 대기합니다. winner is None일 때만 Space 키로 서브할 수 있습니다.
서브 메시지 대신 승자를 (300, 120) 위치에 가운데 정렬하여 표시하세요.
챌린지
중급- 반복문 전에
winner = None으로 설정합니다. - 득점 처리 후,
left_score == 5이면winner를"Left player wins!"로 설정하고,right_score == 5이면"Right player wins!"로 설정합니다. winner is None일 때만 스페이스 키로 서브할 수 있습니다.- 승자가 있으면
Press Space to serve대신(300, 120)위치의 가운데에 승자를 표시합니다.
직접 해보기
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)
vy = (ball.centery - left.centery) // 6
if ball.colliderect(right):
vx = -abs(vx)
vy = (ball.centery - right.centery) // 6
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으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드