游戏文本行B

2024-04-26 05:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pygame,wikipedia编写搜索程序的代码

这是我密码的一部分

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))

然后,我可以渲染文本。 接下来,输入我想在维基百科中获得的信息(代码跳过): 在维基百科中获取信息(下一行) 结果=维基百科摘要(搜索,句子=2)

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

这个句子被删节了。 所以,我想要这样的结果:

上一个

Stack Overflow是一个私人拥有的网站,fl

期望结果

Stack Overflow是一个私有网站 流(句子继续)

我怎么能在pygame中换行? (但我不知道句子的长度


Tags: 代码程序密码stack网站displaymsgwikipedia
1条回答
网友
1楼 · 发布于 2024-04-26 05:36:19

下面是一个运行示例(使用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,因为它提供了^{}和{a4}这样的好函数。在

相关问题 更多 >