如何在上下文中使用Python的cmd模块

时间:2014-01-09 23:49:07

标签: python interpreter dispatch

我正在尝试使用Python的cmd模块来解释玩家的命令,但我不能让它在“游戏世界”受到影响的情况下工作。

从测试开始,似乎player.cmdloop()只是在播放器实例的范围内运行;在下面的代码中,game()会运行,因为它通常会进入player.cmdloop(),此时player.cmdloop()会运行。一旦输入运行,cmdloop()结束,它返回到顶部。

我尝试了很多不同的方法,所以我认为由于缺乏理解,这是我设计/实施的问题。

非常感谢任何帮助!

    import cmd 

    who_dict = {}
    class MyConsole(cmd.Cmd):

        def __init__(self):

            cmd.Cmd.__init__(self)

        def do_who(self, args):
            game().who()


    class Human(object, MyConsole):
        """The human player
        """
        prompt = ">> "
        def __init__(self, name, health, gold):
            MyConsole.__init__(self)
            self.name = name
            self.health = health
            self.gold = gold

        def do_swing(self, args):
            game().swing()



    class Monster(object):
        """Item Class
        """
        def __init__(self, name, hp):
            self.name = name
            self.hp = hp



    def game():
        global who_dict
        """ Main game function """

        # when game is started.  
        # load the game_state file
        # initialize the console 

        # Sample game_state. Will be loaded from file.

        game_state = {
                    'players'   :   [
                                        Human('Joe', 100, 10),
                                        Human('Frank', 100, 20)
                                    ],



                    'monsters'  :   [
                                        Monster('goblin',1)
                                    ]
                    }     



        for player in game_state['players']:
            who_dict.update({player.name:player})

        def who():
            for name in who_dict.keys():
                print name

        def swing():
            print "You briefly flail your arms like a mad man, attempting to hit something."


        player.cmdloop()

    if __name__ == '__main__':
        player = Human('Ben', 100, 10)
        game()

结果:

    >> swing
    >>

0 个答案:

没有答案