일시 정지
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 32개 중 30번째.
키보드를 읽는 방법에는 두 가지가 있습니다. pygame.key.get_pressed()는 매 프레임마다 지금 눌려 있는 키를 알려 줍니다. 이동에는 이 방법이 적합합니다. KEYDOWN 이벤트는 키를 누른 프레임에 한 번 발생하며, 클릭할 때 MOUSEBUTTONDOWN이 발생하는 것과 같습니다. 한 번 누를 때 한 번만 일어나는 동작에는 이 방법이 적합합니다.
일시 정지는 한 번 누를 때 한 번만 일어나는 동작입니다. get_pressed를 사용하면 P를 잠시 누르는 동안 매 프레임마다 일시 정지가 켜졌다 꺼집니다. 이벤트를 사용하면 한 번만 전환됩니다.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
paused = not pausednot paused는 True를 False로, 다시 그 반대로 바꿉니다. 게임이 실행되는 조건에 일시 정지를 추가하고, 일시 정지 상태일 때 Paused를 표시하세요.
챌린지
중급- 루프 전에
paused = False로 설정합니다. - 이벤트 루프에서 KEYDOWN 이벤트의 키가
pygame.K_p이면paused를 반전합니다. - 일시 정지 상태가 아닐 때만 게임을 실행합니다:
if lives > 0 and score < 10 and not paused:. paused가 참이면(240, 160)을 중심으로Paused를 표시합니다.
직접 해보기
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
lives = 3
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if lives > 0 and score < 10:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
basket.x -= 8
if keys[pygame.K_RIGHT]:
basket.x += 8
basket.clamp_ip(screen.get_rect())
block.y += 3
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)
score += 1
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
screen.blit(lives_text, (370, 10))
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
elif score == 10:
message = font.render("You win!", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
게임 루프의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드