使用Chess.js恢复游戏

问题描述

我正在使用Chess.js和Chessboard.js运行一个项目。现在,我想在用户退出页面时存储历史记录和FEN,并在用户返回时恢复它。恢复FEN很容易,但是我不确定恢复历史。我正在考虑将game.history()存储在数据库中,并且在恢复游戏时,使newGame.history()= game.history()。这样行吗?恢复游戏后的新移动历史记录是否会附加在先前的历史记录之后?谢谢!

解决方法

回答得有点晚,但是不要使用history()。而是使用pgn()。当您保存游戏的pgn时,会同时保存fen(最后位置的fen)。 pgn()为您提供了一个字符串,您可以将其保存在任何地方,然后使用load-pgn(mysavedgameinpgnformat)重新加载游戏。例如在客户端,这是我使该库工作的唯一位置:

script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js")
script(type='text/javascript' src="javascripts/chess.js") 
<script>
var game = new Chess();
 console.log(game.fen());
 game.move("e4");
 console.log(game.fen());
 console.log(game.history());
 var storegamepgn = game.pgn();  //storegamepgn is a string which can be stored most anywhere
 game = new Chess();
 console.log(game.fen());
 game.load_pgn(storegamepgn)
 console.log(game.fen());
 game.move("e5");
 console.log(game.fen());
</script>