summaryrefslogtreecommitdiff
path: root/src/engine/Game.ts
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-03-01 18:56:58 -0700
committerElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-03-01 18:56:58 -0700
commita8d07a790395e14fe7aedd3ba638db466f9c0842 (patch)
tree644f60a6bca79ceb55f24fcab7bdb3dee52c2d6e /src/engine/Game.ts
parentaa08a8943a9a2d4a0e51893eebe6900bca7a7251 (diff)
downloadthe-abstraction-engine-a8d07a790395e14fe7aedd3ba638db466f9c0842.tar.gz
the-abstraction-engine-a8d07a790395e14fe7aedd3ba638db466f9c0842.zip
boundingbox + draw player
Diffstat (limited to 'src/engine/Game.ts')
-rw-r--r--src/engine/Game.ts90
1 files changed, 90 insertions, 0 deletions
diff --git a/src/engine/Game.ts b/src/engine/Game.ts
new file mode 100644
index 0000000..2df9f17
--- /dev/null
+++ b/src/engine/Game.ts
@@ -0,0 +1,90 @@
+import { Entity } from "./entities";
+import { System } from "./systems";
+
+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>>;
+
+ constructor() {
+ this.lastTimeStamp = performance.now();
+ this.running = false;
+ this.systemOrder = [];
+ this.systems = new Map();
+ this.entities = new Map();
+ this.componentEntities = new Map();
+ }
+
+ 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 {
+ return this.entities.get(id);
+ }
+
+ public removeEntity(id: string) {
+ this.entities.delete(id);
+ }
+
+ public forEachEntityWithComponent(
+ componentName: string,
+ callback: (entity: Entity) => void,
+ ) {
+ this.componentEntities.get(componentName)?.forEach((entityId) => {
+ const entity = this.getEntity(entityId);
+ if (!entity) return;
+
+ callback(entity);
+ });
+ }
+
+ 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;
+ }
+
+ public doGameLoop(timeStamp: number) {
+ if (!this.running) {
+ return;
+ }
+
+ const dt = timeStamp - this.lastTimeStamp;
+ this.lastTimeStamp = timeStamp;
+
+ // rebuild the Component -> { Entity } map
+ this.componentEntities.clear();
+ this.entities.forEach((entity) =>
+ entity.getComponents().forEach((component) => {
+ if (!this.componentEntities.has(component.name)) {
+ this.componentEntities.set(
+ component.name,
+ new Set<string>([entity.id]),
+ );
+ return;
+ }
+ this.componentEntities.get(component.name)?.add(entity.id);
+ }),
+ );
+
+ this.systemOrder.forEach((systemName) => {
+ this.systems.get(systemName)?.update(dt, this);
+ });
+ }
+}