尝试编写一个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个单词的部分,并将其格式化为有点像段落。现在,我使用了许多表面物体和blits使它看起来像这样看似乏味。还有其他方法可以达到效果吗?
答案 0 :(得分:2)
如果我理解正确,您需要一些代码在多行段落中显示文本。如果是这样,我在这里使用了代码: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.
"""
很抱歉再次发帖 - 错误地点击了社区维基。
答案 1 :(得分:1)
听起来您正在寻找textwrap.fill
提供的功能:
from textwrap import fill
mystr = "Hello World, how are you doing today? I'm fine actually, thank you."
print(fill(mystr, 20))
print()
print(fill(mystr, 40))
print()
print(fill(mystr, 10))
输出:
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. Hello World, how are you doing today? I'm fine actually, thank you.
textwrap.fill
的第一个参数是您想要分解的字符串。第二个是行的最大长度(以字符为单位)。