chess-rule-engine 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +170 -2
- package/dist/board.d.ts +22 -0
- package/dist/board.js +107 -0
- package/dist/chessRuleSet.d.ts +22 -0
- package/dist/chessRuleSet.js +154 -0
- package/dist/constants/board.d.ts +2 -0
- package/dist/constants/board.js +2 -0
- package/dist/constants/castleType.d.ts +7 -0
- package/dist/constants/castleType.js +8 -0
- package/dist/constants/game.d.ts +24 -0
- package/dist/constants/game.js +34 -0
- package/dist/constants/index.d.ts +3 -0
- package/dist/constants/index.js +3 -0
- package/dist/constants/piece.d.ts +34 -0
- package/dist/constants/piece.js +6 -0
- package/dist/game.d.ts +57 -0
- package/dist/game.js +314 -0
- package/dist/hashing/zobrist.d.ts +23 -0
- package/dist/hashing/zobrist.js +97 -0
- package/dist/hashing/zobristUpdater.d.ts +20 -0
- package/dist/hashing/zobristUpdater.js +105 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/pieces/bishop.d.ts +9 -0
- package/dist/pieces/bishop.js +17 -0
- package/dist/pieces/index.d.ts +8 -0
- package/dist/pieces/index.js +7 -0
- package/dist/pieces/king.d.ts +12 -0
- package/dist/pieces/king.js +90 -0
- package/dist/pieces/knight.d.ts +9 -0
- package/dist/pieces/knight.js +21 -0
- package/dist/pieces/pawn.d.ts +11 -0
- package/dist/pieces/pawn.js +90 -0
- package/dist/pieces/piece.d.ts +12 -0
- package/dist/pieces/piece.js +14 -0
- package/dist/pieces/queen.d.ts +9 -0
- package/dist/pieces/queen.js +21 -0
- package/dist/pieces/rook.d.ts +9 -0
- package/dist/pieces/rook.js +17 -0
- package/dist/types/board.d.ts +5 -0
- package/dist/types/board.js +1 -0
- package/dist/types/game.d.ts +38 -0
- package/dist/types/game.js +1 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.js +5 -0
- package/dist/types/move.d.ts +96 -0
- package/dist/types/move.js +1 -0
- package/dist/types/piece.d.ts +23 -0
- package/dist/types/piece.js +1 -0
- package/dist/types/util.d.ts +10 -0
- package/dist/types/util.js +1 -0
- package/dist/utils/color.d.ts +4 -0
- package/dist/utils/color.js +7 -0
- package/dist/utils/piece.d.ts +6 -0
- package/dist/utils/piece.js +7 -0
- package/dist/utils/splitMix64.d.ts +6 -0
- package/dist/utils/splitMix64.js +15 -0
- package/package.json +30 -4
package/dist/game.js
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { Board } from "./board.js";
|
|
2
|
+
import { GameStatus, GameResult, BOARD_SIZE, DefaultBoard } from "./constants/game.js";
|
|
3
|
+
import { ChessRuleSet } from "./chessRuleSet.js";
|
|
4
|
+
import { King, Pawn } from "./pieces/index.js";
|
|
5
|
+
import { ZobristUpdater } from "./hashing/zobristUpdater.js";
|
|
6
|
+
import { CastleType } from "./constants/index.js";
|
|
7
|
+
import { switchColor } from "./utils/color.js";
|
|
8
|
+
import { PieceClassMap, PieceCode } from "./constants/piece.js";
|
|
9
|
+
class Game {
|
|
10
|
+
_moveHistory = [];
|
|
11
|
+
_currentMoveIndex = -1;
|
|
12
|
+
_currentTurnColor = "white";
|
|
13
|
+
_currentStatus = GameStatus.NOT_STARTED;
|
|
14
|
+
_currentResult = GameResult.PENDING;
|
|
15
|
+
_zobristUpdater = new ZobristUpdater();
|
|
16
|
+
_specialRights = {
|
|
17
|
+
castlingRights: {
|
|
18
|
+
[CastleType.WHITE_SHORT_CASTLE]: false,
|
|
19
|
+
[CastleType.WHITE_LONG_CASTLE]: false,
|
|
20
|
+
[CastleType.BLACK_SHORT_CASTLE]: false,
|
|
21
|
+
[CastleType.BLACK_LONG_CASTLE]: false
|
|
22
|
+
},
|
|
23
|
+
enPassantFile: null
|
|
24
|
+
};
|
|
25
|
+
_lastPawnMoveOrCaptureIndex = 0; // 1-based Indexing
|
|
26
|
+
board = new Board(BOARD_SIZE);
|
|
27
|
+
// Getters
|
|
28
|
+
get lastMoveRecord() { return this._moveHistory ? this._moveHistory[this._moveHistory.length - 1] : null; }
|
|
29
|
+
get currentTurnColor() { return this._currentTurnColor; }
|
|
30
|
+
get currentStatus() { return this._currentStatus; }
|
|
31
|
+
get currentResult() { return this._currentResult; }
|
|
32
|
+
get lastPawnMoveOrCaptureIndex() { return this._lastPawnMoveOrCaptureIndex; }
|
|
33
|
+
get moveHistory() { return this._moveHistory; }
|
|
34
|
+
get specialRights() { return this._specialRights; }
|
|
35
|
+
;
|
|
36
|
+
get zobristUpdater() { return this._zobristUpdater; }
|
|
37
|
+
;
|
|
38
|
+
// Board Related Changes
|
|
39
|
+
setBoardLayout(layout = DefaultBoard) {
|
|
40
|
+
if (this.board.isValidLayout(layout)) {
|
|
41
|
+
this.board.applyLayout(layout);
|
|
42
|
+
this.updateSpecialRights();
|
|
43
|
+
this.updateStatus();
|
|
44
|
+
this._zobristUpdater.rebuildHash(this);
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
applyChanges(moveRecord, { updateGameHash = false } = {}) {
|
|
50
|
+
const { moves, captures, promotions } = moveRecord;
|
|
51
|
+
for (const { from } of captures) {
|
|
52
|
+
this.board.setAtPos(from, null);
|
|
53
|
+
}
|
|
54
|
+
for (const { from, to, piece } of moves) {
|
|
55
|
+
this.board.setAtPos(from, null);
|
|
56
|
+
this.board.setAtPos(to, piece);
|
|
57
|
+
piece.movesPlayed++;
|
|
58
|
+
}
|
|
59
|
+
for (const { to, piece } of promotions) {
|
|
60
|
+
this.board.setAtPos(to, piece);
|
|
61
|
+
}
|
|
62
|
+
this.changeCurrentTurn();
|
|
63
|
+
if (updateGameHash)
|
|
64
|
+
this.recordHashForLatestMove();
|
|
65
|
+
}
|
|
66
|
+
removeChanges(moveRecord, { updateGameHash = false } = {}) {
|
|
67
|
+
const { moves, captures, promotions } = moveRecord;
|
|
68
|
+
if (updateGameHash)
|
|
69
|
+
this.removeHashForLatestMove();
|
|
70
|
+
for (const { to } of promotions) {
|
|
71
|
+
this.board.setAtPos(to, null);
|
|
72
|
+
}
|
|
73
|
+
for (const { from, to, piece } of moves) {
|
|
74
|
+
this.board.setAtPos(from, piece);
|
|
75
|
+
this.board.setAtPos(to, null);
|
|
76
|
+
piece.movesPlayed--;
|
|
77
|
+
}
|
|
78
|
+
for (const { from, piece } of captures) {
|
|
79
|
+
this.board.setAtPos(from, piece);
|
|
80
|
+
}
|
|
81
|
+
this.changeCurrentTurn();
|
|
82
|
+
}
|
|
83
|
+
// Comparisons
|
|
84
|
+
isSamePosition(board, turnColor, specialRights) {
|
|
85
|
+
return (Board.isSame(board, this.board) &&
|
|
86
|
+
this.currentTurnColor === turnColor &&
|
|
87
|
+
this.specialRights.castlingRights[CastleType.WHITE_SHORT_CASTLE] === specialRights.castlingRights[CastleType.WHITE_SHORT_CASTLE] &&
|
|
88
|
+
this.specialRights.castlingRights[CastleType.WHITE_LONG_CASTLE] === specialRights.castlingRights[CastleType.WHITE_LONG_CASTLE] &&
|
|
89
|
+
this.specialRights.castlingRights[CastleType.BLACK_SHORT_CASTLE] === specialRights.castlingRights[CastleType.BLACK_SHORT_CASTLE] &&
|
|
90
|
+
this.specialRights.castlingRights[CastleType.BLACK_LONG_CASTLE] === specialRights.castlingRights[CastleType.BLACK_LONG_CASTLE] &&
|
|
91
|
+
this.specialRights.enPassantFile === specialRights.enPassantFile);
|
|
92
|
+
}
|
|
93
|
+
// Evaluation
|
|
94
|
+
evaluateStatus() {
|
|
95
|
+
if (ChessRuleSet.isCheckmated(this)) {
|
|
96
|
+
const winner = switchColor(this.currentTurnColor);
|
|
97
|
+
return {
|
|
98
|
+
status: (winner === "white" ? GameStatus.WHITE_WON : GameStatus.BLACK_WON),
|
|
99
|
+
result: GameResult.CHECKMATE
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const drawConditions = [
|
|
103
|
+
[ChessRuleSet.isDrawByStalemate, GameResult.STALEMATE],
|
|
104
|
+
[ChessRuleSet.isDrawByThreeFoldRepetition, GameResult.THREE_FOLD_REPETITION],
|
|
105
|
+
[ChessRuleSet.isDrawByInsufficientMaterial, GameResult.DRAW_BY_INSUFFICIENT_MATERIAL],
|
|
106
|
+
[ChessRuleSet.isDrawByFiftyMoveRule, GameResult.FIFTY_MOVE_RULE],
|
|
107
|
+
];
|
|
108
|
+
for (const [condition, result] of drawConditions) {
|
|
109
|
+
if (condition(this))
|
|
110
|
+
return { status: GameStatus.DRAW, result };
|
|
111
|
+
}
|
|
112
|
+
return { status: this._currentStatus, result: this._currentResult };
|
|
113
|
+
}
|
|
114
|
+
evaluateAndBacktrack(moveQuery, fn) {
|
|
115
|
+
const piece = this.board.getAtPos(moveQuery.from);
|
|
116
|
+
if (!piece)
|
|
117
|
+
return null;
|
|
118
|
+
this.playMove(moveQuery, { updateGameHash: false });
|
|
119
|
+
try {
|
|
120
|
+
return fn(this);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
this.undoMove({ updateGameHash: false });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
evaluateAt(moveHistoryIndexes, evaluate) {
|
|
127
|
+
const results = Array(moveHistoryIndexes.length);
|
|
128
|
+
try {
|
|
129
|
+
for (let i = 0; i < moveHistoryIndexes.length; ++i) {
|
|
130
|
+
this.jumpToMove(moveHistoryIndexes[i]);
|
|
131
|
+
results[i] = evaluate(this);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
this.jumpToLatestMove();
|
|
136
|
+
this.updateSpecialRights(); // For safely returning to latest position
|
|
137
|
+
}
|
|
138
|
+
return results;
|
|
139
|
+
}
|
|
140
|
+
// Update Game Attributes
|
|
141
|
+
updateStatus() {
|
|
142
|
+
if (this.lastMoveRecord &&
|
|
143
|
+
(this.lastMoveRecord.captures.length > 0 || // Any capture
|
|
144
|
+
this.lastMoveRecord.moves.some(move => move.piece.name === "pawn")) // Or any pawn move
|
|
145
|
+
) {
|
|
146
|
+
this._lastPawnMoveOrCaptureIndex = this._moveHistory.length;
|
|
147
|
+
}
|
|
148
|
+
const { status, result } = this.evaluateStatus();
|
|
149
|
+
this._currentStatus = status;
|
|
150
|
+
this._currentResult = result;
|
|
151
|
+
}
|
|
152
|
+
updateSpecialRights() {
|
|
153
|
+
const { castlingRights } = this._specialRights;
|
|
154
|
+
const whiteKing = this.board.findPiece("white", "king");
|
|
155
|
+
const blackKing = this.board.findPiece("black", "king");
|
|
156
|
+
if (!whiteKing || !blackKing)
|
|
157
|
+
throw Error(`[Invalid Board State] Cannot find white or black king on board`);
|
|
158
|
+
castlingRights[CastleType.WHITE_SHORT_CASTLE] = King.canShortCastle(this, whiteKing);
|
|
159
|
+
castlingRights[CastleType.WHITE_LONG_CASTLE] = King.canLongCastle(this, whiteKing);
|
|
160
|
+
castlingRights[CastleType.BLACK_SHORT_CASTLE] = King.canShortCastle(this, blackKing);
|
|
161
|
+
castlingRights[CastleType.BLACK_LONG_CASTLE] = King.canLongCastle(this, blackKing);
|
|
162
|
+
const pawns = [];
|
|
163
|
+
for (let y = 0; y < BOARD_SIZE; ++y) {
|
|
164
|
+
for (let x = 0; x < BOARD_SIZE; ++x) {
|
|
165
|
+
const piece = this.board.positionMap[y][x];
|
|
166
|
+
if (piece?.name === "pawn")
|
|
167
|
+
pawns.push({ x, y });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
this._specialRights.enPassantFile = null;
|
|
171
|
+
for (const pawnPos of pawns) {
|
|
172
|
+
if (Pawn.isLeftEnPassantLegal(this, pawnPos)) {
|
|
173
|
+
this._specialRights.enPassantFile = pawnPos.x - 1;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
else if (Pawn.isRightEnPassantLegal(this, pawnPos)) {
|
|
177
|
+
this._specialRights.enPassantFile = pawnPos.x + 1;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
// Changing turn
|
|
183
|
+
changeCurrentTurn() {
|
|
184
|
+
this._currentTurnColor = this._currentTurnColor === "white" ? "black" : "white";
|
|
185
|
+
}
|
|
186
|
+
// Move Record helpers
|
|
187
|
+
addMove(moveRecord, moveQuery) {
|
|
188
|
+
const { from, to } = moveQuery;
|
|
189
|
+
const piece = this.board.getAtPos(from);
|
|
190
|
+
if (!piece) {
|
|
191
|
+
console.warn(`[Invalid Call] No piece at position (${from.x}, ${from.y}) at makeMove`);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
moveRecord.moves.push({ type: "move", piece, from, to });
|
|
195
|
+
const capture = this.board.getAtPos(to);
|
|
196
|
+
if (capture)
|
|
197
|
+
this.addCapture(moveRecord, to);
|
|
198
|
+
}
|
|
199
|
+
addCapture(moveRecord, from) {
|
|
200
|
+
const piece = this.board.getAtPos(from);
|
|
201
|
+
if (!piece) {
|
|
202
|
+
console.warn(`[Invalid Call] No piece at position (${from.x}, ${from.y}) at makeCapture`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const change = { type: "capture", piece, from };
|
|
206
|
+
moveRecord.captures.push(change);
|
|
207
|
+
}
|
|
208
|
+
addPromotion(moveRecord, to, promotionColor, promotionName) {
|
|
209
|
+
const promoteTo = promotionName ?? PieceCode["queen"];
|
|
210
|
+
const promotion = new PieceClassMap[promoteTo](promotionColor);
|
|
211
|
+
moveRecord.promotions.push({ type: "promotion", to, piece: promotion });
|
|
212
|
+
}
|
|
213
|
+
// Move Execution
|
|
214
|
+
playMove(moveQuery, { updateGameStatus = false, updateGameHash = true } = {}) {
|
|
215
|
+
const { from, to } = moveQuery;
|
|
216
|
+
const piece = this.board.getAtPos(from);
|
|
217
|
+
if (!piece)
|
|
218
|
+
throw Error(`[Invalid Call] No piece at position (${from.x}, ${from.y}) at playMoveWithoutValidation`);
|
|
219
|
+
// Create Move Record for add to history
|
|
220
|
+
const moveRecord = { moves: [], captures: [], promotions: [] };
|
|
221
|
+
this._moveHistory.push(moveRecord);
|
|
222
|
+
this.addMove(moveRecord, moveQuery);
|
|
223
|
+
// Calling onMove function
|
|
224
|
+
if (to.onMove)
|
|
225
|
+
to.onMove(this, moveQuery, moveRecord);
|
|
226
|
+
// Apply changes to board
|
|
227
|
+
++this._currentMoveIndex;
|
|
228
|
+
this.applyChanges(moveRecord, { updateGameHash });
|
|
229
|
+
// Handling Options
|
|
230
|
+
if (updateGameStatus)
|
|
231
|
+
this.updateStatus();
|
|
232
|
+
}
|
|
233
|
+
playMoveWithValidation(moveQuery) {
|
|
234
|
+
const { from, to } = moveQuery;
|
|
235
|
+
if (!this.board.isInBounds(from) || !this.board.isInBounds(to))
|
|
236
|
+
return { result: "Invalid Move", executed: false, remark: `[Range Error] moveQuery not in board bounds!` };
|
|
237
|
+
this.jumpToLatestMove();
|
|
238
|
+
const piece = this.board.getAtPos(from);
|
|
239
|
+
if (!piece)
|
|
240
|
+
return { result: "Invalid Move", executed: false, remark: `No piece at position (${from.x},${from.y})` };
|
|
241
|
+
if (piece.color !== this._currentTurnColor)
|
|
242
|
+
return { result: "Invalid Turn", remark: `Wait for ${this._currentTurnColor}'s turn!`, executed: false };
|
|
243
|
+
const validation = ChessRuleSet.validateAsLegalMove(this, from, to);
|
|
244
|
+
if (!validation.valid)
|
|
245
|
+
return { result: "Illegal Move", executed: false };
|
|
246
|
+
// Move gets played after getting validated above conditions
|
|
247
|
+
this.playMove({ from, to: validation.move }, { updateGameStatus: true, updateGameHash: true });
|
|
248
|
+
return { result: "Legal Move", executed: true };
|
|
249
|
+
}
|
|
250
|
+
undoMove({ updateGameStatus = false, updateGameHash = true } = {}) {
|
|
251
|
+
if (this._moveHistory.length === 0)
|
|
252
|
+
return;
|
|
253
|
+
const moveRecord = this._moveHistory[this._moveHistory.length - 1];
|
|
254
|
+
// Apply Changes to board
|
|
255
|
+
this.removeChanges(moveRecord, { updateGameHash });
|
|
256
|
+
--this._currentMoveIndex;
|
|
257
|
+
this._moveHistory.pop();
|
|
258
|
+
// Handling Options
|
|
259
|
+
if (updateGameStatus)
|
|
260
|
+
this.updateStatus();
|
|
261
|
+
}
|
|
262
|
+
// Board Hashing
|
|
263
|
+
recordHashForLatestMove() {
|
|
264
|
+
this._zobristUpdater.addMoveRecord(this, this._moveHistory.length - 1);
|
|
265
|
+
}
|
|
266
|
+
removeHashForLatestMove() {
|
|
267
|
+
this._zobristUpdater.removeMoveRecord(this, this._moveHistory.length - 1);
|
|
268
|
+
}
|
|
269
|
+
// Board View
|
|
270
|
+
jumpToStartingMove() {
|
|
271
|
+
const { moveHistory } = this;
|
|
272
|
+
for (let i = this._currentMoveIndex; i >= 0; --i)
|
|
273
|
+
this.removeChanges(moveHistory[i]);
|
|
274
|
+
this._currentMoveIndex = -1;
|
|
275
|
+
}
|
|
276
|
+
jumpToLatestMove() {
|
|
277
|
+
const { moveHistory } = this;
|
|
278
|
+
for (let i = this._currentMoveIndex + 1; i < moveHistory.length; ++i)
|
|
279
|
+
this.applyChanges(moveHistory[i]);
|
|
280
|
+
this._currentMoveIndex = moveHistory.length - 1;
|
|
281
|
+
}
|
|
282
|
+
forwardOneMove() {
|
|
283
|
+
const { moveHistory } = this;
|
|
284
|
+
if (this._currentMoveIndex + 1 >= moveHistory.length)
|
|
285
|
+
return;
|
|
286
|
+
this.applyChanges(moveHistory[++this._currentMoveIndex]);
|
|
287
|
+
}
|
|
288
|
+
reverseOneMove() {
|
|
289
|
+
const { moveHistory } = this;
|
|
290
|
+
if (this._currentMoveIndex < 0)
|
|
291
|
+
return;
|
|
292
|
+
this.applyChanges(moveHistory[this._currentMoveIndex--]);
|
|
293
|
+
}
|
|
294
|
+
jumpToMove(moveHistoryIndex) {
|
|
295
|
+
if (moveHistoryIndex < 0 || moveHistoryIndex >= this._moveHistory.length || moveHistoryIndex === this._currentMoveIndex)
|
|
296
|
+
return;
|
|
297
|
+
let curr = this._currentMoveIndex;
|
|
298
|
+
const direction = Math.sign(moveHistoryIndex - this._currentMoveIndex);
|
|
299
|
+
if (direction > 0) {
|
|
300
|
+
while (curr !== moveHistoryIndex) {
|
|
301
|
+
curr += direction;
|
|
302
|
+
this.applyChanges(this._moveHistory[curr]);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
else if (direction < 0) {
|
|
306
|
+
while (curr !== moveHistoryIndex) {
|
|
307
|
+
this.removeChanges(this._moveHistory[curr]);
|
|
308
|
+
curr += direction;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
this._currentMoveIndex = moveHistoryIndex;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
export { Game };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CastleType } from "../constants/castleType.js";
|
|
2
|
+
import type { PieceColor, PieceLike } from "../types/piece.js";
|
|
3
|
+
import type { GameSpecialRights, GameContext } from "../types/game.js";
|
|
4
|
+
import type { Position } from "../types/move.js";
|
|
5
|
+
type Hash = bigint;
|
|
6
|
+
declare class Zobrist {
|
|
7
|
+
private static readonly rng;
|
|
8
|
+
private static _pieceSquareHashMap;
|
|
9
|
+
private static _sideToMove;
|
|
10
|
+
private static _castlingRights;
|
|
11
|
+
private static _enPassantFile;
|
|
12
|
+
static initializeValues(): void;
|
|
13
|
+
static getPieceIndex(piece: PieceLike): number;
|
|
14
|
+
static getBoardHash(game: GameContext): Hash;
|
|
15
|
+
static togglePieceAtPos(piece: PieceLike, pos: Position, hash: Hash): bigint;
|
|
16
|
+
static toggleEnPassantOnFile(file: number, hash: Hash): bigint;
|
|
17
|
+
static toggleCastlingRights(castleType: CastleType, hash: Hash): bigint;
|
|
18
|
+
static toggleSideToMove(color: PieceColor, hash: Hash): bigint;
|
|
19
|
+
static switchSideToMove(hash: Hash): bigint;
|
|
20
|
+
static toggleSpecialRights(specialRights: GameSpecialRights, hash: Hash): bigint;
|
|
21
|
+
}
|
|
22
|
+
export { Zobrist };
|
|
23
|
+
export type { Hash };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { King, Pawn } from "../pieces/index.js";
|
|
2
|
+
import { BOARD_SIZE } from "../constants/game.js";
|
|
3
|
+
import { CastleType } from "../constants/castleType.js";
|
|
4
|
+
import { PieceType } from "../constants/piece.js";
|
|
5
|
+
import { SplitMix64 } from "../utils/splitMix64.js";
|
|
6
|
+
class Zobrist {
|
|
7
|
+
static rng = new SplitMix64(0x123456789abcdef0n);
|
|
8
|
+
static _pieceSquareHashMap;
|
|
9
|
+
static _sideToMove;
|
|
10
|
+
static _castlingRights;
|
|
11
|
+
static _enPassantFile;
|
|
12
|
+
static initializeValues() {
|
|
13
|
+
Zobrist._pieceSquareHashMap = Array.from({ length: 12 }, () => Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => Zobrist.rng.next())));
|
|
14
|
+
Zobrist._sideToMove = { white: Zobrist.rng.next(), black: Zobrist.rng.next() };
|
|
15
|
+
Zobrist._castlingRights = {
|
|
16
|
+
[CastleType.WHITE_SHORT_CASTLE]: Zobrist.rng.next(),
|
|
17
|
+
[CastleType.WHITE_LONG_CASTLE]: Zobrist.rng.next(),
|
|
18
|
+
[CastleType.BLACK_SHORT_CASTLE]: Zobrist.rng.next(),
|
|
19
|
+
[CastleType.BLACK_LONG_CASTLE]: Zobrist.rng.next()
|
|
20
|
+
};
|
|
21
|
+
Zobrist._enPassantFile = Array.from({ length: BOARD_SIZE }, () => Zobrist.rng.next());
|
|
22
|
+
}
|
|
23
|
+
static getPieceIndex(piece) {
|
|
24
|
+
return (piece.color === "black" ? 6 : 0) + PieceType[piece.name];
|
|
25
|
+
}
|
|
26
|
+
static getBoardHash(game) {
|
|
27
|
+
let hash = Zobrist._sideToMove[game.currentTurnColor];
|
|
28
|
+
const { boardSize, positionMap } = game.board;
|
|
29
|
+
for (let y = 0; y < boardSize; ++y) {
|
|
30
|
+
for (let x = 0; x < boardSize; ++x) {
|
|
31
|
+
const piece = positionMap[y][x];
|
|
32
|
+
if (!piece)
|
|
33
|
+
continue;
|
|
34
|
+
hash ^= Zobrist._pieceSquareHashMap[Zobrist.getPieceIndex(piece)][y][x];
|
|
35
|
+
if (piece.name === "king") {
|
|
36
|
+
if (piece.color === "white" && King.canShortCastle(game, { x, y }))
|
|
37
|
+
hash ^= Zobrist._castlingRights[CastleType.WHITE_SHORT_CASTLE];
|
|
38
|
+
if (piece.color === "white" && King.canLongCastle(game, { x, y }))
|
|
39
|
+
hash ^= Zobrist._castlingRights[CastleType.WHITE_LONG_CASTLE];
|
|
40
|
+
if (piece.color === "black" && King.canShortCastle(game, { x, y }))
|
|
41
|
+
hash ^= Zobrist._castlingRights[CastleType.BLACK_SHORT_CASTLE];
|
|
42
|
+
if (piece.color === "black" && King.canLongCastle(game, { x, y }))
|
|
43
|
+
hash ^= Zobrist._castlingRights[CastleType.BLACK_LONG_CASTLE];
|
|
44
|
+
}
|
|
45
|
+
else if (piece.name === "pawn") {
|
|
46
|
+
if (Pawn.isLeftEnPassantLegal(game, { x, y }))
|
|
47
|
+
hash ^= Zobrist._enPassantFile[x - 1];
|
|
48
|
+
if (Pawn.isRightEnPassantLegal(game, { x, y }))
|
|
49
|
+
hash ^= Zobrist._enPassantFile[x + 1];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// Adding Special Rights
|
|
54
|
+
hash = Zobrist.toggleSpecialRights(game.specialRights, hash);
|
|
55
|
+
// Setting Color for Side To Move
|
|
56
|
+
hash ^= Zobrist._sideToMove[game.currentTurnColor];
|
|
57
|
+
return hash;
|
|
58
|
+
}
|
|
59
|
+
static togglePieceAtPos(piece, pos, hash) {
|
|
60
|
+
hash ^= Zobrist._pieceSquareHashMap[Zobrist.getPieceIndex(piece)][pos.y][pos.x];
|
|
61
|
+
return hash;
|
|
62
|
+
}
|
|
63
|
+
static toggleEnPassantOnFile(file, hash) {
|
|
64
|
+
hash ^= Zobrist._enPassantFile[file];
|
|
65
|
+
return hash;
|
|
66
|
+
}
|
|
67
|
+
static toggleCastlingRights(castleType, hash) {
|
|
68
|
+
hash ^= Zobrist._castlingRights[castleType];
|
|
69
|
+
return hash;
|
|
70
|
+
}
|
|
71
|
+
static toggleSideToMove(color, hash) {
|
|
72
|
+
hash ^= Zobrist._sideToMove[color];
|
|
73
|
+
return hash;
|
|
74
|
+
}
|
|
75
|
+
static switchSideToMove(hash) {
|
|
76
|
+
hash ^= (Zobrist._sideToMove["white"] ^ Zobrist._sideToMove["black"]);
|
|
77
|
+
return hash;
|
|
78
|
+
}
|
|
79
|
+
static toggleSpecialRights(specialRights, hash) {
|
|
80
|
+
const { castlingRights, enPassantFile } = specialRights;
|
|
81
|
+
// Toggling Castling Rights
|
|
82
|
+
if (castlingRights[CastleType.WHITE_SHORT_CASTLE])
|
|
83
|
+
hash = Zobrist.toggleCastlingRights(CastleType.WHITE_SHORT_CASTLE, hash);
|
|
84
|
+
if (castlingRights[CastleType.WHITE_LONG_CASTLE])
|
|
85
|
+
hash = Zobrist.toggleCastlingRights(CastleType.WHITE_LONG_CASTLE, hash);
|
|
86
|
+
if (castlingRights[CastleType.BLACK_SHORT_CASTLE])
|
|
87
|
+
hash = Zobrist.toggleCastlingRights(CastleType.BLACK_SHORT_CASTLE, hash);
|
|
88
|
+
if (castlingRights[CastleType.BLACK_LONG_CASTLE])
|
|
89
|
+
hash = Zobrist.toggleCastlingRights(CastleType.BLACK_LONG_CASTLE, hash);
|
|
90
|
+
// Toggling EnPassant File
|
|
91
|
+
if (enPassantFile !== null)
|
|
92
|
+
hash = Zobrist.toggleEnPassantOnFile(enPassantFile, hash);
|
|
93
|
+
return hash;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
Zobrist.initializeValues();
|
|
97
|
+
export { Zobrist };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Hash } from "./zobrist.js";
|
|
2
|
+
import type { GameContext, GameSpecialRights } from "../types/game.js";
|
|
3
|
+
import type { MoveRecord } from "../types/move.js";
|
|
4
|
+
declare class ZobristUpdater {
|
|
5
|
+
private _currentHash;
|
|
6
|
+
private _hashMap;
|
|
7
|
+
private _hashMoveHistory;
|
|
8
|
+
get currentHash(): Readonly<Hash>;
|
|
9
|
+
rebuildHash(game: GameContext): void;
|
|
10
|
+
toggleMoveChanges(moveRecord: MoveRecord): void;
|
|
11
|
+
switchSideToMove(): void;
|
|
12
|
+
toggleSpecialRights(specialRights: GameSpecialRights): void;
|
|
13
|
+
addMoveRecord(game: GameContext, moveRecordIndex: number): void;
|
|
14
|
+
removeMoveRecord(game: GameContext, moveRecordIndex: number): void;
|
|
15
|
+
private recordCurrentHashOccurrence;
|
|
16
|
+
private removeCurrentHashOccurrence;
|
|
17
|
+
clearAllPreviousOccurrences(): void;
|
|
18
|
+
checkThreeFoldRepetition(game: GameContext): boolean;
|
|
19
|
+
}
|
|
20
|
+
export { ZobristUpdater };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { Zobrist } from "./zobrist.js";
|
|
2
|
+
class ZobristUpdater {
|
|
3
|
+
_currentHash = 0n;
|
|
4
|
+
_hashMap = new Map();
|
|
5
|
+
_hashMoveHistory = [];
|
|
6
|
+
// Getters
|
|
7
|
+
get currentHash() { return this._currentHash; }
|
|
8
|
+
// Update Hash Methods
|
|
9
|
+
rebuildHash(game) {
|
|
10
|
+
this._hashMap.clear();
|
|
11
|
+
this._currentHash = Zobrist.getBoardHash(game);
|
|
12
|
+
this._hashMap.set(this._currentHash, [-1]);
|
|
13
|
+
}
|
|
14
|
+
toggleMoveChanges(moveRecord) {
|
|
15
|
+
const { moves, captures, promotions } = moveRecord;
|
|
16
|
+
for (const { from, piece } of captures)
|
|
17
|
+
this._currentHash = Zobrist.togglePieceAtPos(piece, from, this._currentHash);
|
|
18
|
+
for (const { from, to, piece } of moves) {
|
|
19
|
+
this._currentHash = Zobrist.togglePieceAtPos(piece, from, this._currentHash);
|
|
20
|
+
this._currentHash = Zobrist.togglePieceAtPos(piece, to, this._currentHash);
|
|
21
|
+
}
|
|
22
|
+
for (const { to, piece } of promotions)
|
|
23
|
+
this._currentHash = Zobrist.togglePieceAtPos(piece, to, this._currentHash);
|
|
24
|
+
}
|
|
25
|
+
switchSideToMove() {
|
|
26
|
+
this._currentHash = Zobrist.switchSideToMove(this._currentHash);
|
|
27
|
+
}
|
|
28
|
+
toggleSpecialRights(specialRights) {
|
|
29
|
+
this._currentHash = Zobrist.toggleSpecialRights(specialRights, this._currentHash);
|
|
30
|
+
}
|
|
31
|
+
addMoveRecord(game, moveRecordIndex) {
|
|
32
|
+
if (moveRecordIndex < 0 || moveRecordIndex >= game.moveHistory.length)
|
|
33
|
+
return;
|
|
34
|
+
const moveRecord = game.moveHistory[moveRecordIndex];
|
|
35
|
+
// Removing old info from hash
|
|
36
|
+
this.toggleSpecialRights(game.specialRights);
|
|
37
|
+
// Applying new changes
|
|
38
|
+
game.updateSpecialRights();
|
|
39
|
+
this.switchSideToMove();
|
|
40
|
+
this.toggleMoveChanges(moveRecord);
|
|
41
|
+
this.toggleSpecialRights(game.specialRights);
|
|
42
|
+
this._hashMoveHistory.push(moveRecord);
|
|
43
|
+
// Adding New Occurrence
|
|
44
|
+
this.recordCurrentHashOccurrence(moveRecordIndex);
|
|
45
|
+
}
|
|
46
|
+
removeMoveRecord(game, moveRecordIndex) {
|
|
47
|
+
if (moveRecordIndex < 0 || moveRecordIndex >= game.moveHistory.length)
|
|
48
|
+
return;
|
|
49
|
+
const { _hashMoveHistory: hashMoveHistory } = this;
|
|
50
|
+
const moveRecord = game.moveHistory[moveRecordIndex];
|
|
51
|
+
if (hashMoveHistory.length === 0 || hashMoveHistory[hashMoveHistory.length - 1] !== moveRecord)
|
|
52
|
+
return;
|
|
53
|
+
// Removing Latest Occurrence
|
|
54
|
+
this.removeCurrentHashOccurrence();
|
|
55
|
+
// Reversing Hash
|
|
56
|
+
this.toggleMoveChanges(moveRecord);
|
|
57
|
+
this.toggleSpecialRights(game.specialRights);
|
|
58
|
+
this.switchSideToMove();
|
|
59
|
+
hashMoveHistory.pop();
|
|
60
|
+
game.updateSpecialRights();
|
|
61
|
+
this.toggleSpecialRights(game.specialRights);
|
|
62
|
+
}
|
|
63
|
+
// Hash Occurrences
|
|
64
|
+
recordCurrentHashOccurrence(index) {
|
|
65
|
+
const indexes = this._hashMap.get(this._currentHash) ?? [];
|
|
66
|
+
indexes.push(index);
|
|
67
|
+
this._hashMap.set(this._currentHash, indexes);
|
|
68
|
+
}
|
|
69
|
+
removeCurrentHashOccurrence() {
|
|
70
|
+
const indexes = this._hashMap.get(this._currentHash);
|
|
71
|
+
if (indexes) {
|
|
72
|
+
indexes.pop();
|
|
73
|
+
if (indexes.length === 0)
|
|
74
|
+
this._hashMap.delete(this._currentHash);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
clearAllPreviousOccurrences() {
|
|
78
|
+
const indexes = this._hashMap.get(this._currentHash);
|
|
79
|
+
this._hashMap.clear();
|
|
80
|
+
if (indexes)
|
|
81
|
+
this._hashMap.set(this._currentHash, indexes);
|
|
82
|
+
}
|
|
83
|
+
checkThreeFoldRepetition(game) {
|
|
84
|
+
const occurrences = this._hashMap.get(this._currentHash);
|
|
85
|
+
if (!occurrences || occurrences.length < 3)
|
|
86
|
+
return false;
|
|
87
|
+
// Current Position Snapshot
|
|
88
|
+
const currentBoard = game.board.copyBoard();
|
|
89
|
+
const currentTurnColor = game.currentTurnColor;
|
|
90
|
+
const currentSpecialRights = {
|
|
91
|
+
castlingRights: { ...game.specialRights.castlingRights },
|
|
92
|
+
enPassantFile: game.specialRights.enPassantFile
|
|
93
|
+
};
|
|
94
|
+
// Comparing all positions
|
|
95
|
+
const matches = game.evaluateAt(occurrences, (game) => {
|
|
96
|
+
game.updateSpecialRights();
|
|
97
|
+
return game.isSamePosition(currentBoard, currentTurnColor, currentSpecialRights);
|
|
98
|
+
});
|
|
99
|
+
let totalMatches = 0;
|
|
100
|
+
for (let i = 0; i < matches.length; ++i)
|
|
101
|
+
totalMatches += matches[i] ? 1 : 0;
|
|
102
|
+
return totalMatches === 3;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
export { ZobristUpdater };
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Move } from "../types/move.js";
|
|
2
|
+
import type { PieceColor } from "../types/piece.js";
|
|
3
|
+
import { Piece } from "./piece.js";
|
|
4
|
+
declare class Bishop extends Piece {
|
|
5
|
+
static readonly moves: Move[];
|
|
6
|
+
constructor(color: PieceColor);
|
|
7
|
+
getMoves(): readonly Move[];
|
|
8
|
+
}
|
|
9
|
+
export { Bishop };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Piece } from "./piece.js";
|
|
2
|
+
const BishopMoves = [
|
|
3
|
+
{ vec: { dx: 1, dy: 1 }, isSliding: true, canAttack: true },
|
|
4
|
+
{ vec: { dx: -1, dy: 1 }, isSliding: true, canAttack: true },
|
|
5
|
+
{ vec: { dx: -1, dy: -1 }, isSliding: true, canAttack: true },
|
|
6
|
+
{ vec: { dx: 1, dy: -1 }, isSliding: true, canAttack: true }
|
|
7
|
+
];
|
|
8
|
+
class Bishop extends Piece {
|
|
9
|
+
static moves = BishopMoves;
|
|
10
|
+
constructor(color) {
|
|
11
|
+
super(color, "bishop");
|
|
12
|
+
}
|
|
13
|
+
getMoves() {
|
|
14
|
+
return Bishop.moves;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export { Bishop };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { Piece } from './piece.js';
|
|
2
|
+
export { Pawn } from './pawn.js';
|
|
3
|
+
export { Knight } from './knight.js';
|
|
4
|
+
export { Bishop } from './bishop.js';
|
|
5
|
+
export { Rook } from './rook.js';
|
|
6
|
+
export { Queen } from './queen.js';
|
|
7
|
+
export { King } from './king.js';
|
|
8
|
+
export type { PieceColor, PieceName, PieceColorCode, PieceNameCode, PieceLayoutCode } from "../types/piece.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Move, Position, MoveGameContext } from "../types/move.js";
|
|
2
|
+
import type { PieceColor } from "../types/piece.js";
|
|
3
|
+
import { Piece } from "./piece.js";
|
|
4
|
+
declare class King extends Piece {
|
|
5
|
+
static readonly moves: Move[];
|
|
6
|
+
constructor(color: PieceColor);
|
|
7
|
+
getMoves(): readonly Move[];
|
|
8
|
+
private static canCastle;
|
|
9
|
+
static canShortCastle(game: MoveGameContext, pos: Position): boolean;
|
|
10
|
+
static canLongCastle(game: MoveGameContext, pos: Position): boolean;
|
|
11
|
+
}
|
|
12
|
+
export { King };
|