Menu
CoddyTech

R 키를 눌러 다시 플레이하기

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

게임이 끝나면 플레이어는 프로그램을 다시 시작하지 않고 한 번 더 플레이하고 싶어 합니다. 게임 오버 화면에 한 줄을 추가하고 새 게임을 시작하는 키를 지정하세요:

if event.key == pygame.K_r and state == "over":
    player.x = 220
    rock.y = -24
    rock.x = random.randint(0, 456)
    state = "play"

상태를 다시 "play"로 설정하는 것만으로는 충분하지 않습니다. 바위가 여전히 플레이어에 닿아 있으므로 다음 프레임에서 게임이 다시 끝납니다. 새 게임이 시작될 때의 위치로 움직였던 요소들을 되돌려 놓으세요.

이것은 메뉴와 같은 패턴입니다. 키 입력, 현재 상태 확인, 새로운 상태입니다.

challenge icon

챌린지

쉬움
  1. 게임 오버 화면에서 Game over 아래에 Press R to play again을 (240, 200)에 가운데 정렬해 표시하세요.
  2. R을 눌렀을 때 상태가 "over"이면 플레이어를 x 220으로 되돌리고, 바위를 y -24로 되돌리면서 x는 0부터 456 사이의 무작위 값으로 설정한 다음, 상태를 "play"로 설정하세요.

직접 해보기

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)

player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
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"

    if state == "play":
        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"

    screen.fill((30, 30, 46))
    if state == "menu":
        title = font.render("Meteor Dodge", True, (240, 240, 240))
        screen.blit(title, title.get_rect(center=(240, 140)))
        hint = font.render("Press Enter to play", True, (240, 240, 240))
        screen.blit(hint, hint.get_rect(center=(240, 200)))
    else:
        pygame.draw.rect(screen, (255, 196, 0), player)
        pygame.draw.rect(screen, (235, 80, 80), rock)
        score_text = font.render(f"Score: {score}", True, (240, 240, 240))
        screen.blit(score_text, (10, 10))
        if state == "over":
            message = font.render("Game over", True, (240, 240, 240))
            screen.blit(message, message.get_rect(center=(240, 160)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

게임 규칙의 모든 레슨

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