user3767878
user3767878

Reputation: 199

how to undo and redo chess moves using chessboard.js for analyze mode

I am using the chess.js and chessboard.js for my chess a project.

I just want to implement the undo and redo functionality of chess moves.

I am creating "Move Recorder" for chess moves using chessboard.js, through which users can undo and redo chess moves. User is playing from both sides to analyze chess puzzle.

Please let me know if any one can help on this.

Upvotes: 5

Views: 3325

Answers (2)

Nevermore
Nevermore

Reputation: 7399

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.

Upvotes: 3

ecMode
ecMode

Reputation: 540

Start here for the basic design. data structure used to implement UNDO and REDO option

And I presume there are methods in this framework to keep track of the commands you'll need for designated past actions.

Hope that helps!

Upvotes: 1

Related Questions