在pygame中使用多行渲染文本

Dan*_*lia 8 python pygame render

我正在尝试制作游戏,我正在尝试渲染大量文本.当文本呈现时,文本的其余部分离开屏幕.有没有简单的方法让文本转到pygame窗口的下一行?

helpT = sys_font.render \
                ("This game is a combination of all of the trends\n of 2016. When you press 'Start Game,' a menu will pop up. In order to beat the game, you must get a perfect score on every single one of these games.",0,(hecolor))
        screen.blit(helpT,(0, 0))
Run Code Online (Sandbox Code Playgroud)

Ted*_*man 8

正如我在评论中所说; 你必须分别渲染每个单词并计算文本的宽度是否扩展了表面(或屏幕)的宽度.这是一个例子:

import pygame
pygame.init()


SIZE = WIDTH, HEIGHT = (1024, 720)
FPS = 30
screen = pygame.display.set_mode(SIZE, pygame.RESIZABLE)
clock = pygame.time.Clock()


def blit_text(surface, text, pos, font, color=pygame.Color('black')):
    words = [word.split(' ') for word in text.splitlines()]  # 2D array where each row is a list of words.
    space = font.size(' ')[0]  # The width of a space.
    max_width, max_height = surface.get_size()
    x, y = pos
    for line in words:
        for word in line:
            word_surface = font.render(word, 0, color)
            word_width, word_height = word_surface.get_size()
            if x + word_width >= max_width:
                x = pos[0]  # Reset the x.
                y += word_height  # Start on new row.
            surface.blit(word_surface, (x, y))
            x += word_width + space
        x = pos[0]  # Reset the x.
        y += word_height  # Start on new row.


text = "This is a really long sentence with a couple of breaks.\nSometimes it will break even if there isn't a break " \
       "in the sentence, but that's because the text is too long to fit the screen.\nIt can look strange sometimes.\n" \
       "This function doesn't check if the text is too high to fit on the height of the surface though, so sometimes " \
       "text will disappear underneath the surface"
font = pygame.font.SysFont('Arial', 64)

while True:

    dt = clock.tick(FPS) / 1000

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

    screen.fill(pygame.Color('white'))
    blit_text(screen, text, (20, 20), font)
    pygame.display.update()
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述


小智 5

在 pygame 中没有简单的方法在多行上渲染文本,但是这个辅助函数可以为您提供一些用处。只需传入您的文本(带换行符)、x、y 和字体大小。

def render_multi_line(text, x, y, fsize)
        lines = text.splitlines()
        for i, l in enumerate(lines):
            screen.blit(sys_font.render(l, 0, hecolor), (x, y + fsize*i))
Run Code Online (Sandbox Code Playgroud)

  • 字体大小与字符高度不同。[除了渲染字体之外,没有标准的方法可以确定某个字符在任何给定大小下的高度。](http://stackoverflow.com/a/3496463/6486738) 此外,`sys_font` 和 `hecolor ` 在您的函数中未定义。我建议传递一个字体对象而不是字体大小,然后设置`text_height = font.size(lines[0])[1]`。这将允许您执行 `screen.blit(font.render(l, 0, color), (x, y + text_height*i))`。您还需要一个用于“颜色”的参数。 (2认同)
  • 您可以使用 [font.get_linesize()](https://www.pygame.org/docs/ref/font.html#pygame.font.Font.get_linesize) 来获取字体的行高。 (2认同)