python-3.x - 如何通过输入/答案在 Python 中产生打字效果?
问题描述
我是新手,在 Python 编程方面经验很少,如果我的术语不正确,请纠正我。
我看过一些帖子询问Python 中的打字效果。但我也想在需要你回答或输入内容的脚本中使用这种效果,比如那些选择你自己的冒险游戏。例如:
answer = input("You reach a crossroad, would you like to go left or right?").lower().strip()
if answer == 'left':
answer = input('You encounter a monster, would you like to run or attack?')
elif answer == 'right':
answer = input('You walk aimlessly to the right and fall on a patch of ice.')
我怎么会有这样的东西有打字效果?
解决方案
您可以为打字效果定义一个函数,如下所示:
import sys
import time
def type_effect(string, delay):
for char in string:
time.sleep(delay)
sys.stderr.write(char)
然后每次你想使用效果时使用它:)
type_effect('You reach a crossroad, would you like to go left or right?', 0.1)
answer = input().lower().strip()
if answer == 'left':
type_effect('You encounter a monster, would you like to run or attack?', 0.1)
answer = input()
elif answer == 'right':
type_effect('You walk aimlessly to the right and fall on a patch of ice.', 0.1)
answer = input()
或者,您甚至可以定义一个使用类型效果并返回用户输入的函数,如下所示:
import sys
import time
def type_effect_and_input(string, speed):
for char in string:
time.sleep(speed)
sys.stderr.write(char)
return input().lower().strip()
answer = type_effect_and_input('You reach a crossroad, would you like to go left or right?', 0.1)
if answer == 'left':
answer = type_effect_and_input('You encounter a monster, would you like to run or attack?', 0.1)
elif answer == 'right':
answer = type_effect_and_input('You walk aimlessly to the right and fall on a patch of ice.', 0.1)
推荐阅读
- vba - 如何编写用于调整线箭头的 VBA 代码:根据插入的图像加倍长度?
- huggingface-transformers - 如何截断 Huggingface 管道中的输入?
- python - 如何在 ubuntu 中使用 selenium 解决这个 python 错误?
- angular - 哪个 Angular 函数替换了路由器路径中的标记?
- python - 在 Python 中显示不同值的字典对象的 ID
- javascript - 如何从 Microsoft graph API 访问用户的个人资料照片并显示 React 应用程序?
- winapi - 存在重命名的当前可执行文件的 CreateProcess
- javascript - 如何将调用从 apache 转发到 nodejs?
- c# - 我如何使用等价的 == 字符串 c#
- javascript - 如何在 createdadettime JSP、javascript 中按日期和结果顺序实现 Spring Boot 搜索过滤器?