API reference#

A type-hinted Entity Component System based on Python dictionaries and sets.

Registry management tools.

class tcod.ecs.registry.Registry#

Bases: object

A container for entities and components.

property Q: BoundQuery#

Start a new Query for this registry.

Alias for tcod.ecs.Query(registry).

__getitem__(uid)#

Return an entity associated with a unique id.

Example:

>>> registry = Registry()
>>> foo = registry["foo"]  # Referencing a new entity returns a new empty entity
>>> foo is registry["foo"]
True
>>> entity = registry.new_entity()
>>> registry[entity.uid] is entity  # Anonymous entities can be referred to by their uid
True
Parameters:

uid (object) –

Return type:

Entity

__getstate__()#

Pickle this object.

Return type:

dict[str, Any]

__iter__()#

Raises TypeError, Registry is not iterable.

Return type:

NoReturn

__setstate__(state)#

Unpickle this object and handle state migration.

Parameters:

state (dict[str, Any]) –

Return type:

None

property global_: Entity#

A unique globally accessible entity.

This can be used to store globally accessible components in the registry itself without any extra boilerplate. Otherwise this entity is not special and will show up with other entities in queries, etc.

This entity has a uid of None and may be accessed that way. This syntax my be better for globals in general since it can use any hashable object.

New in version 1.1.

Example:

>>> registry[None].components[("turn", int)] = 0
>>> registry[None].components[("turn", int)]
0
property named: Mapping[object, Entity]#

A view into this registries named entities.

Deprecated since version 3.1: This feature has been deprecated.

new_entity(components=(), *, name=None, tags=())#

Create and return a new entity.

Changed in version 3.1: components can now take a mapping.

Example:

>>> entity = registry.new_entity(
...     components={
...         ("name", str): "my name",
...         ("hp", int): 10,
...     },
...     tags=["Actor"],
... )
>>> entity.components[("name", str)]
'my name'
>>> "Actor" in entity.tags
True
Parameters:
Return type:

Entity

Entity management and interface tools.

class tcod.ecs.entity.Entity(registry, uid=<class 'object'>)#

Bases: object

A unique entity in a registry.

Example:

>>> import tcod.ecs
>>> registry = tcod.ecs.Registry()  # Create a new registry
>>> registry.new_entity()  # Create a new entity
<Entity(uid=object at ...)>
>>> entity = registry["entity"]  # Get an entity from a specific identifier
>>> other_entity = registry["other"]
Parameters:
Return type:

Entity

static __new__(cls, registry, uid=<class 'object'>)#

Return a unique entity for the given registry and uid.

If an entity already exists with a matching registry and uid then that entity is returned.

The uid default of object will create an instance of object as the uid. An entity created this way will never match or collide with an existing entity.

Example:

>>> registry = tcod.ecs.Registry()
>>> Entity(registry, "foo")
<Entity(uid='foo')>
>>> Entity(registry, "foo") is Entity(registry, "foo")
True
>>> Entity(registry) is Entity(registry)
False
Parameters:
Return type:

Entity

__reduce__()#

Pickle this Entity.

Note that any pickled entity will include the registry it belongs to and all the entities of that registry.

Return type:

tuple[type[Entity], tuple[Registry, object]]

__repr__()#

Return a representation of this entity.

Example:

>>> registry.new_entity()
<Entity(uid=object at ...)>
>>> registry["foo"]
<Entity(uid='foo')>
Return type:

str

clear()#

Deletes all of this entities components, tags, and relations.

Relations targeting this component are still kept.

New in version 4.2.0.

Return type:

None

property components: EntityComponents#

Access an entities components.

Example:

>>> entity.components[str] = "foo"  # Assign component
>>> entity.components[("name", str)] = "my_name" # Assign named component
>>> entity.components |= {  # Update components in-place
...     ("hp", int): 10,
...     ("attack", int): 4,
...     ("defense", int): 1,
... }
>>> ("name", str) in entity.components
True
>>> {str, ("name", str)}.issubset(entity.components.keys())
True
>>> list(registry.Q.all_of(components=[str]))  # Query components
[<Entity(uid='entity')>]
>>> list(registry.Q[tcod.ecs.Entity, str, ("name", str)])  # Query zip components
[(<Entity(uid='entity')>, 'foo', 'my_name')]
instantiate()#

Return a new entity which inherits the components, tags, and relations of this entity.

This creates a new unique entity and assigns an IsA relationship with self to the new entity. The IsA relation is the only data this new entity directly holds.

Example:

# 'child = entity.instantiate()' is equivalent to the following:
>>> from tcod.ecs import IsA
>>> child = registry[object()]  # New unique entity
>>> child.relation_tag[IsA] = entity  # Configure IsA relation

Example:

>>> parent = registry.new_entity()
>>> parent.components[str] = "baz"
>>> child = parent.instantiate()
>>> child.components[str]  # Inherits components from parent
'baz'
>>> parent.components[str] = "foo"
>>> child.components[str]  # Changes in parent and reflected in children
'foo'
>>> child.components[str] += "bar"  # In-place assignment operators will copy-on-write immutable objects
>>> child.components[str]
'foobar'
>>> parent.components[str]
'foo'
>>> del child.components[str]
>>> child.components[str]
'foo'

# Note: Mutable objects have the same gotchas as in other Python examples:
>>> from typing import List, Tuple
>>> parent.components[List[str]] = ["foo"]
>>> child.components[List[str]] += ["bar"]  # Will modify list in-place then assign that same list to child
>>> parent.components[List[str]]  # Parent references the same list as the child now
['foo', 'bar']
>>> child.components[List[str]]
['foo', 'bar']
>>> parent.components[List[str]] is child.components[List[str]]
True
>>> parent.components[Tuple[str, ...]] = ("foo",)  # Prefer immutable types to avoid the above issue
>>> child.components[Tuple[str, ...]] += ("bar",)
>>> child.components[Tuple[str, ...]]
('foo', 'bar')
>>> parent.components[Tuple[str, ...]]
('foo',)

New in version 5.0.

Return type:

Self

property name: object#

The unique name of this entity or None.

You may assign a new name, but if an entity of the registry already has that name then it will lose it.

Deprecated since version 3.1: This feature has been deprecated.

registry: Final[Registry]#

The Registry this entity belongs to.

property relation_components: EntityComponentRelations#

Access an entities relation components.

Example:

>>> entity.relation_components[str][other_entity] = "foo" # Assign component to relation
>>> entity.relation_components[("distance", int)][other_entity] = 42 # Also works for named components
>>> other_entity in entity.relation_components[str]
True
>>> list(registry.Q.all_of(relations=[(str, other_entity)]))
[<Entity(uid='entity')>]
>>> list(registry.Q.all_of(relations=[(str, ...)]))
[<Entity(uid='entity')>]
>>> list(registry.Q.all_of(relations=[(entity, str, None)]))
[<Entity(uid='other')>]
>>> list(registry.Q.all_of(relations=[(..., str, None)]))
[<Entity(uid='other')>]
property relation_tag: EntityRelationsExclusive#

Access an entities exclusive relations.

Example:

>>> entity.relation_tag["ChildOf"] = other_entity  # Assign relation
>>> list(registry.Q.all_of(relations=[("ChildOf", other_entity)]))  # Get children of other_entity
[<Entity(uid='entity')>]
>>> list(registry.Q.all_of(relations=[(entity, "ChildOf", None)]))  # Get parents of entity
[<Entity(uid='other')>]
>>> del entity.relation_tag["ChildOf"]
property relation_tags: EntityRelationsExclusive#

Access an entities exclusive relations.

Deprecated since version 3.2: This attribute was renamed to relation_tag.

property relation_tags_many: EntityRelations#

Access an entities many-to-many relations.

Example:

>>> entity.relation_tags_many["KnownBy"].add(other_entity)  # Assign relation
property tags: EntityTags#

Access an entities tags.

Example:

>>> entity.tags.add("tag") # Add tag
>>> "tag" in entity.tags  # Check tag
True
>>> list(registry.Q.all_of(tags=["tag"]))  # Query tags
[<Entity(uid='entity')>]
>>> entity.tags.discard("tag")
>>> entity.tags |= {"IsPortable", "CanBurn", "OnFire"}  # Supports in-place syntax
>>> {"CanBurn", "OnFire"}.issubset(entity.tags)
True
>>> entity.tags -= {"OnFire"}
>>> {"CanBurn", "OnFire"}.issubset(entity.tags)
False
uid: Final[object]#

This entities unique identifier.

property world: Registry#

Deprecated alias for registry.

Deprecated since version Unreleased: Use registry instead.

class tcod.ecs.entity.EntityComponentRelationMapping(entity, key, traverse)#

Bases: Generic[T], MutableMapping[Entity, T]

An entity-component mapping to access the relation target component objects.

See Entity.relation_components.

Parameters:
__attrs_post_init__()#

Validate attributes.

Return type:

None

__delitem__(target)#

Delete a component assigned to the target entity.

Parameters:

target (Entity) –

Return type:

None

__getitem__(target)#

Return the component related to a target entity.

Parameters:

target (Entity) –

Return type:

T

__iter__()#

Iterate over the targets with assigned components.

Return type:

Iterator[Entity]

__len__()#

Return the count of targets for this component relation.

Return type:

int

__setitem__(target, component)#

Assign a component to the target entity.

Parameters:
  • target (Entity) –

  • component (T) –

Return type:

None

entity: Entity#
key: Type[T] | Tuple[object, Type[T]]#
keys()#

Return all entities with an associated component value.

Return type:

Set[Entity]

traverse: tuple[object, ...]#
class tcod.ecs.entity.EntityComponentRelations(entity, traverse)#

Bases: MutableMapping[Union[Type[Any], Tuple[object, Type[Any]]], EntityComponentRelationMapping[Any]]

Proxy to access the component relations of an entity.

See Entity.relation_components.

..versionchanged:: 4.2.0

Is now a collections.abc.MutableMapping subtype.

Parameters:
__attrs_post_init__()#

Validate attributes.

Return type:

None

__call__(*, traverse)#

Update this view with alternative parameters, such as a specific traversal relation.

New in version 5.0.

Parameters:

traverse (Iterable[object]) –

Return type:

Self

__contains__(key)#

Return True if this entity contains a relation component for this component key.

Parameters:

key (object) –

Return type:

bool

__delitem__(key)#

Remove all relations associated with this component key.

Parameters:

key (Type[object] | Tuple[object, Type[object]]) –

Return type:

None

__getitem__(key)#

Access relations for this component key as a {target: component} dict-like object.

Parameters:

key (Type[T] | Tuple[object, Type[T]]) –

Return type:

EntityComponentRelationMapping[T]

__iter__()#

Iterates over the component keys this entity has relations for.

Return type:

Iterator[Type[object] | Tuple[object, Type[object]]]

__len__()#

Returns the number of unique component keys this entity has relations for.

Return type:

int

__setitem__(_EntityComponentRelations__key, _EntityComponentRelations__values)#

Redefine the component relations for this entity.

..versionadded:: 4.2.0

Parameters:
Return type:

None

clear()#

Clears the relation components this entity directly has with other entities.

Does not clear relations targeting this entity.

Return type:

None

entity: Entity#
keys()#

Returns the components keys this entity has relations for.

Return type:

Set[Type[object] | Tuple[object, Type[object]]]

traverse: tuple[object, ...]#
class tcod.ecs.entity.EntityComponents(entity, traverse)#

Bases: MutableMapping[Union[Type[Any], Tuple[object, Type[Any]]], Any]

A proxy attribute to access an entities components like a dictionary.

See Entity.components.

Parameters:
__call__(*, traverse)#

Update this view with alternative parameters, such as a specific traversal relation.

New in version 5.0.

Parameters:

traverse (Iterable[object]) –

Return type:

Self

__contains__(key)#

Return True if this entity has the provided component.

Parameters:

key (Type[object] | Tuple[object, Type[object]]) –

Return type:

bool

__delitem__(key)#

Delete a directly held component from an entity.

Parameters:

key (type[object] | tuple[object, type[object]]) –

Return type:

None

__getitem__(key)#

Return a component belonging to this entity, or an indirect parent.

Parameters:

key (Type[T] | Tuple[object, Type[T]]) –

Return type:

T

__ior__(value: SupportsKeysAndGetItem[ComponentKey[Any], Any]) Self#
__ior__(value: Iterable[tuple[Type[Any] | Tuple[object, Type[Any]], Any]]) Self

Update components in-place.

New in version 3.4.

__iter__()#

Iterate over the component types belonging to this entity.

Return type:

Iterator[Type[Any] | Tuple[object, Type[Any]]]

__len__()#

Return the number of components belonging to this entity.

Return type:

int

__setitem__(key, value)#

Assign a component directly to an entity.

Parameters:
Return type:

None

by_name_type(name_type, component_type)#

Iterate over all of an entities component keys with a specific (name_type, component_type) combination.

New in version 3.0.

Deprecated since version 3.1: This method has been deprecated. Iterate over items instead.

Parameters:
  • name_type (type[_T1]) –

  • component_type (type[_T2]) –

Return type:

Iterator[tuple[_T1, type[_T2]]]

entity: Entity#
get(_EntityComponents__key, _EntityComponents__default=None)#

Return a component, returns None or a default value when the component is missing.

Parameters:
  • _EntityComponents__key (Type[T] | Tuple[object, Type[T]]) –

  • _EntityComponents__default (T | None) –

Return type:

T | None

keys()#

Return the components held by this entity, including inherited components.

Return type:

Set[Type[object] | Tuple[object, Type[object]]]

set(value, *, _stacklevel=1)#

Assign or overwrite a component, automatically deriving the key.

Deprecated since version 3.1: Setting values without an explicit key has been deprecated.

Parameters:
Return type:

None

setdefault(_EntityComponents__key, _EntityComponents__default)#

Assign a default value if a component is missing, then returns the current value.

Parameters:
  • _EntityComponents__key (Type[T] | Tuple[object, Type[T]]) –

  • _EntityComponents__default (T) –

Return type:

T

traverse: tuple[object, ...]#
update_values(values, *, _stacklevel=1)#

Add or overwrite multiple components inplace, deriving the keys from the values.

Deprecated since version 3.1: Setting values without an explicit key has been deprecated.

Parameters:
Return type:

None

class tcod.ecs.entity.EntityRelations(entity, traverse)#

Bases: MutableMapping[object, EntityRelationsMapping]

A proxy attribute to access entity relations like a dict of sets.

See Entity.relation_tags_many.

Parameters:
__call__(*, traverse)#

Update this view with alternative parameters, such as a specific traversal relation.

New in version 5.0.

Parameters:

traverse (Iterable[object]) –

Return type:

Self

__delitem__(key)#

Clear the relation tags of an entity.

This does not remove relation tags towards this entity.

Parameters:

key (object) –

Return type:

None

__getitem__(key)#

Return the relation mapping for a tag.

Parameters:

key (object) –

Return type:

EntityRelationsMapping

__iter__()#

Iterate over the unique relation tags of this entity.

Return type:

Iterator[Any]

__len__()#

Return the number of unique relation tags this entity has.

Return type:

int

__setitem__(key, values)#

Overwrite the targets of a relation tag with the new values.

Parameters:
Return type:

None

clear()#

Discard all tag relations from an entity.

Return type:

None

entity: Entity#
traverse: tuple[object, ...]#
class tcod.ecs.entity.EntityRelationsExclusive(entity, traverse)#

Bases: MutableMapping[object, Entity]

A proxy attribute to access entity relations exclusively.

See Entity.relation_tag.

Parameters:
__call__(*, traverse)#

Update this view with alternative parameters, such as a specific traversal relation.

New in version 5.0.

Parameters:

traverse (Iterable[object]) –

Return type:

Self

__delitem__(key)#

Clear the relation targets of a relation key.

Parameters:

key (object) –

Return type:

None

__getitem__(key)#

Return the relation target for a key.

If the relation has no target then raises KeyError. If the relation is not exclusive then raises ValueError.

Parameters:

key (object) –

Return type:

Entity

__iter__()#

Iterate over the keys of this entities relations.

Return type:

Iterator[Any]

__len__()#

Return the number of relations this entity has.

Return type:

int

__setitem__(key, target)#

Set a relation exclusively to a new target.

Parameters:
Return type:

None

clear()#

Discard all tag relations from an entity.

Return type:

None

entity: Entity#
traverse: tuple[object, ...]#
class tcod.ecs.entity.EntityRelationsMapping(entity, key, traverse)#

Bases: MutableSet[Entity]

A proxy attribute to access entity relation targets like a set.

See Entity.relation_tags_many.

Parameters:
__attrs_post_init__()#

Validate attributes.

Return type:

None

__contains__(target)#

Return True if this relation contains the given value.

Parameters:

target (Entity) –

Return type:

bool

__iter__()#

Iterate over this relation tags targets.

Return type:

Iterator[Entity]

__len__()#

Return the number of targets for this relation tag.

Return type:

int

add(target)#

Add a relation target to this tag.

Parameters:

target (Entity) –

Return type:

None

clear()#

Discard all targets for this tag relation.

Return type:

None

discard(target)#

Discard a directly held relation target from this tag.

Parameters:

target (Entity) –

Return type:

None

entity: Entity#
key: object#
remove(target)#

Remove a directly held relation target from this tag.

This will raise KeyError of only an indirect relation target exists.

Parameters:

target (Entity) –

Return type:

None

traverse: tuple[object, ...]#
class tcod.ecs.entity.EntityTags(entity, traverse)#

Bases: MutableSet[Any]

A proxy attribute to access an entities tags like a set.

See Entity.tags.

Parameters:
__call__(*, traverse)#

Update this view with alternative parameters, such as a specific traversal relation.

New in version 5.0.

Parameters:

traverse (Iterable[object]) –

Return type:

Self

__contains__(x)#

Return True if this entity has the given tag.

Parameters:

x (object) –

Return type:

bool

__ior__(other)#

Add tags in-place.

New in version 3.3.

Parameters:

other (Set[object]) –

Return type:

Self

__isub__(other)#

Remove tags in-place.

New in version 3.3.

Parameters:

other (Set[Any]) –

Return type:

Self

__iter__()#

Iterate over this entities tags.

Return type:

Iterator[Any]

__len__()#

Return the number of tags this entity has.

Return type:

int

add(tag)#

Add a tag to the entity.

Parameters:

tag (object) –

Return type:

None

discard(tag)#

Discard a tag directly held by an entity.

Parameters:

tag (object) –

Return type:

None

entity: Entity#
remove(tag)#

Remove a tag directly held by an entity.

Parameters:

tag (object) –

Return type:

None

traverse: tuple[object, ...]#

Tools for querying Registry objects.

class tcod.ecs.query.BoundQuery(registry, query=_Nothing.NOTHING)#

Bases: object

Collect a set of entities with the provided conditions.

This query is bound to a specific registry.

Parameters:
  • registry (Registry) –

  • query (_Query) –

__getitem__(key: tuple[Type[_T1] | Tuple[object, Type[_T1]]]) Iterable[tuple[_T1]]#
__getitem__(key: tuple[Type[_T1] | Tuple[object, Type[_T1]], Type[_T2] | Tuple[object, Type[_T2]]]) Iterable[tuple[_T1, _T2]]
__getitem__(key: tuple[Type[_T1] | Tuple[object, Type[_T1]], Type[_T2] | Tuple[object, Type[_T2]], Type[_T3] | Tuple[object, Type[_T3]]]) Iterable[tuple[_T1, _T2, _T3]]
__getitem__(key: tuple[Type[_T1] | Tuple[object, Type[_T1]], Type[_T2] | Tuple[object, Type[_T2]], Type[_T3] | Tuple[object, Type[_T3]], Type[_T4] | Tuple[object, Type[_T4]]]) Iterable[tuple[_T1, _T2, _T3, _T4]]
__getitem__(key: tuple[Type[_T1] | Tuple[object, Type[_T1]], Type[_T2] | Tuple[object, Type[_T2]], Type[_T3] | Tuple[object, Type[_T3]], Type[_T4] | Tuple[object, Type[_T4]], Type[_T5] | Tuple[object, Type[_T5]]]) Iterable[tuple[_T1, _T2, _T3, _T4, _T5]]
__getitem__(key: tuple[Type[object] | Tuple[object, Type[object]], ...]) Iterable[tuple[Any, ...]]

Collect components from a query.

__iter__()#

Iterate over the matching entities.

Return type:

Iterator[Entity]

all_of(components=(), *, tags=(), relations=(), traverse=(<IsA>, ), depth=None)#

Filter entities based on having all of the provided elements.

Parameters:
Return type:

Self

get_entities()#

Return entities matching the current query as a read-only set.

This is useful for post-processing the results of a query using set operations.

New in version 4.4.

Return type:

Set[Entity]

none_of(components=(), *, tags=(), relations=(), traverse=(<IsA>, ), depth=None)#

Filter entities based on having none of the provided elements.

Parameters:
Return type:

Self

registry: Registry#
property world: Registry#

Deprecated alias for registry.

Deprecated since version Unreleased: Use registry instead.

tcod.ecs.query.WorldQuery#

alias of BoundQuery

ECS callback management.

tcod.ecs.callbacks.register_component_changed(*, component)#

Return a decorator to register on-component-changed callback functions.

Example:

>>> import tcod.ecs.callbacks
>>> @tcod.ecs.callbacks.register_component_changed(component=int)
... def on_int_changed(entity: Entity, old: int | None, new: int | None) -> None:
...    if old is not None and new is not None:
...        print(f"int changed from {old} to {new}")
...    elif old is not None and new is None:
...        print(f"int value {old} was deleted")
...    else:
...        assert old is None and new is not None
...        print(f"int value {new} was added")
>>> entity.components[int] = 2
int value 2 was added
>>> entity.components[int] = 5
int changed from 2 to 5
>>> del entity.components[int]
int value 5 was deleted
>>> tcod.ecs.callbacks.unregister_component_changed(callback=on_int_changed, component=int)
Parameters:

component (Type[Any] | Tuple[object, Type[Any]]) –

Return type:

Callable[[_OnComponentChangedFuncT], _OnComponentChangedFuncT]

tcod.ecs.callbacks.unregister_component_changed(callback, *, component)#

Unregister a registered on-component-changed callback function.

Parameters:
  • callback (_OnComponentChangedFunc[_T]) –

  • component (ComponentKey[_T]) –

Return type:

None

Special constants and sentinel values.

tcod.ecs.constants.IsA: Final = <IsA>#

The default is-a relationship tag used for entity inheritance.

Common type-hints for tcod.ecs.

tcod.ecs.typing.ComponentKey#

ComponentKey is plain type or tuple (tag, type).

alias of Union[Type[_T], Tuple[object, Type[_T]]]