我正在写文字冒险(有人记得Zork吗?),而且我遇到了这段代码的麻烦:
from random import randint
def prompt():
action = input(">>> ").lower()
if action == "exit":
quit()
elif action == "save":
save()
else:
return action
def action_error(custom=False):
if custom != False:
print(custom)
else:
phrases = ["A bunch", "of funny", "error phrases"]
print(phrases[randint(1, len(phrases)-1)])
return prompt()
action = prompt()
while True:
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action = action_error("What do you want to switch?")
action = action_error()
问题是如果我输入一个包含"开关"的字符串,则不会接收下一个输入。
此外,任何人都有更好的方法来解析动词 - 名词字符串,例如"切换灯光","打开门"或者"环顾四周" /"看看OBJECT"?
答案 0 :(得分:0)
在部分输入复合动作的情况下,如何将新输入连接到旧输入?然后"切换"变成"开关灯",你的两个条件都会通过。
action = prompt()
while True:
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action = action + " " + action_error("What do you want to switch?")
continue
action = action_error()
奖金风格建议:
a.find("b") != -1
替换为"b" in a
random.choice(phrases)
代替phrases[randint(1, len(phrases)-1)]
答案 1 :(得分:0)
首先,我注意到,如果您第二次输入两次切换,则程序会将其作为错误捕获。 我认为问题出在action_error函数的末尾,你将返回值赋给prompt(),因此输入过早消耗。
可能的解决方法是:
def action_error(custom=False):
if custom != False:
print(custom)
else:
phrases = ["A bunch", "of funny", "error phrases"]
print(phrases[randint(1, len(phrases)-1)])
while True:
action = prompt()
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action_error("What do you want to switch?")
else:
action_error()
因此没有action_error()的返回值和while循环开头的直接赋值。