【发布时间】:2021-03-06 09:22:21
【问题描述】:
我是 python 和编程的新手。当我试图获得经验时,我认为我可以制作一个终端谜语游戏。这将是一个简单的问答游戏。
我的方法如下: 有一个 .txt(包含谜语)文件,我用 python 程序打开它。我想模仿在终端上打字,所以我在很大程度上使用了时间模块。现在,我已经设法模仿在终端中打字,它以一种速度输入字母,没有暂停,但在某些地方我希望程序等待 2 或 4 秒才能继续输入(以获得更戏剧性的效果)。
我能够找到的一个解决方案是我在 .txt 文件中放置了符号(例如,“p-2”表示“暂停 2 秒”)。文本文件如下所示:
What is Lorem Ipsum?
p-1
Lorem Ipsum is simply a dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
p-2
Python 文件如下所示:
def text_output(message):
for i in message:
time.sleep(0.05)
print(i, end='', flush=True)
if "p-1" in data:
data = data.replace("p-1", "time.sleep(1)")
if "p-2" in data:
data = data.replace("p-2", "time.sleep(2)")
if "p-4" in data:
data = data.replace("p-4", "time.sleep(4)")
exec(data)
如您所见,代码在文本中查找符号并将其替换为 python 代码,然后 exec() 函数执行此代码。不过我不喜欢这种方式,我觉得有更方便的方式可以达到这种效果。
我们将非常感谢您的帮助。
【问题讨论】:
-
如果我的回答解决了您的问题,您能接受吗?
标签: python python-3.x terminal