python - pygame 中的文本格式为段落?

标签 python text pygame

尝试编写一个 pygame 程序,但我似乎无法弄清楚如何让 pygame 在没有第三方模块的情况下将文本格式化为段落。例如我想要:

"Hello World, how are you doing today? I'm fine actually, thank you."

更多的是:

"Hello World, how are
 you doing today? I'm
fine actually, thank you."

这是我的代码:

def instructions(text):
    pressKey, pressRect = makeText('Last Block is a survival game. Every ten lines that you clear will shorten the screen, clear as many lines as possible before you run out of space!', smallFont, bgColor)
    pressRect.center = (int(windowWidth/ 2), int(windowHeight / 2) + 100)
    displaySurf.blit(pressKey, pressRect)
    while press() == None:
        pygame.display.update()

makeText函数:

def makeText(text, font, color):
    surf = font.render(text, True, color)
    return surf, surf.get_rect()

这样 pygame 就可以将长行文本分成每个包含 x 个单词的部分,并将其格式化为看起来有点像一个段落。现在,我正在使用大量的表面对象和位 block 传输来使其看起来像这样,这似乎很乏味。还有其他方法可以达到这个效果吗?

最佳答案

如果我理解正确的话,您需要一些代码来显示多行段落中的文本。如果是这样,我在这里使用了代码:http://www.pygame.org/pcr/text_rect/index.php

不需要任何额外的模块。该方法采用以下参数:

def render_textrect(string, font, rect, text_color, background_color, justification=0):
    """Returns a surface containing the passed text string, reformatted
    to fit within the given rect, word-wrapping as necessary. The text
    will be anti-aliased.

    Takes the following arguments:

    string - the text you wish to render. \n begins a new line.
    font - a Font object
    rect - a rectstyle giving the size of the surface requested.
    text_color - a three-byte tuple of the rgb value of the
                 text color. ex (0, 0, 0) = BLACK
    background_color - a three-byte tuple of the rgb value of the surface.
    justification - 0 (default) left-justified
                    1 horizontally centered
                    2 right-justified

    Returns the following values:

    Success - a surface object with the text rendered onto it.
    Failure - raises a TextRectException if the text won't fit onto the surface.
    """

抱歉再次发帖 - 错误地点击了社区 wiki。

关于python - pygame 中的文本格式为段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23858489/

相关文章:

python - Odoo 10 - 验证合作伙伴的电子邮件

python - 查找并计算网络中孤立和半孤立节点的数量

c++ - 如何在 C++ 中读取和解析 CSV 文件?

css - 如何删除CSS中文本的空白?

python - 打印到 UTF-8 编码文件,使用平台相关的换行符?

python - Pygame 教程 - 带碰撞检测的坦克

android - 使用 Python/Kivy 的简单条形码扫描器,适用于 Android 设备

python - selenium 不能在 url 中使用 &

python - 为什么我的 pygame 屏幕没有正确更新?

python - 随机砖颜色 -> TypeError : 'pygame.Color' object is not callable