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

时间:2013-11-11 16:35:47

标签: 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"

在变量下,我试图为每一行做一个for循环:

from time import sleep

for x in line_1:
    print (x)
    sleep(0.1)

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

6 个答案:

答案 0 :(得分:9)

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

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

    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
      
    2. sleep来电更改为以下内容:

      sleep(uniform(0, 0.3))  # random sleep from 0 to 0.3 seconds
      

答案 1 :(得分:8)

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)

答案 2 :(得分:1)

要遍历这些行,请将循环更改为:

for x in (line_1, line_2, line_3):

答案 3 :(得分:1)

您可以使用print("", end="")更改通过打印自动添加的行尾字符。要打印foobar,您可以这样做:

print("foo", end="")
print("bar", end="")

来自documentation

  

所有非关键字参数都转换为字符串,如str(),并写入流,由sep分隔,后跟end。 sep和end都必须是字符串;它们也可以是None,这意味着使用默认值。

答案 4 :(得分:1)

Python类型编写器效果

对于字符串中的每个字母,我的答案将等待0.1秒,因此文本将一个接一个地显示。 代码:

import time, sys

def anything(str):

  for letter in str:
    sys.stdout.write(letter)
    sys.stdout.flush()
    time.sleep(0.1)

anything("Blah Blah Blah...")

您的完整代码如下:

import time, sys

def anything(str):

  for letter in str:
    sys.stdout.write(letter)
    sys.stdout.flush()
    time.sleep(0.1)

anything("You have woken up in a mysterious maze")

anything("The building has five levels")

anything("Scans show that the floors increase in size as you go down")

答案 5 :(得分:1)

最简单的解决方法:

def tt(text, delay):
    for i in text:
        print(end = i)
        time.sleep(delay)
print()
相关问题