Menu
CoddyTech

초기화 함수

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

게임을 하고, 몇 점을 얻고, 패배한 뒤 R을 누릅니다. 새 게임이 이전 점수로 시작됩니다. 게임 중에 바뀌는 모든 값은 시작 상태로 되돌려야 하지만, 하나를 빠뜨리는 경우가 종종 있습니다.

모든 시작 값을 하나의 함수에 넣고 첫 게임을 시작하기 전과 R을 눌렀을 때 모두 호출하세요.

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


reset()

global 행이 중요합니다. 함수 안에서 값을 할당한 변수는 달리 지정하지 않는 한 해당 함수에 속합니다. global이 없으면 score = 0은 함수가 끝날 때 사라지는 새로운 지역 변수 score를 만들고, 게임 점수는 바뀌지 않습니다.

이제 게임의 시작 부분을 한 번만 작성하면 됩니다. 나중에 목숨처럼 값을 추가할 때 한 곳에 추가하면 첫 게임과 모든 새 게임에 적용됩니다.

challenge icon

챌린지

중급
  1. global player, rock, score를 첫 줄로 사용하여 player, rock, score를 시작 값으로 설정하는 reset()을 작성하세요.
  2. 이들을 설정하는 세 줄 대신, 반복문 전에 reset()을 한 번 호출하세요.
  3. R 키를 누르면 reset()을 호출하고 상태를 "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 event.key == pygame.K_r and state == "over":
                player.x = 220
                rock.y = -24
                rock.x = random.randint(0, 456)
                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)))
            hint = font.render("Press R to play again", True, (240, 240, 240))
            screen.blit(hint, hint.get_rect(center=(240, 200)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon실력 점검

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

게임 규칙의 모든 레슨

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