首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >chess.js:移动验证不能正常工作

chess.js:移动验证不能正常工作
EN

Stack Overflow用户
提问于 2020-12-22 14:00:17
回答 1查看 265关注 0票数 0

我正在尝试使用chess.jschessboard.jsx库在react.js中编写一个国际象棋游戏

目前,我正在尝试使用以下代码实现移动验证:

代码语言:javascript
复制
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 )检查),尽管它是合法的。

我不知道为什么会发生这种情况。另外,我在网上没有找到任何关于这个问题的答案。

EN

回答 1

Stack Overflow用户

发布于 2021-08-09 19:20:03

我知道这是一个老问题,但这里有一个解决方案。

基本上,只需按如下方式定义chess.js接口:

代码语言:javascript
复制
const [game, setGame] = useState();

useEffect(()=>{
    setGame(new Chess())
  }, [])

希望这能有所帮助!!:D

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65403909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档