2023-07-19 23:38:24 -04:00
|
|
|
import { Entity } from "./entities";
|
|
|
|
import { System } from "./systems";
|
|
|
|
|
|
|
|
export class Game {
|
|
|
|
private systemOrder: string[];
|
|
|
|
|
|
|
|
private running: boolean;
|
|
|
|
private lastTimeStamp: number;
|
|
|
|
|
2023-07-20 23:47:32 -04:00
|
|
|
public entities: Map<number, Entity>;
|
|
|
|
public systems: Map<string, System>;
|
|
|
|
public componentEntities: Map<string, Set<number>>;
|
|
|
|
|
2023-07-19 23:38:24 -04:00
|
|
|
constructor() {
|
|
|
|
this.running = false;
|
|
|
|
this.systemOrder = [];
|
|
|
|
this.systems = new Map();
|
|
|
|
this.entities = new Map();
|
2023-07-20 23:47:32 -04:00
|
|
|
this.componentEntities = new Map();
|
2023-07-19 23:38:24 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
public start() {
|
|
|
|
this.lastTimeStamp = performance.now();
|
|
|
|
this.running = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public addEntity(entity: Entity) {
|
|
|
|
this.entities.set(entity.id, entity);
|
|
|
|
}
|
|
|
|
|
|
|
|
public getEntity(id: number): Entity {
|
|
|
|
return this.entities.get(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
public removeEntity(id: number) {
|
|
|
|
this.entities.delete(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
public addSystem(system: System) {
|
|
|
|
if (!this.systemOrder.includes(system.name)) {
|
|
|
|
this.systemOrder.push(system.name);
|
|
|
|
}
|
|
|
|
this.systems.set(system.name, system);
|
|
|
|
}
|
|
|
|
|
|
|
|
public getSystem(name: string): System {
|
|
|
|
return this.systems.get(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
public doGameLoop = (timeStamp: number) => {
|
|
|
|
if (!this.running) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const dt = timeStamp - this.lastTimeStamp;
|
|
|
|
this.lastTimeStamp = timeStamp;
|
|
|
|
|
2023-07-20 23:47:32 -04:00
|
|
|
this.componentEntities.clear();
|
2023-07-19 23:38:24 -04:00
|
|
|
this.entities.forEach((entity) =>
|
|
|
|
entity.getComponents().forEach((component) => {
|
2023-07-20 23:47:32 -04:00
|
|
|
if (!this.componentEntities.has(component.name)) {
|
|
|
|
this.componentEntities.set(
|
|
|
|
component.name,
|
|
|
|
new Set<number>([entity.id])
|
|
|
|
);
|
2023-07-19 23:38:24 -04:00
|
|
|
return;
|
|
|
|
}
|
2023-07-20 23:47:32 -04:00
|
|
|
this.componentEntities.get(component.name).add(entity.id);
|
2023-07-19 23:38:24 -04:00
|
|
|
})
|
|
|
|
);
|
|
|
|
|
|
|
|
this.systemOrder.forEach((systemName) => {
|
2023-07-20 23:47:32 -04:00
|
|
|
this.systems.get(systemName).update(dt, this);
|
2023-07-19 23:38:24 -04:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|