[英]chess.js: Move validation not working correctly
我正在尝试使用库chess.js和chessboard.jsx在 react.js 中制作国际象棋游戏
目前我正在尝试使用以下代码实现移动验证:-
import "./App.css";
import React, { useState } from "react";
import Chessboard from "chessboardjsx";
import * as ChessJS from "chess.js"; // import { Chess } from 'chess.js' gives an error
function App() {
const Chess = typeof ChessJS === "function" ? ChessJS : ChessJS.Chess; // For VS code intellisence to work
const game = new Chess();
const [position, setPosition] = useState("start");
const onDropMove = ({ sourceSquare, targetSquare }) => {
const move = game.move({
from: sourceSquare,
to: targetSquare,
promotion: "q",
});
if (move === null) return;
setPosition(game.fen());
};
return <Chessboard position={position} onDrop={onDropMove} />;
}
export default App;
但是问题来了:-例如:-当我将白兵从 g2 移动到 g3 时,它可以工作,但是如果我尝试将黑兵从 g7 移动到 g6,则会将其视为非法移动(我通过控制台检查。 log(move)) 虽然它是合法的。
我不知道为什么会这样。 另外,我没有在网上找到任何关于这个问题的答案
我知道这是一个老问题,但这里有一个解决方案。
基本上,只需定义 chess.js API 如下:
const [game, setGame] = useState();
useEffect(()=>{
setGame(new Chess())
}, [])
希望这可以帮助:! :D
您也可以在定义 state 时执行此操作,将游戏 state 定义为 new Chess() 请参见下面的代码。
const [game, setGame] = useState(new Chess());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.