summaryrefslogtreecommitdiff
path: root/src/engine/TheAbstractionEngine.ts
blob: e720293ada1cb7e5f4ccab2dc80174a221be8051 (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
import { Game } from ".";
import { loadAssets } from "./config";
import { Player } from "./entities";
import { Render } from "./systems";

export class TheAbstractionEngine {
  private game: Game;
  private ctx: CanvasRenderingContext2D;
  private animationFrameId: number | null;

  constructor(game: Game, ctx: CanvasRenderingContext2D) {
    this.game = game;
    this.ctx = ctx;
    this.animationFrameId = null;
  }

  public async init() {
    await loadAssets();

    [new Render(this.ctx)].forEach((system) => this.game.addSystem(system));

    const player = new Player();
    this.game.addEntity(player);
  }

  public play() {
    this.game.start();

    const loop = (timestamp: number) => {
      this.game.doGameLoop(timestamp);
      this.animationFrameId = requestAnimationFrame(loop); // tail call recursion! /s
    };
    this.animationFrameId = requestAnimationFrame(loop);
  }

  public stop() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
  }
}