尝试编写一个 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/