Python 文本游戏:如何在类中存储命令

Python 文本游戏:如何在类中存储命令,python,Python,我正在做一个文字游戏(各种较小的文字游戏,直到我完全舒服为止),而且会有很多命令。例如: class Credits(): def __init(self): print "for command 1 press 1:" print "for command 2 press 2:" print "for command 3 press 3:" print "for command 4 press 4:" ch

我正在做一个文字游戏(各种较小的文字游戏,直到我完全舒服为止),而且会有很多命令。例如:

class Credits():
    def __init(self):
        print "for command 1 press 1:"
        print "for command 2 press 2:"
        print "for command 3 press 3:"
        print "for command 4 press 4:"
        choice = raw_input("")

        if choice == "1":
            self.command1()
        elif choice == "2":
            self.command2()
        elif choice == "3":
            self.command3()
        else:
            self.command4()

    def command1(self):
        #do stuff

    def command2(self):
        #do stuff

    def command3(self):
        #do stuff

    def command4(self):
        #do stuff
如果玩家在“信用”屏幕上。如果有一个中央命令,例如“帮助”。如何让命令“帮助”列出所有可用命令


我要问的是,如何将所有自定义命令存储在一个类中,然后调用它们?或者甚至可能吗?

您可以在类中为每个命令创建方法

例如:

class Credits():
    def __init(self):
        print "for command 1 press 1:"
        print "for command 2 press 2:"
        print "for command 3 press 3:"
        print "for command 4 press 4:"
        choice = raw_input("")

        if choice == "1":
            self.command1()
        elif choice == "2":
            self.command2()
        elif choice == "3":
            self.command3()
        else:
            self.command4()

    def command1(self):
        #do stuff

    def command2(self):
        #do stuff

    def command3(self):
        #do stuff

    def command4(self):
        #do stuff
然后每个选项将执行一个不同的操作方法,每个方法将执行一个命令


我不知道这是否正是你想要的,但我希望这会有所帮助,因为这经常被忽视,但听起来正是你需要的。正如他们所说,.

首先,请使用搜索功能,或者至少使用谷歌。如果你没有证明你已经做了你应该做的研究,不要期待帮助

这就是说,这里有一个例子让你开始。您可以编写一个函数来接受来自键盘的输入,并使用条件语句来输出正确的信息:

class MyClass():

    def menu(self):
        strcmd = raw_input('Enter your input:')
        if strcmd == "help":
            self.help_func()
        elif strcmd == "exit":
            sys.exit(0);
        else:
            print("Unknown command")

    def help_func(self):
        print("Type 'help' for help.")
        print("Type 'exit' to quit the application.")

    # ...
如果您想获得更多乐趣,可以将函数指针存储在字典中,并完全避免使用条件:

class MyClass():

    def __init__(self):
        self.cmds = {"help": help_func, "info": info_func}

    def menu(self):
        strcmd = raw_input('Enter your input:')

        if strcmd in self.cmds:
            self.cmds[strcmd]() # can even add extra parameters if you wish
        else:
            print("Unknown command")

    def help_func(self):
        print("Type 'help' for help.")
        print("Type 'exit' to quit the application.")

    def info_func(self):
        print("info_func!")
对于那些对Python有全面了解的人来说,基于文本的菜单是不需要动脑筋的。您必须自己弄清楚如何正确地实现输入和控制流。这是谷歌最热门的搜索结果之一:


首先要记住的可能是函数是python中的一流对象

因此,您可以学习如何使用dict将字符串(帮助主题)映射到函数(该函数可能以某种方式显示您想要的内容)


您需要发布一些代码,并解释您尝试过但不起作用的内容。