File size: 2,260 Bytes
32e1e21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
import Phaser from "phaser";
import { PixelCityScene } from "./PixelCityScene";
import { demoNew } from "../evgrid/api";

type StartArgs = {
  mountId: string;
  statusEl: HTMLPreElement;
  eventEl: HTMLPreElement;
  btnNew: HTMLButtonElement;
  btnStep: HTMLButtonElement;
  btnRun: HTMLButtonElement;
  modeEl: HTMLSelectElement;
  followEl: HTMLInputElement;
  loraEl: HTMLInputElement;
};

export function startGame(args: StartArgs) {
  const mount = document.getElementById(args.mountId);
  if (!mount) throw new Error(`Mount element not found: ${args.mountId}`);

  const ui = {
    statusEl: args.statusEl,
    eventEl: args.eventEl,
    modeEl: args.modeEl,
    followEl: args.followEl,
    loraEl: args.loraEl,
  };

  const config: Phaser.Types.Core.GameConfig = {
    type: Phaser.AUTO,
    parent: mount,
    width: 1280,
    height: 720,
    backgroundColor: "#070911",
    pixelArt: true,
    antialias: false,
    physics: { default: "arcade" },
    scale: {
      mode: Phaser.Scale.FIT,
      autoCenter: Phaser.Scale.CENTER_BOTH,
    },
    scene: [PixelCityScene],
  };

  const game = new Phaser.Game(config);
  game.scene.start("PixelCityScene", { ui });
  const scene = () => game.scene.getScene("PixelCityScene") as PixelCityScene;

  const seedRand = () => Math.floor(Math.random() * 10_000);

  args.btnNew.onclick = async () => {
    try {
      const res = await demoNew(seedRand());
      await scene().bindSession(res.session_id, res.station_nodes);
    } catch (e: any) {
      ui.statusEl.textContent = String(e?.message || e);
    }
  };

  args.btnStep.onclick = async () => {
    try {
      await scene().stepOnce();
    } catch (e: any) {
      ui.statusEl.textContent = String(e?.message || e);
    }
  };

  args.btnRun.onclick = async () => {
    try {
      for (let i = 0; i < 60; i++) {
        // eslint-disable-next-line no-await-in-loop
        await scene().stepOnce();
        // brief pacing so camera movement is visible
        // eslint-disable-next-line no-await-in-loop
        await new Promise((r) => setTimeout(r, 90));
      }
    } catch (e: any) {
      ui.statusEl.textContent = String(e?.message || e);
    }
  };
}