更改函数的字典 - Python

时间:2013-03-23 23:48:08

标签: python dictionary global-variables

所以我在业余时间创造了一个相当基本的RPG,但我遇到了绊脚石。我希望通过每次玩家进入/退出战斗时更改命令字典,在某个时间只能访问某些功能。但是,我设置的用于搜索字典键的循环似乎不适用于除最初编写的命令之外的任何命令。

主要文件:

    from commands import *

    Commands = {
        "travel": Player.travel,
        "explore": Player.explore,
        "help": Player.help,
        }

    p = Player()

    while (john_hero.health > 0):
        line = raw_input("=> ")
        args = line.split()
        if len(args) > 0:
            commandFound = False
            for c in Commands.keys():
                    if args[0] == c[:len(args[0])]:
                            Commands[c](p)
                            commandFound = True
                            break
            if not commandFound:
                    print "John's too simple to understand your complex command."

command.py

            class Player:
                def __init__(self):
                    self.state = "normal"
                    john_hero = John()
                    self.location = "Town"
                    global Commands
                    Commands = {
                            "attack": Player.attack,
                            "flee": Player.flee,
                            "help": Player.help
                            }
                def fight(self):
                    Player.state = "fight"
                    global Commands
                    enemy_a = Enemy()
                    enemy_name = enemy_a.name
                    print "You encounter %s!" % (enemy_name)

*注意:循环取自其他人的代码。我正在使用它,因为我创建的游戏主要用于学习目的。

2 个答案:

答案 0 :(得分:1)

command.py中的代码似乎试图修改Main file中定义的全局变量,换句话说,就像这样:Global Variable from a different file Python

这不起作用,因为您的代码现在有两个Commands变量,一个在command.py范围内,一个在Main file范围内。我建议您将Commands作为Player的属性,而不是尝试让两个文件共享一个全局变量(这是一个相当糟糕的想法IMO):

class Player:
    def __init__(self):
        ...
        self.Commands = {
            "attack": Player.attack,
            "flee": Player.flee,
            "help": Player.help
        }

答案 1 :(得分:0)

我做的事情

commands = {"travel":{"cmd":Player.travel, "is_available":True}}
for key in commands:
    if commands[key]["is_available"]:
        print "do stuff"

但正如@arunkumar指出的那样,如果没有更多的代码,就很难回答这个问题。