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

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);
        });

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

  return (
    <div className="centered-game">
      <canvas ref={canvasRef} width={width} height={height}></canvas>
    </div>
  );
};