首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >文本输入,返回正确的事件,具体取决于用户的输入?

文本输入,返回正确的事件,具体取决于用户的输入?
EN

Stack Overflow用户
提问于 2018-08-28 02:28:57
回答 1查看 0关注 0票数 0

我正在研究基于文本的冒险游戏。基本上我想根据用户输入的内容返回正确的事件。现在,无论用户输入什么类型,它都会提供相同的事件。在游戏的大部分时间里,用户都有1,2或3之间的选择。这种方法完美无缺,但是我想要将其切换并要求用户输入单词。这还没有正常工作。澄清为什么它可以使用数字输入而不是字输入将是值得赞赏的。谢谢。

def main():
    import sys
    from colorama import init
    init()
    init(autoreset=True)
    from colorama import Fore, Back, Style

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



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

    def colored_input():
        return input(Fore.YELLOW + Style.BRIGHT + "> ")

    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 = colored_input()
    if door == "3":
      run_event(EVENT_DOOR3)
      dragon = colored_input()
      if dragon == "yes" or "Yes":
        run_event(EVENT_DRAGON)
      elif dragon == "No":
         run_event(EVENT_DRAGON2)

    restart=input(Fore.YELLOW + Style.BRIGHT + "  Start over? Yes or No?     ").lower()
    if restart == "yes":
        sys.stderr.write("\x1b[2J\x1b[H")
        main()
    else:
        exit()

main()
EN

回答 1

Stack Overflow用户

发布于 2018-08-28 12:22:46

完成此操作的最简单方法是使用相应的函数和名称来保存dict:

def function_1(): pass
def function_2(): pass

functions = {'print values': function_1,
          'get names': function_2}

func = functions.get(input(), None)

现在,当您输入输入时,它会根据您输入的内容返回正确的函数。该功能从字典中提取。现在你可以通过这样做来调用它func()

请参阅我对此问题的回答:https//stackoverflow.com/a/52046800/9917694

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档