-3

我需要一本可以编辑的字典。不是添加一个全新的值,而是添加到一个“类”???字典里面。例如角色统计。

if race == 'orc': if Class == 'worrier': stats = ['strength': 6, 'intelligence': 2]'

我怎样才能增加力量?(我知道你不能添加字典,这就是为什么我需要类似的东西)。

4

4 回答 4

4

我知道你不能用字典添加

实际上,您可以:

>>> characters = {}
>>> characters['warrior'] = {}
>>> characters['warrior']['orc'] = {}
>>> characters['warrior']['orc']['strength'] = 5
>>> characters['warrior']['orc']['intelligence'] = 2
>>> characters
{'warrior': {'orc': {'intelligence': 2, 'strength': 5}}}
>>> characters['warrior']['orc']['strength'] += 3
>>> characters
{'warrior': {'orc': {'intelligence': 2, 'strength': 8}}}

但是,正如您所见,这并不理想。您想要更合适的是一个存储所有属性的对象,提供添加各种属性的方法。然后存储这些对象的集合。

class Character(object):
     def __init__(name, type, category, strength, intelligence):
         self.strength = strength
         self.intelligence = intelligence
         self.name = name
         self.type = type
         self.category = category

     def make_smart_or_dumb(self, intelligence):
         self.intelligence += intelligence

     def make_strong_or_weak(self, strength):
         self.strength += strength

     def is_dead(self):
         return self.strength < 0

gunar_the_orc = Character('Gunar','Orc', 'Warrior', 10, 5)
smith_the_human = Character('Smith','Human','Warrior', 5, 10)

game_characters = [gunar_the_orc, smith_the_human]

现在,你想给兽人一些力量:

gunar_the_orc.make_strong_or_weak(3)

让他变弱:

gunar_the_orc.make_strong_or_weak(-2)

这样,当你“战斗”时,你可以承受每件武器的冲击,然后减去造成的伤害,直到兽人当然因为他的力量小于 0 而死——这就是我添加该is_dead()方法的原因。

这是“游戏”的样子:

while not gunar_the_orc.is_dead() or smith_the_human.is_dead():
     # Gunar attacks Smith!
     smith_the_human.make_strong_or_weak(-1)

     # Smith drinks some potions:
     smith_the_human.make_strong_or_weak(3)

     # Smith attacks!
     gunar_the_orc.make_strong_or_weak(-10)

if gunar_the_orc.is_dead():
   print("Smith won!")
else:
   print("Gunar won!")
于 2013-08-07T20:51:09.933 回答
1

目前还不清楚你在这里问什么,所以我假设你想知道如何添加到字典中的值。

尝试这个:

>>> dictionary = {"strength": 6, "intelligence": 2};
>>> dictionary["strength"] += 7;
>>> print(dictionary);
{'strength': 13, 'intelligence': 2}    print(dictionary)

但是,在这种情况下,我建议您查看classes。这将允许您改为这样做myorc.strength += 7,并进一步创建相互继承的单元类,例如。一个食人魔就像一个兽人,但强度高 5,无需重写大量代码。

编辑:通过阅读您的评论,您可能想要向字典添加一个新的键值对。为此,请执行dictionary[key] = value. key如果还不是字典的键,它将创建该对,如果是,则更新该值。

于 2013-08-07T20:43:50.303 回答
0
char = {"race" : "orc", "class" : "worrier", "stats" : {"strenght" : 6, "intelligence" : 2}}
char["stats"]["strenght"] += 1
# output -> {'race': 'orc', 'stats': {'intelligence': 2, 'strenght': 7}, 'class': 'worrier'}
# Append something to stats
char["stats"].update({"stamina" : 5})
# output -> {'race': 'orc', 'stats': {'stamina': 5, 'intelligence': 2, 'strenght': 7}, 'class': 'worrier'}
于 2013-08-07T20:53:07.630 回答
-1

为什么不stats['strength'] = stats['strength'] + n呢?

于 2013-08-07T20:40:32.270 回答