Created
January 28, 2019 16:38
-
-
Save ItsMeThom-zz/f4414cb2a8723a2ce8aedc70dcc4ad6d to your computer and use it in GitHub Desktop.
ECS prototype in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Entity: | |
| def __init__(self, name, *components): | |
| self.components = {} | |
| self.name = name | |
| for component in components: | |
| component.entity = self | |
| self.components[type(component)] = components | |
| def __str__(self): | |
| return self.name | |
| def __repr__(self): | |
| return self.__str__() | |
| def has(self, component_type): | |
| return self.components[component_type] is not None | |
| def get(self, component_type): | |
| return self.components.get(component_type) | |
| def add(self, component): | |
| component.entity = self | |
| self.components[type(component)] = component | |
| def remove(self, component_type): | |
| self.components.pop(component_type) | |
| class Component: | |
| def __init__(self, parent=None): | |
| self.parent = parent | |
| class Position(Component): | |
| x = 0 | |
| y = 0 | |
| def __init__(self, x, y): | |
| self.x =x | |
| self.y = y | |
| class Flammable(Component): | |
| pass | |
| class Burning(Component): | |
| pass | |
| class Health(Component): | |
| hp = 0 | |
| def __init__(self, hp=0): | |
| super().__init__() | |
| self.hp = hp | |
| def reduce(self, value): | |
| self.hp -= value | |
| def increase(self, value): | |
| self.hp += value | |
| class World: | |
| def __init__(self): | |
| self.components = [] | |
| self.entities = [] | |
| def add_entity(self, entity): | |
| self.entities.append(entity) | |
| # add components to list also? | |
| for component in entity.components: | |
| self.components.append(component) | |
| class System: | |
| def get_entities(self, component_list, component_type): | |
| return {c.parent: c for c in component_list if isinstance(c, component_type)} | |
| def update(self, component_list): | |
| pass | |
| class BurningSystem(System): | |
| def update(self, component_list): | |
| print("Getting all entities with flammable components") | |
| on_fire = self.get_entities(component_list, Burning) | |
| for entity in on_fire: | |
| print(entity) | |
| if entity.has(Health): | |
| entity.get(Health).reduce(10) | |
| wood_log = Entity("Wood Log", | |
| [ | |
| Flammable(), | |
| Health(hp=20), | |
| Position(x=1,y=1) | |
| ]) | |
| world = World() | |
| burner = BurningSystem() | |
| burner.update(world.components) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment