1818 */
1919
2020import { ChessService } from "@/app/_services/ChessService" ;
21- import React , { useState } from "react" ;
21+ import React , { useState , useEffect } from "react" ;
2222import ChessPieceCell from "@/app/_client_components/ChessPieceCell" ;
2323import { ChessPieceType , Color , GameState } from "@/app/_models/enums" ;
2424import { ChessPiece } from "@/app/_models/ChessPiece" ;
@@ -29,15 +29,26 @@ import PromotionModal from "@/app/_client_components/PromotionModal";
2929let gameService : ChessService = new ChessService ( ) ;
3030
3131export default function Chessboard ( { gameInfo, isBotMode} : any ) {
32- let [ chessboard , setChessboard ] = useState ( gameInfo . chessboard ) ;
33- let chessPieces = printChessBoard ( ) ;
32+ let [ chessboard , setChessboard ] = useState ( gameInfo ?. chessboard || [ ] ) ;
3433 let [ allowedPositions , setAllowedPositions ] = useState ( new Set ( ) ) ;
3534 let [ selectedPiece , setSelectedPiece ] = useState ( - 1 ) ;
36- let [ playerTurn , setPlayerTurn ] = useState ( gameInfo . turn ) ;
37- let [ gameState , setGameState ] = useState ( gameInfo . gameState ) ;
35+ let [ playerTurn , setPlayerTurn ] = useState ( gameInfo ? .turn ) ;
36+ let [ gameState , setGameState ] = useState ( gameInfo ? .gameState ) ;
3837 let [ showPromotion , setShowPromotion ] = useState ( false ) ;
3938 let [ promotionMove , setPromotionMove ] = useState < { source : Position , target : Position } | null > ( null ) ;
4039 let [ isComputerThinking , setIsComputerThinking ] = useState ( false ) ;
40+ let chessPieces = printChessBoard ( ) ;
41+
42+ // Reset board state when gameInfo changes (e.g., when game ends/starts)
43+ useEffect ( ( ) => {
44+ if ( gameInfo ) {
45+ setChessboard ( gameInfo . chessboard || [ ] ) ;
46+ setPlayerTurn ( gameInfo . turn ) ;
47+ setGameState ( gameInfo . gameState ) ;
48+ setSelectedPiece ( - 1 ) ;
49+ setAllowedPositions ( new Set ( ) ) ;
50+ }
51+ } , [ gameInfo ] ) ;
4152
4253
4354 async function onCellClick ( chessPiece : ChessPiece ) {
0 commit comments