jumpstorm/engine/entities/Entity.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-08-25 18:48:17 -04:00
import { EntityNames, Player } from '.';
import type { Component } from '../components';
2023-07-19 23:38:24 -04:00
export abstract class Entity {
2023-08-23 21:44:59 -04:00
public id: string;
public components: Map<string, Component>;
public name: string;
2023-07-19 23:38:24 -04:00
2023-08-23 21:44:59 -04:00
constructor(name: string, id: string = crypto.randomUUID()) {
this.name = name;
this.id = id;
2023-07-19 23:38:24 -04:00
this.components = new Map();
}
public addComponent(component: Component) {
this.components.set(component.name, component);
}
public getComponent<T extends Component>(name: string): T {
if (!this.hasComponent(name)) {
2023-08-25 18:48:17 -04:00
throw new Error('Entity does not have component ' + name);
2023-07-19 23:38:24 -04:00
}
return this.components.get(name) as T;
}
public getComponents(): Component[] {
return Array.from(this.components.values());
}
public hasComponent(name: string): boolean {
return this.components.has(name);
}
2023-08-23 21:44:59 -04:00
static from(entityName: string, args: any): Entity {
switch (entityName) {
case EntityNames.Player:
2023-08-25 18:48:17 -04:00
const player = new Player(args.playerId);
player.id = args.id;
return player;
2023-08-23 21:44:59 -04:00
default:
2023-08-25 18:48:17 -04:00
throw new Error('.from() Entity type not implemented: ' + entityName);
2023-08-23 21:44:59 -04:00
}
}
2023-07-19 23:38:24 -04:00
}