Python 如何使用pygame.font.font()在pygame中包装文本?

Python 如何使用pygame.font.font()在pygame中包装文本?,python,fonts,formatting,pygame,Python,Fonts,Formatting,Pygame,我正在做一个“你愿意吗”的游戏,我不想对W.Y.R.问题有性格限制。我在Stack Overflow和其他网站上看到了很多例子,但它们使用了其他模块和方法,我不知道如何使用或想要使用。所以我宁愿使用 button\u text\u font=pygame.font.font(字体位置,20) 红色按钮文本=按钮文本字体。渲染(红色按钮文本,真,背景颜色) 蓝色按钮文本=按钮文本字体。渲染(蓝色按钮文本,真,背景颜色) 我想知道如何使用这个方法,例如,以某种方式输入文本可以走多远,直到它换行到下

我正在做一个“你愿意吗”的游戏,我不想对W.Y.R.问题有性格限制。我在Stack Overflow和其他网站上看到了很多例子,但它们使用了其他模块和方法,我不知道如何使用或想要使用。所以我宁愿使用

button\u text\u font=pygame.font.font(字体位置,20)
红色按钮文本=按钮文本字体。渲染(红色按钮文本,真,背景颜色)
蓝色按钮文本=按钮文本字体。渲染(蓝色按钮文本,真,背景颜色)
我想知道如何使用这个方法,例如,以某种方式输入文本可以走多远,直到它换行到下一行

谢谢


另外,如果可以的话,还请包括居中文本等。

这是根据我写的一些非常古老的代码改编的:

def renderTextCenteredAt(text, font, colour, x, y, screen, allowed_width):
    # first, split the text into words
    words = text.split()

    # now, construct lines out of these words
    lines = []
    while len(words) > 0:
        # get as many words as will fit within allowed_width
        line_words = []
        while len(words) > 0:
            line_words.append(words.pop(0))
            fw, fh = font.size(' '.join(line_words + words[:1]))
            if fw > allowed_width:
                break

        # add a line consisting of those words
        line = ' '.join(line_words)
        lines.append(line)

    # now we've split our text into lines that fit into the width, actually
    # render them

    # we'll render each line below the last, so we need to keep track of
    # the culmative height of the lines we've rendered so far
    y_offset = 0
    for line in lines:
        fw, fh = font.size(line)

        # (tx, ty) is the top-left of the font surface
        tx = x - fw / 2
        ty = y + y_offset

        font_surface = font.render(line, True, colour)
        screen.blit(font_surface, (tx, ty))

        y_offset += fh
基本算法是将文本拆分为单词,逐字迭代地构建行,每次检查生成的宽度,并在超出宽度时拆分为新行


当您可以查询渲染文本的宽度时,您可以确定在何处渲染文本以使其居中。

我仍然有点困惑。这个算法看起来很方便,但是你能添加注释来描述每一行吗,因为我不知道如何将它融入到我的游戏中。重新编写(现在实际测试:)作为一个带有注释和(稍微)更好的变量命名的函数。谢谢!你帮了大忙!