下面显示的是我在pygame中为逐字母打印文本所做的一个函数。在离开屏幕边缘之前,它最多可以打印3行。出于某种原因,如果我打印相当于三行文本的内容,然后尝试打印一个字符,程序就会冻结并暂时停止运行。发生这种情况有原因吗?此外,如果在打印文本方面,我的功能可能无法容纳某些内容,我该如何改进此功能?
这是代码:
def print_text_topleft(string):
global text
letter = 0 # Index of string
text_section = 1 # used for while true loop
counter = 6 # frames to print a single letter
output_text = "" # First string of text
output_text2 = "" # second string of text
output_text3 = "" # third string of text
while text_section == 1:
temp_surface = pygame.Surface((WIDTH,HEIGHT)) # Creates a simple surface to draw the text onto
text = list(string) # turns the string into a list
if counter > 0: # Counter for when to print each letter
counter -= 1
else:
counter = 6 # Resets counter
if letter <= 41:
output_text += text[letter] # prints to first line
elif letter > 41:
if letter > 82:
output_text3 += text[letter] # prints to second
else:
output_text2 += text[letter] # prints to third
if letter == len(text) - 1: # End of string
time.sleep(2)
text_section = 0
else:
letter += 1
temp_surface.fill((0,0,0))
message, rect = gameFont.render(output_text, (255,255,255)) # Gamefont is a font with a size of 24
message2, rect2 = gameFont.render(output_text2, (255,255,255))
message3, rect3 = gameFont.render(output_text3, (255,255,255))
rect.topleft = (20,10)
rect2.topleft = (20,50)
rect3.topleft = (20,90)
temp_surface.blit(message,rect) # All strings are drawn to the screen
temp_surface.blit(message2,rect2)
temp_surface.blit(message3,rect3)
screen.blit(temp_surface, (0,0)) # The surface is drawn to the screen
pygame.display.flip() # and the screen is updated
下面是我穿过它的两个字符串:
print_text_topleft("Emo: Hello friend. My name is an anagram. I would be happy if the next lines would print. That would be cool! ")
print_text_topleft("Hi")
您正在进行大量的原始文本处理,这在某种程度上使用了所有最昂贵的Python函数
text = list(string) # O(n) + list init
if counter > 0: counter -=1 # due to the rest of the structure, you're now
# creating the above list 6 times! Why??
output_text += text[letter] # string concatenation is slow, and you're doing this
# n times (where n is len(string)). Also you're
# calling n list indexing operations, which while
# those are very fast, is still unnecessary.
time.sleep(2) # this will obviously freeze your app for 2s
为什么不提前构建字符串呢?
span = 40 # characters per line
lines = [string[start:start+span] for start in range(0, len(string)+1, span)]
if len(lines) > 3:
# what do you do if the caller has more than three lines of text?
然后像往常一样呈现文本。
我从来没有用过pygame,只是出于好奇读了你的问题。我想您需要优化添加到代码中的多个循环
此外,temp_surface = pygame.Surface((WIDTH,HEIGHT))
指定目标窗口大小。不确定您在哪里指定宽度和高度,以及它是否限制了输出?