javascriptjquerychessboard.js

chessboard.js cannot return snapback for onDrop while checking piece placement


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?

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);

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.