jumpstorm/engine/entities/Entity.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-08-26 19:55:27 -04:00
import { EntityNames, Floor, Player } from '.';
import { type Component } from '../components';
const randomId = () =>
(performance.now() + Math.random() * 10_000_000).toString();
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-26 19:55:27 -04:00
constructor(name: string, id: string = randomId()) {
2023-08-23 21:44:59 -04:00
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
2023-08-26 19:55:27 -04:00
public static from(entityName: string, id: string, args: any): Entity {
let entity: Entity;
2023-08-23 21:44:59 -04:00
switch (entityName) {
case EntityNames.Player:
2023-08-26 19:55:27 -04:00
const player = new Player();
player.setFrom(args);
entity = player;
break;
case EntityNames.Floor:
const floor = new Floor(args.floorWidth);
floor.setFrom(args);
entity = floor;
break;
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-08-26 19:55:27 -04:00
entity.id = id;
return entity;
2023-08-23 21:44:59 -04:00
}
2023-08-26 19:55:27 -04:00
public abstract setFrom(args: Record<string, any>): void;
public abstract serialize(): Record<string, any>;
2023-07-19 23:38:24 -04:00
}