Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x | import React, { useEffect, useRef, useState } from 'react'; import { useParams, useLocation } from 'react-router-dom'; import { PhaserGame, IRefPhaserGame } from '../../PhaserGame'; import { useWebSocket } from '../../contexts/WebSocketContext'; import { AacFood, AacVerb } from '../../Foods'; import { EventBus } from '../../game/EventBus'; import Leaderboard from '../../components/Leaderboard/Leaderboard'; import styles from './PhaserPage.module.css'; import { GameMode, MODE_CONFIG } from '../../config/gameModes'; import { useNavigate } from 'react-router-dom'; import { updatePlayerInSessionStorage } from '../../components/Storage/Storage'; /** * PhaserPage component. * * Shows the game UI, leaderboard, current food, and runs the core game loop via Phaser. * Syncs game state via WebSocket and EventBus. */ interface FoodState { instanceId: string; foodId: string; x: number; y: number; effect: AacVerb | null; } const PhaserPage: React.FC = () => { // ---- ROUTER & CONTEXT ---- const { sessionId, userId, role: roleParam } = useParams<{ sessionId: string, userId: string, role?: string }>(); const location = useLocation(); // ---- REFS & STATE ---- const phaserRef = useRef<IRefPhaserGame | null>(null); const [currentFood, setCurrentFood] = useState<AacFood | null>(null); const [scores, setScores] = useState<Record<string, number>>({}); const [gameMode, setGameMode] = useState<GameMode | null>(null); const navigate = useNavigate(); const [secondsLeft, setSecondsLeft] = useState<number>(60); // Defensive: what if no state? Fallback to false. const isSpectator = location.state?.role === 'Spectator'; const {connectedUsers, lastMessage, sendMessage, clearLastMessage } = useWebSocket(); // Build color map from connected users const colors: Record<string, string> = Object.fromEntries( connectedUsers .filter(user => typeof user.color === 'string') // remove undefined/null .map(user => [user.userId, user.color as string]) // safe to cast now ); // --- ERROR HANDLING --- useEffect(() => { if (lastMessage?.type === 'ERROR_MESSAGE' && lastMessage?.payload?.code === 'SESSION_NOT_FOUND') { alert(`An error occurred: ${lastMessage.payload.message}`); clearLastMessage?.(); navigate('/'); } }, [lastMessage, navigate, clearLastMessage]); // --- INITIALIZE PLAYER IN SESSION STORAGE --- // This is to ensure the player is registered in session storage useEffect(() => { const role = location.state?.role || roleParam; const color = location.state?.color; if (sessionId && userId && role) { updatePlayerInSessionStorage(sessionId, { userId, role, color }); } }, [sessionId, userId, roleParam, location.state]); // --- JOIN on MOUNT --- useEffect(() => { const stored = localStorage.getItem('playerSession'); const storedData = stored ? JSON.parse(stored) : {}; const role = location.state?.role; const color = storedData.color || location.state?.color; const alreadyJoined = connectedUsers.some( (u) => u.userId === userId && u.role === role ); if (sessionId && userId && role && !alreadyJoined) { // Defensive: avoid double joining as both. if (role === 'Spectator') { sendMessage({ type: 'SPECTATOR_JOIN', payload: { sessionId, userId } }); } else { sendMessage({ type: 'PLAYER_JOIN', payload: { sessionId, userId, role } }); if (color) { sendMessage({ type: 'SELECT_COLOR', payload: { sessionId, userId, color } }); } } } }, [sessionId, userId, location.state?.role, roleParam, sendMessage, connectedUsers]); // --- REMOTE PLAYER MOVEMENT SYNC --- useEffect(() => { if (lastMessage?.type === 'PLAYER_MOVE_BROADCAST') { const { userId: movingUserId, x, y } = lastMessage.payload; if (movingUserId !== userId) { const scene = phaserRef.current?.scene as any; if (scene && typeof scene.updateRemotePlayer === 'function') { scene.updateRemotePlayer(movingUserId, x, y); } } if (clearLastMessage) clearLastMessage(); } }, [lastMessage, userId, clearLastMessage]); // --- GAME MODE BROADCAST --- useEffect(() => { if (lastMessage?.type === 'START_GAME_BROADCAST') { const { mode } = lastMessage.payload as { mode: GameMode }; const settings = MODE_CONFIG[mode]; const scene = phaserRef.current?.scene as any; setGameMode(mode); if (scene && typeof scene.applyModeSettings === 'function') { scene.applyModeSettings(settings); } clearLastMessage?.(); } }, [lastMessage, clearLastMessage]); // --- FOOD STATE SYNC --- useEffect(() => { // Handle food state updates if (lastMessage?.type === 'FOOD_STATE_UPDATE') { const { foods } = lastMessage.payload as { foods: FoodState[] }; EventBus.emit('sync-food-state', foods); } // When a new food is set as target if (lastMessage?.type === 'AAC_TARGET_FOOD') { const { targetFoodId, targetFoodData, effect } = lastMessage.payload; const scene = phaserRef.current?.scene as any; if (scene && typeof scene.setTargetFood === 'function') { if (effect) { scene.setTargetFood(targetFoodId, effect); } else { scene.setTargetFood(targetFoodId); } } if (targetFoodData) { setCurrentFood(targetFoodData); } clearLastMessage?.(); } // When a food has been eaten, remove it from the scene if (lastMessage?.type === 'REMOVE_FOOD') { const { instanceId } = lastMessage.payload; const scene = phaserRef.current?.scene as any; if (scene && typeof scene.removeFoodByInstanceId === 'function') { scene.removeFoodByInstanceId(instanceId); } clearLastMessage?.(); } // When a player effect is broadcasted, apply it if (lastMessage?.type === 'PLAYER_EFFECT_BROADCAST') { const { targetUserId, effect } = lastMessage.payload as { targetUserId: string, effect: AacVerb }; EventBus.emit('apply-player-effect', { targetUserId, effect }); clearLastMessage?.(); } }, [lastMessage, clearLastMessage]); // --- FRUIT EATEN LOCAL (EMITTED FROM PHASER) --- useEffect(() => { const handleFruitEaten = ({ instanceId }: { instanceId: string }) => { if (sessionId) { sendMessage({ type: 'FRUIT_EATEN', payload: { sessionId, instanceId } }); } }; EventBus.on('fruit-eaten', handleFruitEaten); return () => { EventBus.off('fruit-eaten', handleFruitEaten); }; }, [sendMessage, sessionId]); // --- SCORE UPDATE BROADCAST (EVENTBUS) --- useEffect(() => { const handleScoreUpdate = ({ scores }: { scores: Record<string, number> }) => { setScores(scores); }; EventBus.on('scoreUpdate', handleScoreUpdate); return () => { EventBus.off('scoreUpdate', handleScoreUpdate); }; }, []); useEffect(() => { const handleTimerUpdate = (time: number) => { setSecondsLeft(time); }; EventBus.on('TIMER_UPDATE', handleTimerUpdate); return () => { EventBus.off('TIMER_UPDATE', handleTimerUpdate); }; }, []); // If GAME_OVER navigate to victory route. // Also, pass the scores and colors of connected users to the Victory page. // If sessionId is not present, navigate to home. useEffect(() => { const handleGameOver = () => { const colors = Object.fromEntries( connectedUsers .filter(user => user.color) .map(user => [user.userId, user.color]) ); console.log('[PhaserPage] Game Over received. Navigating to Victory screen.'); if (sessionId) { navigate(`/victory/${sessionId}`, { state: { scores, colors, sessionId, userId } }); } else { navigate('/'); } }; EventBus.on('gameOver', handleGameOver); return () => { EventBus.off('gameOver', handleGameOver); }; }, [navigate, sessionId, scores, connectedUsers]); useEffect(() => { const handleEdgesReady = (edges: Record<string, string>) => { if ( sessionId && userId && location.state?.role !== 'Spectator' && edges?.[userId] ) { const userEdge = edges[userId]; if (userEdge) { // Update player edge in session storage updatePlayerInSessionStorage(sessionId, { userId, role: 'Hippo Player', edge: userEdge }); } sendMessage({ type: 'SET_EDGE', payload: { sessionId, userId, edge: userEdge }, }); } }; EventBus.on('edges-ready', handleEdgesReady); return () => { EventBus.off('edges-ready', handleEdgesReady); }; }, [sendMessage, sessionId, userId, location.state?.role]); // Check local storage for player edge let localPlayerEdge: string | undefined; if (sessionId && userId) { try { const stored = localStorage.getItem('playerSessions'); const allSessions = stored ? JSON.parse(stored) : {}; const playersInSession = allSessions[sessionId] || []; const currentPlayer = playersInSession.find((p: { userId: string; edge?: string }) => p.userId === userId); if (currentPlayer && currentPlayer.edge) { localPlayerEdge = currentPlayer.edge; } } catch (e) { console.error('Failed to read player edge from storage', e); } } // ---- RENDER ---- return ( <div className={styles.pageWrapper}> {/* Game Canvas */} <div className={styles.canvasWrapper}> <PhaserGame ref={phaserRef} currentActiveScene={(scene: Phaser.Scene) => { if ( scene && userId && connectedUsers && typeof (scene as any).init === 'function' ) { (scene as any).init({ sendMessage, localPlayerId: userId, sessionId, connectedUsers, modeSettings: gameMode ? MODE_CONFIG[gameMode] : undefined, role: location.state?.role, localPlayerEdge: localPlayerEdge, }); } }} /> </div> {/* Sidebar */} <div className={styles.sidebarWrapper}> <div className={styles.sidebar}> {isSpectator && ( <div className={styles.spectatorBanner} role="status" aria-label="Spectator Mode Banner"> <span className={styles.spectatorText}> <span className={styles.spectatorHighlight}>Spectator Mode</span> </span> </div> )} <div className={styles.timerBox}> <h3 className={styles.timerTitle}>Time Left:</h3> <div className={styles.timerValue}>{secondsLeft} sec</div> </div> <div className={styles.currentFood}> <h3>Current Food to Eat:</h3> {currentFood ? ( <> <img src={currentFood.imagePath} alt={currentFood.name} className={styles.foodImage} /> <p>{currentFood.name}</p> </> ) : ( <p>No Food Selected</p> )} </div> <div className={styles.leaderboardBox}> <Leaderboard scores={scores} colors={colors} userId={userId ?? ''} /> </div> </div> </div> </div> ); } export default PhaserPage; |