下面显示的是我在pygame中创建的功能,用于逐个字母打印文本。在超出屏幕边缘之前,它将最多打印三行。由于某种原因,如果我打印了相当于三行文本的内容,然后尝试打印单个字符,则程序将冻结并暂时停止运行。有这种情况发生的原因吗?另外,如果在打印文本方面我的功能可能无法满足某些要求,我该怎么做才能改善此功能?
代码如下:
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")
答案 0 :(得分:1)
您正在执行大量原始文本处理,这是以某种方式使用所有最昂贵的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?
然后照常渲染文本。
答案 1 :(得分:0)
我从不使用pygame,只是出于好奇而阅读了您的问题。 我想您需要优化已添加到代码中的多个循环。
此外,temp_surface = pygame.Surface((WIDTH,HEIGHT))
指定目标窗口的大小。不确定在哪里指定宽度和高度,是否限制了输出?