59 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-03-01 18:56:58 -07:00
import { useState, useEffect, useRef } from "react";
import { TheAbstractionEngine, Game } from "../engine";
2024-03-02 06:00:47 -07:00
import { Miscellaneous } from "../engine/config";
import { Title } from "./Title";
2024-03-01 16:31:27 -07:00
export interface GameCanvasProps {
width: number;
height: number;
}
export const GameCanvas = ({ width, height }: GameCanvasProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
2024-03-02 01:07:55 -07:00
const [game, setGame] = useState<TheAbstractionEngine>();
const [ready, setReady] = useState(false);
const [loading, setLoading] = useState(true);
2024-03-01 18:56:58 -07:00
useEffect(() => {
2024-03-02 01:07:55 -07:00
if (canvasRef.current && !game) {
2024-03-01 18:56:58 -07:00
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();
2024-03-02 06:00:47 -07:00
canvas.focus();
setGame(theAbstractionEngine);
setLoading(false);
2024-03-01 18:56:58 -07:00
});
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>
);
}
2024-03-01 16:31:27 -07:00
return (
<div className="centered-game">
<Title setReady={setReady} />
2024-03-01 16:31:27 -07:00
</div>
);
};