Typically the game logic, validation and move history recording, aren't done with chessboard.js
but with an engine, such as chess.js
.
With an engine there might be an undo()
or takeback()
function, see the chess.js
docs for an example:
chess.move('e4');
chess.fen();
// -> 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'
chess.undo();
// -> { color: 'w', from: 'e2', to: 'e4', flags: 'b', piece: 'p', san: 'e4' }
chess.fen();
// -> 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
There is also an open branch at chess.js
, https://github.com/jhlywa/chess.js/pull/48
this code implements next()
and back()
functions into the engine, (and a future
array for storing the history). These might be what you're looking for, because after you undo, you mention you want to redo.
This branch isn't merged, and I don't think it will be, but it's there to look at; basically just add these two functions:
back: function() {
var moves = this.history();
var tmp = new Chess();
var previous = moves.length-future.length-1;
for(var i=0;i<previous;i++) {
tmp.move(moves[i]);
}
var previous_fen = tmp.fen();
tmp.move(moves[previous]);
future.push(tmp.fen());
return previous_fen;
},
next: function() {
return future.pop();
},
and an array
var future = [];
Then you can call back()
, analyze the position, and then next()
to return to the game state.