【问题标题】:restore a game using chess.js使用 chess.js 恢复游戏
【发布时间】:2020-09-15 08:30:04
【问题描述】:
我正在使用 chess.js 和 chessboard.js 运行一个项目。现在我想在用户退出页面时存储历史记录和 FEN,并在用户返回时恢复。恢复FEN很容易,但我不确定恢复历史。我正在考虑将 game.history() 存储在数据库中,当游戏恢复时,使 newGame.history() = game.history()。这行得通吗?恢复比赛后新的走法历史是否会附加在之前的历史之后?谢谢!
【问题讨论】:
标签:
javascript
chess
chessboard.js
【解决方案1】:
回答有点晚,但不要使用 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>