Menu
CoddyTech

파일에서 불러온 폰트

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

pygame.font.Font(None, 32)은 pygame의 내장 글꼴을 사용합니다. 읽기 쉽지만, 이 글꼴을 사용하는 pygame 게임은 모두 똑같아 보입니다. 글꼴 파일을 사용하면 게임에 고유한 글자를 적용할 수 있습니다.

에셋 팩에는 assets/fonts/에 글꼴 파일이 네 개 있습니다. None 대신 파일 경로를 전달하세요.

font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
big_font = pygame.font.Font("assets/fonts/pixel.ttf", 48)

숫자는 픽셀 단위의 크기입니다. Font 객체 하나는 크기 하나만 가지므로, 제목과 점수를 서로 다른 크기로 표시하려면 객체 두 개가 필요합니다. 반복문을 시작하기 전에 한 번만 만드세요. 글꼴을 불러오면 파일을 읽는데, 매 프레임마다 하기에는 너무 느립니다.

경로는 main.py가 있는 폴더를 기준으로 합니다. 경로가 잘못되면 프로그램이 중단되고, 찾으려던 파일의 이름과 함께 FileNotFoundError가 표시됩니다.

각 글꼴은 지정한 크기로 그려집니다. 크기가 24인 pixel.ttf는 내장 글꼴 크기 32와 거의 같은 높이이므로, 눈으로 비교하며 조정하세요.

challenge icon

챌린지

쉬움

게임의 텍스트를 픽셀 글꼴로 그리세요.

  1. font를 크기 24의 파일 assets/fonts/pixel.ttf로 만드세요.
  2. 같은 파일을 크기 48로 사용하는 big_font를 추가하세요.
  3. big_font로 Meteor Dodge와 Game over를 그리세요.

‘플레이’를 누르세요. 제목이 큰 픽셀 글자로 표시됩니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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()

게임 규칙의 모든 레슨

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