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

68
waddlerafter•

You can avoid the hardcoded set of attributes pretty simply, like this:

def __init__(self, x, y, char, color, name, **kwargs):
    self.x = x
    self.y = y
    self.char = char
    self.color = color
    self.name = name
    self.__dict__.update(**kwargs)

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.

6
_escaronOP•

Nice and elegant. Thank you.

1
itsnotxhad•

I didn't like this either and ended up changing it in my version. I ended up making a Component class that all components inherit from:

class Component:
    def __init__(self, name):
        self.name = name

    def add_to_entity(self, entity):
        setattr(entity, self.name, self)
        self.owner = entity

I then added a method to Entity to test if a component is present:

def try_component(self, name):
    return getattr(self, name, None)

So testing for ai would change from if entity.ai to if entity.try_component('ai').

Then an example component would look like:

class Stairs(Component):
    def __init__(self, floor):
        super().__init__('stairs')
        self.floor = floor

And the Entity initializer now looks like:

def __init__(self, x, y, char, color, name, blocks=False, render_order=RenderOrder.CORPSE):
    self.x = x
    self.y = y
    self.char = char
    self.color = color
    self.name = name
    self.blocks = blocks
    self.render_order = render_order

And an example of creating an actual game object with all of this looks like:

dagger = Entity(0, 0, '-', libtcod.sky, 'Dagger')
equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=2)
equippable_component.add_to_entity(dagger)

Obligatory full repo link

3
karlmonaghan•

I've gone a slightly different direction, inspired by this repo and some reading up on Python (this is, like for many, my first Python project).

In the Entity class, I've added these three methods:

    def __getattribute__(self, attr):
        try:
            return object.__getattribute__(self, attr)
        except AttributeError:
            return None

    def add_component(self, component, component_name):
        """Add a component as an attribute of the current object, and set the
        owner of the component to the current object.
        """
        if component:
            component.owner = self
        setattr(self, component_name, component)

    def del_component(self, component_name):
        """Remove a component as an attribute of the current object.
        """
        delattr(self, component_name)

To add it's then:

    ai_component = BasicNPC()
    npc.add_component(ai_component, 'ai')

To remove:

    npc.del_component('ai')

To check if an entity has a component,

    if npc.ai:
        npc.ai.take_turn()

My obligatory full repo link.

1
[deleted]•

can you link the python3 + libcod tutorial please? I can't seem to find it.

1
PhreakPhR•
2
[deleted]•

thanks

1

I'm not familiar with tutorial you referenced, but the attrs library is written to help with situations like this. https://www.attrs.org/en/stable/

As an aside, throwing everything into base classes to reuse attributes is an easy way to end up with god objects.

1