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

Dav*_* K. 6 python python-3.x

就像在电影和游戏中一样,一个地方的位置出现在屏幕上,好像它是在现场打字一样.我想做一个关于在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"
Run Code Online (Sandbox Code Playgroud)

在变量下,我试着为每一行做一个for循环,类似于:

from time import sleep

for x in line_1:
    print (x)
    sleep(0.1)
Run Code Online (Sandbox Code Playgroud)

唯一的问题是它每行打印一个字母.它的时机还可以,但我怎么能让它在一条线上?

Tob*_*arg 10

因为你用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)
Run Code Online (Sandbox Code Playgroud)

使它随机也很简单.

  1. 添加此导入:

    from random import uniform
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将您的sleep通话更改为以下内容:

    sleep(uniform(0, 0.3))  # random sleep from 0 to 0.3 seconds
    
    Run Code Online (Sandbox Code Playgroud)

  • 另一种选择是`print(x,end ='',flush = True)`.它更容易阅读. (3认同)

Inb*_*ose 9

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)
Run Code Online (Sandbox Code Playgroud)

  • 不是在Python3中,它不会.问题是标记为python3. (2认同)