dictionary - How to add to dictionaries, but not dictionaries - Python -
i need dictionary, can edit to. not add entire new value, add 'class'??? inside of dictionary. example character stats.
if race == 'orc': if class == 'worrier': stats = ['strength': 6, 'intelligence': 2]'
how can add strength? (i know can't add dictionaries, why need similar).
i know can't add dictionaries
actually, can:
>>> 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}}}
however, can tell not ideal. want more appropriately object stores properties, provides methods add various attributes. store collection of these objects.
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]
now, want give orc strength:
gunar_the_orc.make_strong_or_weak(3)
to make him weaker:
gunar_the_orc.make_strong_or_weak(-2)
that way, when have "fight" can take impact of each weapon, , minus damage inflicted, until of course orc dies because strength less 0 - that's why added is_dead()
method.
here "game" like:
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 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!")
Comments
Post a Comment