slime/src/core/Entity.ts
2026-01-06 23:25:33 -05:00

82 lines
1.9 KiB
TypeScript

import { Component } from './Component.ts';
/**
* Entity class - represents a game object with a unique ID.
* Entities are containers for components.
*/
export class Entity {
private static nextId = 0;
readonly id: number;
private components: Map<string, Component>;
active: boolean;
owner?: number;
startX?: number;
startY?: number;
maxRange?: number;
lifetime?: number;
damage?: number;
deathTime?: number;
constructor() {
this.id = Entity.nextId++;
this.components = new Map();
this.active = true;
}
/**
* Add a component to this entity.
* @param component - The component to add
* @returns This entity for chaining
*/
addComponent(component: Component): Entity {
this.components.set(component.type, component);
return this;
}
/**
* Get a component by type.
* @param type - The component type name
* @returns The component instance if found
*/
getComponent<T extends Component>(type: string): T | undefined {
return this.components.get(type) as T | undefined;
}
/**
* Check if entity has a component.
* @param type - The component type name
* @returns True if the component exists
*/
hasComponent(type: string): boolean {
return this.components.has(type);
}
/**
* Check if entity has all specified components.
* @param types - List of component type names
* @returns True if all components exist
*/
hasComponents(...types: string[]): boolean {
return types.every((type) => this.components.has(type));
}
/**
* Remove a component.
* @param type - The component type name
* @returns This entity for chaining
*/
removeComponent(type: string): Entity {
this.components.delete(type);
return this;
}
/**
* Get all components attached to this entity.
* @returns Array of components
*/
getAllComponents(): Component[] {
return Array.from(this.components.values());
}
}