2016-07-29 134 views
0

對於我創建的基於文本的RPG,我有字典概述了各種遊戲中的宗教,種族等。這些宗教的一些價值包括例如:在一個字典中識別一個關鍵字,並使用它來修改另一個字典的值

religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3}, 
            'abilities': [...], 
            'description': '...'}} 

我的問題出現時,試圖將一個宗教的統計愛好者應用到玩家的統計。如果我有一個球員類,看起來像:

class Player(object)  
    def __init__(self): 
     ... 
     self.religion = None 
     self.stats = {'intelligence': 10, 'defense': 8} 

現在,讓我們假設玩家加入宗教Way of the White,我怎麼去識別鍵intelligencedefense及其各自的價值觀 - 字典內religion_dict - 並將它們應用於玩家的stats字典的值?

我知道我可以使用religion_Dict.keys()或基本的for循環來取得鍵名,但是如何使用它來正確修改相應的球員統計值?

我確定我只是缺少一個基本概念。無論如何,感謝任何願意幫助解答這個簡單問題的人!我很感激!

+0

當你可以使用鍵進行查找時,爲什麼要使用.keys? –

+0

你想添加從宗教到玩家統計的增益? –

回答

2

這裏是你將如何去這個草圖:

religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3}, 
            'abilities': [...], 
            'description': '...'}} 
buffs = religion_Dict['Way of the White']['buffs'] 

for key in buffs: 
    player.stats[key] = player.stats.get(key,0) + buffs[key] 

當然,你應該在你的播放器類中的方法包裝這樣的邏輯,但上面的邏輯是你是什麼尋找。注意.get方法接受第二個參數,如果沒有鍵值,它將返回一個默認值。因此,這條線將加1到任何有統計數據的位置,如果不存在,則它將1加1到0.

1

這增加了一個方法Player將字典中的值賦予玩家統計。它使用get來確保該值在字典中,並且它包含字段buffs。如果是這樣,它會得到intelligencedefense的值,並將它們添加到玩家的統計信息中。

class Player(object)  
    def __init__(self): 
     ... 
     self.religion = None 
     self.stats = {'intelligence': 10, 'defense': 8} 

    def join_religion(religion): 
     stats = religion_dict.get(religion) 
     if stats and 'buffs' in stats: 
      self.intelligence += stats['buffs'].get('intelligence', 0) 
      self.defense += stats['buffs'].get('defense', 0) 

p = Player() 
p.join_religion('Way of the White') 
0
self.stats = religion_Dict['Way of the White']['buffs'] 
相關問題