详解Pygame 在窗口中显示文本

  • Post category:Python

Pygame 是一款广泛使用的 Python 游戏开发库,提供了一系列的功能,包括图形、音频、输入设备处理以及文本显示等。在 Pygame 中,可以通过 Pygame 的内置渲染文本功能实现在游戏窗口中显示文本。

一、Pygame 中渲染文本的方法

Pygame 提供了 pygame.font.Font 类来创建字体对象,同时也可以使用默认字体创建字体对象。创建字体对象之后,可以通过 Font.render() 方法进行渲染文本,从而生成一个 Surface 对象。

其中,Surface 对象既可以在窗口中显示,还可以使用 Pygame 的其他渲染功能进行绘制。

下面是 Pygame 中渲染文本的一般流程:

  1. 创建字体对象。当没有指定字体文件路径时,将使用默认字体。
import pygame
pygame.init()
font = pygame.font.Font(None, 36)  # 创建一个默认字体的 Font 对象,并设置字体大小为 36
  1. 使用字体对象的 render() 方法渲染文本。
text_surface = font.render("Hello, Pygame!", True, (255, 255, 255))  # 在窗口中显示的文本色调为白色

其中,render() 方法的第一个参数为要渲染的文本,第二个参数为是否抗锯齿(True 为开启抗锯齿,False 为关闭),第三个参数为文本颜色。

  1. 在窗口中显示渲染后的 Surface 对象。通过调用 pygame.display.blit() 方法可以将 Surface 上的内容渲染到窗口上。最后使用 pygame.display.update() 方法刷新窗口。
screen = pygame.display.set_mode((600, 400))  # 创建窗口对象
screen.fill((0, 0, 0))  # 填充背景色为黑色
screen.blit(text_surface, (50, 50))  # 将渲染的文本显示在窗口上
pygame.display.update()  # 刷新窗口

二、绘制包含变量的文本

由于渲染出来的文本是一个 Surface 对象,因此可以使用 + 运算符拼接字符串的方式来将变量包含在文本中:

score = 100
score_surface = font.render("Score: " + str(score), True, (255, 255, 255))

三、带有阴影效果的文本显示

我们可以创建两个 Surface 对象来实现文本阴影的效果,先绘制一个使用阴影色调的 Surface,再绘制一个文本使用的 Surface。将文本 Surface 坐标与阴影 Surface 坐标略微偏移即可:

text_surface = font.render("Hello, Pygame!", True, (255, 255, 255))  # 设置文本颜色为白色
shadow_surface = font.render("Hello, Pygame!", True, (50, 50, 50))  # 设置阴影色调为灰色,或者其他暗色调
x, y = 50, 50  # 设置文本渲染的位置
screen.blit(shadow_surface, (x+3, y+3))  # 绘制阴影效果,偏移阴影的坐标
screen.blit(text_surface, (x, y))  # 绘制正常文本

四、示例程序:Pygame 在窗口中显示文本

import pygame

pygame.init()

# 创建字体对象
font = pygame.font.Font(None, 36)

# 创建显示的文本 Surface 对象
text_surface = font.render("Hello, Pygame!", True, (255, 255, 255))

# 创建显示的分数 Surface 对象
score = 100
score_surface = font.render("Score: " + str(score), True, (255, 255, 255))

# 创建窗口对象
screen = pygame.display.set_mode((600, 400))
# 填充背景色为黑色
screen.fill((0, 0, 0))
# 将文本显示在窗口上
screen.blit(text_surface, (50, 50))
screen.blit(score_surface, (50, 100))
# 刷新窗口
pygame.display.update()

# 程序主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

上面的程序可以在 Pygame 窗口中显示带有阴影效果的文本和变量的文本。