就像在电影和游戏中一样,地点的位置会出现在屏幕上,就好像是在现场输入一样。我想制作一个关于在 python 中逃离迷宫的游戏。在游戏开始时它给出了游戏的背景信息:
line_1 = "You have woken up in a mysterious maze"
line_2 = "The building has 5 levels"
line_3 = "Scans show that the floors increase in size as you go down"
在变量下,我试着为每一行做一个类似这样的for循环:
from time import sleep
for x in line_1:
print (x)
sleep(0.1)
唯一的问题是它每行打印一个字母。它的时间是可以的,但是我怎样才能让它在一条线上呢?
最佳答案
因为你用 python 3 标记了你的问题,我将提供一个 python 3 解决方案:
- 将 print 的结束字符更改为空字符串:
print(..., end='')
- 添加
sys.stdout.flush()
使其立即打印(因为输出是缓冲的)
最终代码:
from time import sleep
import sys
for x in line_1:
print(x, end='')
sys.stdout.flush()
sleep(0.1)
让它随机化也很简单。
添加这个导入:
from random import uniform
将您的
sleep
调用更改为以下内容:sleep(uniform(0, 0.3)) # random sleep from 0 to 0.3 seconds
关于python - 在 Python 中为字符串创建打字机效果动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911346/