Pygame文本换行符

问题描述 投票:1回答:1

我正在编写用pygame,维基百科搜索程序的代码

这是我的代码的一部分

display = pygame.display.set_mode((420, 990))

sem = pygame.font.Font("fonts.ttf", 30)

def write(msg, color, x, y):
    surface = sem.render(msg, True, color)
    display.blit(surface, (x,y))

然后,我可以渲染文字。然后,在维基百科中输入我想要获取信息的单词(代码跳过):并在维基百科中获取信息(下一行)结果= wikipedia.summary(search,sentences = 2)

但如果我写长句,结果是这样的:enter image description here

这句话被削减了。所以,我想要这样的结果:

以前

Stack Overflow是一个私营网站,fl

期望的结果

Stack Overflow是一个私人拥有的网站,流程(句子继续)

我如何在pygame中打破? (但我不知道句子长度

python text pygame
1个回答
1
投票

这是一个运行的例子(使用word_wrap函数from the documentation):

import pygame
import pygame.freetype
pygame.init()

screen = pygame.display.set_mode((100, 200))
running = True

def word_wrap(surf, text, font, color=(0, 0, 0)):
    font.origin = True
    words = text.split(' ')
    width, height = surf.get_size()
    line_spacing = font.get_sized_height() + 2
    x, y = 0, line_spacing
    space = font.get_rect(' ')
    for word in words:
        bounds = font.get_rect(word)
        if x + bounds.width + bounds.x >= width:
            x, y = 0, y + line_spacing
        if x + bounds.width + bounds.x >= width:
            raise ValueError("word too wide for the surface")
        if y + bounds.height - bounds.y >= height:
            raise ValueError("text to long for the surface")
        font.render_to(surf, (x, y), None, color)
        x += bounds.width + space.width
    return x, y

font = pygame.freetype.SysFont('Arial', 20)

while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
    screen.fill((255, 255, 255))
    word_wrap(screen, 'Hey, this is a very long text! Maybe it is too long... We need more than one line!', font)
    pygame.display.update()

结果:

result

注意这段代码如何使用pygame.freetype模块而不是pygame.font,因为它提供了Font.render_toFont.get_rect等不错的功能。

© www.soinside.com 2019 - 2024. All rights reserved.