GAME ENTITY (ECS)
game-entity.ts
Entity Component System with component stores, systems, and object pooling.
StarkWHAT THIS PATTERN TEACHES
How to organize game objects using the Entity Component System pattern — entities are IDs, components are data, systems are behavior.
WHEN TO USE THIS
Games with many entities that share behaviors (bullets, enemies, particles, NPCs).
AT A GLANCE
class World {
createEntity(): number {
return this.nextId++
}
addComponent<T>(entity: number, type: string, data: T) {
this.stores[type].set(entity, data)
}
}FRAMEWORK IMPLEMENTATIONS
TypeScript
type Entity = number;
class World {
private nextId = 0;
private stores: Map<string, Map<Entity, unknown>> = new Map();
createEntity(): Entity {
return this.nextId++;
}
addComponent<T>(entity: Entity, type: string, data: T) {
if (!this.stores.has(type)) this.stores.set(type, new Map());
this.stores.get(type)!.set(entity, data);
}
query(...types: string[]): Entity[] {
const [first, ...rest] = types;
const candidates = [...(this.stores.get(first)?.keys() ?? [])];
return candidates.filter(e =>
rest.every(t => this.stores.get(t)?.has(e))