import pygame as pg
import ptext
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
# Triple quoted strings contain newline characters.
text_orig = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum."""
# Create an iterator so that we can get one character after the other.
text_iterator = iter(text_orig)
text = ''
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# Press 'r' to reset the text.
elif event.type == pg.KEYDOWN:
if event.key == pg.K_r:
text_iterator = iter(text_orig)
text = ''
if len(text) < len(text_orig):
# Call `next(text_iterator)` to get the next character,
# then concatenate it with the text.
text += next(text_iterator)
screen.fill(BG_COLOR)
ptext.draw(text, (10, 10), color=BLUE) # Recognizes newline characters.
pg.display.flip()
clock.tick(60)
pg.quit()
另一种方法是对字符串进行切片:
i = 0 # End position of the string.
done = False
while not done:
# ...
i += 1.5 # You can control the speed here.
screen.fill(BG_COLOR)
ptext.draw(text_orig[:int(i)], (10, 10), color=BLUE)
第一个想法:
可以创建动画函数:
这可能是一个遍历每个字符并显示它们的循环。唯一真正的问题是主线程pygame的中断时间减慢了游戏的其他逻辑。你知道吗
更好的替代品
另一种方法是将字母渲染为精灵,然后通过设置它们的运动来逐个移动它们,这样就消除了延迟。你知道吗
使用迭代器可以很容易地做到这一点。只需从原始文本创建一个迭代器,调用
next(iterator)
来获取下一个字符,并将一个字符一个接一个地添加到字符串变量中,直到其长度等于原始字符串的长度。你知道吗要重新启动动画或显示其他文本,请创建新的迭代器
text_iterator = iter(text_orig)
,然后再次设置text = ''
。你知道吗我在这里也使用^{} 库,因为它能够识别换行符来创建多行文本。你知道吗
另一种方法是对字符串进行切片:
要重新启动,只需设置
i = 0
。你知道吗相关问题 更多 >
编程相关推荐