스카이 러너 메뉴
Coddy Pygame 여정의 게임 규칙 섹션에 포함된 레슨. 30개 중 29번째.
Sky Runner는 이 섹션에서 규칙을 가져오며, 메뉴부터 시작합니다. 새 게임은 모든 것을 시작 상태로 되돌려야 하므로 reset()에 새 러너, 비어 있는 그룹, 속도와 점수, 그리고 다시 시작되는 두 타이머를 설정하세요.
이제 스페이스 키는 상태별로 하나씩 두 가지 역할을 합니다.
if state == "play":
runner.jump()
elif state == "menu":
reset()
state = "play"메뉴에는 가운데 정렬된 두 줄이 필요하고 게임 오버 화면에는 세 줄이 필요하므로, 작은 함수를 만들어 x 320을 기준으로 한 줄을 가운데 정렬해 그립니다.
def show(text, text_font, y):
picture = text_font.render(text, True, INK)
screen.blit(picture, picture.get_rect(center=(320, y)))점수는 게임에 속하므로 게임이 시작된 뒤에만 표시하고, 메뉴에는 표시하지 마세요.
챌린지
중급Sky Runner에 메뉴를 추가하세요.
- 러너, 그룹,
speed,score와 두 타이머를 위한reset()을 작성하세요. 루프 전에 호출하고state = "menu"로 설정하세요. - 메뉴에서
big_font로Sky Runner와Press Space to start를 표시하는 데show()를 사용하세요. 메뉴가 아닐 때만 점수를 표시하세요. - 메뉴에서 스페이스 키를 누르면
reset()을 호출하고state = "play"로 설정하세요.
‘플레이’를 누르세요. 스페이스 키를 누르면 실행이 시작됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 320))
pygame.display.set_caption("Sky Runner")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 32)
SKY = (140, 200, 240)
GROUND = (90, 160, 80)
GROUND_Y = 260
GRAVITY = 1
SPAWN = pygame.USEREVENT + 1
POINT = pygame.USEREVENT + 2
class Runner(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.frames = [
pygame.image.load("assets/images/player.png").convert_alpha(),
pygame.image.load("assets/images/player_walk.png").convert_alpha(),
]
self.image = self.frames[0]
self.step = 0
self.rect = self.image.get_rect(midbottom=(100, GROUND_Y))
self.vy = 0
def jump(self):
if self.rect.bottom == GROUND_Y:
self.vy = -16
def update(self):
self.vy += GRAVITY
self.rect.y += self.vy
if self.rect.bottom >= GROUND_Y:
self.rect.bottom = GROUND_Y
self.vy = 0
if self.rect.bottom == GROUND_Y:
self.step += 1
self.image = self.frames[self.step // 8 % 2]
else:
self.image = self.frames[1]
class Obstacle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = random.choice(obstacle_images)
self.rect = self.image.get_rect(midbottom=(664, GROUND_Y))
def update(self):
self.rect.x -= speed
if self.rect.right < 0:
self.kill()
obstacle_images = [
pygame.image.load("assets/images/spike_ball.png").convert_alpha(),
pygame.image.load("assets/images/blob.png").convert_alpha(),
]
runner = Runner()
obstacles = pygame.sprite.Group()
speed = 6
pygame.time.set_timer(SPAWN, 1500)
pygame.time.set_timer(POINT, 100)
score = 0
state = "play"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
if state == "play":
runner.jump()
if event.type == SPAWN and state == "play":
obstacles.add(Obstacle())
pygame.time.set_timer(SPAWN, random.randint(1000, 2000))
if event.type == POINT and state == "play":
score += 1
if state == "play":
speed = min(14, 6 + score // 100)
runner.update()
obstacles.update()
if pygame.sprite.spritecollideany(runner, obstacles, pygame.sprite.collide_mask):
state = "over"
screen.fill(SKY)
pygame.draw.rect(screen, GROUND, (0, GROUND_Y, 640, 60))
screen.blit(runner.image, runner.rect)
obstacles.draw(screen)
score_text = font.render(f"{score:05}", True, (40, 50, 80))
screen.blit(score_text, score_text.get_rect(topright=(630, 10)))
if state == "over":
message = font.render("Game over", True, (40, 50, 80))
screen.blit(message, message.get_rect(center=(320, 140)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
게임 규칙의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드