1 回答

TA贡献2041条经验 获得超4个赞
您的方法不起作用,因为您在构建字典时立即调用input()
or函数。,例如,返回,这就是你得到错误的原因。time.sleep()
time.sleep()
None
当您从字典中检索值并且实际上想要“慢打印”描述时,您需要稍后调用这些函数。
您可以通过多种不同的方式来做到这一点。你可以
使用字符串序列(例如列表或元组)而不是单个字符串,并让您的
slowprint()
函数接受序列并在打印每个元素后暂停。使用一系列字符串并混合特殊值来
slowprint()
寻找做不同的事情,比如睡觉或请求输入。在字典中存储一个函数,然后调用。函数也是对象,就像字符串一样。该函数将处理所有打印和暂停。
例如存储一个字符串元组:
EXAMINATION: (
"The grass in this field is extremely soft.",
"The wind feels cool on your face.",
"The sun is beginning to set.",
)
然后让你的slowprint()函数处理:
def slowprint(lines):
"""Print each line with a pause in between"""
for line in lines:
print(line)
input("> ") # or use time.sleep(2), or some other technique
第二个选项,插入特殊值,使您能够将各种额外功能委托给其他代码。您需要测试序列中对象的类型,但这会让您在检查描述中插入任意操作。就像睡觉和要求用户击键之间的区别一样:
class ExaminationAction:
def do_action(self):
# the default is to do nothing
return
class Sleep(ExaminationAction):
def __init__(self, duration):
self.duration = duration
def do_action(self):
time.sleep(self.duration)
class Prompt(ExaminationAction):
def __init__(self, prompt):
self.prompt = prompt
def do_action(self):
return input(self.prompt)
并让slowprint()函数查找这些实例:
def slowprint(examine_lines):
for action_or_line in examine_lines:
if isinstance(action_or_line, ExamineAction):
# special action, execute it
action_or_line.do_action()
else:
# string, print it
print(action_or_line)
您可以进行任意数量的此类操作;关键是它们都是子类ExamineAction,因此可以与普通字符串区分开来。将它们放入您的EXAMINATION密钥序列中:
EXAMINATION: (
"The grass in this field is extremely soft.",
Prompt("> "),
"The wind feels cool on your face.",
Sleep(2),
"The sun is beginning to set.",
)
可能性是无止境。
添加回答
举报