首页 > 解决方案 > 如何通过输入/答案在 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.')

我怎么会有这样的东西有打字效果?

标签: python-3.x

解决方案


您可以为打字效果定义一个函数,如下所示:

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)

推荐阅读