Python + libtcod tutorial, entities and components initialization
Hello,
I've finished the python3 + libtcod tutorial, however as I continue developing the game I'm not sure about the way entities and components are handled. Each component is passed as parameter during entity creation and the entity keeps a hardcoded set of attributes for the components.
class Entity:
def __init__(self, x, y, char, color, name, blocks=False, render_order=RenderOrder.CORPSE,
fighter=None, ai=None, item=None, inventory=None, stairs=None,
equipment=None, equippable=None):
self.x = x
self.y = y
self.char = char
self.color = color
self.name = name
self.blocks = blocks
self.render_order = render_order
self.fighter = fighter
self.ai = ai
self.item = item
self.inventory = inventory
self.stairs = stairs
self.equipment = equipment
self.equippable = equippable
...
How sustainable is this? It doesn't seem very. For every aspect of the entity can have, there is a component. This will get very long very fast. I was thinking about moving all the components to a separate Dictionary called components. Would that be a good idea?
Posted Aug 18, 2019, 4:57 PM UTC
You can avoid the hardcoded set of attributes pretty simply, like this:
Now you can define any new components you want in the constructor call, like:
player = Entity(0, 0, '@', white, 'player', newcomponent=NewComponent())To avoid attribute errors, you could check whether an object has a component with
getattr(player, 'newcomponent', None)where 'None' is a default.That said, in my own project I keep a hardcoded list of attributes, and use **kwargs so I don't have to update the parameter list all the time. It works fine.
Nice and elegant. Thank you.