Search code examples
javascriptchesschessboard.js

restore a game using chess.js


I am running a project using chess.js and chessboard.js. Right now I want to store the history and FEN when the user quit the page, and restore the when the user is back. Restoring the FEN is easy, but I am not really sure about restoring the history. I am thinking to store the game.history() in the database and when the game is resumed, make newGame.history() = game.history(). Will this work? Will the new move history after the game is resumed be appended after the previous history? Thanks!


Solution

  • A bit late to answer but don't use history(). instead use pgn(). when you save the pgn of the game you save the fen (fen of last position) at the same time. pgn() gives you a string which you can save anywhere then to reload the game use load-pgn(mysavedgameinpgnformat). For instance on the client side which is the only place I have gotten this library to work:

    var game = new Chess();
    console.log(game.fen());
    game.move("e4");
    console.log(game.fen());
    console.log(game.history());
    var storegamepgn = game.pgn(); // a string which can be stored most anywhere
    console.log(storegamepgn);
    game = new Chess();
    console.log(game.fen());
    game.load_pgn(storegamepgn);
    console.log(game.fen());
    game.move("e5");
    console.log(game.fen());
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.3/chess.min.js"></script>