summaryrefslogtreecommitdiff
path: root/client/lib/Game.ts
blob: d6ffb47599539fc89d42af3e916a2fb88c9ea9bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { Entity } from "./entities";
import { System } from "./systems";

export class Game {
  private entities: Map<number, Entity>;
  private systems: Map<string, System>;
  private systemOrder: string[];

  private running: boolean;
  private lastTimeStamp: number;

  constructor() {
    this.running = false;
    this.systemOrder = [];
    this.systems = new Map();
    this.entities = new Map();
  }

  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;

    const componentEntities = new Map<string, Set<number>>();
    this.entities.forEach((entity) =>
      entity.getComponents().forEach((component) => {
        if (!componentEntities.has(component.name)) {
          componentEntities.set(component.name, new Set<number>([entity.id]));
          return;
        }
        componentEntities.get(component.name).add(entity.id);
      })
    );

    this.systemOrder.forEach((systemName) => {
      this.systems.get(systemName).update(dt, this.entities, componentEntities);
    });
  };
}