Menu
CoddyTech

상태마다 함수 하나씩

Coddy Pygame 여정의 게임 규칙 섹션에 포함된 레슨. 29개 중 5번째.

루프에서 세 화면을 섞어 처리하면, 상태가 추가될 때마다 그리기와 업데이트 코드 안에 if가 한 겹씩 더 생깁니다. 스타터 코드는 대신 각 상태에 자체 함수를 제공하고, 루프에서 그중 하나를 선택합니다:

if state == "menu":
    draw_menu()
elif state == "play":
    play_frame()
else:
    draw_over()

play_frame()은 요소를 움직이고, 충돌을 확인하고, 그립니다. draw_menu()와 draw_over()는 그리기만 합니다. 게임 오버 화면은 메시지 아래에 정지된 게임 화면을 보여 주므로, 두 화면 모두 플레이어, 바위, 점수를 그릴 때 공통으로 draw_game()을 사용합니다.

상태나 점수를 바꾸는 함수에서는 global 뒤에 해당 변수를 지정해야 합니다:

def play_frame():
    global score, state

player.x를 이동할 때는 global이 필요하지 않습니다. 새 Rect를 대입하는 것이 아니라 Rect를 변경하기 때문입니다.

이 구조에서는 새 상태를 함수 하나와 elif 하나로 추가할 수 있습니다. 같은 방식으로 일시 정지 화면을 추가해 보세요.

challenge icon

챌린지

중급
  1. "paused" 상태를 추가하세요. 플레이 중 P를 누르면 일시 정지되고, P를 다시 누르면 플레이로 돌아갑니다.
  2. draw_paused()를 작성하세요. 멈춘 게임 화면의 (240, 160) 위치에 Paused를 가운데 정렬해 표시합니다.
  3. 상태가 "paused"일 때 루프에서 함수를 호출하도록 elif를 하나 더 추가하세요.

직접 해보기

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
WHITE = (240, 240, 240)


def reset():
    global player, rock, score
    player = pygame.Rect(220, 300, 40, 40)
    rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
    score = 0


def draw_menu():
    screen.fill((30, 30, 46))
    title = font.render("Meteor Dodge", True, WHITE)
    screen.blit(title, title.get_rect(center=(240, 140)))
    hint = font.render("Press Enter to play", True, WHITE)
    screen.blit(hint, hint.get_rect(center=(240, 200)))


def draw_game():
    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), player)
    pygame.draw.rect(screen, (235, 80, 80), rock)
    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))


def play_frame():
    global score, state
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.x -= 6
    if keys[pygame.K_RIGHT]:
        player.x += 6
    player.clamp_ip(screen.get_rect())

    rock.y += 4
    if rock.top > 360:
        rock.y = -24
        rock.x = random.randint(0, 456)
        score += 1
    if rock.colliderect(player):
        state = "over"
    draw_game()


def draw_over():
    draw_game()
    message = font.render("Game over", True, WHITE)
    screen.blit(message, message.get_rect(center=(240, 160)))
    hint = font.render("Press R to play again", True, WHITE)
    screen.blit(hint, hint.get_rect(center=(240, 200)))


reset()
state = "menu"

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN and state == "menu":
                state = "play"
            elif event.key == pygame.K_r and state == "over":
                reset()
                state = "play"

    if state == "menu":
        draw_menu()
    elif state == "play":
        play_frame()
    else:
        draw_over()
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

게임 규칙의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드