Menu
CoddyTech

从文件加载字体

本课属于 Coddy Pygame 学习旅程的“游戏规则”单元。第 6 课,共 30 课。

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 设置为文件 assets/fonts/pixel.ttf,字号为 24。
  2. 添加 big_font,使用同一个文件,字号为 48。
  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 在线编辑器