0

所以我在业余时间一直在创建一个相当基本的 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."

命令.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)

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

4

2 回答 2

1

It seems that your code in command.py trying to modify a global variable that is defined in Main file, in other words, something like this: Global Variable from a different file Python

This doesn't work because your code now has two Commands variables, one in the scope of command.py, one in the scope of Main file. Rather than trying to make two files share a global variable (which is a rather terrible idea IMO), I suggest you make Commands an attribute of Player:

class Player:
    def __init__(self):
        ...
        self.Commands = {
            "attack": Player.attack,
            "flee": Player.flee,
            "help": Player.help
        }
于 2013-03-24T09:55:50.437 回答
0

我会做类似的事情

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

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

于 2013-03-23T23:57:24.817 回答