就像在电影和游戏中一样,一个地方的位置会出现在屏幕上,就像是在现场输入一样。我想制作一个关于在 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)
唯一的问题是它每行打印一个字母。它的时间是可以的,但是我怎样才能让它在一条线上呢?
原文由 David K. 发布,翻译遵循 CC BY-SA 4.0 许可协议
因为您用 python 3 标记了您的问题,所以我将提供一个 python 3 解决方案:
print(..., end='')
sys.stdout.flush()
使其立即打印(因为输出是缓冲的)最终代码:
让它随机也很简单。
sleep
调用更改为以下内容: