在 Python 中为字符串创建打字机效果动画

新手上路,请多包涵

就像在电影和游戏中一样,一个地方的位置会出现在屏幕上,就像是在现场输入一样。我想制作一个关于在 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 许可协议

阅读 529
2 个回答

因为您用 python 3 标记了您的问题,所以我将提供一个 python 3 解决方案:

  1. 将打印的结束字符更改为空字符串: print(..., end='')
  2. 添加 sys.stdout.flush() 使其立即打印(因为输出是缓冲的)

最终代码:

 from time import sleep
import sys

for x in line_1:
    print(x, end='')
    sys.stdout.flush()
    sleep(0.1)


让它随机也很简单。

  1. 添加此导入:
    from random import uniform

  1. 将您的 sleep 调用更改为以下内容:
    sleep(uniform(0, 0.3))  # random sleep from 0 to 0.3 seconds

原文由 TobiMarg 发布,翻译遵循 CC BY-SA 3.0 许可协议

lines = ["You have woken up in a mysterious maze",
         "The building has 5 levels",
         "Scans show that the floors increase in size as you go down"]

from time import sleep
import sys

for line in lines:          # for each line of text (or each message)
    for c in line:          # for each character in each line
        print(c, end='')    # print a single character, and keep the cursor there.
        sys.stdout.flush()  # flush the buffer
        sleep(0.1)          # wait a little to make the effect look good.
    print('')               # line break (optional, could also be part of the message)

原文由 Inbar Rose 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题