在 Python 中为字符串创建打字机效果动画 [英] Create a typewriter-effect animation for strings in Python

查看:51
本文介绍了在 Python 中为字符串创建打字机效果动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像在电影和游戏中一样,某个地点的位置会出现在屏幕上,就像是实时输入一样.我想制作一个关于在 python 中逃离迷宫的游戏.在游戏开始时它给出了游戏的背景信息:

Just like in the movies and in games, the location of a place comes up on screen as if it's being typed live. I want to make a game about escaping a maze in python. At the start of the game it gives the background information of the game:

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 循环:

Under the variables, I tried to do a for loop for each line similar to this:

from time import sleep

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

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

The only problem with this is that it print one letter per line. The timing of it is ok, but how can I get it to go on one line?

推荐答案

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

Because you tagged your question with python 3 I will provide a python 3 solution:

  1. 将打印的结束字符更改为空字符串:print(..., end='')
  2. 添加 sys.stdout.flush() 使其立即打印(因为输出已缓冲)
  1. Change your end character of print to an empty string: print(..., end='')
  2. Add sys.stdout.flush() to make it print instantly (because the output is buffered)

最终代码:

from time import sleep
import sys

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

<小时>

让它随机也很简单.


Making it random is also very simple.

  1. 添加此导入:

  1. Add this import:

from random import uniform

  • 将您的 sleep 调用更改为以下内容:

  • Change your sleep call to the following:

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

  • 这篇关于在 Python 中为字符串创建打字机效果动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆