打印正确的事件,具体取决于用户的输入

时间:2018-08-28 15:28:06

标签: python events input tuples adventure

我正在开发基于文本的冒险游戏。本质上,我想根据用户的类型返回正确的事件。现在,无论用户键入什么,它都会发出相同的事件(每次都会返回EVENT_DRAGON)。在大多数游戏中,用户可以在1、2或3之间进行选择。效果很好,但我想将其切换并要求用户输入单词。这不能正常工作。请澄清为什么它可以与数字输入一起使用而不能与单词输入一起使用。谢谢。

def main():
    import sys


    def run_event(event):
        text, choices = event
        text_lines = text.split("\n")
        for line in text_lines:
            print('' + line)
            print("")
        choices = choices.strip("\n")
        choices_lines = choices.split("\n")
        for num, line in enumerate(choices_lines):
            print('' + line)
            print("")

    print ("")
    print ("You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..")
    print ("")
    print ("Do you want to enter door 1,2,3,4, or 5?")
    print ("")


    EVENT_DOOR3 = ("""
    A dragon awaits you
    ""","""
    'Welcome' remarks the dragon. 'Do you wish to escape?""")

    EVENT_DRAGON = ("""
    'Good choice' says the dragon. Where would you like to escape to?
    ""","""
    1. Just get me out of here!
    2. Where should I escape to?
    """)

    EVENT_DRAGON2 = ("""
    Interesting..
    ""","""
    Test..
    """)

    door = input("> ")
    if door == "3":
      run_event(EVENT_DOOR3)
      dragon = input()
      if dragon in ['yes','Yes']:
        run_event(EVENT_DRAGON)
      elif dragon in ['no','No']:
        run_event(EVENT_DRAGON2)


main()

1 个答案:

答案 0 :(得分:0)

此行会给您带来一些麻烦,因为它总是评估为True

if dragon == "yes" or "Yes":
    run_event(EVENT_DRAGON)

这种情况类似于说:

if (dragon == 'yes') or ('Yes'):
    run_event(EVENT_DRAGON)

由于“是”是一个非空字符串,它将求值为True,并且将始终执行run_event(EVENT_DRAGON)。我们可以通过几种不同的方法来解决此问题。首先,您可以将输入更改为小写以仅评估一个单词:

if dragon.lower() == 'yes':
    run_event(EVENT_DRAGON)

此外,您可以将可接受的单词放在列表中:

if dragon in ['Yes', 'yes']:
    run_event(EVENT_DRAGON)

您还可以分别测试每个单词:

if dragon == 'yes' or dragon == 'Yes':
    run_event(EVENT_DRAGON)

希望这会有所帮助。让我知道那是否行不通。

相关问题