8

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

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

4

6 回答 6

13

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

  1. 将 print 的结束字符更改为空字符串: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
    
  2. 将您的sleep呼叫更改为以下内容:

    sleep(uniform(0, 0.3))  # random sleep from 0 to 0.3 seconds
    
于 2013-11-11T16:40:04.077 回答
10
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)
于 2013-11-11T16:37:28.923 回答
2

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

for x in (line_1, line_2, line_3):
于 2013-11-11T16:38:21.507 回答
2

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

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

文档中:

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

于 2013-11-11T16:41:15.063 回答
1

Python 打字机效果

对于字符串中的每个字母,我的回答提供了 0.1 秒的等待时间,因此文本会一个一个出现。Python 3 允许使用sys.stdout.write.

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")
于 2019-11-22T19:16:26.410 回答
1

最简单的解决方法:

进口时间
def tt(文本,延迟):
    对于我在文本中:
        打印(结束 = 我)
        time.sleep(延迟)
print(tt("示例文本", 0.2)
于 2020-07-10T16:55:58.183 回答