Menu
CoddyTech

파일에서 불러온 폰트

Coddy Pygame 여정의 게임 규칙 섹션에 포함된 레슨. 29개 중 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가 발생합니다.

각 글꼴은 지정된 크기로 그려집니다. pixel.ttf를 24로 설정하면 내장 글꼴을 32로 설정했을 때와 높이가 거의 같으므로, 눈으로 비교하고 조정하세요.

challenge icon

챌린지

쉬움
  1. font를 assets/fonts/pixel.ttf 파일의 크기 24로 설정합니다.
  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 플레이그라운드