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

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

export const GameCanvas = ({ width, height }: GameCanvasProps) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [game, setGame] = useState<TheAbstractionEngine>();

  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();
          setGame(theAbstractionEngine);

          canvas.focus();
        });

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

  return (
    <div className="centered-game">
      <canvas
        id={Miscellaneous.CANVAS_ID}
        tabIndex={1}
        ref={canvasRef}
        width={width}
        height={height}
      ></canvas>
    </div>
  );
};