Python一秒也不读string

2024-03-29 10:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一篇文字冒险(有人记得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”的字符串,下一个输入就不会被拾取。你知道吗

还有,任何人都有更好的方法来解析动词-名词字符串,比如“开灯”、“开门”或“环顾四周”/“注视对象”?你知道吗


Tags: falsereturnifsavedefcustomactionerror
2条回答

首先我注意到,如果你第二次输入switch两次,你的程序就会发现它是一个错误。 我认为问题出在action\u 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\u error()和direct赋值的返回值。你知道吗

在部分输入的复合动作的情况下,将新的输入连接到旧的输入,怎么样?然后“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()

奖励风格建议:

  • "b" in a替换a.find("b") != -1
  • random.choice(phrases)代替phrases[randint(1, len(phrases)-1)]

相关问题 更多 >