summaryrefslogtreecommitdiff
path: root/src/components/GameCanvas.tsx
blob: 18dd52eb8fdb8d4893379a67505ca793fda62207 (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
import { useState, useEffect, useRef } from "react";
import { TheAbstractionEngine, Game } from "../engine";
import { Miscellaneous } from "../engine/config";
import { Title } from "./Title";

export interface GameCanvasProps {
  width: number;
  height: number;
}

export const GameCanvas = ({ width, height }: GameCanvasProps) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [game, setGame] = useState<TheAbstractionEngine>();
  const [ready, setReady] = useState(true); // false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (canvasRef.current && !game) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext("2d");
      if (ctx) {
        const game = new Game();
        const theAbstractionEngine = new TheAbstractionEngine(game, ctx);

        theAbstractionEngine.init().then(() => {
          theAbstractionEngine.play();
          canvas.focus();

          setGame(theAbstractionEngine);
          setLoading(false);
        });

        return () => theAbstractionEngine.stop();
      }
    }
  }, [canvasRef, ready]);

  if (ready) {
    return (
      <div className="centered-game">
        <canvas
          id={Miscellaneous.CANVAS_ID}
          tabIndex={1}
          ref={canvasRef}
          width={loading ? 50 : width}
          height={loading ? 50 : height}
        ></canvas>
        {loading && <span className="loading">Loading...</span>}
      </div>
    );
  }

  return (
    <div className="centered-game">
      <Title setReady={setReady} />
    </div>
  );
};