How to carry out promotion (piece replacement )in chessboard.js

2k views Asked by At

I have my own pgn parser which supports n parallel variation and nested variation.

I have written a wrapper to use chessboard.js with it.

I am facing two issues

  1. Removing pawn after en passant move.
  2. changing piece after pawn promotion.

These two issues have same common root that is to replace the piece on a particular position on board. One solution seems to provide FEN to board object and set it.

didn't find any thing in documentation. I want some other elegant solution where in I can replace a particular piece type any suggestions will be helpful.

EDIT It seems that the only way to achieve piece replacement for en passant according to example is

// for castling, en passant, pawn promotion
var onSnapEnd = function() {
  board.position(game.fen());// re positioning board by providing FEN
};   

Providing board.move("<en passant>") carries out the move but does not remove the pawn which is actually ahead of the destination position.

2

There are 2 answers

1
omarjebari On

To move any pieces you have to register the onDrop handler when initializing the chessboard js object. This function should return:

  • true (boolean) for a valid move
  • 'trash' (string) if you want the dropped piece to be removed from the board (eg for pawn promotion)
  • 'snapback' (string) if the move is invalid (will return the piece to it's original square

When you return any of these values from onDrop the board will update accordingly.

Note that handling promotion is tricky as you need to select a piece to promote to.

Anytime you want to update the board (eg once user has selected a promotion piece) just use a new fen to do so, eg:

board.position(fen);
0
Wassim Fellah On

Try to add promotion: "q" to your on drag function like these:

  game.current.move({
    from: sourceSquare,
    to: targetSquare,
    promotion: "q",
  });
  setFen(game.current.fen());