我想让你更喜欢游戏,我想不要对W.Y.R进行角色限制。的问题。我在Stack Overflow和其他网站上看过很多例子,但他们使用的其他模块和方法我不懂如何使用或想要使用。所以我宁愿使用
button_text_font = pygame.font.Font(font_location, 20)
red_button_text = button_text_font.render(red_text, True, bg_color)
blue_button_text = button_text_font.render(blue_text, True, bg_color)
我想知道如何使用这种方法,例如,以某种方式输入文本在包装到下一行之前可以走多远。
由于
P.S。如果可以,请同时包括居中文本等。
答案 0 :(得分:3)
这是根据我写的一些非常古老的代码改编的:
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
基本算法是将文本拆分为单词,并逐字逐句地逐行构建行,并在超出宽度时分割为新行。
正如您可以查询渲染文本的宽度,您可以找出将其渲染到中心的位置。