【问题标题】:Python not reading string a second timePython没有第二次读取字符串
【发布时间】:2014-12-09 18:49:17
【问题描述】:

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

【问题讨论】:

  • 我不知道我是否理解得很好,但if "switch" in action是不是你想的那样?
  • 让我们看看我是否理解。您的预期行为是:用户输入“开关”。游戏打印“你想切换什么?”。用户输入“光”。游戏进入第二个房间。正确的?但是此刻,如果用户输入“开关”再输入“灯”,就没有按预期工作了?

标签: python string adventure


【解决方案1】:

首先我注意到,如果您第二次输入 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()没有返回值,直接赋值。

【讨论】:

    【解决方案2】:

    在部分输入复合动作的情况下,将新输入连接到旧输入怎么样?然后“switch”变成“switch light”,你的两个条件都会通过。

    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)]

    【讨论】:

    • 预期行为是回答“你想切换什么?”如果用户刚刚输入“开关”,如果他输入“开关灯”或“打开灯”之类的内容,则进入第二个房间。主要思想是通过输入“grepping”并尝试猜测用户的意思。
    • 啊,在这种情况下,您可能需要一个 continue 语句来跳过最底部的 action_error() 调用。已编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2015-12-29
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2020-02-26
    • 2020-11-10
    相关资源
    最近更新 更多