1

我正在写一篇文字冒险(有人记得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()

问题是,如果我输入一个包含“switch”的字符串,则不会拾取下一个输入。

此外,任何人都有更好的方法来解析动词名词字符串,如“switch the light”、“open the door”或“look around”/“look at OBJECT”?

4

2 回答 2

0

首先,我注意到如果您第二次输入 switch 两次,它会被您的程序捕获为错误。我认为问题出在 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()

所以在 while 循环开始时 action_error() 没有返回值和直接赋值。

于 2014-12-09T19:24:06.007 回答
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)]
于 2014-12-09T19:00:58.800 回答