서브하기
Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 33개 중 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) 위치에 표시하세요.
챌린지
중급각 점수가 난 뒤 서브를 기다리세요.
- 루프 전에
waiting = False로 설정하세요. - 공의 이동, 튕김, 점수 처리를
if not waiting:아래에 두고, 점수가 날 때마다waiting = True로 설정하세요. pygame.K_SPACE의 KEYDOWN 이벤트가 발생하면waiting = False로 설정하세요. 기다리는 동안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 플레이그라운드