jumpstorm/engine/Game.ts

91 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-08-25 18:48:17 -04:00
import { Entity } from './entities';
import { System } from './systems';
2023-07-19 23:38:24 -04:00
export class Game {
private systemOrder: string[];
private running: boolean;
private lastTimeStamp: number;
public entities: Map<string, Entity>;
public systems: Map<string, System>;
public componentEntities: Map<string, Set<string>>;
2023-07-19 23:38:24 -04:00
constructor() {
2023-08-12 15:49:16 -04:00
this.lastTimeStamp = performance.now();
2023-07-19 23:38:24 -04:00
this.running = false;
this.systemOrder = [];
this.systems = new Map();
this.entities = new Map();
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: string): Entity | undefined {
2023-07-19 23:38:24 -04:00
return this.entities.get(id);
}
public removeEntity(id: string) {
2023-07-19 23:38:24 -04:00
this.entities.delete(id);
}
2023-08-12 15:49:16 -04:00
public forEachEntityWithComponent(
componentName: string,
2023-08-25 18:48:17 -04:00
callback: (entity: Entity) => void
2023-08-12 15:49:16 -04:00
) {
this.componentEntities.get(componentName)?.forEach((entityId) => {
const entity = this.getEntity(entityId);
if (!entity) return;
callback(entity);
});
}
2023-07-19 23:38:24 -04:00
public addSystem(system: System) {
if (!this.systemOrder.includes(system.name)) {
this.systemOrder.push(system.name);
}
this.systems.set(system.name, system);
}
public getSystem<T>(name: string): T {
return this.systems.get(name) as unknown as T;
2023-07-19 23:38:24 -04:00
}
2023-08-23 21:44:59 -04:00
public doGameLoop(timeStamp: number) {
2023-07-19 23:38:24 -04:00
if (!this.running) {
return;
}
const dt = timeStamp - this.lastTimeStamp;
this.lastTimeStamp = timeStamp;
2023-07-21 01:22:26 -04:00
// rebuild the Component -> { Entity } map
this.componentEntities.clear();
2023-07-19 23:38:24 -04:00
this.entities.forEach((entity) =>
entity.getComponents().forEach((component) => {
if (!this.componentEntities.has(component.name)) {
this.componentEntities.set(
component.name,
2023-08-25 18:48:17 -04:00
new Set<string>([entity.id])
);
2023-07-19 23:38:24 -04:00
return;
}
2023-08-12 15:49:16 -04:00
this.componentEntities.get(component.name)?.add(entity.id);
2023-08-25 18:48:17 -04:00
})
2023-07-19 23:38:24 -04:00
);
this.systemOrder.forEach((systemName) => {
2023-08-12 15:49:16 -04:00
this.systems.get(systemName)?.update(dt, this);
2023-07-19 23:38:24 -04:00
});
2023-08-23 21:44:59 -04:00
}
2023-07-19 23:38:24 -04:00
}