gigachess 0.6.0 → 0.7.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.
Files changed (87) hide show
  1. package/README.md +82 -49
  2. package/dist/attacks.d.ts +7 -4
  3. package/dist/attacks.d.ts.map +1 -1
  4. package/dist/attacks.js +36 -15
  5. package/dist/chess960.d.ts +2 -9
  6. package/dist/chess960.d.ts.map +1 -1
  7. package/dist/chess960.js +2 -18
  8. package/dist/chessjs.d.ts +1 -1
  9. package/dist/chessjs.d.ts.map +1 -1
  10. package/dist/chessjs.js +1 -1
  11. package/dist/chessops/board.d.ts +1 -1
  12. package/dist/chessops/board.d.ts.map +1 -1
  13. package/dist/chessops/board.js +1 -1
  14. package/dist/chessops/chess.d.ts +6 -10
  15. package/dist/chessops/chess.d.ts.map +1 -1
  16. package/dist/chessops/chess.js +73 -97
  17. package/dist/chessops/convert.d.ts +1 -1
  18. package/dist/chessops/convert.d.ts.map +1 -1
  19. package/dist/chessops/convert.js +1 -1
  20. package/dist/chessops/debug.d.ts.map +1 -1
  21. package/dist/chessops/debug.js +7 -0
  22. package/dist/chessops/fen.d.ts.map +1 -1
  23. package/dist/chessops/fen.js +13 -2
  24. package/dist/chessops/fenInternal.d.ts +1 -1
  25. package/dist/chessops/fenInternal.d.ts.map +1 -1
  26. package/dist/chessops/fenInternal.js +1 -1
  27. package/dist/chessops/nativeBridge.d.ts +14 -0
  28. package/dist/chessops/nativeBridge.d.ts.map +1 -0
  29. package/dist/chessops/nativeBridge.js +87 -0
  30. package/dist/chessops/san.d.ts.map +1 -1
  31. package/dist/chessops/san.js +12 -10
  32. package/dist/chesstree.d.ts.map +1 -1
  33. package/dist/chesstree.js +23 -62
  34. package/dist/core.d.ts +6 -8
  35. package/dist/core.d.ts.map +1 -1
  36. package/dist/core.js +5 -10
  37. package/dist/fast/index.js +1 -1
  38. package/dist/fast.d.ts +1 -11
  39. package/dist/fast.d.ts.map +1 -1
  40. package/dist/fast.js +2 -11
  41. package/dist/index.d.ts +1 -14
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +2 -19
  44. package/dist/native96.d.ts +16 -0
  45. package/dist/native96.d.ts.map +1 -0
  46. package/dist/native96.js +6 -0
  47. package/dist/nativeBoard96.d.ts +118 -0
  48. package/dist/nativeBoard96.d.ts.map +1 -0
  49. package/dist/nativeBoard96.js +1077 -0
  50. package/dist/nativeChess.d.ts +97 -0
  51. package/dist/nativeChess.d.ts.map +1 -0
  52. package/dist/nativeChess.js +201 -0
  53. package/dist/nativeMovegen96.d.ts +2 -0
  54. package/dist/nativeMovegen96.d.ts.map +1 -0
  55. package/dist/{standardMovegen.js → nativeMovegen96.js} +77 -48
  56. package/dist/nativePublicTypes.d.ts +3 -0
  57. package/dist/nativePublicTypes.d.ts.map +1 -0
  58. package/dist/nativePublicTypes.js +1 -0
  59. package/dist/perftCompact.d.ts +7 -0
  60. package/dist/perftCompact.d.ts.map +1 -1
  61. package/dist/perftCompact.js +124 -62
  62. package/dist/pgn.d.ts +2 -3
  63. package/dist/pgn.d.ts.map +1 -1
  64. package/dist/pgn.js +2 -5
  65. package/dist/setupBoard.d.ts +54 -0
  66. package/dist/setupBoard.d.ts.map +1 -0
  67. package/dist/setupBoard.js +249 -0
  68. package/dist/{fen.d.ts → setupFen.d.ts} +1 -1
  69. package/dist/setupFen.d.ts.map +1 -0
  70. package/dist/{fen.js → setupFen.js} +1 -1
  71. package/dist/types.d.ts +1 -1
  72. package/dist/types.d.ts.map +1 -1
  73. package/dist/zobrist.d.ts +2 -2
  74. package/dist/zobrist.d.ts.map +1 -1
  75. package/package.json +10 -7
  76. package/dist/board.d.ts +0 -242
  77. package/dist/board.d.ts.map +0 -1
  78. package/dist/board.js +0 -1403
  79. package/dist/chess.d.ts +0 -259
  80. package/dist/chess.d.ts.map +0 -1
  81. package/dist/chess.js +0 -2314
  82. package/dist/fen.d.ts.map +0 -1
  83. package/dist/san.d.ts +0 -38
  84. package/dist/san.d.ts.map +0 -1
  85. package/dist/san.js +0 -523
  86. package/dist/standardMovegen.d.ts +0 -3
  87. package/dist/standardMovegen.d.ts.map +0 -1
package/dist/board.js DELETED
@@ -1,1403 +0,0 @@
1
- import { compactPerft } from "./perftCompact.js";
2
- import * as sq from "./squareSet.js";
3
- import { Color, Role } from "./types.js";
4
- import { opposite } from "./util.js";
5
- import { kingAttackers, attackersTo } from "./attacks.js";
6
- import { zobristTablesLoaded, calculateZobrist, zobristHex, pieceKeyIdx, castlingKeyIdx, epIsHashable, keyLo, keyHi, castleKeyLo, castleKeyHi, IDX_EP, IDX_SIDE, } from "./zobrist.js";
7
- import { CASTLE_CLEAR_STD, CASTLING_RIGHTS_TABLE, fixedRookRights, getCastlingMask, detectCastling, } from "./castling.js";
8
- import { packOf, unpackToMove, promoCodeToRole, isNull, } from "./packedMove.js";
9
- import { parseFen, makeFen } from "./fen.js";
10
- import { parseSan, parseSanCandidates, makeSan, parseUci, makeUci } from "./san.js";
11
- import { legalMovesInto, forEachLegalMove, countLegalMoves, analyzeCheckContext, isLegal, INITIAL_FEN } from "./chess.js";
12
- const PERFT_ADJACENT_FILES = Int32Array.from({ length: 64 }, (_, square) => ((square & 7) !== 0 ? 1 << ((square - 1) & 31) : 0) |
13
- ((square & 7) !== 7 ? 1 << ((square + 1) & 31) : 0));
14
- // Internal synchronous move generation has no user callbacks. Scratch does
15
- // not escape: each public result is an independently owned typed array.
16
- const ownedMoveScratch = new Uint16Array(256);
17
- let ownedMoveScratchBusy = false;
18
- // Cache only the canonical initial position, not arbitrary user FENs.
19
- // Each instance receives independent mutable bitboards and king coordinates.
20
- let initialTemplate;
21
- let buildingInitialTemplate = false;
22
- export class Board {
23
- constructor(input) {
24
- // Prepare the single canonical template on first ordinary Board use,
25
- // even for an arbitrary input FEN. In addition to cheap start-position
26
- // creation, keeping this reusable instance stabilizes V8's weak
27
- // optimized-code dependencies across full collections.
28
- // Avoid eager module evaluation (the board/FEN modules are cyclic).
29
- if (new.target === Board && initialTemplate === undefined && !buildingInitialTemplate) {
30
- buildingInitialTemplate = true;
31
- try {
32
- initialTemplate = new Board(INITIAL_FEN);
33
- }
34
- finally {
35
- buildingInitialTemplate = false;
36
- }
37
- }
38
- // String construction owns the newly parsed board. Unlike loadFen on an
39
- // existing Board, there are no prior public bitboard references to retain.
40
- // Subclass initialization keeps the original virtual loadFen behavior.
41
- if (new.target === Board && (input === undefined || typeof input === "string")) {
42
- const fen = input ?? INITIAL_FEN;
43
- const template = fen === INITIAL_FEN ? initialTemplate : undefined;
44
- let pos, b;
45
- if (template) {
46
- pos = template;
47
- b = cloneAsWritable(template);
48
- }
49
- else {
50
- const parsed = parseFen(fen);
51
- if (!parsed.ok)
52
- throw new Error(`Invalid FEN: ${fen}`);
53
- pos = parsed.value;
54
- b = pos.board;
55
- }
56
- this.white = b.white;
57
- this.black = b.black;
58
- this.pawn = b.pawn;
59
- this.knight = b.knight;
60
- this.bishop = b.bishop;
61
- this.rook = b.rook;
62
- this.queen = b.queen;
63
- this.king = b.king;
64
- this.occupied = b.occupied;
65
- this.promoted = b.promoted;
66
- this.kingSq = b.kingSq;
67
- this.turn = pos.turn;
68
- this.castling = pos.castling;
69
- this.castlingMask = pos.castlingMask;
70
- this.epSquare = pos.epSquare;
71
- this.halfmoves = pos.halfmoves ?? pos.halfmove ?? 0;
72
- this.fullmoves = pos.fullmoves ?? pos.fullmove ?? 1;
73
- this.checkers = template ? { lo: template.checkers.lo, hi: template.checkers.hi } : pos.checkers;
74
- this.isChess960 = !!pos.isChess960;
75
- this._zobristLo = pos.zobristLo ?? 0;
76
- this._zobristHi = pos.zobristHi ?? 0;
77
- if (this._zobristLo === 0 && this._zobristHi === 0 && zobristTablesLoaded())
78
- this.refreshZobrist();
79
- return;
80
- }
81
- this.white = { lo: 0, hi: 0 };
82
- this.black = { lo: 0, hi: 0 };
83
- this.pawn = { lo: 0, hi: 0 };
84
- this.knight = { lo: 0, hi: 0 };
85
- this.bishop = { lo: 0, hi: 0 };
86
- this.rook = { lo: 0, hi: 0 };
87
- this.queen = { lo: 0, hi: 0 };
88
- this.king = { lo: 0, hi: 0 };
89
- this.occupied = { lo: 0, hi: 0 };
90
- this.promoted = { lo: 0, hi: 0 };
91
- this.kingSq = [-1, -1];
92
- this.turn = Color.White;
93
- this.castling = {
94
- white: new Set(),
95
- black: new Set(),
96
- whiteKing: false,
97
- whiteQueen: false,
98
- blackKing: false,
99
- blackQueen: false,
100
- };
101
- this.castlingMask = 0;
102
- this.epSquare = null;
103
- this.halfmoves = 0;
104
- this.fullmoves = 1;
105
- this.checkers = { lo: 0, hi: 0 };
106
- this._zobristLo = 0;
107
- this._zobristHi = 0;
108
- this.isChess960 = false;
109
- if (input === undefined) {
110
- this.loadFen(INITIAL_FEN);
111
- }
112
- else if (typeof input === "string") {
113
- this.loadFen(input);
114
- }
115
- else {
116
- this.copyFrom(input);
117
- }
118
- }
119
- static startpos() {
120
- return new Board();
121
- }
122
- static empty() {
123
- const b = new Board();
124
- b.clear();
125
- return b;
126
- }
127
- static fromFen(fen, opts) {
128
- if (!opts)
129
- return new Board(fen);
130
- const parsed = parseFen(fen, opts);
131
- if (!parsed.ok)
132
- throw new Error(`Invalid FEN: ${fen}`);
133
- return new Board(parsed.value);
134
- }
135
- static fromMoves2(buffer, startFen = INITIAL_FEN, isChess960 = false) {
136
- const b = Board.fromFen(startFen, isChess960 ? { chess960: true } : undefined);
137
- // moves2 is little-endian; a Uint8Array slice may have an odd byte offset.
138
- // Retain zero-copy for aligned words and decode only unaligned input.
139
- const moves = Board.moveWords(buffer);
140
- for (let i = 0; i < moves.length; i++) {
141
- b.makeMove(moves[i]);
142
- }
143
- return b;
144
- }
145
- /** Decode a moves2 byte stream, including unaligned Uint8Array views. */
146
- static moveWords(buffer) {
147
- if (buffer instanceof Uint16Array)
148
- return buffer;
149
- const length = buffer.byteLength >>> 1;
150
- if ((buffer.byteOffset & 1) === 0) {
151
- return new Uint16Array(buffer.buffer, buffer.byteOffset, length);
152
- }
153
- const words = new Uint16Array(length);
154
- for (let i = 0; i < length; i++)
155
- words[i] = buffer[i * 2] | (buffer[i * 2 + 1] << 8);
156
- return words;
157
- }
158
- /** Checked moves2 replay for untrusted files and network input. */
159
- static fromMoves2Checked(buffer, startFen = INITIAL_FEN, isChess960 = false) {
160
- if (buffer instanceof Uint8Array && !(buffer instanceof Uint16Array) && (buffer.byteLength & 1)) {
161
- throw new Error("moves2: truncated 16-bit word");
162
- }
163
- const b = Board.fromFen(startFen, isChess960 ? { chess960: true } : undefined);
164
- const moves = Board.moveWords(buffer);
165
- for (let i = 0; i < moves.length; i++) {
166
- if (!isLegal(b.pos, unpackToMove(moves[i]))) {
167
- throw new Error(`moves2: illegal move at ply ${i + 1}`);
168
- }
169
- b.makeMove(moves[i]);
170
- }
171
- return b;
172
- }
173
- get board() {
174
- return this;
175
- }
176
- get pos() {
177
- return this;
178
- }
179
- toPosition() {
180
- return {
181
- board: {
182
- white: { lo: this.white.lo >>> 0, hi: this.white.hi >>> 0 },
183
- black: { lo: this.black.lo >>> 0, hi: this.black.hi >>> 0 },
184
- pawn: { lo: this.pawn.lo >>> 0, hi: this.pawn.hi >>> 0 },
185
- knight: { lo: this.knight.lo >>> 0, hi: this.knight.hi >>> 0 },
186
- bishop: { lo: this.bishop.lo >>> 0, hi: this.bishop.hi >>> 0 },
187
- rook: { lo: this.rook.lo >>> 0, hi: this.rook.hi >>> 0 },
188
- queen: { lo: this.queen.lo >>> 0, hi: this.queen.hi >>> 0 },
189
- king: { lo: this.king.lo >>> 0, hi: this.king.hi >>> 0 },
190
- occupied: { lo: this.occupied.lo >>> 0, hi: this.occupied.hi >>> 0 },
191
- promoted: { lo: this.promoted.lo >>> 0, hi: this.promoted.hi >>> 0 },
192
- kingSq: [this.kingSq[0], this.kingSq[1]],
193
- },
194
- turn: this.turn,
195
- castling: this.castling,
196
- castlingMask: this.castlingMask,
197
- isChess960: this.isChess960,
198
- epSquare: this.epSquare,
199
- halfmoves: this.halfmoves,
200
- fullmoves: this.fullmoves,
201
- halfmove: this.halfmoves,
202
- fullmove: this.fullmoves,
203
- kingSq: [this.kingSq[0], this.kingSq[1]],
204
- checkers: { lo: this.checkers.lo >>> 0, hi: this.checkers.hi >>> 0 },
205
- zobristLo: this.zobristLo,
206
- zobristHi: this.zobristHi,
207
- };
208
- }
209
- get halfmove() {
210
- return this.halfmoves;
211
- }
212
- get fullmove() {
213
- return this.fullmoves;
214
- }
215
- get zobristLo() {
216
- if (this._zobristLo === 0 && this._zobristHi === 0 && zobristTablesLoaded()) {
217
- this.refreshZobrist();
218
- }
219
- return this._zobristLo;
220
- }
221
- get zobristHi() {
222
- if (this._zobristLo === 0 && this._zobristHi === 0 && zobristTablesLoaded()) {
223
- this.refreshZobrist();
224
- }
225
- return this._zobristHi;
226
- }
227
- zobrist() {
228
- return { lo: this.zobristLo, hi: this.zobristHi };
229
- }
230
- zobristBigInt() {
231
- return (BigInt(this.zobristHi >>> 0) << 32n) | BigInt(this.zobristLo >>> 0);
232
- }
233
- zobristHex() {
234
- return zobristHex({ lo: this.zobristLo, hi: this.zobristHi });
235
- }
236
- inCheck() {
237
- return ((this.checkers.lo | this.checkers.hi) !== 0);
238
- }
239
- refreshZobrist() {
240
- if (zobristTablesLoaded()) {
241
- const zk = calculateZobrist(this);
242
- this._zobristLo = zk.lo;
243
- this._zobristHi = zk.hi;
244
- }
245
- }
246
- clear() {
247
- this.white.lo = 0;
248
- this.white.hi = 0;
249
- this.black.lo = 0;
250
- this.black.hi = 0;
251
- this.pawn.lo = 0;
252
- this.pawn.hi = 0;
253
- this.knight.lo = 0;
254
- this.knight.hi = 0;
255
- this.bishop.lo = 0;
256
- this.bishop.hi = 0;
257
- this.rook.lo = 0;
258
- this.rook.hi = 0;
259
- this.queen.lo = 0;
260
- this.queen.hi = 0;
261
- this.king.lo = 0;
262
- this.king.hi = 0;
263
- this.occupied.lo = 0;
264
- this.occupied.hi = 0;
265
- this.promoted.lo = 0;
266
- this.promoted.hi = 0;
267
- this.kingSq[0] = -1;
268
- this.kingSq[1] = -1;
269
- this.turn = Color.White;
270
- this.castling = {
271
- white: new Set(),
272
- black: new Set(),
273
- whiteKing: false,
274
- whiteQueen: false,
275
- blackKing: false,
276
- blackQueen: false,
277
- };
278
- this.castlingMask = 0;
279
- this.epSquare = null;
280
- this.halfmoves = 0;
281
- this.fullmoves = 1;
282
- this.checkers = { lo: 0, hi: 0 };
283
- this._zobristLo = 0;
284
- this._zobristHi = 0;
285
- this.isChess960 = false;
286
- return this;
287
- }
288
- loadFen(fen) {
289
- const res = parseFen(fen);
290
- if (!res.ok)
291
- throw new Error(`Invalid FEN: ${fen}`);
292
- this.copyFrom(res.value);
293
- }
294
- copyFrom(src) {
295
- const b = "board" in src && src.board ? src.board : src;
296
- this.white.lo = b.white.lo;
297
- this.white.hi = b.white.hi;
298
- this.black.lo = b.black.lo;
299
- this.black.hi = b.black.hi;
300
- this.pawn.lo = b.pawn.lo;
301
- this.pawn.hi = b.pawn.hi;
302
- this.knight.lo = b.knight.lo;
303
- this.knight.hi = b.knight.hi;
304
- this.bishop.lo = b.bishop.lo;
305
- this.bishop.hi = b.bishop.hi;
306
- this.rook.lo = b.rook.lo;
307
- this.rook.hi = b.rook.hi;
308
- this.queen.lo = b.queen.lo;
309
- this.queen.hi = b.queen.hi;
310
- this.king.lo = b.king.lo;
311
- this.king.hi = b.king.hi;
312
- this.occupied.lo = b.occupied.lo;
313
- this.occupied.hi = b.occupied.hi;
314
- this.promoted.lo = b.promoted.lo;
315
- this.promoted.hi = b.promoted.hi;
316
- const pos = src;
317
- this.turn = pos.turn ?? Color.White;
318
- const rights = pos.castling;
319
- this.castling = rights
320
- ? (!pos.isChess960 && pos.castlingMask !== undefined
321
- ? CASTLING_RIGHTS_TABLE[pos.castlingMask]
322
- : Object.freeze({
323
- ...rights,
324
- white: fixedRookRights(rights.white),
325
- black: fixedRookRights(rights.black),
326
- }))
327
- : CASTLING_RIGHTS_TABLE[0];
328
- this.castlingMask = pos.castlingMask;
329
- this.epSquare = pos.epSquare ?? null;
330
- this.halfmoves = pos.halfmoves ?? pos.halfmove ?? 0;
331
- this.fullmoves = pos.fullmoves ?? pos.fullmove ?? 1;
332
- this.isChess960 = !!pos.isChess960;
333
- if (b.kingSq) {
334
- this.kingSq[0] = b.kingSq[0];
335
- this.kingSq[1] = b.kingSq[1];
336
- }
337
- else if (pos.kingSq) {
338
- this.kingSq[0] = pos.kingSq[0];
339
- this.kingSq[1] = pos.kingSq[1];
340
- }
341
- else {
342
- this.kingSq[0] = kingSquare(this, Color.White) ?? -1;
343
- this.kingSq[1] = kingSquare(this, Color.Black) ?? -1;
344
- }
345
- if (pos.checkers) {
346
- this.checkers = { lo: pos.checkers.lo, hi: pos.checkers.hi };
347
- }
348
- else {
349
- this.checkers = kingAttackers(this, this.turn);
350
- }
351
- this._zobristLo = pos.zobristLo ?? 0;
352
- this._zobristHi = pos.zobristHi ?? 0;
353
- if (this._zobristLo === 0 && this._zobristHi === 0 && zobristTablesLoaded()) {
354
- this.refreshZobrist();
355
- }
356
- return this;
357
- }
358
- clone() {
359
- const nb = Board.empty();
360
- nb.copyFrom(this);
361
- return nb;
362
- }
363
- roleAt(sqIdx) {
364
- const bit = sqIdx < 32 ? (1 << sqIdx) >>> 0 : (1 << (sqIdx - 32)) >>> 0;
365
- const occ = sqIdx < 32 ? this.occupied.lo : this.occupied.hi;
366
- if (((occ & bit) >>> 0) === 0)
367
- return undefined;
368
- const pawnW = sqIdx < 32 ? this.pawn.lo : this.pawn.hi;
369
- if (((pawnW & bit) >>> 0) !== 0)
370
- return Role.Pawn;
371
- const knightW = sqIdx < 32 ? this.knight.lo : this.knight.hi;
372
- if (((knightW & bit) >>> 0) !== 0)
373
- return Role.Knight;
374
- const bishopW = sqIdx < 32 ? this.bishop.lo : this.bishop.hi;
375
- if (((bishopW & bit) >>> 0) !== 0)
376
- return Role.Bishop;
377
- const rookW = sqIdx < 32 ? this.rook.lo : this.rook.hi;
378
- if (((rookW & bit) >>> 0) !== 0)
379
- return Role.Rook;
380
- const queenW = sqIdx < 32 ? this.queen.lo : this.queen.hi;
381
- if (((queenW & bit) >>> 0) !== 0)
382
- return Role.Queen;
383
- return Role.King;
384
- }
385
- colorAt(sqIdx) {
386
- const bit = sqIdx < 32 ? (1 << sqIdx) >>> 0 : (1 << (sqIdx - 32)) >>> 0;
387
- const occ = sqIdx < 32 ? this.occupied.lo : this.occupied.hi;
388
- if (((occ & bit) >>> 0) === 0)
389
- return undefined;
390
- const whiteW = sqIdx < 32 ? this.white.lo : this.white.hi;
391
- return ((whiteW & bit) >>> 0) !== 0 ? Color.White : Color.Black;
392
- }
393
- pieceAt(sqIdx) {
394
- const role = this.roleAt(sqIdx);
395
- if (role === undefined)
396
- return undefined;
397
- const color = this.colorAt(sqIdx);
398
- return { color, role };
399
- }
400
- hasPiece(sqIdx) {
401
- const bit = sqIdx < 32 ? (1 << sqIdx) >>> 0 : (1 << (sqIdx - 32)) >>> 0;
402
- const occ = sqIdx < 32 ? this.occupied.lo : this.occupied.hi;
403
- return ((occ & bit) >>> 0) !== 0;
404
- }
405
- kingSquare(color) {
406
- const k = this.kingSq[color];
407
- if (k >= 0)
408
- return k;
409
- const ks = color === Color.White ? sq.and(this.white, this.king) : sq.and(this.black, this.king);
410
- return sq.first(ks);
411
- }
412
- _clearSquare(sqIdx) {
413
- if (sqIdx < 32) {
414
- const inv = ~(1 << sqIdx);
415
- this.white.lo &= inv;
416
- this.black.lo &= inv;
417
- this.pawn.lo &= inv;
418
- this.knight.lo &= inv;
419
- this.bishop.lo &= inv;
420
- this.rook.lo &= inv;
421
- this.queen.lo &= inv;
422
- this.king.lo &= inv;
423
- this.occupied.lo &= inv;
424
- this.promoted.lo &= inv;
425
- }
426
- else {
427
- const inv = ~(1 << (sqIdx - 32));
428
- this.white.hi &= inv;
429
- this.black.hi &= inv;
430
- this.pawn.hi &= inv;
431
- this.knight.hi &= inv;
432
- this.bishop.hi &= inv;
433
- this.rook.hi &= inv;
434
- this.queen.hi &= inv;
435
- this.king.hi &= inv;
436
- this.occupied.hi &= inv;
437
- this.promoted.hi &= inv;
438
- }
439
- }
440
- _putPiece(sqIdx, color, role) {
441
- if (sqIdx < 32) {
442
- const bit = (1 << sqIdx) >>> 0;
443
- if (color === Color.White)
444
- this.white.lo |= bit;
445
- else
446
- this.black.lo |= bit;
447
- switch (role) {
448
- case Role.Pawn:
449
- this.pawn.lo |= bit;
450
- break;
451
- case Role.Knight:
452
- this.knight.lo |= bit;
453
- break;
454
- case Role.Bishop:
455
- this.bishop.lo |= bit;
456
- break;
457
- case Role.Rook:
458
- this.rook.lo |= bit;
459
- break;
460
- case Role.Queen:
461
- this.queen.lo |= bit;
462
- break;
463
- case Role.King:
464
- this.king.lo |= bit;
465
- break;
466
- }
467
- this.occupied.lo |= bit;
468
- }
469
- else {
470
- const bit = (1 << (sqIdx - 32)) >>> 0;
471
- if (color === Color.White)
472
- this.white.hi |= bit;
473
- else
474
- this.black.hi |= bit;
475
- switch (role) {
476
- case Role.Pawn:
477
- this.pawn.hi |= bit;
478
- break;
479
- case Role.Knight:
480
- this.knight.hi |= bit;
481
- break;
482
- case Role.Bishop:
483
- this.bishop.hi |= bit;
484
- break;
485
- case Role.Rook:
486
- this.rook.hi |= bit;
487
- break;
488
- case Role.Queen:
489
- this.queen.hi |= bit;
490
- break;
491
- case Role.King:
492
- this.king.hi |= bit;
493
- break;
494
- }
495
- this.occupied.hi |= bit;
496
- }
497
- if (role === Role.King) {
498
- this.kingSq[color] = sqIdx;
499
- }
500
- }
501
- /**
502
- * Plays a null move (pass): the position stays, the side to move flips.
503
- *
504
- * Castling rights are untouched, the en-passant square clears, the halfmove
505
- * clock advances and the move always completes a full move (the number
506
- * advances whoever passed). The Polyglot key and the cached `checkers` are
507
- * both maintained.
508
- *
509
- * Throws when the side to move is in check: a pass answers no check. The test
510
- * is computed from the bitboards (never from the cached `checkers`, which a
511
- * cache-free make may have left stale). Mirrors gigachess-rs
512
- * `Board::make_null_move`.
513
- */
514
- makeNullMove() {
515
- if (zobristTablesLoaded() && this._zobristLo === 0 && this._zobristHi === 0) {
516
- this.refreshZobrist();
517
- }
518
- const us = this.turn;
519
- const them = opposite(us);
520
- // Fresh in-check scan — the cache may describe an earlier position.
521
- const ksq = this.kingSq[us === Color.White ? 0 : 1];
522
- if (ksq >= 0 && !sq.isEmpty(attackersTo(this, ksq, them, this.occupied))) {
523
- throw new Error("illegal null move: the side to move is in check");
524
- }
525
- const undo = {
526
- isNull: true,
527
- epSquare: this.epSquare,
528
- castling: this.castling,
529
- castlingMask: this.castlingMask,
530
- halfmoves: this.halfmoves,
531
- fullmoves: this.fullmoves,
532
- kingSq: [this.kingSq[0], this.kingSq[1]],
533
- checkers: this.checkers,
534
- zobristLo: this._zobristLo,
535
- zobristHi: this._zobristHi,
536
- };
537
- // Hash out the old en-passant contribution (relevance uses the mover's
538
- // pawns, which a pass does not move) before clearing it.
539
- if (zobristTablesLoaded() && keyLo && keyHi) {
540
- if (this._zobristLo === 0 && this._zobristHi === 0)
541
- this.refreshZobrist();
542
- if (this.epSquare !== null && epIsHashable(this, this.epSquare, us)) {
543
- const kEp = IDX_EP + (this.epSquare & 7);
544
- this._zobristLo = (this._zobristLo ^ keyLo[kEp]) >>> 0;
545
- this._zobristHi = (this._zobristHi ^ keyHi[kEp]) >>> 0;
546
- }
547
- // a pass is a full move — the side key always flips
548
- this._zobristLo = (this._zobristLo ^ keyLo[IDX_SIDE]) >>> 0;
549
- this._zobristHi = (this._zobristHi ^ keyHi[IDX_SIDE]) >>> 0;
550
- }
551
- this.epSquare = null;
552
- this.halfmoves = this.halfmoves + 1;
553
- this.fullmoves = this.fullmoves + 1;
554
- this.turn = them;
555
- this.checkers = kingAttackers(this, them);
556
- return undo;
557
- }
558
- /**
559
- * Reverts the most recent null move, restoring the exact prior position.
560
- *
561
- * Each null must be unmade before an older one, with no ordinary moves
562
- * interleaved past the matching make — exactly like `unmakeMove`.
563
- */
564
- unmakeNullMove(undo) {
565
- this.turn = opposite(this.turn);
566
- this.fullmoves = undo.fullmoves;
567
- this.epSquare = undo.epSquare;
568
- this.castling = undo.castling;
569
- this.castlingMask = undo.castlingMask;
570
- this.halfmoves = undo.halfmoves;
571
- this.kingSq[0] = undo.kingSq[0];
572
- this.kingSq[1] = undo.kingSq[1];
573
- this.checkers = undo.checkers;
574
- this._zobristLo = undo.zobristLo;
575
- this._zobristHi = undo.zobristHi;
576
- }
577
- /** Public move execution always maintains the Polyglot hash. */
578
- makeMove(moveWord) {
579
- return this._makeMoveCore(moveWord, true);
580
- }
581
- /** Internal perft-only fast path; the cached hash is invalid until undo.
582
- * The method is PRIVATE so ordinary callers cannot corrupt their board.
583
- * Mirrors gigachess-rs make_move_perft without changing public semantics.
584
- */
585
- _makeMoveCore(moveWord, updateHash) {
586
- // Tables can become ready after this Board was constructed; refresh the
587
- // pre-move state BEFORE edits, never hash the new state as the old key.
588
- if (updateHash && zobristTablesLoaded() && this._zobristLo === 0 && this._zobristHi === 0) {
589
- this.refreshZobrist();
590
- }
591
- const word = typeof moveWord === "number" ? moveWord : packOf(moveWord);
592
- // The null sentinel is a first-class pass, not a from/to/promo word.
593
- if (isNull(word))
594
- return this.makeNullMove();
595
- const from = word & 0x3f;
596
- const to = (word >> 6) & 0x3f;
597
- const promoCode = (word >> 12) & 0x0f;
598
- const promoRole = promoCodeToRole(promoCode) ?? null;
599
- const movingRole = this.roleAt(from);
600
- if (movingRole === undefined) {
601
- throw new Error(`no piece at from square ${from}`);
602
- }
603
- const us = this.turn;
604
- const them = opposite(us);
605
- const prevCheckers = this.checkers;
606
- const prevZobristLo = this._zobristLo;
607
- const prevZobristHi = this._zobristHi;
608
- const prevCastling = this.castling;
609
- const prevCastlingMask = this.castlingMask;
610
- const prevEpSquare = this.epSquare;
611
- const prevHalfmoves = this.halfmoves;
612
- const prevFullmoves = this.fullmoves;
613
- const prevKingSq = [this.kingSq[0], this.kingSq[1]];
614
- const prevEpHashable = updateHash && prevEpSquare !== null && zobristTablesLoaded() && epIsHashable(this, prevEpSquare, us);
615
- let plan = null;
616
- if (movingRole === Role.King) {
617
- plan = detectCastling(this, from, to);
618
- }
619
- const isCastling = plan !== null;
620
- let isEnPassant = false;
621
- if (movingRole === Role.Pawn &&
622
- this.epSquare !== null &&
623
- to === this.epSquare &&
624
- (from & 7) !== (to & 7)) {
625
- isEnPassant = true;
626
- }
627
- let capturedRole = -1;
628
- let capturedSq = -1;
629
- if (isEnPassant) {
630
- capturedRole = Role.Pawn;
631
- capturedSq = us === Color.White ? to - 8 : to + 8;
632
- }
633
- else if (!isCastling) {
634
- const capRole = this.roleAt(to);
635
- if (capRole !== undefined) {
636
- capturedRole = capRole;
637
- capturedSq = to;
638
- }
639
- }
640
- this._clearSquare(from);
641
- if (capturedSq >= 0) {
642
- this._clearSquare(capturedSq);
643
- }
644
- if (isCastling && plan !== null) {
645
- this._clearSquare(plan.rookFrom);
646
- this._putPiece(plan.rookTo, us, Role.Rook);
647
- this._putPiece(plan.kingTo, us, Role.King);
648
- this.kingSq[us] = plan.kingTo;
649
- }
650
- else {
651
- const finalRole = promoRole ?? movingRole;
652
- this._putPiece(to, us, finalRole);
653
- if (movingRole === Role.King) {
654
- this.kingSq[us] = to;
655
- }
656
- }
657
- let newCastling;
658
- let newMask;
659
- if (!this.isChess960) {
660
- const mask = this.castlingMask ?? getCastlingMask(this);
661
- newMask = (mask & CASTLE_CLEAR_STD[from] & CASTLE_CLEAR_STD[to]) >>> 0;
662
- newCastling = CASTLING_RIGHTS_TABLE[newMask];
663
- }
664
- else {
665
- let newWhite = this.castling.white;
666
- let newBlack = this.castling.black;
667
- if (movingRole === Role.King) {
668
- if (us === Color.White) {
669
- if (newWhite.size > 0)
670
- newWhite = new Set();
671
- }
672
- else {
673
- if (newBlack.size > 0)
674
- newBlack = new Set();
675
- }
676
- }
677
- if (movingRole === Role.Rook) {
678
- if (us === Color.White && newWhite.has(from)) {
679
- const next = new Set(newWhite);
680
- next.delete(from);
681
- newWhite = next;
682
- }
683
- else if (us === Color.Black && newBlack.has(from)) {
684
- const next = new Set(newBlack);
685
- next.delete(from);
686
- newBlack = next;
687
- }
688
- }
689
- if (capturedRole === Role.Rook && capturedSq >= 0) {
690
- if (them === Color.White && newWhite.has(capturedSq)) {
691
- const next = new Set(newWhite);
692
- next.delete(capturedSq);
693
- newWhite = next;
694
- }
695
- else if (them === Color.Black && newBlack.has(capturedSq)) {
696
- const next = new Set(newBlack);
697
- next.delete(capturedSq);
698
- newBlack = next;
699
- }
700
- }
701
- newCastling = {
702
- white: newWhite,
703
- black: newBlack,
704
- whiteKing: newWhite.has(7),
705
- whiteQueen: newWhite.has(0),
706
- blackKing: newBlack.has(63),
707
- blackQueen: newBlack.has(56),
708
- };
709
- }
710
- this.castling = this.isChess960
711
- ? Object.freeze({
712
- ...newCastling,
713
- white: newCastling.white === prevCastling.white ? prevCastling.white : fixedRookRights(newCastling.white),
714
- black: newCastling.black === prevCastling.black ? prevCastling.black : fixedRookRights(newCastling.black),
715
- })
716
- : newCastling;
717
- this.castlingMask = newMask;
718
- let newEp = null;
719
- if (movingRole === Role.Pawn && Math.abs((to >> 3) - (from >> 3)) === 2) {
720
- const epRank = us === Color.White ? (from >> 3) + 1 : (from >> 3) - 1;
721
- newEp = (epRank << 3) | (from & 7);
722
- }
723
- this.epSquare = newEp;
724
- const isCapture = capturedSq >= 0;
725
- const isPawnMove = movingRole === Role.Pawn;
726
- this.halfmoves = isCapture || isPawnMove ? 0 : prevHalfmoves + 1;
727
- this.fullmoves = us === Color.Black ? prevFullmoves + 1 : prevFullmoves;
728
- this.turn = them;
729
- this.checkers = kingAttackers(this, them);
730
- if (updateHash && zobristTablesLoaded() && keyLo && keyHi && castleKeyLo && castleKeyHi) {
731
- let zLo = this._zobristLo;
732
- let zHi = this._zobristHi;
733
- // 1. Moving piece leaves from
734
- const kFrom = pieceKeyIdx(us, movingRole, from);
735
- zLo = (zLo ^ keyLo[kFrom]) >>> 0;
736
- zHi = (zHi ^ keyHi[kFrom]) >>> 0;
737
- // 2. Moving piece lands on to (or castling / promo)
738
- if (plan !== null) {
739
- const kRookFrom = pieceKeyIdx(us, Role.Rook, plan.rookFrom);
740
- const kRookTo = pieceKeyIdx(us, Role.Rook, plan.rookTo);
741
- const kKingTo = pieceKeyIdx(us, Role.King, plan.kingTo);
742
- zLo = (zLo ^ keyLo[kRookFrom] ^ keyLo[kRookTo] ^ keyLo[kKingTo]) >>> 0;
743
- zHi = (zHi ^ keyHi[kRookFrom] ^ keyHi[kRookTo] ^ keyHi[kKingTo]) >>> 0;
744
- }
745
- else if (promoRole !== null) {
746
- const kPromo = pieceKeyIdx(us, promoRole, to);
747
- zLo = (zLo ^ keyLo[kPromo]) >>> 0;
748
- zHi = (zHi ^ keyHi[kPromo]) >>> 0;
749
- }
750
- else {
751
- const kTo = pieceKeyIdx(us, movingRole, to);
752
- zLo = (zLo ^ keyLo[kTo]) >>> 0;
753
- zHi = (zHi ^ keyHi[kTo]) >>> 0;
754
- }
755
- // 3. Captured piece leaves board
756
- if (isEnPassant) {
757
- const capSq = us === Color.White ? to - 8 : to + 8;
758
- const kCap = pieceKeyIdx(them, Role.Pawn, capSq);
759
- zLo = (zLo ^ keyLo[kCap]) >>> 0;
760
- zHi = (zHi ^ keyHi[kCap]) >>> 0;
761
- }
762
- else if (capturedRole !== -1) {
763
- const kCap = pieceKeyIdx(them, capturedRole, to);
764
- zLo = (zLo ^ keyLo[kCap]) >>> 0;
765
- zHi = (zHi ^ keyHi[kCap]) >>> 0;
766
- }
767
- // 4. Castling rights diff
768
- if (!this.isChess960) {
769
- const diff = (prevCastlingMask ?? 0) ^ (newMask ?? 0);
770
- if (diff !== 0) {
771
- if (diff & 1) {
772
- zLo = (zLo ^ castleKeyLo[15]) >>> 0;
773
- zHi = (zHi ^ castleKeyHi[15]) >>> 0;
774
- }
775
- if (diff & 2) {
776
- zLo = (zLo ^ castleKeyLo[8]) >>> 0;
777
- zHi = (zHi ^ castleKeyHi[8]) >>> 0;
778
- }
779
- if (diff & 4) {
780
- zLo = (zLo ^ castleKeyLo[7]) >>> 0;
781
- zHi = (zHi ^ castleKeyHi[7]) >>> 0;
782
- }
783
- if (diff & 8) {
784
- zLo = (zLo ^ castleKeyLo[0]) >>> 0;
785
- zHi = (zHi ^ castleKeyHi[0]) >>> 0;
786
- }
787
- }
788
- }
789
- else {
790
- for (const rs of prevCastling.white) {
791
- const idx = castlingKeyIdx(Color.White, rs);
792
- zLo = (zLo ^ castleKeyLo[idx]) >>> 0;
793
- zHi = (zHi ^ castleKeyHi[idx]) >>> 0;
794
- }
795
- for (const rs of prevCastling.black) {
796
- const idx = castlingKeyIdx(Color.Black, rs);
797
- zLo = (zLo ^ castleKeyLo[idx]) >>> 0;
798
- zHi = (zHi ^ castleKeyHi[idx]) >>> 0;
799
- }
800
- for (const rs of newCastling.white) {
801
- const idx = castlingKeyIdx(Color.White, rs);
802
- zLo = (zLo ^ castleKeyLo[idx]) >>> 0;
803
- zHi = (zHi ^ castleKeyHi[idx]) >>> 0;
804
- }
805
- for (const rs of newCastling.black) {
806
- const idx = castlingKeyIdx(Color.Black, rs);
807
- zLo = (zLo ^ castleKeyLo[idx]) >>> 0;
808
- zHi = (zHi ^ castleKeyHi[idx]) >>> 0;
809
- }
810
- }
811
- // 5. En passant square diff
812
- if (prevEpHashable) {
813
- const kEp = IDX_EP + (prevEpSquare & 7);
814
- zLo = (zLo ^ keyLo[kEp]) >>> 0;
815
- zHi = (zHi ^ keyHi[kEp]) >>> 0;
816
- }
817
- if (newEp !== null && epIsHashable(this, newEp, them)) {
818
- const kEp = IDX_EP + (newEp & 7);
819
- zLo = (zLo ^ keyLo[kEp]) >>> 0;
820
- zHi = (zHi ^ keyHi[kEp]) >>> 0;
821
- }
822
- // 6. Turn flip
823
- zLo = (zLo ^ keyLo[IDX_SIDE]) >>> 0;
824
- zHi = (zHi ^ keyHi[IDX_SIDE]) >>> 0;
825
- this._zobristLo = zLo;
826
- this._zobristHi = zHi;
827
- }
828
- return {
829
- move: word,
830
- movingRole,
831
- capturedRole,
832
- capturedSq,
833
- castlingPlan: plan,
834
- isEnPassant,
835
- promoRole,
836
- epSquare: prevEpSquare,
837
- castling: prevCastling,
838
- castlingMask: prevCastlingMask,
839
- halfmoves: prevHalfmoves,
840
- fullmoves: prevFullmoves,
841
- kingSq: prevKingSq,
842
- checkers: prevCheckers,
843
- zobristLo: prevZobristLo,
844
- zobristHi: prevZobristHi,
845
- };
846
- }
847
- unmakeMove(undo) {
848
- // A pass records no piece edits — restore clocks/turn/caches only.
849
- if (undo.isNull === true) {
850
- this.unmakeNullMove(undo);
851
- return;
852
- }
853
- const normal = undo;
854
- const from = normal.move & 0x3f;
855
- const to = (normal.move >> 6) & 0x3f;
856
- const us = opposite(this.turn);
857
- this.turn = us;
858
- this.halfmoves = normal.halfmoves;
859
- this.fullmoves = normal.fullmoves;
860
- this.epSquare = normal.epSquare;
861
- this.castling = normal.castling;
862
- this.castlingMask = normal.castlingMask;
863
- this.kingSq[0] = normal.kingSq[0];
864
- this.kingSq[1] = normal.kingSq[1];
865
- this.checkers = normal.checkers;
866
- this._zobristLo = normal.zobristLo;
867
- this._zobristHi = normal.zobristHi;
868
- if (normal.castlingPlan !== null) {
869
- const plan = normal.castlingPlan;
870
- this._clearSquare(plan.kingTo);
871
- this._clearSquare(plan.rookTo);
872
- this._putPiece(plan.kingFrom, us, Role.King);
873
- this._putPiece(plan.rookFrom, us, Role.Rook);
874
- }
875
- else {
876
- this._clearSquare(to);
877
- this._putPiece(from, us, normal.movingRole);
878
- if (normal.capturedSq >= 0 && normal.capturedRole >= 0) {
879
- const them = opposite(us);
880
- this._putPiece(normal.capturedSq, them, normal.capturedRole);
881
- }
882
- }
883
- }
884
- legalMoves(outBuffer) {
885
- if (outBuffer) {
886
- const count = legalMovesInto(this, outBuffer);
887
- return outBuffer.subarray(0, count);
888
- }
889
- // Reentrant calls (e.g. through custom property accessors) must not
890
- // overwrite an in-flight list. Caller-owned buffer contract unchanged.
891
- if (ownedMoveScratchBusy) {
892
- const local = new Uint16Array(256);
893
- return local.subarray(0, legalMovesInto(this, local));
894
- }
895
- ownedMoveScratchBusy = true;
896
- try {
897
- const count = legalMovesInto(this, ownedMoveScratch);
898
- return ownedMoveScratch.slice(0, count);
899
- }
900
- finally {
901
- ownedMoveScratchBusy = false;
902
- }
903
- }
904
- forEachLegalMove(fn) {
905
- forEachLegalMove(this, (from, to, promo) => {
906
- fn(((from & 0x3f) | ((to & 0x3f) << 6) | ((promo & 0x0f) << 12)) >>> 0);
907
- });
908
- }
909
- toSan(moveWord) {
910
- const move = unpackToMove(moveWord);
911
- return makeSan(move, this);
912
- }
913
- toUci(moveWord) {
914
- const move = unpackToMove(moveWord);
915
- return makeUci(move);
916
- }
917
- toFen() {
918
- return makeFen(this);
919
- }
920
- parseSan(san) {
921
- const res = parseSan(san, this);
922
- return res.ok ? packOf(res.value) : null;
923
- }
924
- /**
925
- * `parseSan` with the failure reason kept.
926
- *
927
- * `parseSan` maps every error — `san/ambiguous`, `san/noLegalMove`,
928
- * `san/invalidSan` — onto the same `null`, so a caller cannot tell "no such
929
- * move" from "several moves answer to this and you must disambiguate". Those
930
- * are different answers for a UI: one is an error, the other needs the
931
- * candidates named (BlindBase ADR-042, field report #11).
932
- *
933
- * The error code is returned rather than a richer object because the codes
934
- * are the library's own error vocabulary (`SanError["code"]`), already
935
- * documented and already i18n-keyed upstream.
936
- */
937
- parseSanResult(san) {
938
- const res = parseSan(san, this);
939
- return res.ok
940
- ? { ok: true, moveWord: packOf(res.value) }
941
- : { ok: false, code: res.error.code };
942
- }
943
- parseUci(uci) {
944
- const res = parseUci(uci);
945
- return res.ok && isLegal(this, res.value) ? packOf(res.value) : null;
946
- }
947
- /**
948
- * Every packed move word `san` could denote here, or the reason it names none.
949
- *
950
- * `parseSan` reports `san/ambiguous` and discards the matches, so a caller
951
- * can tell the user the input was ambiguous but not which moves it meant.
952
- * This returns them, letting a caller present the disambiguated spellings
953
- * rather than making the user guess (BlindBase ADR-042, field report #11).
954
- *
955
- * A resolved move comes back as a one-element array, so this can replace
956
- * `parseSan` wherever the caller only needs "one move, or a reason".
957
- */
958
- parseSanCandidates(san) {
959
- const res = parseSanCandidates(san, this);
960
- return res.ok
961
- ? { ok: true, moveWords: res.value.map(packOf) }
962
- : { ok: false, code: res.error.code };
963
- }
964
- /**
965
- * Perft with caller-owned per-ply scratch buffers and analysis contexts.
966
- * Correctness: the parent ply's moves and castling plans remain untouched
967
- * when the recursive child recalculates check/pin/castling information.
968
- * This preserves the ordinary fully-maintained make/unmake contract.
969
- */
970
- /** Specialized perft-only make: no clock/hash updates or Undo snapshot array.
971
- * Public makeMove/unmakeMove remain entirely unchanged.
972
- * All rule-relevant state (castling, en-passant, checkers, turn, piece boards)
973
- * is updated exactly, and restored by _unmakePerft.
974
- */
975
- _makePerft(word, pieceCodes) {
976
- const from = word & 63, to = (word >>> 6) & 63;
977
- const promoRole = promoCodeToRole((word >>> 12) & 15) ?? null;
978
- const movingRole = (pieceCodes[from] - 1);
979
- const us = this.turn;
980
- const them = opposite(us);
981
- const prevCastling = this.castling;
982
- const prevMask = this.castlingMask;
983
- const prevEp = this.epSquare;
984
- const prevCheckers = this.checkers;
985
- const plan = movingRole === Role.King ? detectCastling(this, from, to) : null;
986
- const isEp = movingRole === Role.Pawn && prevEp !== null &&
987
- to === prevEp && (from & 7) !== (to & 7);
988
- let capturedRole = -1, capturedSq = -1;
989
- if (isEp) {
990
- capturedRole = Role.Pawn;
991
- capturedSq = us === Color.White ? to - 8 : to + 8;
992
- }
993
- else if (plan === null) {
994
- const cap = pieceCodes[to] === 0 ? undefined : (pieceCodes[to] - 1);
995
- if (cap !== undefined) {
996
- capturedRole = cap;
997
- capturedSq = to;
998
- }
999
- }
1000
- // Perft-private exact square cache: eliminates roleAt bitboard probing.
1001
- // Update in the same order as chess960 overlapping source/dest edits.
1002
- pieceCodes[from] = 0;
1003
- if (capturedSq >= 0)
1004
- pieceCodes[capturedSq] = 0;
1005
- this._clearSquare(from);
1006
- if (capturedSq >= 0)
1007
- this._clearSquare(capturedSq);
1008
- if (plan !== null) {
1009
- pieceCodes[plan.rookFrom] = 0;
1010
- pieceCodes[plan.rookTo] = Role.Rook + 1;
1011
- pieceCodes[plan.kingTo] = Role.King + 1;
1012
- this._clearSquare(plan.rookFrom);
1013
- this._putPiece(plan.rookTo, us, Role.Rook);
1014
- this._putPiece(plan.kingTo, us, Role.King);
1015
- this.kingSq[us] = plan.kingTo;
1016
- }
1017
- else {
1018
- pieceCodes[to] = (promoRole ?? movingRole) + 1;
1019
- this._putPiece(to, us, promoRole ?? movingRole);
1020
- if (movingRole === Role.King)
1021
- this.kingSq[us] = to;
1022
- }
1023
- if (!this.isChess960) {
1024
- const mask = prevMask ?? getCastlingMask(this);
1025
- const updated = (mask & CASTLE_CLEAR_STD[from] & CASTLE_CLEAR_STD[to]) >>> 0;
1026
- this.castlingMask = updated;
1027
- this.castling = CASTLING_RIGHTS_TABLE[updated];
1028
- }
1029
- else {
1030
- let nextWhite = prevCastling.white;
1031
- let nextBlack = prevCastling.black;
1032
- if (movingRole === Role.King) {
1033
- if (us === Color.White) {
1034
- if (nextWhite.size)
1035
- nextWhite = new Set();
1036
- }
1037
- else if (nextBlack.size)
1038
- nextBlack = new Set();
1039
- }
1040
- if (movingRole === Role.Rook) {
1041
- if (us === Color.White && nextWhite.has(from)) {
1042
- const next = new Set(nextWhite);
1043
- next.delete(from);
1044
- nextWhite = next;
1045
- }
1046
- else if (us === Color.Black && nextBlack.has(from)) {
1047
- const next = new Set(nextBlack);
1048
- next.delete(from);
1049
- nextBlack = next;
1050
- }
1051
- }
1052
- if (capturedRole === Role.Rook && capturedSq >= 0) {
1053
- if (them === Color.White && nextWhite.has(capturedSq)) {
1054
- const next = new Set(nextWhite);
1055
- next.delete(capturedSq);
1056
- nextWhite = next;
1057
- }
1058
- else if (them === Color.Black && nextBlack.has(capturedSq)) {
1059
- const next = new Set(nextBlack);
1060
- next.delete(capturedSq);
1061
- nextBlack = next;
1062
- }
1063
- }
1064
- if (nextWhite !== prevCastling.white || nextBlack !== prevCastling.black) {
1065
- this.castling = Object.freeze({
1066
- white: fixedRookRights(nextWhite),
1067
- black: fixedRookRights(nextBlack),
1068
- whiteKing: nextWhite.has(7), whiteQueen: nextWhite.has(0),
1069
- blackKing: nextBlack.has(63), blackQueen: nextBlack.has(56),
1070
- });
1071
- }
1072
- }
1073
- this.epSquare = null;
1074
- if (movingRole === Role.Pawn && Math.abs(to - from) === 16) {
1075
- // The target of a double push is reachable only by an opposing
1076
- // pawn next to the mover on the same rank. No cross-halfboard shifts.
1077
- const enemy = them === Color.White ? this.white : this.black;
1078
- const adjacent = PERFT_ADJACENT_FILES[to];
1079
- if ((us === Color.White
1080
- ? this.pawn.lo & enemy.lo & adjacent
1081
- : this.pawn.hi & enemy.hi & adjacent) !== 0) {
1082
- this.epSquare = (from + to) >>> 1;
1083
- }
1084
- }
1085
- this.turn = them;
1086
- this.checkers = kingAttackers(this, them);
1087
- return {
1088
- word, movingRole, capturedRole, capturedSq, promoRole,
1089
- castlingPlan: plan, castling: prevCastling, castlingMask: prevMask,
1090
- epSquare: prevEp, checkers: prevCheckers,
1091
- };
1092
- }
1093
- _unmakePerft(undo, pieceCodes) {
1094
- const from = undo.word & 63, to = (undo.word >>> 6) & 63;
1095
- const us = opposite(this.turn);
1096
- this.turn = us;
1097
- this.castling = undo.castling;
1098
- this.castlingMask = undo.castlingMask;
1099
- this.epSquare = undo.epSquare;
1100
- this.checkers = undo.checkers;
1101
- if (undo.castlingPlan !== null) {
1102
- const plan = undo.castlingPlan;
1103
- pieceCodes[plan.kingTo] = 0;
1104
- pieceCodes[plan.rookTo] = 0;
1105
- pieceCodes[plan.kingFrom] = Role.King + 1;
1106
- pieceCodes[plan.rookFrom] = Role.Rook + 1;
1107
- this._clearSquare(plan.kingTo);
1108
- this._clearSquare(plan.rookTo);
1109
- this._putPiece(plan.kingFrom, us, Role.King);
1110
- this._putPiece(plan.rookFrom, us, Role.Rook);
1111
- this.kingSq[us] = plan.kingFrom;
1112
- }
1113
- else {
1114
- pieceCodes[to] = 0;
1115
- pieceCodes[from] = undo.movingRole + 1;
1116
- this._clearSquare(to);
1117
- this._putPiece(from, us, undo.movingRole);
1118
- if (undo.capturedSq >= 0) {
1119
- pieceCodes[undo.capturedSq] = undo.capturedRole + 1;
1120
- this._putPiece(undo.capturedSq, opposite(us), undo.capturedRole);
1121
- }
1122
- if (undo.movingRole === Role.King)
1123
- this.kingSq[us] = from;
1124
- }
1125
- }
1126
- perft(depth) {
1127
- if (depth <= 0)
1128
- return 1;
1129
- const compact = compactPerft(this, depth);
1130
- if (compact !== undefined)
1131
- return compact;
1132
- const lists = Array.from({ length: depth }, () => new Uint16Array(256));
1133
- const contexts = new Array(depth);
1134
- // Local to this invocation; never observed by public move API.
1135
- const pieceCodes = new Uint8Array(64);
1136
- for (let sqIdx = 0; sqIdx < 64; sqIdx++) {
1137
- const role = this.roleAt(sqIdx);
1138
- if (role !== undefined)
1139
- pieceCodes[sqIdx] = role + 1;
1140
- }
1141
- const visit = (ply, remaining) => {
1142
- const ctx = analyzeCheckContext(this, contexts[ply], true);
1143
- contexts[ply] = ctx;
1144
- if (remaining === 1)
1145
- return countLegalMoves(this, ctx);
1146
- const moves = lists[ply];
1147
- const count = legalMovesInto(this, moves, ctx);
1148
- let nodes = 0;
1149
- for (let i = 0; i < count; i++) {
1150
- const undo = this._makePerft(moves[i], pieceCodes);
1151
- nodes += visit(ply + 1, remaining - 1);
1152
- this._unmakePerft(undo, pieceCodes);
1153
- }
1154
- return nodes;
1155
- };
1156
- return visit(0, depth);
1157
- }
1158
- }
1159
- export function emptyBoard() {
1160
- const e = sq.empty();
1161
- return {
1162
- white: e,
1163
- black: e,
1164
- pawn: e,
1165
- knight: e,
1166
- bishop: e,
1167
- rook: e,
1168
- queen: e,
1169
- king: e,
1170
- occupied: e,
1171
- promoted: e,
1172
- kingSq: [-1, -1],
1173
- };
1174
- }
1175
- export function cloneBoard(board) {
1176
- return {
1177
- white: { lo: board.white.lo >>> 0, hi: board.white.hi >>> 0 },
1178
- black: { lo: board.black.lo >>> 0, hi: board.black.hi >>> 0 },
1179
- pawn: { lo: board.pawn.lo >>> 0, hi: board.pawn.hi >>> 0 },
1180
- knight: { lo: board.knight.lo >>> 0, hi: board.knight.hi >>> 0 },
1181
- bishop: { lo: board.bishop.lo >>> 0, hi: board.bishop.hi >>> 0 },
1182
- rook: { lo: board.rook.lo >>> 0, hi: board.rook.hi >>> 0 },
1183
- queen: { lo: board.queen.lo >>> 0, hi: board.queen.hi >>> 0 },
1184
- king: { lo: board.king.lo >>> 0, hi: board.king.hi >>> 0 },
1185
- occupied: { lo: board.occupied.lo >>> 0, hi: board.occupied.hi >>> 0 },
1186
- promoted: { lo: board.promoted.lo >>> 0, hi: board.promoted.hi >>> 0 },
1187
- kingSq: board.kingSq ? [board.kingSq[0], board.kingSq[1]] : [-1, -1],
1188
- };
1189
- }
1190
- export function newScratchBoard() {
1191
- return {
1192
- white: { lo: 0, hi: 0 },
1193
- black: { lo: 0, hi: 0 },
1194
- pawn: { lo: 0, hi: 0 },
1195
- knight: { lo: 0, hi: 0 },
1196
- bishop: { lo: 0, hi: 0 },
1197
- rook: { lo: 0, hi: 0 },
1198
- queen: { lo: 0, hi: 0 },
1199
- king: { lo: 0, hi: 0 },
1200
- occupied: { lo: 0, hi: 0 },
1201
- promoted: { lo: 0, hi: 0 },
1202
- kingSq: [-1, -1],
1203
- };
1204
- }
1205
- export function cloneAsWritable(board) {
1206
- return {
1207
- white: { lo: board.white.lo >>> 0, hi: board.white.hi >>> 0 },
1208
- black: { lo: board.black.lo >>> 0, hi: board.black.hi >>> 0 },
1209
- pawn: { lo: board.pawn.lo >>> 0, hi: board.pawn.hi >>> 0 },
1210
- knight: { lo: board.knight.lo >>> 0, hi: board.knight.hi >>> 0 },
1211
- bishop: { lo: board.bishop.lo >>> 0, hi: board.bishop.hi >>> 0 },
1212
- rook: { lo: board.rook.lo >>> 0, hi: board.rook.hi >>> 0 },
1213
- queen: { lo: board.queen.lo >>> 0, hi: board.queen.hi >>> 0 },
1214
- king: { lo: board.king.lo >>> 0, hi: board.king.hi >>> 0 },
1215
- occupied: { lo: board.occupied.lo >>> 0, hi: board.occupied.hi >>> 0 },
1216
- promoted: { lo: board.promoted.lo >>> 0, hi: board.promoted.hi >>> 0 },
1217
- kingSq: board.kingSq ? [board.kingSq[0], board.kingSq[1]] : [-1, -1],
1218
- };
1219
- }
1220
- export function copyBoardInto(dst, src) {
1221
- dst.white.lo = src.white.lo;
1222
- dst.white.hi = src.white.hi;
1223
- dst.black.lo = src.black.lo;
1224
- dst.black.hi = src.black.hi;
1225
- dst.pawn.lo = src.pawn.lo;
1226
- dst.pawn.hi = src.pawn.hi;
1227
- dst.knight.lo = src.knight.lo;
1228
- dst.knight.hi = src.knight.hi;
1229
- dst.bishop.lo = src.bishop.lo;
1230
- dst.bishop.hi = src.bishop.hi;
1231
- dst.rook.lo = src.rook.lo;
1232
- dst.rook.hi = src.rook.hi;
1233
- dst.queen.lo = src.queen.lo;
1234
- dst.queen.hi = src.queen.hi;
1235
- dst.king.lo = src.king.lo;
1236
- dst.king.hi = src.king.hi;
1237
- dst.occupied.lo = src.occupied.lo;
1238
- dst.occupied.hi = src.occupied.hi;
1239
- dst.promoted.lo = src.promoted.lo;
1240
- dst.promoted.hi = src.promoted.hi;
1241
- if (src.kingSq) {
1242
- dst.kingSq[0] = src.kingSq[0];
1243
- dst.kingSq[1] = src.kingSq[1];
1244
- }
1245
- }
1246
- export function clearSquareInPlace(b, sqIdx) {
1247
- if (sqIdx < 32) {
1248
- const inv = ~(1 << sqIdx);
1249
- b.white.lo &= inv;
1250
- b.black.lo &= inv;
1251
- b.pawn.lo &= inv;
1252
- b.knight.lo &= inv;
1253
- b.bishop.lo &= inv;
1254
- b.rook.lo &= inv;
1255
- b.queen.lo &= inv;
1256
- b.king.lo &= inv;
1257
- b.occupied.lo &= inv;
1258
- b.promoted.lo &= inv;
1259
- }
1260
- else {
1261
- const inv = ~(1 << (sqIdx - 32));
1262
- b.white.hi &= inv;
1263
- b.black.hi &= inv;
1264
- b.pawn.hi &= inv;
1265
- b.knight.hi &= inv;
1266
- b.bishop.hi &= inv;
1267
- b.rook.hi &= inv;
1268
- b.queen.hi &= inv;
1269
- b.king.hi &= inv;
1270
- b.occupied.hi &= inv;
1271
- b.promoted.hi &= inv;
1272
- }
1273
- if (b.kingSq) {
1274
- if (b.kingSq[0] === sqIdx)
1275
- b.kingSq[0] = -1;
1276
- else if (b.kingSq[1] === sqIdx)
1277
- b.kingSq[1] = -1;
1278
- }
1279
- }
1280
- export function putPieceInPlace(b, sqIdx, piece) {
1281
- if (sqIdx < 32) {
1282
- const bit = (1 << sqIdx) >>> 0;
1283
- if (piece.color === Color.White)
1284
- b.white.lo |= bit;
1285
- else
1286
- b.black.lo |= bit;
1287
- switch (piece.role) {
1288
- case Role.Pawn:
1289
- b.pawn.lo |= bit;
1290
- break;
1291
- case Role.Knight:
1292
- b.knight.lo |= bit;
1293
- break;
1294
- case Role.Bishop:
1295
- b.bishop.lo |= bit;
1296
- break;
1297
- case Role.Rook:
1298
- b.rook.lo |= bit;
1299
- break;
1300
- case Role.Queen:
1301
- b.queen.lo |= bit;
1302
- break;
1303
- case Role.King:
1304
- b.king.lo |= bit;
1305
- break;
1306
- }
1307
- b.occupied.lo |= bit;
1308
- }
1309
- else {
1310
- const bit = (1 << (sqIdx - 32)) >>> 0;
1311
- if (piece.color === Color.White)
1312
- b.white.hi |= bit;
1313
- else
1314
- b.black.hi |= bit;
1315
- switch (piece.role) {
1316
- case Role.Pawn:
1317
- b.pawn.hi |= bit;
1318
- break;
1319
- case Role.Knight:
1320
- b.knight.hi |= bit;
1321
- break;
1322
- case Role.Bishop:
1323
- b.bishop.hi |= bit;
1324
- break;
1325
- case Role.Rook:
1326
- b.rook.hi |= bit;
1327
- break;
1328
- case Role.Queen:
1329
- b.queen.hi |= bit;
1330
- break;
1331
- case Role.King:
1332
- b.king.hi |= bit;
1333
- break;
1334
- }
1335
- b.occupied.hi |= bit;
1336
- }
1337
- if (piece.role === Role.King && b.kingSq) {
1338
- b.kingSq[piece.color] = sqIdx;
1339
- }
1340
- }
1341
- export function setPiece(board, sqIdx, piece) {
1342
- const nb = new Board(board);
1343
- putPieceInPlace(nb, sqIdx, piece);
1344
- return nb;
1345
- }
1346
- export function removePiece(board, sqIdx) {
1347
- const nb = new Board(board);
1348
- clearSquareInPlace(nb, sqIdx);
1349
- return nb;
1350
- }
1351
- export function pieceAt(board, sqIdx) {
1352
- const bit = sq.singleton(sqIdx);
1353
- if (sq.isEmpty(sq.and(board.occupied, bit)))
1354
- return undefined;
1355
- const color = sq.has(board.white, sqIdx) ? Color.White : Color.Black;
1356
- let role;
1357
- if (sq.has(board.pawn, sqIdx))
1358
- role = Role.Pawn;
1359
- else if (sq.has(board.knight, sqIdx))
1360
- role = Role.Knight;
1361
- else if (sq.has(board.bishop, sqIdx))
1362
- role = Role.Bishop;
1363
- else if (sq.has(board.rook, sqIdx))
1364
- role = Role.Rook;
1365
- else if (sq.has(board.queen, sqIdx))
1366
- role = Role.Queen;
1367
- else if (sq.has(board.king, sqIdx))
1368
- role = Role.King;
1369
- if (role === undefined)
1370
- return undefined;
1371
- return { color, role };
1372
- }
1373
- export function hasPiece(board, sqIdx) {
1374
- return sq.has(board.occupied, sqIdx);
1375
- }
1376
- export function kingSquare(board, color) {
1377
- if (board.kingSq !== undefined) {
1378
- const k = board.kingSq[color];
1379
- if (k >= 0)
1380
- return k;
1381
- }
1382
- const ks = color === Color.White ? sq.and(board.white, board.king) : sq.and(board.black, board.king);
1383
- return sq.first(ks);
1384
- }
1385
- export function occupiedEqualsWhiteBlack(board) {
1386
- return sq.equals(board.occupied, sq.or(board.white, board.black));
1387
- }
1388
- export function rolePartitionEqualsOccupied(board) {
1389
- const roles = sq.or(sq.or(sq.or(board.pawn, board.knight), sq.or(board.bishop, board.rook)), sq.or(board.queen, board.king));
1390
- return sq.equals(roles, board.occupied);
1391
- }
1392
- export function boardEquals(a, b) {
1393
- return (sq.equals(a.white, b.white) &&
1394
- sq.equals(a.black, b.black) &&
1395
- sq.equals(a.pawn, b.pawn) &&
1396
- sq.equals(a.knight, b.knight) &&
1397
- sq.equals(a.bishop, b.bishop) &&
1398
- sq.equals(a.rook, b.rook) &&
1399
- sq.equals(a.queen, b.queen) &&
1400
- sq.equals(a.king, b.king) &&
1401
- sq.equals(a.occupied, b.occupied) &&
1402
- sq.equals(a.promoted, b.promoted));
1403
- }