This commit is contained in:
Maciej Caderek
2022-01-13 06:00:00 +01:00
commit f3069d6dd1
48 changed files with 2220 additions and 0 deletions

80
src/game/Game.ts Normal file
View File

@@ -0,0 +1,80 @@
import { Chess, ChessInstance, Move } from "chess.js";
class Game {
private game: ChessInstance;
private replay: ChessInstance;
private moves: Move[];
private currentPly: number = 0;
constructor() {
this.game = new Chess();
this.replay = new Chess();
this.moves = [];
}
loadPGN(pgn: string) {
this.game.load_pgn(pgn);
this.moves = this.game.history({ verbose: true });
this.currentPly = 0;
const fen = this.game.header().FEN;
if (fen) {
this.replay.load(fen);
}
return this;
}
loadFEN(fen: string) {
this.game.load(fen);
return this;
}
next() {
const move = this.moves[this.currentPly];
if (!move) {
return null;
}
this.replay.move(move);
this.currentPly++;
return move;
}
prev() {
const move = this.replay.undo();
if (!move) {
return null;
}
this.currentPly--;
return move;
}
last() {
while (this.next()) {}
}
first() {
while (this.prev()) {}
}
goto(ply: number) {
if (ply === this.currentPly || ply < 0 || ply > this.moves.length - 1) {
return;
}
while (this.currentPly !== ply) {
ply > this.currentPly ? this.next() : this.prev();
}
}
getBoardData() {
return this.replay.board();
}
}
export default Game;