MCPcopy Create free account
hub / github.com/RootbeerComputer/backend-GPT / ChessBoard

Function ChessBoard

frontend-chess/src/ChessBoard.js:5–64  ·  view source on GitHub ↗
({ setComputerTurn })

Source from the content-addressed store, hash-verified

3import { Chessboard } from "react-chessboard";
4
5function ChessBoard({ setComputerTurn }) {
6 const [game, setGame] = useState(new Chess());
7
8 function makeAMove(move) {
9 // const gameCopy = game;
10 let gameCopy = Object.assign(
11 Object.create(Object.getPrototypeOf(game)),
12 game
13 );
14
15 const result = gameCopy.move(move);
16 setGame(gameCopy);
17 return result; // null if the move was illegal, the move object if the move was legal
18 }
19
20 function makeRandomMove() {
21 let gameCopy = Object.assign(
22 Object.create(Object.getPrototypeOf(game)),
23 game
24 );
25 let gameFen = gameCopy.fen();
26 const newFen = gameFen.replace("w", "b");
27 gameCopy.load(newFen);
28 console.log(gameCopy);
29
30 setGame(gameCopy);
31
32 const possibleMoves = gameCopy.moves();
33
34 console.log(possibleMoves);
35 if (game.isGameOver() || game.isDraw() || possibleMoves.length === 0)
36 return; // exit if the game is over
37 const randomIndex = Math.floor(Math.random() * possibleMoves.length);
38 makeAMove(possibleMoves[randomIndex]);
39 // makeAMove(possibleMoves[0]);
40 setComputerTurn(false);
41 }
42
43 function onDrop(sourceSquare, targetSquare) {
44 const move = makeAMove({
45 from: sourceSquare,
46 to: targetSquare,
47 promotion: "q", // always promote to a queen for example simplicity
48 });
49
50 // illegal move
51 if (move === null) return false;
52 setComputerTurn(true);
53
54 setTimeout(makeRandomMove, 4500);
55
56 return true;
57 }
58
59 return (
60 <>
61 <Chessboard position={game.fen()} onPieceDrop={onDrop} boardWidth={600} />
62 </>

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected