lets have game can train units have cost attached them , want able calculate total cost of training amount of said units.
the units share same attributes value of said attributes change across different units.
i have found 2 potential solutions, using dictionaries:
spearmen = {'gold' : 2, 'wood' : 10, 'stone' : 5, 'iron' : 0} swordsmen = {'gold' : 5, 'wood' : 30, 'stone': 0, 'iron' : 10}
but find way access information bit verbose:
swordsmen['gold'] * 1200
so wondered if doing appropriate:
class spearmen: gold = 2 wood = 10 stone = 5 iron = 0 class swordsmen gold = 5 wood = 30 stone = 0 iron = 10
using classes makes accessing information less verbose:
spearmen.gold * 1200
doing cursory research found this question, suggests more not trying considered anti pattern. not sure solution either.
when thinking evolution of program, highly unlikely have add new attributes units, more not need add new units (with same attributes).
so wonder if either of these solutions appropriate or if there better way (and why wrong).
attributes objects should part of object definition (class). if objects share common set of attributes, should inherited parent class.
as how should store them, there many ways this. can have parent class defines default attributes common object (as @zondo suggested, unit class); these attributes can stored dictionary.
you can modify dictionary in inherited classes override values of default attributes or create new ones specific unit type.
class baseunit(object): def __init__(self, name, stats={}): self.stats = {} if not stats: self.stats['health'] = 10 self.stats['armor'] = 10 self.stats['strength'] = 10 else: self.stats.update(stats) self.name = name class peon(baseunit): pass class warrior(baseunit): pass grunt = peon(name='igor', {'strength': 5, 'armor': 5}) soldier = warrior(name='frank', {'armor': 10, 'health': 20, 'damage': 50})
Comments
Post a Comment