서브하기
Coddy의 Pygame으로 게임 만들기 코스 레슨. 41개 중 35번째.
득점한 뒤에는 플레이어가 준비될 때까지 공이 중앙에서 기다려야 합니다. 플래그는 공이 기다리는지 여부를 나타냅니다.
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으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드