Using react-chessboard with chess.js. I modified the example code at: https://www.npmjs.com/package/react-chessboard.
My code:
import { Chessboard } from "react-chessboard";
import { useState } from "react";
import { Chess } from "chess.js";
const Board = () =>{
const [game, setGame] = useState(new Chess());
function makeAMove(move) {
const gameCopy = new Chess();
gameCopy.loadPgn(game.pgn());
gameCopy.move(move);
setGame(gameCopy);
}
function onDrop(sourceSquare, targetSquare) {
makeAMove({
from: sourceSquare,
to: targetSquare,
});
if(game.isGameOver()){
if(game.isStalemate() || game.isThreefoldRepetition()){
alert("Stalemate")
}
if(game.turn() == "b"){
alert("White won")
}
else if(game.turn() == "w"){
alert("Black won")
}
}
}
return (
<>
<div style = {{width: '50%',alignItems: 'center', marginLeft: '25%',justifyContent: 'center'}}>
<Chessboard position={game.fen()} onPieceDrop={onDrop} id="BasicBoard"/>
</div>
</>
);
}
export default Board;
Why is the isGameOver() one move behind for me? If white checkmates black then the "White won" alert pops up only after black tries to make another move after being checkmated and vice versa.