Skip to content

Commit

Permalink
add shortcut to get component
Browse files Browse the repository at this point in the history
  • Loading branch information
chromy committed Oct 19, 2015
1 parent 7dada27 commit e424d22
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 5 deletions.
2 changes: 1 addition & 1 deletion essence/__init__.py
@@ -1,4 +1,4 @@
from .world import World, NoSuchComponentError, DuplicateComponentError
from .entity import Entity
from .entity import Entity, UnregisteredComponentError
from .component import Component
from .system import System
11 changes: 11 additions & 0 deletions essence/entity.py
Expand Up @@ -66,6 +66,14 @@ def destroy(self, *args, **kargs):
"""
return self.world.destroy_entitiy(self, *args, **kargs)

def __getattr__(self, name):
try:
component_type = self.world.registry[name]
except KeyError:
raise UnregisteredComponentError()
else:
return self.get(component_type)

def __eq__(self, other):
return self.world is other.world and self.uid == other.uid

Expand All @@ -78,4 +86,7 @@ def __repr__(self):
def __lt__(self, other):
return self.uid < other.uid

class UnregisteredComponentError(KeyError):
pass


6 changes: 4 additions & 2 deletions essence/world.py
Expand Up @@ -13,6 +13,7 @@ def __init__(self):
self._entities = []
self._entities_by_component = {}
self.systems = []
self.registry = {}

def _get_relation(self, component_type):
try:
Expand Down Expand Up @@ -138,10 +139,11 @@ def update(self, *args, **kwargs):
for system in self.systems:
system.update(self, *args, **kwargs)

def register(self, name, component_type):
self.registry[name] = component_type

class DuplicateComponentError(Exception):
pass

class NoSuchComponentError(KeyError):
pass


1 change: 0 additions & 1 deletion tests/test_entity.py
Expand Up @@ -36,4 +36,3 @@ def test_equilivent_entities_are_equal():
assert alice != bob
assert mars_alice != mars_bob


14 changes: 13 additions & 1 deletion tests/test_shortcuts.py
@@ -1,6 +1,8 @@
from essence import World, System, Component
from essence import World, System, Component, UnregisteredComponentError
from fixtures import world

import pytest

def xtest_there_is_a_global_world_instance():
from essence.base import world

Expand All @@ -18,4 +20,14 @@ def test_entity_shorthand(world):
entity.destroy()
assert entity not in world.entities

def test_shortcut_for_registered_components(world):
world.register('component', Component)
c = Component()
e = world.create_entity()
e.add(c)
assert e.component == c

def test_fails_on_unregistered_components(world):
e = world.create_entity()
with pytest.raises(UnregisteredComponentError):
e.component

0 comments on commit e424d22

Please sign in to comment.