import { useEffect } from "react"; import { useAudio } from "../lib/stores/useAudio"; import { useGame } from "../lib/stores/useGame"; import { useCabbages } from "../lib/stores/useCabbages"; import Ground from "./Ground"; import Player from "./Player"; import Cabbage from "./Cabbage"; import GameUI from "./GameUI"; import WinScreen from "./WinScreen"; import { Perf } from "r3f-perf"; // Main game component const Game = () => { const { phase, start, restart } = useGame(); const { backgroundMusic, toggleMute, isMuted } = useAudio(); const { cabbages, resetCabbages } = useCabbages(); // Handle game restart const handleRestart = () => { resetCabbages(); restart(); start(); }; // Start background music when game starts useEffect(() => { if (phase === "playing" && backgroundMusic && !isMuted) { backgroundMusic.play().catch((error) => { console.log("Background music play prevented:", error); }); } return () => { if (backgroundMusic) { backgroundMusic.pause(); } }; }, [phase, backgroundMusic, isMuted]); // Generate cabbage positions - only run once on component mount useEffect(() => { console.log("Initializing cabbages"); // Clear any existing cabbages resetCabbages(); }, []); // Empty dependency array means this runs once on mount // Check if we need to generate more cabbages useEffect(() => { // If we don't have exactly 10 cabbages and we're in playing phase, reset if (cabbages.length !== 10 && phase === "playing") { console.log(`Found ${cabbages.length} cabbages, ensuring we have all 10`); resetCabbages(); } // Log the number of cabbages created for debugging console.log("Current cabbages:", cabbages.length); }, [cabbages.length, phase, resetCabbages]); // Start the game automatically useEffect(() => { if (phase === "ready") { start(); } }, [phase, start]); return ( <> {/* Performance monitor in dev mode */} {process.env.NODE_ENV === "development" && } {/* Game environment */} {/* Game world */} {/* Render cabbages based on their positions */} {cabbages.map((cabbage) => ( ))} {/* UI Components */} {phase === "ended" && } ); }; export default Game;