Question

I am trying to make a small game where the aim is to correctly place the pieces on the board. The following code is able to log "wrong" to the console at the correct time, but it does not return 'snapback' to onDrop which is the intended behaviour.

var setup1 = ChessBoard.fenToObj('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR');
var onDrop = function(source, target, piece, newPos, oldPos, orientation) {

$.each( setup1, function( key, value ) {
if (target == key && piece !== value) {
console.log("wrong")
return 'snapback'
}

});

};

var cfg = {
  draggable: true,
  dropOffBoard: 'trash',
  sparePieces: true,
  showErrors: 'console',
  onDrop: onDrop,
};
var board = new ChessBoard('board', cfg);

Any ideas why this is not working, or is there a better solution?

  • Edited to include the whole JS section of the script

Edit: The following is based on Chris's answer, it is probably pretty clunky, but it works.

var correct = 1
var setup1 = ChessBoard.fenToObj('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR');
var onDrop = function(source, target, piece, newPos, oldPos, orientation) {
correct = 1

if (target.match(/3|4|5|6/)) {
correct = 0
}

$.each( setup1, function( key, value ) {
if (target == key && piece !== value) {
correct = 0
}

})
if (correct == 0) return 'trash';
};

var cfg = {
  draggable: true,
  dropOffBoard: 'trash',
  sparePieces: true,
  showErrors: 'console',
  onDrop: onDrop,
};
var board = new ChessBoard('board', cfg);
Was it helpful?

Solution

You need to return "snapback" from the onDrop function. In the code you've posted you're returning "snapback" from a different function (the one being called by $.each).

Check out Example 4004 and Example 4005 for how to use onDrop.

OTHER TIPS

The onDrop function allows you to return the string 'trash' to remove the piece from the board, or 'snapback' to return the piece to the square it was originally dragged from. In the code you're returning 'snapback' from the $.each back to the scope of the onDrop function. Warning: i also found that if you make onDrop an async function it won't work (eg when promoting a pawn you may want to use an async approach to displaying a modal to select the piece to promote to).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top