gpt4 book ai didi

python - 为什么这个文本打印函数在 pygame 中会产生延迟?

转载 作者:行者123 更新时间:2023-12-01 08:38:24 25 4
gpt4 key购买 nike

下面显示的是我在 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?

然后照常渲染文本。

关于python - 为什么这个文本打印函数在 pygame 中会产生延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53598765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com