我正在尝试使用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,它会将其视为非法移动(我由console.log( move )检查),尽管它是合法的。
我不知道为什么会发生这种情况。另外,我在网上没有找到任何关于这个问题的答案。
发布于 2021-08-09 19:20:03
我知道这是一个老问题,但这里有一个解决方案。
基本上,只需按如下方式定义chess.js接口:
const [game, setGame] = useState();
useEffect(()=>{
setGame(new Chess())
}, [])希望这能有所帮助!!:D
https://stackoverflow.com/questions/65403909
复制相似问题