0

So I've been creating a fairly basic rpg in my spare time, but I've reached a stumbling block. I want to make it so that only certain functions are accessible at a certain time by changing a dictionary of commands every time the player goes into/exits battle. However, the loop I set up for searching through the dictionary keys doesn't seem to work for any commands except for the ones initially written.

Main file:

    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)

*Note: The loop was taken from someone else's code. I'm using it since I'm creating the game mostly for learning purposes.

2 Answers2

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
        }
Community
  • 1
  • 1
xuanji
  • 5,007
  • 2
  • 26
  • 35
0

I'd do something like

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

but as pointed out by @arunkumar it is going to be difficult to answer this question without more of the code.

John
  • 13,197
  • 7
  • 51
  • 101