import React, { useState, useEffect } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
import { renderToString } from "https://esm.sh/react-dom/server";
const Hexagon = ({ x, y, size, fill, onClick, isEdge }) => {
const points = [];
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 3) * i;
points.push(`${x + size * Math.cos(angle)},${y + size * Math.sin(angle)}`);
}
return (
<polygon
points={points.join(" ")}
fill={fill}
stroke={isEdge ? "red" : "black"}
strokeWidth={isEdge ? "3" : "1"}
onClick={onClick}
/>
);
};
function Game() {
const gridSize = 5;
const hexSize = 30;
const [grid, setGrid] = useState([]);
const [catPosition, setCatPosition] = useState(null);
const [gameStatus, setGameStatus] = useState("playing");
const initializeGame = () => {
const newGrid = [];
for (let q = -gridSize; q <= gridSize; q++) {
for (let r = Math.max(-gridSize, -q - gridSize); r <= Math.min(gridSize, -q + gridSize); r++) {
const s = -q - r;
const isEdge = Math.abs(q) === gridSize || Math.abs(r) === gridSize || Math.abs(s) === gridSize;
newGrid.push({ q, r, s, state: "empty", isEdge });
}
}
setGrid(newGrid);
const centerHex = newGrid.find(h => h.q === 0 && h.r === 0 && h.s === 0);
setCatPosition(centerHex);
setGameStatus("playing");
};
useEffect(initializeGame, []);
const cubeToPixel = (q, r) => {
const x = hexSize * (3/2 * q);
const y = hexSize * (Math.sqrt(3)/2 * q + Math.sqrt(3) * r);
return { x, y };
};
const checkCatEscape = () => {
return catPosition && catPosition.isEdge;
};
const moveCat = () => {
if (gameStatus !== "playing") return;
const neighbors = [
{ q: 1, r: 0, s: -1 }, { q: 1, r: -1, s: 0 }, { q: 0, r: -1, s: 1 },
{ q: -1, r: 0, s: 1 }, { q: -1, r: 1, s: 0 }, { q: 0, r: 1, s: -1 }
];
const possibleMoves = neighbors
.map(n => ({ q: catPosition.q + n.q, r: catPosition.r + n.r, s: catPosition.s + n.s }))
.filter(pos => {
const hex = grid.find(h => h.q === pos.q && h.r === pos.r && h.s === pos.s);
return hex && hex.state === "empty";
});
if (possibleMoves.length === 0) {
setGameStatus("playerWin");
return;
}
const newPos = possibleMoves.reduce((closest, move) => {
const closestEdgeDist = Math.min(
gridSize - Math.abs(closest.q),
gridSize - Math.abs(closest.r),
gridSize - Math.abs(closest.s)
);
const moveDist = Math.min(
gridSize - Math.abs(move.q),
gridSize - Math.abs(move.r),
gridSize - Math.abs(move.s)
);
return moveDist < closestEdgeDist ? move : closest;
});
const newCatPosition = grid.find(h => h.q === newPos.q && h.r === newPos.r && h.s === newPos.s);
setCatPosition(newCatPosition);