2

I am trying to make a chess game in react.js using the libraries chess.js and chessboard.jsx

Currently i am trying to implement move validation with the following code :-

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;

But the problem coming is:- For example: - When i move white pawn from g2 to g3 it works but then if i try to move the black pawn from g7 to g6, it counts it as an illegal move(i checked by console.log(move)) although it is legal.

I don't have any idea why this is occurring. Also, I did not find any answers online regarding this issue

2
  • Do you have to explicitly change the turn from white to black after the first move? That second move would be invalid if it were still evaluating as a white move. Commented Dec 22, 2020 at 6:03
  • No, i checked the turn was of black by console.log(game.turn()); Commented Dec 22, 2020 at 6:04

2 Answers 2

3

I know this is an old question, but here's a solution.

Basically, just define the chess.js API as follows:


const [game, setGame] = useState();

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

Hope this helps!! :D

Sign up to request clarification or add additional context in comments.

Comments

0

You can also do this when you are defining the state give the game state as new Chess() see code below.

  const [game, setGame] = useState(new Chess());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.