2013-03-23 55 views
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." 

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) 

*注:環是從別人的代碼服用。我正在使用它,因爲我主要是爲了學習目的而創建遊戲。

+1

其中可修改代碼'Commands'? – arunkumar 2013-03-23 23:51:41

+0

@arunkumar嗯,我剛剛添加了它。回想起來,對我來說這是愚蠢的,不包括它。 – IndustrialPioneer 2013-03-24 04:55:17

回答

0

我會做這樣的事情

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

但通過@arunkumar這將是很難回答這個問題,沒有更多的代碼中指出。

1

看來你在command.py代碼試圖修改在Main file定義,換句話說,一個全局變量,像這樣:Global Variable from a different file Python

這不起作用,因爲你的代碼現在有兩個Commands變量,一個在command.py範圍內,一個在Main file範圍內。而不是試圖使兩個文件共享一個全局變量(這是一個相當可怕的想法IMO),我建議你CommandsPlayer屬性:

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