feat: add GameContainer Phaser-React bridge

This commit is contained in:
2026-04-07 21:10:15 +07:00
parent a6ea58703a
commit 818e17e9dc
2 changed files with 65 additions and 2 deletions
+11 -2
View File
@@ -1,8 +1,9 @@
import { useState, useRef } from "react";
import { useState, useRef, useCallback } from "react";
import { Difficulty } from "../types";
import { GameStateManager } from "../game/state";
import { Menu } from "./Menu";
import { DifficultySelect } from "./DifficultySelect";
import { GameContainer } from "./GameContainer";
type Screen = "menu" | "difficulty" | "game" | "gameover";
@@ -17,6 +18,10 @@ function App() {
setScreen("game");
};
const handleGameOver = useCallback(() => {
setScreen("gameover");
}, []);
return (
<div style={{ textAlign: "center" }}>
{screen === "menu" && (
@@ -29,7 +34,11 @@ function App() {
/>
)}
{screen === "game" && (
<div>Game placeholder {difficulty}</div>
<GameContainer
difficulty={difficulty}
stateManager={stateManager}
onGameOver={handleGameOver}
/>
)}
{screen === "gameover" && (
<div>Game Over placeholder</div>
+54
View File
@@ -0,0 +1,54 @@
import { useEffect, useRef } from "react";
import Phaser from "phaser";
import { createPhaserConfig } from "../phaser/config";
import { Difficulty } from "../types";
import { GameStateManager } from "../game/state";
interface GameContainerProps {
difficulty: Difficulty;
stateManager: GameStateManager;
onGameOver: () => void;
}
export function GameContainer({ difficulty, stateManager, onGameOver }: GameContainerProps) {
const containerRef = useRef<HTMLDivElement>(null);
const gameRef = useRef<Phaser.Game | null>(null);
useEffect(() => {
if (!containerRef.current) return;
const config = createPhaserConfig(containerRef.current, 800, 600);
const game = new Phaser.Game(config);
gameRef.current = game;
// Pass data to Phaser scenes via the registry
game.registry.set("difficulty", difficulty);
game.registry.set("stateManager", stateManager);
// Listen for game over
const handleStateChange = () => {
const state = stateManager.getState();
if (state.status === "won" || state.status === "lost") {
onGameOver();
}
};
stateManager.on("stateChange", handleStateChange);
return () => {
stateManager.off("stateChange", handleStateChange);
game.destroy(true);
gameRef.current = null;
};
}, [difficulty, stateManager, onGameOver]);
return (
<div
ref={containerRef}
style={{
width: "800px",
height: "600px",
margin: "0 auto",
}}
/>
);
}