Elizabeth Hunt 07f508365f
Some checks failed
continuous-integration/drone Build is failing
add carcadr level
2025-03-01 15:31:27 -07:00

61 lines
1.6 KiB
TypeScript

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>();
// TODO: go back to this after done
// const [ready, setReady] = useState(false);
const [ready, setReady] = useState(document.location.hostname.includes("localhost"));
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>
);
};