1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
from enum import Enum
from kennel.engine.components.component import Component, ComponentType
from typing import List, Optional
class EntityType(str, Enum):
LASER = "LASER"
class Entity:
def __init__(
self, entity_type: EntityType, id: str, component_list: List[Component]
):
self.entity_type = entity_type
self.id = id
self.components = {}
for component in component_list:
self.add_component(component)
def get_component(self, component_type: ComponentType) -> Optional[Component]:
return self.components[component_type]
def add_component(self, component: Component) -> None:
self.components[component.component_type] = component
class EntityManager:
def __init__(self):
self.entities = {}
self.component_entities = {}
def update(self) -> None:
self.component_entities = {}
for entity in self.entities.values():
for component in entity.components.values():
if component.component_type not in self.component_entities:
self.component_entities[component.component_type] = set()
self.component_entities[component.component_type].add(entity)
def get_entities_with_component(
self, component_type: ComponentType
) -> List[Entity]:
return self.component_entities.get(component_type, [])
def add_entity(self, entity: Entity) -> None:
self.entities[entity.id] = entity
for component in entity.components.values():
if component.component_type not in self.component_entities:
self.component_entities[component.component_type] = set()
self.component_entities[component.component_type].add(entity)
def remove_entity(self, entity_id: str) -> None:
if entity_id in self.entities:
entity = self.entities[entity_id]
for component in entity.components.values():
if component.component_type in self.component_entities:
self.component_entities[component.component_type].remove(entity)
def get_entity(self, entity_id: str) -> Optional[Entity]:
return self.entities.get(entity_id)
|