일시 정지
Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 16번째.
키보드를 읽는 방법은 두 가지입니다. pygame.key.get_pressed()는 매 프레임마다 현재 눌려 있는 키를 알려 줍니다. 오른쪽 이동처럼 계속 움직이는 동작에 적합합니다. KEYDOWN 이벤트는 키를 누른 프레임에 한 번 발생합니다. 키를 누를 때 한 번만 실행되는 동작에 적합합니다.
일시 정지는 키를 누를 때 한 번만 실행되는 동작입니다. 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가 참이면Paused를(240, 160)의 중앙에 표시합니다.
직접 해보기
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으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드