import React, { useState } from "react"; import { Chess } from "chess.js"; import { Chessboard } from "react-chessboard";
export default function ChessGame() { const [game, setGame] = useState(new Chess()); const [fen, setFen] = useState(game.fen());
function makeMove(move) { const gameCopy = new Chess(game.fen()); const result = gameCopy.move(move); if (result) { setGame(gameCopy); setFen(gameCopy.fen()); setTimeout(() => botMove(gameCopy), 500); } return result; }
function botMove(currentGame) { const moves = currentGame.moves(); if (moves.length === 0) return; const randomMove = moves[Math.floor(Math.random() * moves.length)]; currentGame.move(randomMove); setGame(currentGame); setFen(currentGame.fen()); }
function onDrop(sourceSquare, targetSquare) { const move = { from: sourceSquare, to: targetSquare, promotion: "q", // always promote to a queen }; const result = makeMove(move); return result !== null; }