gigachess 0.5.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.
- package/README.md +142 -54
- package/dist/attacks.d.ts +18 -7
- package/dist/attacks.d.ts.map +1 -1
- package/dist/attacks.js +197 -89
- package/dist/bishopSplit32Blob.d.ts +2 -0
- package/dist/bishopSplit32Blob.d.ts.map +1 -0
- package/dist/bishopSplit32Blob.js +2 -0
- package/dist/castling.d.ts +2 -0
- package/dist/castling.d.ts.map +1 -1
- package/dist/castling.js +27 -12
- package/dist/chess960.d.ts +2 -9
- package/dist/chess960.d.ts.map +1 -1
- package/dist/chess960.js +2 -18
- package/dist/chessjs.d.ts +1 -1
- package/dist/chessjs.d.ts.map +1 -1
- package/dist/chessjs.js +1 -1
- package/dist/chessops/board.d.ts +1 -1
- package/dist/chessops/board.d.ts.map +1 -1
- package/dist/chessops/board.js +1 -1
- package/dist/chessops/chess.d.ts +6 -10
- package/dist/chessops/chess.d.ts.map +1 -1
- package/dist/chessops/chess.js +73 -97
- package/dist/chessops/convert.d.ts +1 -1
- package/dist/chessops/convert.d.ts.map +1 -1
- package/dist/chessops/convert.js +1 -1
- package/dist/chessops/debug.d.ts.map +1 -1
- package/dist/chessops/debug.js +7 -0
- package/dist/chessops/fen.d.ts.map +1 -1
- package/dist/chessops/fen.js +13 -2
- package/dist/chessops/fenInternal.d.ts +1 -1
- package/dist/chessops/fenInternal.d.ts.map +1 -1
- package/dist/chessops/fenInternal.js +1 -1
- package/dist/chessops/nativeBridge.d.ts +14 -0
- package/dist/chessops/nativeBridge.d.ts.map +1 -0
- package/dist/chessops/nativeBridge.js +87 -0
- package/dist/chessops/san.d.ts.map +1 -1
- package/dist/chessops/san.js +12 -10
- package/dist/chesstree.d.ts.map +1 -1
- package/dist/chesstree.js +23 -62
- package/dist/core.d.ts +6 -8
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +5 -10
- package/dist/fast/bishopSplit32Blob-NOHWZEWR.js +1 -0
- package/dist/fast/index.js +1 -0
- package/dist/fast/rookSplit32Blob-C3ANUNTJ.js +1 -0
- package/dist/fast/zobristBlob-HIMMLZLJ.js +1 -0
- package/dist/fast.d.ts +2 -0
- package/dist/fast.d.ts.map +1 -0
- package/dist/fast.js +2 -0
- package/dist/index.d.ts +1 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -19
- package/dist/native96.d.ts +16 -0
- package/dist/native96.d.ts.map +1 -0
- package/dist/native96.js +6 -0
- package/dist/nativeBoard96.d.ts +118 -0
- package/dist/nativeBoard96.d.ts.map +1 -0
- package/dist/nativeBoard96.js +1077 -0
- package/dist/nativeChess.d.ts +97 -0
- package/dist/nativeChess.d.ts.map +1 -0
- package/dist/nativeChess.js +201 -0
- package/dist/nativeMovegen96.d.ts +2 -0
- package/dist/nativeMovegen96.d.ts.map +1 -0
- package/dist/nativeMovegen96.js +282 -0
- package/dist/nativePublicTypes.d.ts +3 -0
- package/dist/nativePublicTypes.d.ts.map +1 -0
- package/dist/nativePublicTypes.js +1 -0
- package/dist/perftCompact.d.ts +10 -0
- package/dist/perftCompact.d.ts.map +1 -0
- package/dist/perftCompact.js +420 -0
- package/dist/pgn.d.ts +2 -3
- package/dist/pgn.d.ts.map +1 -1
- package/dist/pgn.js +2 -5
- package/dist/rookSplit32Blob.d.ts +2 -0
- package/dist/rookSplit32Blob.d.ts.map +1 -0
- package/dist/rookSplit32Blob.js +2 -0
- package/dist/setupBoard.d.ts +54 -0
- package/dist/setupBoard.d.ts.map +1 -0
- package/dist/setupBoard.js +249 -0
- package/dist/{fen.d.ts → setupFen.d.ts} +1 -1
- package/dist/setupFen.d.ts.map +1 -0
- package/dist/{fen.js → setupFen.js} +140 -125
- package/dist/squareSet.d.ts +2 -0
- package/dist/squareSet.d.ts.map +1 -1
- package/dist/squareSet.js +6 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/zobrist.d.ts +2 -2
- package/dist/zobrist.d.ts.map +1 -1
- package/dist/zobrist.js +17 -15
- package/package.json +18 -6
- package/dist/bishopMagicBlob.d.ts +0 -2
- package/dist/bishopMagicBlob.d.ts.map +0 -1
- package/dist/bishopMagicBlob.js +0 -11
- package/dist/board.d.ts +0 -216
- package/dist/board.d.ts.map +0 -1
- package/dist/board.js +0 -1088
- package/dist/chess.d.ts +0 -252
- package/dist/chess.d.ts.map +0 -1
- package/dist/chess.js +0 -1930
- package/dist/fen.d.ts.map +0 -1
- package/dist/rookMagicBlob.d.ts +0 -2
- package/dist/rookMagicBlob.d.ts.map +0 -1
- package/dist/rookMagicBlob.js +0 -11
- package/dist/san.d.ts +0 -38
- package/dist/san.d.ts.map +0 -1
- package/dist/san.js +0 -549
package/dist/chess.js
DELETED
|
@@ -1,1930 +0,0 @@
|
|
|
1
|
-
// src/chess.ts — core chess rules, Position/Setup, dests, isLegal, isCheck, perft etc
|
|
2
|
-
// MIT gigachess, clean-room from specs + FIDE notes (no G P L)
|
|
3
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
4
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
5
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
6
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
7
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
8
|
-
};
|
|
9
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
10
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
11
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
12
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
13
|
-
};
|
|
14
|
-
var _Chess_instances, _Chess_board, _Chess_startFen, _Chess_history, _Chess_movetext, _Chess_positions, _Chess_describe, _Chess_fenOf;
|
|
15
|
-
import * as sq from "./squareSet.js";
|
|
16
|
-
import * as board from "./board.js";
|
|
17
|
-
import { Board } from "./board.js";
|
|
18
|
-
import * as attacks from "./attacks.js";
|
|
19
|
-
import { Color, Role } from "./types.js";
|
|
20
|
-
import { opposite, squareFile, squareRank, parseSquare, squareName } from "./util.js";
|
|
21
|
-
import { zobristTablesLoaded, zobristAfterMove, zobristAfterNullMove } from "./zobrist.js";
|
|
22
|
-
import { parseFen, makeFen } from "./fen.js";
|
|
23
|
-
import { parseSan, makeSan, parseUci, makeUci } from "./san.js";
|
|
24
|
-
import { packOf, packedToMoves, isNullMove, PROMO_NONE, PROMO_KNIGHT, PROMO_BISHOP, PROMO_ROOK, PROMO_QUEEN, } from "./packedMove.js";
|
|
25
|
-
import { build as buildTreeWrapper, pgnImport as pgnImportData } from "./chesstree.js";
|
|
26
|
-
import { pieceAt } from "./board.js";
|
|
27
|
-
import { CASTLE_WK, CASTLE_WQ, CASTLE_BK, CASTLE_BQ, CASTLE_CLEAR_STD, CASTLING_RIGHTS_TABLE, PLAN_WHITE_K, PLAN_WHITE_Q, PLAN_BLACK_K, PLAN_BLACK_Q, getCastlingMask, CASTLE_PATH_LO, CASTLE_PATH_HI, CASTLE_TRAVERSAL_WHITE, CASTLE_TRAVERSAL_BLACK, } from "./castling.js";
|
|
28
|
-
// helpers
|
|
29
|
-
export function isCheck(pos) {
|
|
30
|
-
if (pos.checkers !== undefined) {
|
|
31
|
-
return ((pos.checkers.lo | pos.checkers.hi) !== 0);
|
|
32
|
-
}
|
|
33
|
-
const ksq = board.kingSquare(pos.board, pos.turn);
|
|
34
|
-
if (ksq === undefined)
|
|
35
|
-
return false;
|
|
36
|
-
const attacker = opposite(pos.turn);
|
|
37
|
-
return attacks.isAttacked(pos.board, ksq, attacker);
|
|
38
|
-
}
|
|
39
|
-
export function kingAttackers(pos, color) {
|
|
40
|
-
return attacks.kingAttackers(pos.board, color);
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* In-check test computed FRESH from the attack tables — never from the cached
|
|
44
|
-
* `checkers` bitboard.
|
|
45
|
-
*
|
|
46
|
-
* The null-move legality gate must use this: a caller that reached a pass
|
|
47
|
-
* through a cache-free make holds a `checkers` value describing some earlier
|
|
48
|
-
* position, and reading it would accept or refuse the wrong positions. The scan
|
|
49
|
-
* costs one `attackersTo` on a path taken roughly once per ten thousand plies.
|
|
50
|
-
* Mirrors gigachess-rs `make_null_move` (board.rs).
|
|
51
|
-
*/
|
|
52
|
-
export function isCheckFresh(pos) {
|
|
53
|
-
const ksq = board.kingSquare(pos.board, pos.turn);
|
|
54
|
-
if (ksq === undefined)
|
|
55
|
-
return false;
|
|
56
|
-
const them = opposite(pos.turn);
|
|
57
|
-
return !sq.isEmpty(attacks.attackersTo(pos.board, ksq, them, pos.board.occupied));
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* A pass is legal iff the side to move is NOT in check (a null move answers no
|
|
61
|
-
* check). Always judged from the attack tables — see {@link isCheckFresh}.
|
|
62
|
-
*/
|
|
63
|
-
export function isNullMoveLegal(pos) {
|
|
64
|
-
return !isCheckFresh(pos);
|
|
65
|
-
}
|
|
66
|
-
// insufficient material per spec
|
|
67
|
-
export function isInsufficientMaterial(pos) {
|
|
68
|
-
const b = pos.board;
|
|
69
|
-
// only kings
|
|
70
|
-
if (sq.equals(b.occupied, b.king))
|
|
71
|
-
return true;
|
|
72
|
-
// count pieces
|
|
73
|
-
const whitePawns = sq.popcnt(sq.and(b.white, b.pawn));
|
|
74
|
-
const blackPawns = sq.popcnt(sq.and(b.black, b.pawn));
|
|
75
|
-
const whiteRooks = sq.popcnt(sq.and(b.white, b.rook));
|
|
76
|
-
const blackRooks = sq.popcnt(sq.and(b.black, b.rook));
|
|
77
|
-
const whiteQueens = sq.popcnt(sq.and(b.white, b.queen));
|
|
78
|
-
const blackQueens = sq.popcnt(sq.and(b.black, b.queen));
|
|
79
|
-
if (whitePawns > 0 || blackPawns > 0 || whiteRooks > 0 || blackRooks > 0 || whiteQueens > 0 || blackQueens > 0) {
|
|
80
|
-
return false;
|
|
81
|
-
}
|
|
82
|
-
const whiteKnights = sq.popcnt(sq.and(b.white, b.knight));
|
|
83
|
-
const blackKnights = sq.popcnt(sq.and(b.black, b.knight));
|
|
84
|
-
const whiteBishops = sq.popcnt(sq.and(b.white, b.bishop));
|
|
85
|
-
const blackBishops = sq.popcnt(sq.and(b.black, b.bishop));
|
|
86
|
-
const totalKnights = whiteKnights + blackKnights;
|
|
87
|
-
const totalBishops = whiteBishops + blackBishops;
|
|
88
|
-
// K vs K already handled
|
|
89
|
-
// K+B vs K, K+N vs K
|
|
90
|
-
if (totalKnights === 1 && totalBishops === 0)
|
|
91
|
-
return true;
|
|
92
|
-
if (totalBishops === 1 && totalKnights === 0)
|
|
93
|
-
return true;
|
|
94
|
-
// K+B vs K+B same color bishops
|
|
95
|
-
if (totalBishops === 2 && totalKnights === 0) {
|
|
96
|
-
// find bishop squares
|
|
97
|
-
let firstB = sq.first(sq.or(sq.and(b.white, b.bishop), sq.and(b.black, b.bishop)));
|
|
98
|
-
// Actually need both bishops
|
|
99
|
-
const bishops = sq.or(sq.and(b.white, b.bishop), sq.and(b.black, b.bishop));
|
|
100
|
-
const iter = [...sq.iter(bishops)];
|
|
101
|
-
if (iter.length === 2) {
|
|
102
|
-
const c1 = (squareFile(iter[0]) + squareRank(iter[0])) % 2;
|
|
103
|
-
const c2 = (squareFile(iter[1]) + squareRank(iter[1])) % 2;
|
|
104
|
-
if (c1 === c2)
|
|
105
|
-
return true;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
// K+B vs K+B same color insufficient, opposite color sufficient -> false
|
|
109
|
-
// K+N vs K+N etc not insufficient
|
|
110
|
-
return false;
|
|
111
|
-
}
|
|
112
|
-
export function isFiftyMoveDraw(pos) {
|
|
113
|
-
return (pos.halfmoves ?? pos.halfmove ?? 0) >= 100;
|
|
114
|
-
}
|
|
115
|
-
export function isSeventyFiveMoveDraw(pos) {
|
|
116
|
-
return (pos.halfmoves ?? pos.halfmove ?? 0) >= 150;
|
|
117
|
-
}
|
|
118
|
-
export function isThreefoldRepetition(history) {
|
|
119
|
-
if (history.length < 3)
|
|
120
|
-
return false;
|
|
121
|
-
const last = history[history.length - 1];
|
|
122
|
-
let count = 0;
|
|
123
|
-
for (const h of history) {
|
|
124
|
-
if (positionsEqualForRepetition(h, last))
|
|
125
|
-
count++;
|
|
126
|
-
if (count >= 3)
|
|
127
|
-
return true;
|
|
128
|
-
}
|
|
129
|
-
return false;
|
|
130
|
-
}
|
|
131
|
-
export function isFivefoldRepetition(history) {
|
|
132
|
-
if (history.length < 5)
|
|
133
|
-
return false;
|
|
134
|
-
const last = history[history.length - 1];
|
|
135
|
-
let count = 0;
|
|
136
|
-
for (const h of history)
|
|
137
|
-
if (positionsEqualForRepetition(h, last))
|
|
138
|
-
count++;
|
|
139
|
-
return count >= 5;
|
|
140
|
-
}
|
|
141
|
-
function positionsEqualForRepetition(a, b) {
|
|
142
|
-
if (a.turn !== b.turn)
|
|
143
|
-
return false;
|
|
144
|
-
if (a.epSquare !== b.epSquare)
|
|
145
|
-
return false;
|
|
146
|
-
if (!board.boardEquals(a.board, b.board))
|
|
147
|
-
return false;
|
|
148
|
-
// castling sets equality
|
|
149
|
-
if (a.castling.white.size !== b.castling.white.size)
|
|
150
|
-
return false;
|
|
151
|
-
if (a.castling.black.size !== b.castling.black.size)
|
|
152
|
-
return false;
|
|
153
|
-
for (const s of a.castling.white)
|
|
154
|
-
if (!b.castling.white.has(s))
|
|
155
|
-
return false;
|
|
156
|
-
for (const s of a.castling.black)
|
|
157
|
-
if (!b.castling.black.has(s))
|
|
158
|
-
return false;
|
|
159
|
-
return true;
|
|
160
|
-
}
|
|
161
|
-
// ---------- castling: one detect/apply path (ADR-013 as amended) ----------
|
|
162
|
-
// ADR-013 bake-off result (change purechess-gates-green, task 1.1): the
|
|
163
|
-
// baseline-style king-captures-rook representation (e1h1) is the single
|
|
164
|
-
// canonical OUTPUT encoding used by dests/allDests/genLegalMoves (and hence
|
|
165
|
-
// makeUci). It measured equal-or-faster than the normalized-landing encoding
|
|
166
|
-
// (perft d3 11.26 vs 11.42 ms median; makeMove walk 425 vs 430 ms; allDests
|
|
167
|
-
// 6.27 vs 6.39 ms — see bench/castling-bakeoff.mjs) and deletes the
|
|
168
|
-
// canonicalization layer: standard-chess and Chess960 handling converge and
|
|
169
|
-
// dests are byte-identical to baseline. Both INPUT forms are still accepted
|
|
170
|
-
// by detectCastling (king→rook square e1h1, and king→landing e1g1 as a
|
|
171
|
-
// two-file step) so `parseUci("e1g1")` in standard chess and 960 `e1h1`
|
|
172
|
-
// input keep working (UCI protocol boundary documented in ADR-013: engines
|
|
173
|
-
// are sent e1g1 for standard castling; conversion belongs to the engine
|
|
174
|
-
// boundary, not to makeUci).
|
|
175
|
-
import { detectCastling, castlingPlanFor, planForDest, } from "./castling.js";
|
|
176
|
-
export { detectCastling, castlingPlanFor, planForDest, };
|
|
177
|
-
// ---------- move execution (play) ----------
|
|
178
|
-
/**
|
|
179
|
-
* Shared board-edit sequence used by BOTH the pure `makeMove` and the
|
|
180
|
-
* hot-loop scratch tester below — a single source of truth so the fast path
|
|
181
|
-
* can never drift from the pure path.
|
|
182
|
-
*/
|
|
183
|
-
function computeCaptured(pos, origTo, to, isCastling, piece) {
|
|
184
|
-
// capture handling (re-evaluate after normalization; for castling, captured is the rook but we handle rook move separately)
|
|
185
|
-
// if we normalized 960 castling, original captured is rook but normalized to is now empty dest, so captured should be undefined for that case
|
|
186
|
-
if (isCastling && piece.role === Role.King) {
|
|
187
|
-
// For 960 normalized, the original rook capture is not a capture in normal sense; we should not treat as capture
|
|
188
|
-
// Check if original move was king-captures-rook: then captured was rook, but after normalization we don't want to treat as capture of piece on dest (dest is empty)
|
|
189
|
-
const origTarget = board.pieceAt(pos.board, origTo);
|
|
190
|
-
if (origTarget && origTarget.color === piece.color && origTarget.role === Role.Rook) {
|
|
191
|
-
return undefined;
|
|
192
|
-
}
|
|
193
|
-
return board.pieceAt(pos.board, to);
|
|
194
|
-
}
|
|
195
|
-
return board.pieceAt(pos.board, to);
|
|
196
|
-
}
|
|
197
|
-
function applyBoardEdits(nb, pos, from, to, // normalized dest (castling → G1/C1/G8/C8)
|
|
198
|
-
origTo, // move.to before normalization (for capture removal)
|
|
199
|
-
piece, isEnPassant, plan, // non-null ⇒ castling, with the full king+rook plan
|
|
200
|
-
isPromotion, promotion, captured) {
|
|
201
|
-
// remove moving piece from from
|
|
202
|
-
board.clearSquareInPlace(nb, from);
|
|
203
|
-
// if en passant, remove captured pawn which is not on to square
|
|
204
|
-
if (isEnPassant) {
|
|
205
|
-
const epCaptureRank = pos.turn === Color.White ? squareRank(to) - 1 : squareRank(to) + 1;
|
|
206
|
-
const epCaptureSq = epCaptureRank * 8 + squareFile(to);
|
|
207
|
-
board.clearSquareInPlace(nb, epCaptureSq);
|
|
208
|
-
}
|
|
209
|
-
else if (captured) {
|
|
210
|
-
// captured is only ever non-undefined when to === origTo (capture removal
|
|
211
|
-
// square), so removing at origTo is exactly equivalent to the original
|
|
212
|
-
// `removePiece(nb, to)`.
|
|
213
|
-
board.clearSquareInPlace(nb, origTo);
|
|
214
|
-
}
|
|
215
|
-
// handle castling: king + rook relocation + rights context all come from the
|
|
216
|
-
// single detectCastling plan (design D2) — no per-site rook scanning left.
|
|
217
|
-
if (plan) {
|
|
218
|
-
board.clearSquareInPlace(nb, plan.rookFrom);
|
|
219
|
-
board.putPieceInPlace(nb, plan.rookTo, { color: pos.turn, role: Role.Rook });
|
|
220
|
-
// place king on destination (to)
|
|
221
|
-
board.putPieceInPlace(nb, to, { color: pos.turn, role: Role.King });
|
|
222
|
-
}
|
|
223
|
-
else {
|
|
224
|
-
// normal move: place moving piece (with promotion)
|
|
225
|
-
let role = piece.role;
|
|
226
|
-
if (isPromotion && promotion !== undefined && promotion !== null) {
|
|
227
|
-
role = promotion;
|
|
228
|
-
}
|
|
229
|
-
board.putPieceInPlace(nb, to, { color: piece.color, role });
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* Plays a null move (pass): the position stays, the side to move flips.
|
|
234
|
-
*
|
|
235
|
-
* Semantics mirror an ordinary move's state transition: castling rights are
|
|
236
|
-
* untouched, the en-passant square clears (any pending double push lapses), the
|
|
237
|
-
* halfmove clock advances and the move always completes a full move (a pass is
|
|
238
|
-
* a move, not a half-move: after the pass White is to move with the number
|
|
239
|
-
* advanced, whoever passed). The incremental Polyglot hash and the cached
|
|
240
|
-
* `checkers` are maintained, so `zobrist()` still equals a full recompute and
|
|
241
|
-
* `isCheck` stays branch-free.
|
|
242
|
-
*
|
|
243
|
-
* Throws when the side to move is in check: a pass answers no check. The test
|
|
244
|
-
* is computed from the bitboards rather than read from the cache — see
|
|
245
|
-
* {@link isCheckFresh}.
|
|
246
|
-
*
|
|
247
|
-
* Mirrors gigachess-rs `Board::make_null_move` (board.rs).
|
|
248
|
-
*/
|
|
249
|
-
export function makeNullMove(pos) {
|
|
250
|
-
if (!isNullMoveLegal(pos)) {
|
|
251
|
-
throw new Error("illegal null move: the side to move is in check");
|
|
252
|
-
}
|
|
253
|
-
const us = pos.turn;
|
|
254
|
-
const newTurn = opposite(us);
|
|
255
|
-
const newHalf = (pos.halfmoves ?? pos.halfmove ?? 0) + 1;
|
|
256
|
-
// A pass is a move, not a half-move: the number advances whoever passed
|
|
257
|
-
// (this is what keeps FEN's "White to move" and number incremented
|
|
258
|
-
// consistent).
|
|
259
|
-
const newFull = (pos.fullmoves ?? pos.fullmove ?? 1) + 1;
|
|
260
|
-
const nextKingSq = pos.kingSq
|
|
261
|
-
? [pos.kingSq[0], pos.kingSq[1]]
|
|
262
|
-
: [board.kingSquare(pos.board, Color.White) ?? -1, board.kingSquare(pos.board, Color.Black) ?? -1];
|
|
263
|
-
const newPos = {
|
|
264
|
-
// A pass moves no piece, so the board is carried over untouched (the input
|
|
265
|
-
// position is never mutated).
|
|
266
|
-
board: pos.board,
|
|
267
|
-
turn: newTurn,
|
|
268
|
-
castling: pos.castling,
|
|
269
|
-
castlingMask: pos.castlingMask,
|
|
270
|
-
isChess960: pos.isChess960 ?? false,
|
|
271
|
-
epSquare: null,
|
|
272
|
-
halfmoves: newHalf,
|
|
273
|
-
fullmoves: newFull,
|
|
274
|
-
halfmove: newHalf,
|
|
275
|
-
fullmove: newFull,
|
|
276
|
-
kingSq: nextKingSq,
|
|
277
|
-
checkers: attacks.kingAttackers(pos.board, newTurn),
|
|
278
|
-
};
|
|
279
|
-
if (zobristTablesLoaded()) {
|
|
280
|
-
const zk = zobristAfterNullMove(pos);
|
|
281
|
-
newPos.zobristLo = zk.lo;
|
|
282
|
-
newPos.zobristHi = zk.hi;
|
|
283
|
-
}
|
|
284
|
-
return newPos;
|
|
285
|
-
}
|
|
286
|
-
export function makeMove(pos, move) {
|
|
287
|
-
// First-class pass: the null sentinel dispatches here, before any from/to
|
|
288
|
-
// interpretation (a pass has no origin square).
|
|
289
|
-
if (isNullMove(move))
|
|
290
|
-
return makeNullMove(pos);
|
|
291
|
-
let from = move.from;
|
|
292
|
-
let to = move.to;
|
|
293
|
-
let piece = board.pieceAt(pos.board, from);
|
|
294
|
-
if (!piece)
|
|
295
|
-
throw new Error("no piece at from");
|
|
296
|
-
// Single castling detection for BOTH input representations (normalized
|
|
297
|
-
// landing e1g1 and baseline/960 king-captures-rook e1h1) — fixes the defect
|
|
298
|
-
// where `makeMove(pos, {from: king, to: landing})` moved only the king and
|
|
299
|
-
// left the rook behind.
|
|
300
|
-
let isEnPassant = !!move.isEnPassant;
|
|
301
|
-
// Robust ep derivation: a pawn moving DIAGONALLY onto the ep square is an
|
|
302
|
-
// en-passant capture even when the caller did not set the flag (external
|
|
303
|
-
// move objects) — keeps the board edit AND the Zobrist delta correct.
|
|
304
|
-
if (!isEnPassant &&
|
|
305
|
-
piece.role === Role.Pawn &&
|
|
306
|
-
pos.epSquare !== null &&
|
|
307
|
-
move.to === pos.epSquare &&
|
|
308
|
-
squareFile(move.from) !== squareFile(move.to)) {
|
|
309
|
-
isEnPassant = true;
|
|
310
|
-
}
|
|
311
|
-
// Single castling detection for BOTH input representations (normalized
|
|
312
|
-
// landing e1g1 and baseline/960 king-captures-rook e1h1) — fixes the defect
|
|
313
|
-
// where `makeMove(pos, {from: king, to: landing})` moved only the king and
|
|
314
|
-
// left the rook behind. detectCastling is the ONLY castling apply path
|
|
315
|
-
// (design D2: no second castling code path); a move explicitly flagged
|
|
316
|
-
// isCastling whose rights no longer support detection is not castling.
|
|
317
|
-
let plan = null;
|
|
318
|
-
if (piece.role === Role.King) {
|
|
319
|
-
plan = detectCastling(pos, from, to);
|
|
320
|
-
}
|
|
321
|
-
const isCastling = plan !== null;
|
|
322
|
-
if (plan)
|
|
323
|
-
to = plan.kingTo;
|
|
324
|
-
const isPromotion = !!move.isPromotion || move.promotion !== undefined && move.promotion !== null;
|
|
325
|
-
// Board construction: clone→mutate-clone (spec-sanctioned technique). `nb`
|
|
326
|
-
// is a fresh writable board owned locally and returned as a read-only Board;
|
|
327
|
-
// the input position is never touched, so the observable contract stays pure.
|
|
328
|
-
// The edit sequence itself lives in applyBoardEdits (shared with the
|
|
329
|
-
// hot-loop scratch tester).
|
|
330
|
-
const nb = board.cloneAsWritable(pos.board);
|
|
331
|
-
const captured = computeCaptured(pos, move.to, to, isCastling, piece);
|
|
332
|
-
applyBoardEdits(nb, pos, from, to, move.to, piece, isEnPassant, plan, isPromotion, move.promotion ?? null, captured);
|
|
333
|
-
// handle promotion: pawn must promote if reaching back rank
|
|
334
|
-
// Already handled via move.promotion
|
|
335
|
-
// update castling rights — standard chess uses 4-bit integer mask and O(1) table lookup
|
|
336
|
-
let newCastling;
|
|
337
|
-
let newMask;
|
|
338
|
-
if (!pos.isChess960) {
|
|
339
|
-
const mask = pos.castlingMask ?? getCastlingMask(pos);
|
|
340
|
-
newMask = (mask & CASTLE_CLEAR_STD[from] & CASTLE_CLEAR_STD[to]) >>> 0;
|
|
341
|
-
newCastling = CASTLING_RIGHTS_TABLE[newMask];
|
|
342
|
-
}
|
|
343
|
-
else {
|
|
344
|
-
let newWhite = pos.castling.white;
|
|
345
|
-
let newBlack = pos.castling.black;
|
|
346
|
-
if (piece.role === Role.King) {
|
|
347
|
-
if (pos.turn === Color.White) {
|
|
348
|
-
if (newWhite.size > 0)
|
|
349
|
-
newWhite = new Set();
|
|
350
|
-
}
|
|
351
|
-
else {
|
|
352
|
-
if (newBlack.size > 0)
|
|
353
|
-
newBlack = new Set();
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
if (piece.role === Role.Rook) {
|
|
357
|
-
if (pos.turn === Color.White) {
|
|
358
|
-
if (newWhite.has(from)) {
|
|
359
|
-
const next = new Set(newWhite);
|
|
360
|
-
next.delete(from);
|
|
361
|
-
newWhite = next;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
else {
|
|
365
|
-
if (newBlack.has(from)) {
|
|
366
|
-
const next = new Set(newBlack);
|
|
367
|
-
next.delete(from);
|
|
368
|
-
newBlack = next;
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
if (captured && captured.role === Role.Rook) {
|
|
373
|
-
if (captured.color === Color.White) {
|
|
374
|
-
if (newWhite.has(to)) {
|
|
375
|
-
const next = new Set(newWhite);
|
|
376
|
-
next.delete(to);
|
|
377
|
-
newWhite = next;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
else {
|
|
381
|
-
if (newBlack.has(to)) {
|
|
382
|
-
const next = new Set(newBlack);
|
|
383
|
-
next.delete(to);
|
|
384
|
-
newBlack = next;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
newCastling = {
|
|
389
|
-
white: newWhite,
|
|
390
|
-
black: newBlack,
|
|
391
|
-
whiteKing: newWhite.has(7),
|
|
392
|
-
whiteQueen: newWhite.has(0),
|
|
393
|
-
blackKing: newBlack.has(63),
|
|
394
|
-
blackQueen: newBlack.has(56),
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
// en passant square for next position
|
|
398
|
-
let newEp = null;
|
|
399
|
-
if (piece.role === Role.Pawn && Math.abs(squareRank(to) - squareRank(from)) === 2) {
|
|
400
|
-
// double push
|
|
401
|
-
const epRank = pos.turn === Color.White ? squareRank(from) + 1 : squareRank(from) - 1;
|
|
402
|
-
newEp = epRank * 8 + squareFile(from);
|
|
403
|
-
}
|
|
404
|
-
// halfmove
|
|
405
|
-
const isCapture = !!captured || isEnPassant;
|
|
406
|
-
const isPawnMove = piece.role === Role.Pawn;
|
|
407
|
-
const newHalf = isCapture || isPawnMove ? 0 : (pos.halfmoves ?? pos.halfmove ?? 0) + 1;
|
|
408
|
-
// fullmove
|
|
409
|
-
const newFull = pos.turn === Color.Black ? (pos.fullmoves ?? pos.fullmove ?? 1) + 1 : (pos.fullmoves ?? pos.fullmove ?? 1);
|
|
410
|
-
const newTurn = opposite(pos.turn);
|
|
411
|
-
const nextKingSq = pos.kingSq
|
|
412
|
-
? [pos.kingSq[0], pos.kingSq[1]]
|
|
413
|
-
: [board.kingSquare(pos.board, Color.White) ?? -1, board.kingSquare(pos.board, Color.Black) ?? -1];
|
|
414
|
-
if (piece.role === Role.King) {
|
|
415
|
-
nextKingSq[pos.turn] = to;
|
|
416
|
-
}
|
|
417
|
-
nb.kingSq = nextKingSq;
|
|
418
|
-
const newCheckers = attacks.kingAttackers(nb, newTurn);
|
|
419
|
-
const newPos = {
|
|
420
|
-
board: nb,
|
|
421
|
-
turn: newTurn,
|
|
422
|
-
castling: newCastling,
|
|
423
|
-
castlingMask: newMask,
|
|
424
|
-
isChess960: pos.isChess960 ?? false,
|
|
425
|
-
epSquare: newEp,
|
|
426
|
-
halfmoves: newHalf,
|
|
427
|
-
fullmoves: newFull,
|
|
428
|
-
halfmove: newHalf,
|
|
429
|
-
fullmove: newFull,
|
|
430
|
-
kingSq: nextKingSq,
|
|
431
|
-
checkers: newCheckers,
|
|
432
|
-
};
|
|
433
|
-
// Incremental O(1) Zobrist maintenance (design D2). Skipped (positions
|
|
434
|
-
// carry no zobrist fields) until the Polyglot key tables have loaded via
|
|
435
|
-
// ensureZobristLoaded() — the same lazy-loading contract as the magic
|
|
436
|
-
// tables. The input position is never mutated: the key is attached to the
|
|
437
|
-
// freshly built newPos before it escapes.
|
|
438
|
-
if (zobristTablesLoaded()) {
|
|
439
|
-
const zk = zobristAfterMove(pos, move, plan, isEnPassant, captured, newPos);
|
|
440
|
-
newPos.zobristLo = zk.lo;
|
|
441
|
-
newPos.zobristHi = zk.hi;
|
|
442
|
-
}
|
|
443
|
-
return newPos;
|
|
444
|
-
}
|
|
445
|
-
// alias play
|
|
446
|
-
export const play = makeMove;
|
|
447
|
-
// ---------- pseudo-legal generation ----------
|
|
448
|
-
const P_W_P = { color: Color.White, role: Role.Pawn };
|
|
449
|
-
const P_W_N = { color: Color.White, role: Role.Knight };
|
|
450
|
-
const P_W_B = { color: Color.White, role: Role.Bishop };
|
|
451
|
-
const P_W_R = { color: Color.White, role: Role.Rook };
|
|
452
|
-
const P_W_Q = { color: Color.White, role: Role.Queen };
|
|
453
|
-
const P_W_K = { color: Color.White, role: Role.King };
|
|
454
|
-
const P_B_P = { color: Color.Black, role: Role.Pawn };
|
|
455
|
-
const P_B_N = { color: Color.Black, role: Role.Knight };
|
|
456
|
-
const P_B_B = { color: Color.Black, role: Role.Bishop };
|
|
457
|
-
const P_B_R = { color: Color.Black, role: Role.Rook };
|
|
458
|
-
const P_B_Q = { color: Color.Black, role: Role.Queen };
|
|
459
|
-
const P_B_K = { color: Color.Black, role: Role.King };
|
|
460
|
-
function whitePawnPseudoDests(pos, from) {
|
|
461
|
-
const occ = pos.board.occupied;
|
|
462
|
-
const them = pos.board.black;
|
|
463
|
-
let lo = 0, hi = 0;
|
|
464
|
-
const to1 = from + 8;
|
|
465
|
-
if (!sq.has(occ, to1)) {
|
|
466
|
-
if (to1 < 32)
|
|
467
|
-
lo |= (1 << to1) >>> 0;
|
|
468
|
-
else
|
|
469
|
-
hi |= (1 << (to1 - 32)) >>> 0;
|
|
470
|
-
if (from >= 8 && from <= 15) {
|
|
471
|
-
const to2 = from + 16;
|
|
472
|
-
if (!sq.has(occ, to2)) {
|
|
473
|
-
lo |= (1 << to2) >>> 0;
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
const f = from & 7;
|
|
478
|
-
if (f > 0) {
|
|
479
|
-
const capL = from + 7;
|
|
480
|
-
if (sq.has(them, capL) || pos.epSquare === capL) {
|
|
481
|
-
if (capL < 32)
|
|
482
|
-
lo |= (1 << capL) >>> 0;
|
|
483
|
-
else
|
|
484
|
-
hi |= (1 << (capL - 32)) >>> 0;
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
if (f < 7) {
|
|
488
|
-
const capR = from + 9;
|
|
489
|
-
if (sq.has(them, capR) || pos.epSquare === capR) {
|
|
490
|
-
if (capR < 32)
|
|
491
|
-
lo |= (1 << capR) >>> 0;
|
|
492
|
-
else
|
|
493
|
-
hi |= (1 << (capR - 32)) >>> 0;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
return { lo: lo >>> 0, hi: hi >>> 0 };
|
|
497
|
-
}
|
|
498
|
-
function blackPawnPseudoDests(pos, from) {
|
|
499
|
-
const occ = pos.board.occupied;
|
|
500
|
-
const them = pos.board.white;
|
|
501
|
-
let lo = 0, hi = 0;
|
|
502
|
-
const to1 = from - 8;
|
|
503
|
-
if (!sq.has(occ, to1)) {
|
|
504
|
-
if (to1 < 32)
|
|
505
|
-
lo |= (1 << to1) >>> 0;
|
|
506
|
-
else
|
|
507
|
-
hi |= (1 << (to1 - 32)) >>> 0;
|
|
508
|
-
if (from >= 48 && from <= 55) {
|
|
509
|
-
const to2 = from - 16;
|
|
510
|
-
if (!sq.has(occ, to2)) {
|
|
511
|
-
hi |= (1 << (to2 - 32)) >>> 0;
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
const f = from & 7;
|
|
516
|
-
if (f > 0) {
|
|
517
|
-
const capL = from - 9;
|
|
518
|
-
if (sq.has(them, capL) || pos.epSquare === capL) {
|
|
519
|
-
if (capL < 32)
|
|
520
|
-
lo |= (1 << capL) >>> 0;
|
|
521
|
-
else
|
|
522
|
-
hi |= (1 << (capL - 32)) >>> 0;
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
if (f < 7) {
|
|
526
|
-
const capR = from - 7;
|
|
527
|
-
if (sq.has(them, capR) || pos.epSquare === capR) {
|
|
528
|
-
if (capR < 32)
|
|
529
|
-
lo |= (1 << capR) >>> 0;
|
|
530
|
-
else
|
|
531
|
-
hi |= (1 << (capR - 32)) >>> 0;
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
return { lo: lo >>> 0, hi: hi >>> 0 };
|
|
535
|
-
}
|
|
536
|
-
function genPseudoDests(pos, from, piece) {
|
|
537
|
-
const p = piece ?? board.pieceAt(pos.board, from);
|
|
538
|
-
if (!p || p.color !== pos.turn)
|
|
539
|
-
return sq.empty();
|
|
540
|
-
const occ = pos.board.occupied;
|
|
541
|
-
const own = p.color === Color.White ? pos.board.white : pos.board.black;
|
|
542
|
-
let pseudo;
|
|
543
|
-
switch (p.role) {
|
|
544
|
-
case Role.Pawn:
|
|
545
|
-
pseudo = p.color === Color.White ? whitePawnPseudoDests(pos, from) : blackPawnPseudoDests(pos, from);
|
|
546
|
-
break;
|
|
547
|
-
case Role.Knight:
|
|
548
|
-
pseudo = attacks.knightAttacks(from);
|
|
549
|
-
pseudo = sq.minus(pseudo, own);
|
|
550
|
-
break;
|
|
551
|
-
case Role.Bishop:
|
|
552
|
-
pseudo = attacks.bishopAttacks(from, occ);
|
|
553
|
-
pseudo = sq.minus(pseudo, own);
|
|
554
|
-
break;
|
|
555
|
-
case Role.Rook:
|
|
556
|
-
pseudo = attacks.rookAttacks(from, occ);
|
|
557
|
-
pseudo = sq.minus(pseudo, own);
|
|
558
|
-
break;
|
|
559
|
-
case Role.Queen:
|
|
560
|
-
pseudo = attacks.queenAttacks(from, occ);
|
|
561
|
-
pseudo = sq.minus(pseudo, own);
|
|
562
|
-
break;
|
|
563
|
-
case Role.King: {
|
|
564
|
-
pseudo = attacks.kingAttacks(from);
|
|
565
|
-
pseudo = sq.minus(pseudo, own);
|
|
566
|
-
// castling destinations
|
|
567
|
-
const ks = from;
|
|
568
|
-
// `from` IS this color's king square by definition (invariant: exactly
|
|
569
|
-
// one king per color), so no kingSquare lookup is needed here.
|
|
570
|
-
// Conditions to add castling dest: rights exist, between empty, not in check, traversal not attacked
|
|
571
|
-
if (!pos.isChess960) {
|
|
572
|
-
const mask = pos.castlingMask ?? getCastlingMask(pos);
|
|
573
|
-
if (p.color === Color.White) {
|
|
574
|
-
if (ks === 4 && (mask & (CASTLE_WK | CASTLE_WQ)) !== 0 && !isCheck(pos)) {
|
|
575
|
-
const occLo = occ.lo;
|
|
576
|
-
if ((mask & CASTLE_WK) !== 0 && (occLo & 0x60) === 0) {
|
|
577
|
-
const rp = board.pieceAt(pos.board, 7);
|
|
578
|
-
if (rp && rp.color === Color.White && rp.role === Role.Rook) {
|
|
579
|
-
if (!attacks.isAttacked(pos.board, 5, Color.Black) && !attacks.isAttacked(pos.board, 6, Color.Black)) {
|
|
580
|
-
pseudo = sq.or(pseudo, sq.singleton(7));
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
if ((mask & CASTLE_WQ) !== 0 && (occLo & 0x0E) === 0) {
|
|
585
|
-
const rp = board.pieceAt(pos.board, 0);
|
|
586
|
-
if (rp && rp.color === Color.White && rp.role === Role.Rook) {
|
|
587
|
-
if (!attacks.isAttacked(pos.board, 3, Color.Black) && !attacks.isAttacked(pos.board, 2, Color.Black)) {
|
|
588
|
-
pseudo = sq.or(pseudo, sq.singleton(0));
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
else {
|
|
595
|
-
if (ks === 60 && (mask & (CASTLE_BK | CASTLE_BQ)) !== 0 && !isCheck(pos)) {
|
|
596
|
-
const occHi = occ.hi;
|
|
597
|
-
if ((mask & CASTLE_BK) !== 0 && (occHi & 0x60000000) === 0) {
|
|
598
|
-
const rp = board.pieceAt(pos.board, 63);
|
|
599
|
-
if (rp && rp.color === Color.Black && rp.role === Role.Rook) {
|
|
600
|
-
if (!attacks.isAttacked(pos.board, 61, Color.White) && !attacks.isAttacked(pos.board, 62, Color.White)) {
|
|
601
|
-
pseudo = sq.or(pseudo, sq.singleton(63));
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
if ((mask & CASTLE_BQ) !== 0 && (occHi & 0x0E000000) === 0) {
|
|
606
|
-
const rp = board.pieceAt(pos.board, 56);
|
|
607
|
-
if (rp && rp.color === Color.Black && rp.role === Role.Rook) {
|
|
608
|
-
if (!attacks.isAttacked(pos.board, 59, Color.White) && !attacks.isAttacked(pos.board, 58, Color.White)) {
|
|
609
|
-
pseudo = sq.or(pseudo, sq.singleton(56));
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
else {
|
|
617
|
-
// Chess960 fallback using precomputed CASTLE_PATH and traversal tables
|
|
618
|
-
if (p.color === Color.White) {
|
|
619
|
-
if (pos.castling.white.size > 0 && !isCheck(pos)) {
|
|
620
|
-
const kingFile = ks & 7;
|
|
621
|
-
for (const rs of pos.castling.white) {
|
|
622
|
-
const rp = board.pieceAt(pos.board, rs);
|
|
623
|
-
if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
|
|
624
|
-
continue;
|
|
625
|
-
const rookFile = rs & 7;
|
|
626
|
-
const idx = (kingFile << 3) | rookFile;
|
|
627
|
-
if (((CASTLE_PATH_LO[idx] & occ.lo) | (CASTLE_PATH_HI[idx] & occ.hi)) !== 0)
|
|
628
|
-
continue;
|
|
629
|
-
const trav = CASTLE_TRAVERSAL_WHITE[idx];
|
|
630
|
-
let attacked = false;
|
|
631
|
-
for (let ti = 0; ti < trav.length; ti++) {
|
|
632
|
-
if (attacks.isAttacked(pos.board, trav[ti], Color.Black)) {
|
|
633
|
-
attacked = true;
|
|
634
|
-
break;
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
if (attacked)
|
|
638
|
-
continue;
|
|
639
|
-
pseudo = sq.or(pseudo, sq.singleton(rs));
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
else {
|
|
644
|
-
if (pos.castling.black.size > 0 && !isCheck(pos)) {
|
|
645
|
-
const kingFile = ks & 7;
|
|
646
|
-
for (const rs of pos.castling.black) {
|
|
647
|
-
const rp = board.pieceAt(pos.board, rs);
|
|
648
|
-
if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
|
|
649
|
-
continue;
|
|
650
|
-
const rookFile = rs & 7;
|
|
651
|
-
const idx = 64 | (kingFile << 3) | rookFile;
|
|
652
|
-
if (((CASTLE_PATH_LO[idx] & occ.lo) | (CASTLE_PATH_HI[idx] & occ.hi)) !== 0)
|
|
653
|
-
continue;
|
|
654
|
-
const trav = CASTLE_TRAVERSAL_BLACK[idx & 63];
|
|
655
|
-
let attacked = false;
|
|
656
|
-
for (let ti = 0; ti < trav.length; ti++) {
|
|
657
|
-
if (attacks.isAttacked(pos.board, trav[ti], Color.White)) {
|
|
658
|
-
attacked = true;
|
|
659
|
-
break;
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
if (attacked)
|
|
663
|
-
continue;
|
|
664
|
-
pseudo = sq.or(pseudo, sq.singleton(rs));
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
break;
|
|
670
|
-
}
|
|
671
|
-
default:
|
|
672
|
-
pseudo = sq.empty();
|
|
673
|
-
}
|
|
674
|
-
return pseudo;
|
|
675
|
-
}
|
|
676
|
-
// ---------- dests filtered for legality ----------
|
|
677
|
-
// ---- Hot-loop scratch (see FP policy in board.ts) ---------------------------
|
|
678
|
-
// `destScratch` is owned exclusively by moveLeavesKingSafe, a leaf function:
|
|
679
|
-
// while the scratch is live it only calls board/attacks helpers that never
|
|
680
|
-
// re-enter movegen, so no re-entrant caller can observe intermediate state.
|
|
681
|
-
// The public API remains pure — the scratch never escapes and its state is
|
|
682
|
-
// fully rewritten from the input position before each use.
|
|
683
|
-
const destScratch = board.newScratchBoard();
|
|
684
|
-
/**
|
|
685
|
-
* Hot-loop legality tester: applies the shared board-edit sequence
|
|
686
|
-
* (applyBoardEdits — same code path as makeMove) to the reusable scratch
|
|
687
|
-
* board, then checks whether our king is left attacked. Semantically
|
|
688
|
-
* identical to `makeMove(pos, mv)` + `!isAttacked(our king)`, minus all the
|
|
689
|
-
* per-pseudo-move allocation (Position, Sets, Move object, 3 board spreads).
|
|
690
|
-
* Mutation is sanctioned here per the FP policy: hot loop, locally owned
|
|
691
|
-
* scratch, inputs never mutated.
|
|
692
|
-
*/
|
|
693
|
-
function moveLeavesKingSafe(pos, piece, from, to, // normalized dest
|
|
694
|
-
origTo, // move.to before normalization
|
|
695
|
-
isEnPassant, plan, // non-null ⇒ castling (exact king+rook apply)
|
|
696
|
-
isPromotion, promotion) {
|
|
697
|
-
board.copyBoardInto(destScratch, pos.board);
|
|
698
|
-
const captured = computeCaptured(pos, origTo, to, plan !== null, piece);
|
|
699
|
-
applyBoardEdits(destScratch, pos, from, to, origTo, piece, isEnPassant, plan, isPromotion, promotion, captured);
|
|
700
|
-
const ksq = board.kingSquare(destScratch, pos.turn);
|
|
701
|
-
if (ksq === undefined)
|
|
702
|
-
return false;
|
|
703
|
-
return !attacks.isAttacked(destScratch, ksq, opposite(pos.turn));
|
|
704
|
-
}
|
|
705
|
-
// Reused castling plan scratch (same ownership discipline): avoids allocating
|
|
706
|
-
// two plan objects per analyzed position in the perft/movegen hot loop. The
|
|
707
|
-
// referenced position data is read-only and consumed within the same call.
|
|
708
|
-
const scratchCastlingPlans = [];
|
|
709
|
-
const scratchCastlingPlanA = { side: "king", kingFrom: 0, kingTo: 0, rookFrom: 0, rookTo: 0 };
|
|
710
|
-
const scratchCastlingPlanB = { side: "king", kingFrom: 0, kingTo: 0, rookFrom: 0, rookTo: 0 };
|
|
711
|
-
export function analyzeCheckContext(pos) {
|
|
712
|
-
const us = pos.turn;
|
|
713
|
-
const them = opposite(us);
|
|
714
|
-
const ksq = board.kingSquare(pos.board, us);
|
|
715
|
-
if (ksq === undefined) {
|
|
716
|
-
// degenerate (kingless) position: no pins, no masks
|
|
717
|
-
return { us, ksq: -1, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinned: sq.EMPTY, castlingPlans: [] };
|
|
718
|
-
}
|
|
719
|
-
const ctx = { us, ksq, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinned: sq.EMPTY, castlingPlans: [] };
|
|
720
|
-
// Precompute the position's castling plans once (design D2): the hot loops
|
|
721
|
-
// (destsFast king branch, genLegalMoves) look them up instead of re-running
|
|
722
|
-
// the full detectCastling per king move. Plans are written into the reused
|
|
723
|
-
// scratch array — no allocation in the hot loop.
|
|
724
|
-
ctx.castlingPlans = scratchCastlingPlans;
|
|
725
|
-
ctx.castlingPlans.length = 0;
|
|
726
|
-
if (!pos.isChess960) {
|
|
727
|
-
const mask = pos.castlingMask ?? getCastlingMask(pos);
|
|
728
|
-
if (us === Color.White) {
|
|
729
|
-
if ((mask & CASTLE_WK) !== 0 && ksq === 4) {
|
|
730
|
-
const rp = board.pieceAt(pos.board, 7);
|
|
731
|
-
if (rp && rp.color === Color.White && rp.role === Role.Rook)
|
|
732
|
-
ctx.castlingPlans.push(PLAN_WHITE_K);
|
|
733
|
-
}
|
|
734
|
-
if ((mask & CASTLE_WQ) !== 0 && ksq === 4) {
|
|
735
|
-
const rp = board.pieceAt(pos.board, 0);
|
|
736
|
-
if (rp && rp.color === Color.White && rp.role === Role.Rook)
|
|
737
|
-
ctx.castlingPlans.push(PLAN_WHITE_Q);
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
else {
|
|
741
|
-
if ((mask & CASTLE_BK) !== 0 && ksq === 60) {
|
|
742
|
-
const rp = board.pieceAt(pos.board, 63);
|
|
743
|
-
if (rp && rp.color === Color.Black && rp.role === Role.Rook)
|
|
744
|
-
ctx.castlingPlans.push(PLAN_BLACK_K);
|
|
745
|
-
}
|
|
746
|
-
if ((mask & CASTLE_BQ) !== 0 && ksq === 60) {
|
|
747
|
-
const rp = board.pieceAt(pos.board, 56);
|
|
748
|
-
if (rp && rp.color === Color.Black && rp.role === Role.Rook)
|
|
749
|
-
ctx.castlingPlans.push(PLAN_BLACK_Q);
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
else {
|
|
754
|
-
const rights = us === Color.White ? pos.castling.white : pos.castling.black;
|
|
755
|
-
if (rights.size > 0) {
|
|
756
|
-
for (const rs of rights) {
|
|
757
|
-
const rp = board.pieceAt(pos.board, rs);
|
|
758
|
-
if (rp && rp.color === us && rp.role === Role.Rook) {
|
|
759
|
-
const slot = ctx.castlingPlans.length === 0 ? scratchCastlingPlanA : scratchCastlingPlanB;
|
|
760
|
-
const next = castlingPlanFor(us, ksq, rs);
|
|
761
|
-
slot.side = next.side;
|
|
762
|
-
slot.kingFrom = next.kingFrom;
|
|
763
|
-
slot.kingTo = next.kingTo;
|
|
764
|
-
slot.rookFrom = next.rookFrom;
|
|
765
|
-
slot.rookTo = next.rookTo;
|
|
766
|
-
ctx.castlingPlans.push(slot);
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
const checkers = pos.checkers ?? attacks.kingAttackers(pos.board, us);
|
|
772
|
-
const nCheckers = sq.popcount(checkers);
|
|
773
|
-
if (nCheckers === 1) {
|
|
774
|
-
const c = sq.first(checkers);
|
|
775
|
-
ctx.checkMask = sq.or(attacks.between(ksq, c), sq.singleton(c));
|
|
776
|
-
}
|
|
777
|
-
else if (nCheckers >= 2) {
|
|
778
|
-
ctx.doubleCheck = true;
|
|
779
|
-
}
|
|
780
|
-
// Pinned pieces: enemy slider "snipers" x-raying our king with exactly one
|
|
781
|
-
// blocker between; if the blocker is ours, it is pinned to the sniper's ray.
|
|
782
|
-
const themOcc = them === Color.White ? pos.board.white : pos.board.black;
|
|
783
|
-
const themBQ = sq.or(sq.and(themOcc, pos.board.bishop), sq.and(themOcc, pos.board.queen));
|
|
784
|
-
const themRQ = sq.or(sq.and(themOcc, pos.board.rook), sq.and(themOcc, pos.board.queen));
|
|
785
|
-
const noOcc = sq.EMPTY;
|
|
786
|
-
const snipers = sq.or(sq.and(themRQ, attacks.rookAttacks(ksq, noOcc)), sq.and(themBQ, attacks.bishopAttacks(ksq, noOcc)));
|
|
787
|
-
let pinnedLo = 0, pinnedHi = 0;
|
|
788
|
-
let sLo = snipers.lo >>> 0, sHi = snipers.hi >>> 0;
|
|
789
|
-
while (sLo !== 0) {
|
|
790
|
-
const lsb = (sLo & -sLo) >>> 0;
|
|
791
|
-
const sniper = Math.clz32(lsb) ^ 31;
|
|
792
|
-
sLo = (sLo ^ lsb) >>> 0;
|
|
793
|
-
const b = attacks.between(ksq, sniper);
|
|
794
|
-
const bLo = (b.lo & pos.board.occupied.lo) >>> 0;
|
|
795
|
-
const bHi = (b.hi & pos.board.occupied.hi) >>> 0;
|
|
796
|
-
const nBlockers = sq.popcount({ lo: bLo, hi: bHi });
|
|
797
|
-
if (nBlockers === 1) {
|
|
798
|
-
const blockerSq = bLo !== 0 ? (Math.clz32((bLo & -bLo) >>> 0) ^ 31) : (32 + (Math.clz32((bHi & -bHi) >>> 0) ^ 31));
|
|
799
|
-
if (!sq.has(themOcc, blockerSq)) {
|
|
800
|
-
if (blockerSq < 32)
|
|
801
|
-
pinnedLo |= (1 << blockerSq) >>> 0;
|
|
802
|
-
else
|
|
803
|
-
pinnedHi |= (1 << (blockerSq - 32)) >>> 0;
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
while (sHi !== 0) {
|
|
808
|
-
const lsb = (sHi & -sHi) >>> 0;
|
|
809
|
-
const sniper = 32 + (Math.clz32(lsb) ^ 31);
|
|
810
|
-
sHi = (sHi ^ lsb) >>> 0;
|
|
811
|
-
const b = attacks.between(ksq, sniper);
|
|
812
|
-
const bLo = (b.lo & pos.board.occupied.lo) >>> 0;
|
|
813
|
-
const bHi = (b.hi & pos.board.occupied.hi) >>> 0;
|
|
814
|
-
const nBlockers = sq.popcount({ lo: bLo, hi: bHi });
|
|
815
|
-
if (nBlockers === 1) {
|
|
816
|
-
const blockerSq = bLo !== 0 ? (Math.clz32((bLo & -bLo) >>> 0) ^ 31) : (32 + (Math.clz32((bHi & -bHi) >>> 0) ^ 31));
|
|
817
|
-
if (!sq.has(themOcc, blockerSq)) {
|
|
818
|
-
if (blockerSq < 32)
|
|
819
|
-
pinnedLo |= (1 << blockerSq) >>> 0;
|
|
820
|
-
else
|
|
821
|
-
pinnedHi |= (1 << (blockerSq - 32)) >>> 0;
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
ctx.pinned = { lo: pinnedLo >>> 0, hi: pinnedHi >>> 0 };
|
|
826
|
-
// King-safe mask: attackedness evaluated with our king removed from the
|
|
827
|
-
// occupancy, so sliders x-raying the king keep it attacked on the far side.
|
|
828
|
-
const occWithoutKing = sq.minus(pos.board.occupied, sq.singleton(ksq));
|
|
829
|
-
const usOcc = us === Color.White ? pos.board.white : pos.board.black;
|
|
830
|
-
let kingLo = 0, kingHi = 0;
|
|
831
|
-
sq.forEachSquare(attacks.kingAttacks(ksq), (d) => {
|
|
832
|
-
if (sq.has(usOcc, d))
|
|
833
|
-
return;
|
|
834
|
-
if (sq.isEmpty(attacks.attackersTo(pos.board, d, them, occWithoutKing))) {
|
|
835
|
-
if (d < 32)
|
|
836
|
-
kingLo |= (1 << d) >>> 0;
|
|
837
|
-
else
|
|
838
|
-
kingHi |= (1 << (d - 32)) >>> 0;
|
|
839
|
-
}
|
|
840
|
-
});
|
|
841
|
-
ctx.kingSafe = { lo: kingLo >>> 0, hi: kingHi >>> 0 };
|
|
842
|
-
return ctx;
|
|
843
|
-
}
|
|
844
|
-
/**
|
|
845
|
-
* dests for one piece, given the per-position CheckContext. Legality is a
|
|
846
|
-
* pure set intersection for all cases except the trap cases listed above.
|
|
847
|
-
*/
|
|
848
|
-
export function destsFast(pos, from, piece, ctx) {
|
|
849
|
-
const pseudo = genPseudoDests(pos, from, piece);
|
|
850
|
-
if (sq.isEmpty(pseudo))
|
|
851
|
-
return pseudo;
|
|
852
|
-
if (piece.role === Role.King) {
|
|
853
|
-
// Castling dests (detected by the shared detectCastling path — fixes the
|
|
854
|
-
// defect where ANY king move to {6,2,62,58} was treated as castling while
|
|
855
|
-
// ANY color held rights, corrupting the scratch board via fallback rook
|
|
856
|
-
// placement) keep the exact play-and-test semantics; other king dests come
|
|
857
|
-
// from the precomputed king-safe mask.
|
|
858
|
-
let lo = 0, hi = 0;
|
|
859
|
-
const plans = ctx.castlingPlans;
|
|
860
|
-
sq.forEachSquare(pseudo, (to) => {
|
|
861
|
-
// Castling dests (precomputed per-position plans — the shared
|
|
862
|
-
// detectCastling semantics, without the per-move cost) keep the exact
|
|
863
|
-
// play-and-test semantics; other king dests come from the precomputed
|
|
864
|
-
// king-safe mask.
|
|
865
|
-
const plan = planForDest(plans, to);
|
|
866
|
-
if (plan) {
|
|
867
|
-
if (moveLeavesKingSafe(pos, piece, from, plan.kingTo, to, false, plan, false, null)) {
|
|
868
|
-
if (to < 32)
|
|
869
|
-
lo |= (1 << to) >>> 0;
|
|
870
|
-
else
|
|
871
|
-
hi |= (1 << (to - 32)) >>> 0;
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
else if (sq.has(ctx.kingSafe, to)) {
|
|
875
|
-
if (to < 32)
|
|
876
|
-
lo |= (1 << to) >>> 0;
|
|
877
|
-
else
|
|
878
|
-
hi |= (1 << (to - 32)) >>> 0;
|
|
879
|
-
}
|
|
880
|
-
});
|
|
881
|
-
return { lo: lo >>> 0, hi: hi >>> 0 };
|
|
882
|
-
}
|
|
883
|
-
// Any single non-king move can never resolve a double check.
|
|
884
|
-
if (ctx.doubleCheck)
|
|
885
|
-
return { lo: 0, hi: 0 };
|
|
886
|
-
let nonEp = pseudo;
|
|
887
|
-
let epLegal = false;
|
|
888
|
-
const epSquare = pos.epSquare;
|
|
889
|
-
if (piece.role === Role.Pawn && epSquare !== null && sq.has(pseudo, epSquare)) {
|
|
890
|
-
nonEp = sq.minus(pseudo, sq.singleton(epSquare));
|
|
891
|
-
epLegal = moveLeavesKingSafe(pos, piece, from, epSquare, epSquare, true, null, false, null);
|
|
892
|
-
}
|
|
893
|
-
let result = sq.and(nonEp, ctx.checkMask);
|
|
894
|
-
if (sq.has(ctx.pinned, from)) {
|
|
895
|
-
const pIdx = (ctx.ksq << 6) | from;
|
|
896
|
-
result = {
|
|
897
|
-
lo: (result.lo & attacks.LINE_RAY_LO[pIdx]) >>> 0,
|
|
898
|
-
hi: (result.hi & attacks.LINE_RAY_HI[pIdx]) >>> 0,
|
|
899
|
-
};
|
|
900
|
-
}
|
|
901
|
-
if (epLegal && epSquare !== null)
|
|
902
|
-
result = sq.or(result, sq.singleton(epSquare));
|
|
903
|
-
return result;
|
|
904
|
-
}
|
|
905
|
-
export function dests(pos, from) {
|
|
906
|
-
const piece = board.pieceAt(pos.board, from);
|
|
907
|
-
if (!piece)
|
|
908
|
-
return { lo: 0, hi: 0 };
|
|
909
|
-
return destsFast(pos, from, piece, analyzeCheckContext(pos));
|
|
910
|
-
}
|
|
911
|
-
export function allDests(pos) {
|
|
912
|
-
const m = new Map();
|
|
913
|
-
const ctx = analyzeCheckContext(pos);
|
|
914
|
-
const isWhite = pos.turn === Color.White;
|
|
915
|
-
const own = isWhite ? pos.board.white : pos.board.black;
|
|
916
|
-
// 1. King
|
|
917
|
-
const ksq = ctx.ksq;
|
|
918
|
-
if (ksq >= 0) {
|
|
919
|
-
const kingPiece = isWhite ? P_W_K : P_B_K;
|
|
920
|
-
const d = destsFast(pos, ksq, kingPiece, ctx);
|
|
921
|
-
if (!sq.isEmpty(d))
|
|
922
|
-
m.set(ksq, d);
|
|
923
|
-
}
|
|
924
|
-
if (ctx.doubleCheck)
|
|
925
|
-
return m;
|
|
926
|
-
const addRole = (roleBB, piece) => {
|
|
927
|
-
sq.forEachSquare(sq.and(own, roleBB), (sqIdx) => {
|
|
928
|
-
const d = destsFast(pos, sqIdx, piece, ctx);
|
|
929
|
-
if (!sq.isEmpty(d))
|
|
930
|
-
m.set(sqIdx, d);
|
|
931
|
-
});
|
|
932
|
-
};
|
|
933
|
-
addRole(pos.board.pawn, isWhite ? P_W_P : P_B_P);
|
|
934
|
-
addRole(pos.board.knight, isWhite ? P_W_N : P_B_N);
|
|
935
|
-
addRole(pos.board.bishop, isWhite ? P_W_B : P_B_B);
|
|
936
|
-
addRole(pos.board.rook, isWhite ? P_W_R : P_B_R);
|
|
937
|
-
addRole(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
|
|
938
|
-
return m;
|
|
939
|
-
}
|
|
940
|
-
export function isLegal(pos, move) {
|
|
941
|
-
// A pass is legal iff the side to move is not in check — judged fresh from
|
|
942
|
-
// the attack tables, never from the cached `checkers` bitboard.
|
|
943
|
-
if (isNullMove(move))
|
|
944
|
-
return isNullMoveLegal(pos);
|
|
945
|
-
// Single castling path (design D2): both the normalized (e1g1) and the
|
|
946
|
-
// baseline/960 (e1h1) input forms resolve through detectCastling.
|
|
947
|
-
const castling = detectCastling(pos, move.from, move.to);
|
|
948
|
-
if (castling) {
|
|
949
|
-
const d = dests(pos, move.from);
|
|
950
|
-
// dests emits the rook-square representation (ADR-013 as amended); the
|
|
951
|
-
// normalized e1g1 input form is accepted via the plan's rook square.
|
|
952
|
-
return sq.has(d, castling.rookFrom);
|
|
953
|
-
}
|
|
954
|
-
const piece = board.pieceAt(pos.board, move.from);
|
|
955
|
-
const to = move.to;
|
|
956
|
-
const d = dests(pos, move.from);
|
|
957
|
-
if (!sq.has(d, to))
|
|
958
|
-
return false;
|
|
959
|
-
if (piece && piece.role === Role.Pawn) {
|
|
960
|
-
const destRank = squareRank(to);
|
|
961
|
-
const isPromoRank = (piece.color === Color.White && destRank === 7) || (piece.color === Color.Black && destRank === 0);
|
|
962
|
-
if (isPromoRank && !move.promotion)
|
|
963
|
-
return false;
|
|
964
|
-
}
|
|
965
|
-
return true;
|
|
966
|
-
}
|
|
967
|
-
// helpers for checkmate/stalemate
|
|
968
|
-
function hasAnyLegalMove(pos) {
|
|
969
|
-
const ctx = analyzeCheckContext(pos);
|
|
970
|
-
const ksq = ctx.ksq;
|
|
971
|
-
if (ksq >= 0) {
|
|
972
|
-
const kd = destsFast(pos, ksq, { color: pos.turn, role: Role.King }, ctx);
|
|
973
|
-
if (!sq.isEmpty(kd))
|
|
974
|
-
return true;
|
|
975
|
-
}
|
|
976
|
-
if (ctx.doubleCheck)
|
|
977
|
-
return false;
|
|
978
|
-
const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
|
|
979
|
-
let ownLo = own.lo >>> 0, ownHi = own.hi >>> 0;
|
|
980
|
-
while (ownLo !== 0 || ownHi !== 0) {
|
|
981
|
-
let from;
|
|
982
|
-
if (ownLo !== 0) {
|
|
983
|
-
const lsb = (ownLo & -ownLo) >>> 0;
|
|
984
|
-
from = Math.clz32(lsb) ^ 31;
|
|
985
|
-
ownLo = (ownLo ^ lsb) >>> 0;
|
|
986
|
-
}
|
|
987
|
-
else {
|
|
988
|
-
const lsb = (ownHi & -ownHi) >>> 0;
|
|
989
|
-
from = 32 + (Math.clz32(lsb) ^ 31);
|
|
990
|
-
ownHi = (ownHi ^ lsb) >>> 0;
|
|
991
|
-
}
|
|
992
|
-
if (from === ksq)
|
|
993
|
-
continue;
|
|
994
|
-
const piece = board.pieceAt(pos.board, from);
|
|
995
|
-
if (!piece)
|
|
996
|
-
continue;
|
|
997
|
-
const d = destsFast(pos, from, piece, ctx);
|
|
998
|
-
if (!sq.isEmpty(d))
|
|
999
|
-
return true;
|
|
1000
|
-
}
|
|
1001
|
-
return false;
|
|
1002
|
-
}
|
|
1003
|
-
export function isCheckmate(pos) {
|
|
1004
|
-
return isCheck(pos) && !hasAnyLegalMove(pos);
|
|
1005
|
-
}
|
|
1006
|
-
export function isStalemate(pos) {
|
|
1007
|
-
return !isCheck(pos) && !hasAnyLegalMove(pos);
|
|
1008
|
-
}
|
|
1009
|
-
// ---------- perft ----------
|
|
1010
|
-
export function perft(pos, depth) {
|
|
1011
|
-
if (depth === 0)
|
|
1012
|
-
return 1;
|
|
1013
|
-
if (depth === 1) {
|
|
1014
|
-
return countLegalMoves(pos);
|
|
1015
|
-
}
|
|
1016
|
-
let nodes = 0;
|
|
1017
|
-
const moves = genLegalMoves(pos);
|
|
1018
|
-
for (const m of moves) {
|
|
1019
|
-
const next = makeMove(pos, m);
|
|
1020
|
-
nodes += perft(next, depth - 1);
|
|
1021
|
-
}
|
|
1022
|
-
return nodes;
|
|
1023
|
-
}
|
|
1024
|
-
export class MoveCounter {
|
|
1025
|
-
constructor() {
|
|
1026
|
-
this.count = 0;
|
|
1027
|
-
}
|
|
1028
|
-
add(set) {
|
|
1029
|
-
this.count += sq.popcount(set);
|
|
1030
|
-
}
|
|
1031
|
-
addPawns(legal, isWhite) {
|
|
1032
|
-
const total = sq.popcount(legal);
|
|
1033
|
-
const promos = isWhite
|
|
1034
|
-
? sq.popcount({ lo: 0, hi: (legal.hi & 0xff000000) >>> 0 })
|
|
1035
|
-
: sq.popcount({ lo: (legal.lo & 0x000000ff) >>> 0, hi: 0 });
|
|
1036
|
-
this.count += total + promos * 3;
|
|
1037
|
-
}
|
|
1038
|
-
reset() {
|
|
1039
|
-
this.count = 0;
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
export function countLegalMoves(pos) {
|
|
1043
|
-
const ctx = analyzeCheckContext(pos);
|
|
1044
|
-
const us = pos.turn;
|
|
1045
|
-
const isWhite = us === Color.White;
|
|
1046
|
-
const own = isWhite ? pos.board.white : pos.board.black;
|
|
1047
|
-
let count = 0;
|
|
1048
|
-
// 1. King
|
|
1049
|
-
const ksq = ctx.ksq;
|
|
1050
|
-
if (ksq >= 0) {
|
|
1051
|
-
const kingPiece = isWhite ? P_W_K : P_B_K;
|
|
1052
|
-
count += sq.popcount(destsFast(pos, ksq, kingPiece, ctx));
|
|
1053
|
-
}
|
|
1054
|
-
if (ctx.doubleCheck)
|
|
1055
|
-
return count;
|
|
1056
|
-
// 2. Pawns (bulk popcount without inner destination loops)
|
|
1057
|
-
const pawnPiece = isWhite ? P_W_P : P_B_P;
|
|
1058
|
-
let pLo = (own.lo & pos.board.pawn.lo) >>> 0;
|
|
1059
|
-
let pHi = (own.hi & pos.board.pawn.hi) >>> 0;
|
|
1060
|
-
while (pLo !== 0) {
|
|
1061
|
-
const lsb = (pLo & -pLo) >>> 0;
|
|
1062
|
-
const from = Math.clz32(lsb) ^ 31;
|
|
1063
|
-
pLo = (pLo ^ lsb) >>> 0;
|
|
1064
|
-
const legal = destsFast(pos, from, pawnPiece, ctx);
|
|
1065
|
-
const total = sq.popcount(legal);
|
|
1066
|
-
const promos = isWhite
|
|
1067
|
-
? sq.popcount({ lo: 0, hi: (legal.hi & 0xff000000) >>> 0 })
|
|
1068
|
-
: sq.popcount({ lo: (legal.lo & 0x000000ff) >>> 0, hi: 0 });
|
|
1069
|
-
count += total + promos * 3;
|
|
1070
|
-
}
|
|
1071
|
-
while (pHi !== 0) {
|
|
1072
|
-
const lsb = (pHi & -pHi) >>> 0;
|
|
1073
|
-
const from = 32 + (Math.clz32(lsb) ^ 31);
|
|
1074
|
-
pHi = (pHi ^ lsb) >>> 0;
|
|
1075
|
-
const legal = destsFast(pos, from, pawnPiece, ctx);
|
|
1076
|
-
const total = sq.popcount(legal);
|
|
1077
|
-
const promos = isWhite
|
|
1078
|
-
? sq.popcount({ lo: 0, hi: (legal.hi & 0xff000000) >>> 0 })
|
|
1079
|
-
: sq.popcount({ lo: (legal.lo & 0x000000ff) >>> 0, hi: 0 });
|
|
1080
|
-
count += total + promos * 3;
|
|
1081
|
-
}
|
|
1082
|
-
// 3. Knights, Bishops, Rooks, Queens (bulk popcount on legal dests)
|
|
1083
|
-
const countPieces = (roleBB, piece) => {
|
|
1084
|
-
let rLo = (own.lo & roleBB.lo) >>> 0;
|
|
1085
|
-
let rHi = (own.hi & roleBB.hi) >>> 0;
|
|
1086
|
-
while (rLo !== 0) {
|
|
1087
|
-
const lsb = (rLo & -rLo) >>> 0;
|
|
1088
|
-
const from = Math.clz32(lsb) ^ 31;
|
|
1089
|
-
rLo = (rLo ^ lsb) >>> 0;
|
|
1090
|
-
count += sq.popcount(destsFast(pos, from, piece, ctx));
|
|
1091
|
-
}
|
|
1092
|
-
while (rHi !== 0) {
|
|
1093
|
-
const lsb = (rHi & -rHi) >>> 0;
|
|
1094
|
-
const from = 32 + (Math.clz32(lsb) ^ 31);
|
|
1095
|
-
rHi = (rHi ^ lsb) >>> 0;
|
|
1096
|
-
count += sq.popcount(destsFast(pos, from, piece, ctx));
|
|
1097
|
-
}
|
|
1098
|
-
};
|
|
1099
|
-
countPieces(pos.board.knight, isWhite ? P_W_N : P_B_N);
|
|
1100
|
-
countPieces(pos.board.bishop, isWhite ? P_W_B : P_B_B);
|
|
1101
|
-
countPieces(pos.board.rook, isWhite ? P_W_R : P_B_R);
|
|
1102
|
-
countPieces(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
|
|
1103
|
-
return count;
|
|
1104
|
-
}
|
|
1105
|
-
export function legalMovesInto(pos, out) {
|
|
1106
|
-
let count = 0;
|
|
1107
|
-
const ctx = analyzeCheckContext(pos);
|
|
1108
|
-
const us = pos.turn;
|
|
1109
|
-
const isWhite = us === Color.White;
|
|
1110
|
-
const own = isWhite ? pos.board.white : pos.board.black;
|
|
1111
|
-
// 1. King
|
|
1112
|
-
const ksq = ctx.ksq;
|
|
1113
|
-
if (ksq >= 0) {
|
|
1114
|
-
const kingPiece = isWhite ? P_W_K : P_B_K;
|
|
1115
|
-
const kd = destsFast(pos, ksq, kingPiece, ctx);
|
|
1116
|
-
let dLo = kd.lo >>> 0, dHi = kd.hi >>> 0;
|
|
1117
|
-
while (dLo !== 0) {
|
|
1118
|
-
const lsb = (dLo & -dLo) >>> 0;
|
|
1119
|
-
const to = Math.clz32(lsb) ^ 31;
|
|
1120
|
-
dLo = (dLo ^ lsb) >>> 0;
|
|
1121
|
-
out[count++] = (ksq | (to << 6)) >>> 0;
|
|
1122
|
-
}
|
|
1123
|
-
while (dHi !== 0) {
|
|
1124
|
-
const lsb = (dHi & -dHi) >>> 0;
|
|
1125
|
-
const to = 32 + (Math.clz32(lsb) ^ 31);
|
|
1126
|
-
dHi = (dHi ^ lsb) >>> 0;
|
|
1127
|
-
out[count++] = (ksq | (to << 6)) >>> 0;
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
if (ctx.doubleCheck)
|
|
1131
|
-
return count;
|
|
1132
|
-
// 2. Pawns
|
|
1133
|
-
const pawnPiece = isWhite ? P_W_P : P_B_P;
|
|
1134
|
-
let pLo = (own.lo & pos.board.pawn.lo) >>> 0;
|
|
1135
|
-
let pHi = (own.hi & pos.board.pawn.hi) >>> 0;
|
|
1136
|
-
const promoRank = isWhite ? 7 : 0;
|
|
1137
|
-
const emitPawnDests = (from) => {
|
|
1138
|
-
const legal = destsFast(pos, from, pawnPiece, ctx);
|
|
1139
|
-
let dLo = legal.lo >>> 0, dHi = legal.hi >>> 0;
|
|
1140
|
-
while (dLo !== 0) {
|
|
1141
|
-
const lsb = (dLo & -dLo) >>> 0;
|
|
1142
|
-
const to = Math.clz32(lsb) ^ 31;
|
|
1143
|
-
dLo = (dLo ^ lsb) >>> 0;
|
|
1144
|
-
if ((to >> 3) === promoRank) {
|
|
1145
|
-
out[count++] = (from | (to << 6) | (PROMO_QUEEN << 12)) >>> 0;
|
|
1146
|
-
out[count++] = (from | (to << 6) | (PROMO_ROOK << 12)) >>> 0;
|
|
1147
|
-
out[count++] = (from | (to << 6) | (PROMO_BISHOP << 12)) >>> 0;
|
|
1148
|
-
out[count++] = (from | (to << 6) | (PROMO_KNIGHT << 12)) >>> 0;
|
|
1149
|
-
}
|
|
1150
|
-
else {
|
|
1151
|
-
out[count++] = (from | (to << 6)) >>> 0;
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
while (dHi !== 0) {
|
|
1155
|
-
const lsb = (dHi & -dHi) >>> 0;
|
|
1156
|
-
const to = 32 + (Math.clz32(lsb) ^ 31);
|
|
1157
|
-
dHi = (dHi ^ lsb) >>> 0;
|
|
1158
|
-
if ((to >> 3) === promoRank) {
|
|
1159
|
-
out[count++] = (from | (to << 6) | (PROMO_QUEEN << 12)) >>> 0;
|
|
1160
|
-
out[count++] = (from | (to << 6) | (PROMO_ROOK << 12)) >>> 0;
|
|
1161
|
-
out[count++] = (from | (to << 6) | (PROMO_BISHOP << 12)) >>> 0;
|
|
1162
|
-
out[count++] = (from | (to << 6) | (PROMO_KNIGHT << 12)) >>> 0;
|
|
1163
|
-
}
|
|
1164
|
-
else {
|
|
1165
|
-
out[count++] = (from | (to << 6)) >>> 0;
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
};
|
|
1169
|
-
while (pLo !== 0) {
|
|
1170
|
-
const lsb = (pLo & -pLo) >>> 0;
|
|
1171
|
-
const from = Math.clz32(lsb) ^ 31;
|
|
1172
|
-
pLo = (pLo ^ lsb) >>> 0;
|
|
1173
|
-
emitPawnDests(from);
|
|
1174
|
-
}
|
|
1175
|
-
while (pHi !== 0) {
|
|
1176
|
-
const lsb = (pHi & -pHi) >>> 0;
|
|
1177
|
-
const from = 32 + (Math.clz32(lsb) ^ 31);
|
|
1178
|
-
pHi = (pHi ^ lsb) >>> 0;
|
|
1179
|
-
emitPawnDests(from);
|
|
1180
|
-
}
|
|
1181
|
-
// 3. Knights, Bishops, Rooks, Queens
|
|
1182
|
-
const emitRole = (roleBB, piece) => {
|
|
1183
|
-
let rLo = (own.lo & roleBB.lo) >>> 0;
|
|
1184
|
-
let rHi = (own.hi & roleBB.hi) >>> 0;
|
|
1185
|
-
while (rLo !== 0) {
|
|
1186
|
-
const lsb = (rLo & -rLo) >>> 0;
|
|
1187
|
-
const from = Math.clz32(lsb) ^ 31;
|
|
1188
|
-
rLo = (rLo ^ lsb) >>> 0;
|
|
1189
|
-
const d = destsFast(pos, from, piece, ctx);
|
|
1190
|
-
let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
|
|
1191
|
-
while (dLo !== 0) {
|
|
1192
|
-
const lsbD = (dLo & -dLo) >>> 0;
|
|
1193
|
-
const to = Math.clz32(lsbD) ^ 31;
|
|
1194
|
-
dLo = (dLo ^ lsbD) >>> 0;
|
|
1195
|
-
out[count++] = (from | (to << 6)) >>> 0;
|
|
1196
|
-
}
|
|
1197
|
-
while (dHi !== 0) {
|
|
1198
|
-
const lsbD = (dHi & -dHi) >>> 0;
|
|
1199
|
-
const to = 32 + (Math.clz32(lsbD) ^ 31);
|
|
1200
|
-
dHi = (dHi ^ lsbD) >>> 0;
|
|
1201
|
-
out[count++] = (from | (to << 6)) >>> 0;
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
while (rHi !== 0) {
|
|
1205
|
-
const lsb = (rHi & -rHi) >>> 0;
|
|
1206
|
-
const from = 32 + (Math.clz32(lsb) ^ 31);
|
|
1207
|
-
rHi = (rHi ^ lsb) >>> 0;
|
|
1208
|
-
const d = destsFast(pos, from, piece, ctx);
|
|
1209
|
-
let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
|
|
1210
|
-
while (dLo !== 0) {
|
|
1211
|
-
const lsbD = (dLo & -dLo) >>> 0;
|
|
1212
|
-
const to = Math.clz32(lsbD) ^ 31;
|
|
1213
|
-
dLo = (dLo ^ lsbD) >>> 0;
|
|
1214
|
-
out[count++] = (from | (to << 6)) >>> 0;
|
|
1215
|
-
}
|
|
1216
|
-
while (dHi !== 0) {
|
|
1217
|
-
const lsbD = (dHi & -dHi) >>> 0;
|
|
1218
|
-
const to = 32 + (Math.clz32(lsbD) ^ 31);
|
|
1219
|
-
dHi = (dHi ^ lsbD) >>> 0;
|
|
1220
|
-
out[count++] = (from | (to << 6)) >>> 0;
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
};
|
|
1224
|
-
emitRole(pos.board.knight, isWhite ? P_W_N : P_B_N);
|
|
1225
|
-
emitRole(pos.board.bishop, isWhite ? P_W_B : P_B_B);
|
|
1226
|
-
emitRole(pos.board.rook, isWhite ? P_W_R : P_B_R);
|
|
1227
|
-
emitRole(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
|
|
1228
|
-
return count;
|
|
1229
|
-
}
|
|
1230
|
-
export function forEachLegalMove(pos, fn) {
|
|
1231
|
-
const ctx = analyzeCheckContext(pos);
|
|
1232
|
-
const us = pos.turn;
|
|
1233
|
-
const isWhite = us === Color.White;
|
|
1234
|
-
const own = isWhite ? pos.board.white : pos.board.black;
|
|
1235
|
-
// 1. King
|
|
1236
|
-
const ksq = ctx.ksq;
|
|
1237
|
-
if (ksq >= 0) {
|
|
1238
|
-
const kingPiece = isWhite ? P_W_K : P_B_K;
|
|
1239
|
-
const kd = destsFast(pos, ksq, kingPiece, ctx);
|
|
1240
|
-
let dLo = kd.lo >>> 0, dHi = kd.hi >>> 0;
|
|
1241
|
-
while (dLo !== 0) {
|
|
1242
|
-
const lsb = (dLo & -dLo) >>> 0;
|
|
1243
|
-
const to = Math.clz32(lsb) ^ 31;
|
|
1244
|
-
dLo = (dLo ^ lsb) >>> 0;
|
|
1245
|
-
fn(ksq, to, PROMO_NONE);
|
|
1246
|
-
}
|
|
1247
|
-
while (dHi !== 0) {
|
|
1248
|
-
const lsb = (dHi & -dHi) >>> 0;
|
|
1249
|
-
const to = 32 + (Math.clz32(lsb) ^ 31);
|
|
1250
|
-
dHi = (dHi ^ lsb) >>> 0;
|
|
1251
|
-
fn(ksq, to, PROMO_NONE);
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
if (ctx.doubleCheck)
|
|
1255
|
-
return;
|
|
1256
|
-
// 2. Pawns
|
|
1257
|
-
const pawnPiece = isWhite ? P_W_P : P_B_P;
|
|
1258
|
-
let pLo = (own.lo & pos.board.pawn.lo) >>> 0;
|
|
1259
|
-
let pHi = (own.hi & pos.board.pawn.hi) >>> 0;
|
|
1260
|
-
const promoRank = isWhite ? 7 : 0;
|
|
1261
|
-
const visitPawnDests = (from) => {
|
|
1262
|
-
const legal = destsFast(pos, from, pawnPiece, ctx);
|
|
1263
|
-
let dLo = legal.lo >>> 0, dHi = legal.hi >>> 0;
|
|
1264
|
-
while (dLo !== 0) {
|
|
1265
|
-
const lsb = (dLo & -dLo) >>> 0;
|
|
1266
|
-
const to = Math.clz32(lsb) ^ 31;
|
|
1267
|
-
dLo = (dLo ^ lsb) >>> 0;
|
|
1268
|
-
if ((to >> 3) === promoRank) {
|
|
1269
|
-
fn(from, to, PROMO_QUEEN);
|
|
1270
|
-
fn(from, to, PROMO_ROOK);
|
|
1271
|
-
fn(from, to, PROMO_BISHOP);
|
|
1272
|
-
fn(from, to, PROMO_KNIGHT);
|
|
1273
|
-
}
|
|
1274
|
-
else {
|
|
1275
|
-
fn(from, to, PROMO_NONE);
|
|
1276
|
-
}
|
|
1277
|
-
}
|
|
1278
|
-
while (dHi !== 0) {
|
|
1279
|
-
const lsb = (dHi & -dHi) >>> 0;
|
|
1280
|
-
const to = 32 + (Math.clz32(lsb) ^ 31);
|
|
1281
|
-
dHi = (dHi ^ lsb) >>> 0;
|
|
1282
|
-
if ((to >> 3) === promoRank) {
|
|
1283
|
-
fn(from, to, PROMO_QUEEN);
|
|
1284
|
-
fn(from, to, PROMO_ROOK);
|
|
1285
|
-
fn(from, to, PROMO_BISHOP);
|
|
1286
|
-
fn(from, to, PROMO_KNIGHT);
|
|
1287
|
-
}
|
|
1288
|
-
else {
|
|
1289
|
-
fn(from, to, PROMO_NONE);
|
|
1290
|
-
}
|
|
1291
|
-
}
|
|
1292
|
-
};
|
|
1293
|
-
while (pLo !== 0) {
|
|
1294
|
-
const lsb = (pLo & -pLo) >>> 0;
|
|
1295
|
-
const from = Math.clz32(lsb) ^ 31;
|
|
1296
|
-
pLo = (pLo ^ lsb) >>> 0;
|
|
1297
|
-
visitPawnDests(from);
|
|
1298
|
-
}
|
|
1299
|
-
while (pHi !== 0) {
|
|
1300
|
-
const lsb = (pHi & -pHi) >>> 0;
|
|
1301
|
-
const from = 32 + (Math.clz32(lsb) ^ 31);
|
|
1302
|
-
pHi = (pHi ^ lsb) >>> 0;
|
|
1303
|
-
visitPawnDests(from);
|
|
1304
|
-
}
|
|
1305
|
-
// 3. Knights, Bishops, Rooks, Queens
|
|
1306
|
-
const visitRole = (roleBB, piece) => {
|
|
1307
|
-
let rLo = (own.lo & roleBB.lo) >>> 0;
|
|
1308
|
-
let rHi = (own.hi & roleBB.hi) >>> 0;
|
|
1309
|
-
while (rLo !== 0) {
|
|
1310
|
-
const lsb = (rLo & -rLo) >>> 0;
|
|
1311
|
-
const from = Math.clz32(lsb) ^ 31;
|
|
1312
|
-
rLo = (rLo ^ lsb) >>> 0;
|
|
1313
|
-
const d = destsFast(pos, from, piece, ctx);
|
|
1314
|
-
let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
|
|
1315
|
-
while (dLo !== 0) {
|
|
1316
|
-
const lsbD = (dLo & -dLo) >>> 0;
|
|
1317
|
-
const to = Math.clz32(lsbD) ^ 31;
|
|
1318
|
-
dLo = (dLo ^ lsbD) >>> 0;
|
|
1319
|
-
fn(from, to, PROMO_NONE);
|
|
1320
|
-
}
|
|
1321
|
-
while (dHi !== 0) {
|
|
1322
|
-
const lsbD = (dHi & -dHi) >>> 0;
|
|
1323
|
-
const to = 32 + (Math.clz32(lsbD) ^ 31);
|
|
1324
|
-
dHi = (dHi ^ lsbD) >>> 0;
|
|
1325
|
-
fn(from, to, PROMO_NONE);
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
while (rHi !== 0) {
|
|
1329
|
-
const lsb = (rHi & -rHi) >>> 0;
|
|
1330
|
-
const from = 32 + (Math.clz32(lsb) ^ 31);
|
|
1331
|
-
rHi = (rHi ^ lsb) >>> 0;
|
|
1332
|
-
const d = destsFast(pos, from, piece, ctx);
|
|
1333
|
-
let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
|
|
1334
|
-
while (dLo !== 0) {
|
|
1335
|
-
const lsbD = (dLo & -dLo) >>> 0;
|
|
1336
|
-
const to = Math.clz32(lsbD) ^ 31;
|
|
1337
|
-
dLo = (dLo ^ lsbD) >>> 0;
|
|
1338
|
-
fn(from, to, PROMO_NONE);
|
|
1339
|
-
}
|
|
1340
|
-
while (dHi !== 0) {
|
|
1341
|
-
const lsbD = (dHi & -dHi) >>> 0;
|
|
1342
|
-
const to = 32 + (Math.clz32(lsbD) ^ 31);
|
|
1343
|
-
dHi = (dHi ^ lsbD) >>> 0;
|
|
1344
|
-
fn(from, to, PROMO_NONE);
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
};
|
|
1348
|
-
visitRole(pos.board.knight, isWhite ? P_W_N : P_B_N);
|
|
1349
|
-
visitRole(pos.board.bishop, isWhite ? P_W_B : P_B_B);
|
|
1350
|
-
visitRole(pos.board.rook, isWhite ? P_W_R : P_B_R);
|
|
1351
|
-
visitRole(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
|
|
1352
|
-
}
|
|
1353
|
-
// Promotion pieces in generation order (hoisted module constant — the old
|
|
1354
|
-
// per-call array literal allocated on every promotion move in the hot loop).
|
|
1355
|
-
const PROMO_ROLES = [Role.Queen, Role.Rook, Role.Bishop, Role.Knight];
|
|
1356
|
-
function genLegalMoves(pos) {
|
|
1357
|
-
const moves = [];
|
|
1358
|
-
const ctx = analyzeCheckContext(pos);
|
|
1359
|
-
const us = pos.turn;
|
|
1360
|
-
const isWhite = us === Color.White;
|
|
1361
|
-
const own = isWhite ? pos.board.white : pos.board.black;
|
|
1362
|
-
const plans = ctx.castlingPlans;
|
|
1363
|
-
// 1. King
|
|
1364
|
-
const ksq = ctx.ksq;
|
|
1365
|
-
if (ksq >= 0) {
|
|
1366
|
-
const kingPiece = isWhite ? P_W_K : P_B_K;
|
|
1367
|
-
sq.forEachSquare(destsFast(pos, ksq, kingPiece, ctx), (to) => {
|
|
1368
|
-
const isCastling = plans.length > 0 && planForDest(plans, to) !== null;
|
|
1369
|
-
moves.push({ from: ksq, to, promotion: null, isEnPassant: false, isCastling, isPromotion: false });
|
|
1370
|
-
});
|
|
1371
|
-
}
|
|
1372
|
-
if (ctx.doubleCheck)
|
|
1373
|
-
return moves;
|
|
1374
|
-
// 2. Pawns
|
|
1375
|
-
const pawnPiece = isWhite ? P_W_P : P_B_P;
|
|
1376
|
-
sq.forEachSquare(sq.and(own, pos.board.pawn), (from) => {
|
|
1377
|
-
const legal = destsFast(pos, from, pawnPiece, ctx);
|
|
1378
|
-
sq.forEachSquare(legal, (to) => {
|
|
1379
|
-
const destRank = to >> 3;
|
|
1380
|
-
if ((isWhite && destRank === 7) || (!isWhite && destRank === 0)) {
|
|
1381
|
-
for (const promo of PROMO_ROLES) {
|
|
1382
|
-
moves.push({ from, to, promotion: promo, isPromotion: true, isEnPassant: false, isCastling: false });
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
else {
|
|
1386
|
-
let isEnPassant = false;
|
|
1387
|
-
if (pos.epSquare !== null && to === pos.epSquare) {
|
|
1388
|
-
const fileDiff = Math.abs((to & 7) - (from & 7));
|
|
1389
|
-
const dir = isWhite ? 1 : -1;
|
|
1390
|
-
if (fileDiff === 1 && destRank - (from >> 3) === dir)
|
|
1391
|
-
isEnPassant = true;
|
|
1392
|
-
}
|
|
1393
|
-
moves.push({ from, to, promotion: null, isEnPassant, isCastling: false, isPromotion: false });
|
|
1394
|
-
}
|
|
1395
|
-
});
|
|
1396
|
-
});
|
|
1397
|
-
// 3. Knights, Bishops, Rooks, Queens
|
|
1398
|
-
const addPieceMoves = (roleBB, piece) => {
|
|
1399
|
-
sq.forEachSquare(sq.and(own, roleBB), (from) => {
|
|
1400
|
-
sq.forEachSquare(destsFast(pos, from, piece, ctx), (to) => {
|
|
1401
|
-
moves.push({ from, to, promotion: null, isEnPassant: false, isCastling: false, isPromotion: false });
|
|
1402
|
-
});
|
|
1403
|
-
});
|
|
1404
|
-
};
|
|
1405
|
-
addPieceMoves(pos.board.knight, isWhite ? P_W_N : P_B_N);
|
|
1406
|
-
addPieceMoves(pos.board.bishop, isWhite ? P_W_B : P_B_B);
|
|
1407
|
-
addPieceMoves(pos.board.rook, isWhite ? P_W_R : P_B_R);
|
|
1408
|
-
addPieceMoves(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
|
|
1409
|
-
return moves;
|
|
1410
|
-
}
|
|
1411
|
-
// Promotion pieces in generation order (hoisted module constant — the old
|
|
1412
|
-
// per-call array literal allocated on every promotion move in the hot loop).
|
|
1413
|
-
export const INITIAL_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
|
1414
|
-
// Deterministic unique 2-char node id (same alphabet/contract the
|
|
1415
|
-
// workstation's `createUniqueMoveNodeId` relies on — mirrors chesstree.ts).
|
|
1416
|
-
const TREE_ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
1417
|
-
function nextTreeNodeId(siblings) {
|
|
1418
|
-
const used = new Set(siblings.map((x) => x.id));
|
|
1419
|
-
for (const first of TREE_ID_ALPHABET) {
|
|
1420
|
-
for (const second of TREE_ID_ALPHABET) {
|
|
1421
|
-
const id = first + second;
|
|
1422
|
-
if (!used.has(id))
|
|
1423
|
-
return id;
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
return "zz";
|
|
1427
|
-
}
|
|
1428
|
-
const ROLE_CHARS = {
|
|
1429
|
-
0: "p", 1: "n", 2: "b", 3: "r", 4: "q", 5: "k",
|
|
1430
|
-
};
|
|
1431
|
-
const PROMO_ORDER = [4, 3, 2, 1]; // Role.Queen, Role.Rook, Role.Bishop, Role.Knight
|
|
1432
|
-
function colorName(turn) {
|
|
1433
|
-
return turn === Color.White ? "w" : "b";
|
|
1434
|
-
}
|
|
1435
|
-
export { Board };
|
|
1436
|
-
/** Expands pawn back-rank destinations into the four promotions. */
|
|
1437
|
-
function buildMoves(pos, role, from, to) {
|
|
1438
|
-
const toRank = to >> 3;
|
|
1439
|
-
if (role === 0 && (toRank === 7 || toRank === 0)) {
|
|
1440
|
-
return PROMO_ORDER.map((promotion) => ({
|
|
1441
|
-
from,
|
|
1442
|
-
to,
|
|
1443
|
-
promotion: promotion,
|
|
1444
|
-
isPromotion: true,
|
|
1445
|
-
isEnPassant: false,
|
|
1446
|
-
isCastling: false,
|
|
1447
|
-
}));
|
|
1448
|
-
}
|
|
1449
|
-
const isEp = role === 0 &&
|
|
1450
|
-
pos.epSquare !== null &&
|
|
1451
|
-
to === pos.epSquare &&
|
|
1452
|
-
(to & 7) !== (from & 7);
|
|
1453
|
-
const isCastling = role === 5 ? detectCastling(pos, from, to) !== null : false;
|
|
1454
|
-
return [{ from, to, promotion: null, isPromotion: false, isEnPassant: isEp, isCastling }];
|
|
1455
|
-
}
|
|
1456
|
-
function parseFullmove(fen) {
|
|
1457
|
-
const fields = fen.split(/\s+/);
|
|
1458
|
-
const n = Number(fields[5]);
|
|
1459
|
-
return Number.isFinite(n) && n > 0 ? n : 1;
|
|
1460
|
-
}
|
|
1461
|
-
/** True when a LEGAL en passant capture onto `pos.epSquare` exists. */
|
|
1462
|
-
function hasLegalEpCapture(pos) {
|
|
1463
|
-
const ep = pos.epSquare;
|
|
1464
|
-
if (ep === null || ep === undefined)
|
|
1465
|
-
return false;
|
|
1466
|
-
for (const [from, set] of allDests(pos)) {
|
|
1467
|
-
if ((from & 7) === (ep & 7))
|
|
1468
|
-
continue; // ep capture is diagonal
|
|
1469
|
-
const p = pieceAt(pos.board, from);
|
|
1470
|
-
if (!p || p.role !== 0)
|
|
1471
|
-
continue;
|
|
1472
|
-
if (sq.has(set, ep))
|
|
1473
|
-
return true;
|
|
1474
|
-
}
|
|
1475
|
-
return false;
|
|
1476
|
-
}
|
|
1477
|
-
/**
|
|
1478
|
-
* Unified root `Chess` (design D1): the chess.js-ergonomic mutable façade
|
|
1479
|
-
* over the immutable engine core, extended with the high-performance
|
|
1480
|
-
* bitboard surface, zero-alloc Zobrist hashing and 16-bit packed moves2, and
|
|
1481
|
-
* native tree navigation. Lives at the ROOT entrypoint so the tree-shakeable
|
|
1482
|
-
* `gigachess/core` graph stays free of FEN/PGN/tree facade code.
|
|
1483
|
-
*/
|
|
1484
|
-
export class Chess {
|
|
1485
|
-
constructor(fen = INITIAL_FEN) {
|
|
1486
|
-
_Chess_instances.add(this);
|
|
1487
|
-
_Chess_board.set(this, void 0);
|
|
1488
|
-
_Chess_startFen.set(this, void 0);
|
|
1489
|
-
_Chess_history.set(this, []);
|
|
1490
|
-
__classPrivateFieldSet(this, _Chess_board, new Board(fen), "f");
|
|
1491
|
-
__classPrivateFieldSet(this, _Chess_startFen, __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, __classPrivateFieldGet(this, _Chess_board, "f").pos), "f");
|
|
1492
|
-
}
|
|
1493
|
-
/** Replaces the current position (throws on an invalid FEN). */
|
|
1494
|
-
load(fen) {
|
|
1495
|
-
const r = parseFen(fen);
|
|
1496
|
-
if (!r.ok)
|
|
1497
|
-
throw new Error(`Invalid FEN: ${fen}`);
|
|
1498
|
-
__classPrivateFieldSet(this, _Chess_board, new Board(r.value), "f");
|
|
1499
|
-
__classPrivateFieldSet(this, _Chess_startFen, __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, r.value), "f");
|
|
1500
|
-
__classPrivateFieldSet(this, _Chess_history, [], "f");
|
|
1501
|
-
}
|
|
1502
|
-
/** Resets to the initial position and clears history. */
|
|
1503
|
-
reset() {
|
|
1504
|
-
this.load(INITIAL_FEN);
|
|
1505
|
-
}
|
|
1506
|
-
/** Current FEN (byte-identical to the engine's makeFen modulo ep filtering). */
|
|
1507
|
-
fen() {
|
|
1508
|
-
return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, __classPrivateFieldGet(this, _Chess_board, "f").pos);
|
|
1509
|
-
}
|
|
1510
|
-
/** Side to move: "w" | "b". */
|
|
1511
|
-
turn() {
|
|
1512
|
-
return colorName(__classPrivateFieldGet(this, _Chess_board, "f").turn);
|
|
1513
|
-
}
|
|
1514
|
-
/** Current fullmove number (starts at 1). */
|
|
1515
|
-
moveNumber() {
|
|
1516
|
-
return __classPrivateFieldGet(this, _Chess_board, "f").fullmoves;
|
|
1517
|
-
}
|
|
1518
|
-
/**
|
|
1519
|
-
* Plays a move given as SAN (tolerant: `+`/`#` suffixes, `x` on quiet moves,
|
|
1520
|
-
* `0-0`/`O-O`), as UCI (`e2e4`, `e7e8q`), or as a {from,to,promotion?}
|
|
1521
|
-
* object. Returns the verbose move, or null when the move is illegal.
|
|
1522
|
-
*/
|
|
1523
|
-
move(input) {
|
|
1524
|
-
const pos = __classPrivateFieldGet(this, _Chess_board, "f").pos;
|
|
1525
|
-
let mv = null;
|
|
1526
|
-
let moveWord = null;
|
|
1527
|
-
if (typeof input === "string") {
|
|
1528
|
-
const sanRes = parseSan(input, pos);
|
|
1529
|
-
if (sanRes.ok) {
|
|
1530
|
-
mv = sanRes.value;
|
|
1531
|
-
moveWord = packOf(mv);
|
|
1532
|
-
}
|
|
1533
|
-
else {
|
|
1534
|
-
const uciRes = parseUci(input);
|
|
1535
|
-
if (uciRes.ok && isLegal(pos, uciRes.value)) {
|
|
1536
|
-
mv = uciRes.value;
|
|
1537
|
-
moveWord = packOf(mv);
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
else {
|
|
1542
|
-
const from = parseSquare(input.from);
|
|
1543
|
-
const to = parseSquare(input.to);
|
|
1544
|
-
if (from !== undefined && to !== undefined) {
|
|
1545
|
-
const piece = pieceAt(__classPrivateFieldGet(this, _Chess_board, "f").board, from);
|
|
1546
|
-
const promotion = input.promotion
|
|
1547
|
-
? { q: 4, r: 3, b: 2, n: 1 }[input.promotion.toLowerCase()]
|
|
1548
|
-
: undefined;
|
|
1549
|
-
for (const cand of buildMoves(pos, piece ? piece.role : -1, from, to)) {
|
|
1550
|
-
if (cand.promotion !== null && cand.promotion !== undefined && promotion !== undefined && cand.promotion !== promotion)
|
|
1551
|
-
continue;
|
|
1552
|
-
if (isLegal(pos, cand)) {
|
|
1553
|
-
mv = cand;
|
|
1554
|
-
moveWord = packOf(mv);
|
|
1555
|
-
break;
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
}
|
|
1560
|
-
if (!mv || moveWord === null)
|
|
1561
|
-
return null;
|
|
1562
|
-
const before = __classPrivateFieldGet(this, _Chess_board, "f").toPosition();
|
|
1563
|
-
const san = makeSan(mv, before);
|
|
1564
|
-
const boardUndo = __classPrivateFieldGet(this, _Chess_board, "f").makeMove(moveWord);
|
|
1565
|
-
const after = __classPrivateFieldGet(this, _Chess_board, "f").toPosition();
|
|
1566
|
-
__classPrivateFieldGet(this, _Chess_history, "f").push({
|
|
1567
|
-
before,
|
|
1568
|
-
after,
|
|
1569
|
-
move: mv,
|
|
1570
|
-
san,
|
|
1571
|
-
boardUndo,
|
|
1572
|
-
prev_checkers: before.checkers,
|
|
1573
|
-
prev_zobrist: before.zobristLo !== undefined && before.zobristHi !== undefined ? { lo: before.zobristLo, hi: before.zobristHi } : undefined,
|
|
1574
|
-
});
|
|
1575
|
-
return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, before, mv, after, san);
|
|
1576
|
-
}
|
|
1577
|
-
moves(options) {
|
|
1578
|
-
const pos = __classPrivateFieldGet(this, _Chess_board, "f").pos;
|
|
1579
|
-
const out = [];
|
|
1580
|
-
const emit = (from, set) => {
|
|
1581
|
-
const piece = pieceAt(__classPrivateFieldGet(this, _Chess_board, "f").board, from);
|
|
1582
|
-
if (!piece)
|
|
1583
|
-
return;
|
|
1584
|
-
sq.forEachSquare(set, (to) => {
|
|
1585
|
-
for (const mv of buildMoves(pos, piece.role, from, to)) {
|
|
1586
|
-
const san = makeSan(mv, pos);
|
|
1587
|
-
if (options?.verbose)
|
|
1588
|
-
out.push(__classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, pos, mv, makeMove(pos, mv), san));
|
|
1589
|
-
else
|
|
1590
|
-
out.push(san);
|
|
1591
|
-
}
|
|
1592
|
-
});
|
|
1593
|
-
};
|
|
1594
|
-
if (options?.square !== undefined) {
|
|
1595
|
-
const sqIdx = parseSquare(options.square);
|
|
1596
|
-
if (sqIdx === undefined)
|
|
1597
|
-
return [];
|
|
1598
|
-
emit(sqIdx, dests(pos, sqIdx));
|
|
1599
|
-
}
|
|
1600
|
-
else {
|
|
1601
|
-
for (const [from, set] of allDests(pos))
|
|
1602
|
-
emit(from, set);
|
|
1603
|
-
}
|
|
1604
|
-
return out;
|
|
1605
|
-
}
|
|
1606
|
-
history(options) {
|
|
1607
|
-
if (options?.verbose) {
|
|
1608
|
-
return __classPrivateFieldGet(this, _Chess_history, "f").map((h) => __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, h.before, h.move, h.after, h.san));
|
|
1609
|
-
}
|
|
1610
|
-
return __classPrivateFieldGet(this, _Chess_history, "f").map((h) => h.san);
|
|
1611
|
-
}
|
|
1612
|
-
/** Reverts the last move; returns it in verbose shape, or null if none. */
|
|
1613
|
-
undo() {
|
|
1614
|
-
const last = __classPrivateFieldGet(this, _Chess_history, "f").pop();
|
|
1615
|
-
if (!last)
|
|
1616
|
-
return null;
|
|
1617
|
-
if (last.boardUndo) {
|
|
1618
|
-
__classPrivateFieldGet(this, _Chess_board, "f").unmakeMove(last.boardUndo);
|
|
1619
|
-
}
|
|
1620
|
-
else {
|
|
1621
|
-
__classPrivateFieldSet(this, _Chess_board, new Board(last.before), "f");
|
|
1622
|
-
}
|
|
1623
|
-
return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, last.before, last.move, last.after, last.san);
|
|
1624
|
-
}
|
|
1625
|
-
isCheck() { return __classPrivateFieldGet(this, _Chess_board, "f").inCheck(); }
|
|
1626
|
-
inCheck() { return __classPrivateFieldGet(this, _Chess_board, "f").inCheck(); }
|
|
1627
|
-
isCheckmate() { return isCheckmate(__classPrivateFieldGet(this, _Chess_board, "f").pos); }
|
|
1628
|
-
isStalemate() { return isStalemate(__classPrivateFieldGet(this, _Chess_board, "f").pos); }
|
|
1629
|
-
/** Draw by insufficient material, the fifty-move rule, or threefold repetition. */
|
|
1630
|
-
isDraw() {
|
|
1631
|
-
if (isInsufficientMaterial(__classPrivateFieldGet(this, _Chess_board, "f").pos))
|
|
1632
|
-
return true;
|
|
1633
|
-
if (isFiftyMoveDraw(__classPrivateFieldGet(this, _Chess_board, "f").pos))
|
|
1634
|
-
return true;
|
|
1635
|
-
if (isThreefoldRepetition(__classPrivateFieldGet(this, _Chess_instances, "m", _Chess_positions).call(this)))
|
|
1636
|
-
return true;
|
|
1637
|
-
return false;
|
|
1638
|
-
}
|
|
1639
|
-
/** Draw by the fifty-move rule. */
|
|
1640
|
-
isDrawByFiftyMoves() { return isFiftyMoveDraw(__classPrivateFieldGet(this, _Chess_board, "f").pos); }
|
|
1641
|
-
/** Draw by insufficient material. */
|
|
1642
|
-
isInsufficientMaterial() { return isInsufficientMaterial(__classPrivateFieldGet(this, _Chess_board, "f").pos); }
|
|
1643
|
-
/** Draw by threefold repetition over the game's position history. */
|
|
1644
|
-
isThreefoldRepetition() { return isThreefoldRepetition(__classPrivateFieldGet(this, _Chess_instances, "m", _Chess_positions).call(this)); }
|
|
1645
|
-
/** Game over: checkmate, stalemate, or draw. */
|
|
1646
|
-
isGameOver() { return this.isCheckmate() || this.isStalemate() || this.isDraw(); }
|
|
1647
|
-
/** Piece on a square ("e2"), or undefined. */
|
|
1648
|
-
get(square) {
|
|
1649
|
-
const sqIdx = parseSquare(square);
|
|
1650
|
-
if (sqIdx === undefined)
|
|
1651
|
-
return undefined;
|
|
1652
|
-
const p = pieceAt(__classPrivateFieldGet(this, _Chess_board, "f").board, sqIdx);
|
|
1653
|
-
if (!p)
|
|
1654
|
-
return undefined;
|
|
1655
|
-
return { type: ROLE_CHARS[p.role], color: colorName(p.color) };
|
|
1656
|
-
}
|
|
1657
|
-
/** 8x8 board, rank 8 first; null on empty squares. */
|
|
1658
|
-
board() {
|
|
1659
|
-
const rows = [];
|
|
1660
|
-
for (let rank = 7; rank >= 0; rank--) {
|
|
1661
|
-
const row = [];
|
|
1662
|
-
for (let file = 0; file < 8; file++) {
|
|
1663
|
-
const sqIdx = rank * 8 + file;
|
|
1664
|
-
const p = pieceAt(__classPrivateFieldGet(this, _Chess_board, "f").board, sqIdx);
|
|
1665
|
-
row.push(p ? { square: squareName(sqIdx), type: ROLE_CHARS[p.role], color: colorName(p.color) } : null);
|
|
1666
|
-
}
|
|
1667
|
-
rows.push(row);
|
|
1668
|
-
}
|
|
1669
|
-
return rows;
|
|
1670
|
-
}
|
|
1671
|
-
/** "light" | "dark" square color ("a1" is light, like the consumer baseline). */
|
|
1672
|
-
squareColor(square) {
|
|
1673
|
-
const sqIdx = parseSquare(square);
|
|
1674
|
-
if (sqIdx === undefined)
|
|
1675
|
-
return undefined;
|
|
1676
|
-
return (((sqIdx & 7) + (sqIdx >> 3)) & 1) === 0 ? "light" : "dark";
|
|
1677
|
-
}
|
|
1678
|
-
/** PGN: Seven Tag Roster defaults, FEN/SetUp for non-default starts, numbered movetext. */
|
|
1679
|
-
pgn() {
|
|
1680
|
-
const headers = new Map([
|
|
1681
|
-
["Event", "?"],
|
|
1682
|
-
["Site", "?"],
|
|
1683
|
-
["Date", "????.??.??"],
|
|
1684
|
-
["Round", "?"],
|
|
1685
|
-
["White", "?"],
|
|
1686
|
-
["Black", "?"],
|
|
1687
|
-
["Result", "*"],
|
|
1688
|
-
]);
|
|
1689
|
-
if (__classPrivateFieldGet(this, _Chess_startFen, "f") !== INITIAL_FEN) {
|
|
1690
|
-
headers.set("SetUp", "1");
|
|
1691
|
-
headers.set("FEN", __classPrivateFieldGet(this, _Chess_startFen, "f"));
|
|
1692
|
-
}
|
|
1693
|
-
let out = "";
|
|
1694
|
-
for (const [k, v] of headers)
|
|
1695
|
-
out += `[${k} "${v}"]\n`;
|
|
1696
|
-
out += "\n";
|
|
1697
|
-
out += __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_movetext).call(this);
|
|
1698
|
-
return out;
|
|
1699
|
-
}
|
|
1700
|
-
// ---- unified high-performance surface (design D1) ----
|
|
1701
|
-
/** Legal destinations for one square ("e2" or index). */
|
|
1702
|
-
dests(square) {
|
|
1703
|
-
const sqIdx = typeof square === "number" ? square : parseSquare(square);
|
|
1704
|
-
if (sqIdx === undefined)
|
|
1705
|
-
return { lo: 0, hi: 0 };
|
|
1706
|
-
return dests(__classPrivateFieldGet(this, _Chess_board, "f").pos, sqIdx);
|
|
1707
|
-
}
|
|
1708
|
-
/** Legal destinations for every piece of the side to move. */
|
|
1709
|
-
allDests() { return allDests(__classPrivateFieldGet(this, _Chess_board, "f").pos); }
|
|
1710
|
-
/** True when `move` is legal in the current position. */
|
|
1711
|
-
isLegal(move) { return isLegal(__classPrivateFieldGet(this, _Chess_board, "f").pos, move); }
|
|
1712
|
-
/** Genuine recursive perft node count (no shortcuts). */
|
|
1713
|
-
perft(depth) { return __classPrivateFieldGet(this, _Chess_board, "f").perft(depth); }
|
|
1714
|
-
/** Applies an engine move in place (immutable core stays pure underneath). */
|
|
1715
|
-
play(move) {
|
|
1716
|
-
const before = __classPrivateFieldGet(this, _Chess_board, "f").toPosition();
|
|
1717
|
-
const san = makeSan(move, before);
|
|
1718
|
-
const moveWord = packOf(move);
|
|
1719
|
-
const boardUndo = __classPrivateFieldGet(this, _Chess_board, "f").makeMove(moveWord);
|
|
1720
|
-
const after = __classPrivateFieldGet(this, _Chess_board, "f").toPosition();
|
|
1721
|
-
__classPrivateFieldGet(this, _Chess_history, "f").push({
|
|
1722
|
-
before,
|
|
1723
|
-
after,
|
|
1724
|
-
move,
|
|
1725
|
-
san,
|
|
1726
|
-
boardUndo,
|
|
1727
|
-
prev_checkers: before.checkers,
|
|
1728
|
-
prev_zobrist: before.zobristLo !== undefined && before.zobristHi !== undefined ? { lo: before.zobristLo, hi: before.zobristHi } : undefined,
|
|
1729
|
-
});
|
|
1730
|
-
return this;
|
|
1731
|
-
}
|
|
1732
|
-
/** Current 64-bit Zobrist key (zero-BigInt {lo, hi} halves). */
|
|
1733
|
-
zobrist() {
|
|
1734
|
-
return __classPrivateFieldGet(this, _Chess_board, "f").zobrist();
|
|
1735
|
-
}
|
|
1736
|
-
/** Current Zobrist key as 16 zero-padded hex digits (hi first). */
|
|
1737
|
-
zobristHex() { return __classPrivateFieldGet(this, _Chess_board, "f").zobristHex(); }
|
|
1738
|
-
/** Packs the game's move history into a 16-bit moves2 stream. */
|
|
1739
|
-
toMoves2() {
|
|
1740
|
-
const words = new Uint16Array(__classPrivateFieldGet(this, _Chess_history, "f").length);
|
|
1741
|
-
for (let i = 0; i < __classPrivateFieldGet(this, _Chess_history, "f").length; i++)
|
|
1742
|
-
words[i] = packOf(__classPrivateFieldGet(this, _Chess_history, "f")[i].move);
|
|
1743
|
-
return words;
|
|
1744
|
-
}
|
|
1745
|
-
/** Replays a moves2 stream (Uint16Array or little-endian Uint8Array) in place. */
|
|
1746
|
-
loadMoves2(buffer, startFen = INITIAL_FEN) {
|
|
1747
|
-
this.load(startFen);
|
|
1748
|
-
__classPrivateFieldSet(this, _Chess_startFen, startFen, "f");
|
|
1749
|
-
for (const mv of packedToMoves(buffer)) {
|
|
1750
|
-
if (!isLegal(__classPrivateFieldGet(this, _Chess_board, "f").pos, mv))
|
|
1751
|
-
throw new Error(`moves2 replay: illegal move ${mv.from}->${mv.to}`);
|
|
1752
|
-
this.play(mv);
|
|
1753
|
-
}
|
|
1754
|
-
}
|
|
1755
|
-
/** Builds a Chess game from a moves2 stream (startpos, or a custom start FEN). */
|
|
1756
|
-
static fromMoves2(buffer, startFen = INITIAL_FEN) {
|
|
1757
|
-
const game = new Chess(startFen);
|
|
1758
|
-
game.loadMoves2(buffer, startFen);
|
|
1759
|
-
return game;
|
|
1760
|
-
}
|
|
1761
|
-
/** Wraps an arbitrary engine Setup. */
|
|
1762
|
-
static fromSetup(setup) {
|
|
1763
|
-
return new Chess(setup);
|
|
1764
|
-
}
|
|
1765
|
-
/** Fresh game from the standard initial position. */
|
|
1766
|
-
static default() {
|
|
1767
|
-
return new Chess(INITIAL_FEN);
|
|
1768
|
-
}
|
|
1769
|
-
/** FEN the game started from (for tree roots / PGN headers). */
|
|
1770
|
-
get startFen() { return __classPrivateFieldGet(this, _Chess_startFen, "f"); }
|
|
1771
|
-
/** Live engine position (read-only view over the internal state). */
|
|
1772
|
-
get pos() { return __classPrivateFieldGet(this, _Chess_board, "f").pos; }
|
|
1773
|
-
get _pos() { return __classPrivateFieldGet(this, _Chess_board, "f").pos; }
|
|
1774
|
-
get boardInstance() { return __classPrivateFieldGet(this, _Chess_board, "f"); }
|
|
1775
|
-
/** Internal history log (read-only view; used by toTree). */
|
|
1776
|
-
get historyEntries() { return __classPrivateFieldGet(this, _Chess_history, "f"); }
|
|
1777
|
-
/**
|
|
1778
|
-
* Exports the live game as a chesstree wrapper: recursive variation
|
|
1779
|
-
* navigation (`nodeAtPath`, `getNodeList`, `addNode`, `setCommentAt`, …)
|
|
1780
|
-
* and full recursive PGN rendering via `tree.pgn()`.
|
|
1781
|
-
*/
|
|
1782
|
-
toTree() {
|
|
1783
|
-
const root = { id: "", ply: 0, fen: __classPrivateFieldGet(this, _Chess_startFen, "f"), uci: "", children: [] };
|
|
1784
|
-
let ply = 0;
|
|
1785
|
-
let node = root;
|
|
1786
|
-
for (const h of __classPrivateFieldGet(this, _Chess_history, "f")) {
|
|
1787
|
-
const child = {
|
|
1788
|
-
id: nextTreeNodeId(node.children),
|
|
1789
|
-
ply: ++ply,
|
|
1790
|
-
san: h.san,
|
|
1791
|
-
fen: makeFen(h.after),
|
|
1792
|
-
uci: makeUci(h.move),
|
|
1793
|
-
children: [],
|
|
1794
|
-
};
|
|
1795
|
-
node.children.push(child);
|
|
1796
|
-
node = child;
|
|
1797
|
-
}
|
|
1798
|
-
return buildTreeWrapper(root);
|
|
1799
|
-
}
|
|
1800
|
-
/**
|
|
1801
|
-
* Imports a PGN (headers + recursive variations), loads the mainline into
|
|
1802
|
-
* this game, and returns the analysis tree wrapper.
|
|
1803
|
-
*/
|
|
1804
|
-
loadTree(pgn) {
|
|
1805
|
-
const data = pgnImportData(pgn);
|
|
1806
|
-
const root = data.treeParts[0];
|
|
1807
|
-
this.reset();
|
|
1808
|
-
if (root && root.fen && root.fen !== INITIAL_FEN) {
|
|
1809
|
-
const r = parseFen(root.fen);
|
|
1810
|
-
if (r.ok)
|
|
1811
|
-
this.load(root.fen);
|
|
1812
|
-
}
|
|
1813
|
-
let node = root?.children[0];
|
|
1814
|
-
while (node) {
|
|
1815
|
-
if (node.san)
|
|
1816
|
-
this.move(node.san);
|
|
1817
|
-
node = node.children[0];
|
|
1818
|
-
}
|
|
1819
|
-
return buildTreeWrapper(root ?? { id: "", ply: 0, fen: INITIAL_FEN, uci: "", children: [] });
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
_Chess_board = new WeakMap(), _Chess_startFen = new WeakMap(), _Chess_history = new WeakMap(), _Chess_instances = new WeakSet(), _Chess_movetext = function _Chess_movetext() {
|
|
1823
|
-
const sans = __classPrivateFieldGet(this, _Chess_history, "f").map((h) => h.san);
|
|
1824
|
-
let fullmove = parseFullmove(__classPrivateFieldGet(this, _Chess_startFen, "f"));
|
|
1825
|
-
const blackToStart = __classPrivateFieldGet(this, _Chess_startFen, "f").split(/\s+/)[1] === "b";
|
|
1826
|
-
let s = "";
|
|
1827
|
-
let ply = 0;
|
|
1828
|
-
if (blackToStart && sans.length > 0) {
|
|
1829
|
-
s += `${fullmove}... ${sans[0]} `;
|
|
1830
|
-
ply = 1;
|
|
1831
|
-
fullmove++;
|
|
1832
|
-
}
|
|
1833
|
-
while (ply < sans.length) {
|
|
1834
|
-
s += `${fullmove}. ${sans[ply]} `;
|
|
1835
|
-
ply++;
|
|
1836
|
-
if (ply < sans.length) {
|
|
1837
|
-
s += `${sans[ply]} `;
|
|
1838
|
-
ply++;
|
|
1839
|
-
}
|
|
1840
|
-
fullmove++;
|
|
1841
|
-
}
|
|
1842
|
-
s = s.trimEnd();
|
|
1843
|
-
return s + (s ? " " : "") + "*";
|
|
1844
|
-
}, _Chess_positions = function _Chess_positions() {
|
|
1845
|
-
const out = [];
|
|
1846
|
-
if (__classPrivateFieldGet(this, _Chess_history, "f").length > 0)
|
|
1847
|
-
out.push(__classPrivateFieldGet(this, _Chess_history, "f")[0].before);
|
|
1848
|
-
for (const h of __classPrivateFieldGet(this, _Chess_history, "f"))
|
|
1849
|
-
out.push(h.after);
|
|
1850
|
-
return out;
|
|
1851
|
-
}, _Chess_describe = function _Chess_describe(pos, mv, after, san) {
|
|
1852
|
-
// A pass moves no piece: it has no origin, destination or piece, so the
|
|
1853
|
-
// chess.js-shaped record is built from the pass contract instead.
|
|
1854
|
-
if (isNullMove(mv)) {
|
|
1855
|
-
return {
|
|
1856
|
-
color: colorName(pos.turn),
|
|
1857
|
-
from: "",
|
|
1858
|
-
to: "",
|
|
1859
|
-
flags: "",
|
|
1860
|
-
san,
|
|
1861
|
-
lan: makeUci(mv),
|
|
1862
|
-
before: __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, pos),
|
|
1863
|
-
after: __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, after),
|
|
1864
|
-
};
|
|
1865
|
-
}
|
|
1866
|
-
const piece = pieceAt(pos.board, mv.from);
|
|
1867
|
-
if (!piece)
|
|
1868
|
-
throw new Error("corrupt move: missing origin piece");
|
|
1869
|
-
const target = pieceAt(pos.board, mv.to);
|
|
1870
|
-
const isEp = !!mv.isEnPassant ||
|
|
1871
|
-
(piece.role === 0 && pos.epSquare !== null && mv.to === pos.epSquare && (mv.to & 7) !== (mv.from & 7));
|
|
1872
|
-
const isCapture = !!target && target.color !== pos.turn && !isEp;
|
|
1873
|
-
const isDoublePush = piece.role === 0 && Math.abs((mv.to >> 3) - (mv.from >> 3)) === 2;
|
|
1874
|
-
let castlingKingside = null;
|
|
1875
|
-
if (mv.isCastling) {
|
|
1876
|
-
const plan = detectCastling(pos, mv.from, mv.to);
|
|
1877
|
-
castlingKingside = plan ? plan.side === "king" : (mv.to & 7) === 6;
|
|
1878
|
-
}
|
|
1879
|
-
// Baseline flag semantics: castling is exclusively "k"/"q"; otherwise one
|
|
1880
|
-
// base flag — "e" (en passant), "c" (capture), "b" (double pawn push) or
|
|
1881
|
-
// "n" (quiet) — plus "p" appended for promotions ("np"/"cp").
|
|
1882
|
-
const flags = [];
|
|
1883
|
-
if (castlingKingside !== null) {
|
|
1884
|
-
flags.push(castlingKingside ? "k" : "q");
|
|
1885
|
-
}
|
|
1886
|
-
else {
|
|
1887
|
-
if (isEp)
|
|
1888
|
-
flags.push("e");
|
|
1889
|
-
else if (isCapture)
|
|
1890
|
-
flags.push("c");
|
|
1891
|
-
else if (isDoublePush)
|
|
1892
|
-
flags.push("b");
|
|
1893
|
-
else
|
|
1894
|
-
flags.push("n");
|
|
1895
|
-
if (mv.promotion)
|
|
1896
|
-
flags.push("p");
|
|
1897
|
-
}
|
|
1898
|
-
// consumer-baseline parity: castling reports the king's landing square
|
|
1899
|
-
// ("e1g1") for both `to` and `lan`, not the engine's rook-capture form
|
|
1900
|
-
const landingSq = castlingKingside !== null ? (mv.from >> 3) * 8 + (castlingKingside ? 6 : 2) : null;
|
|
1901
|
-
const lan = landingSq !== null ? squareName(mv.from) + squareName(landingSq) : makeUci(mv);
|
|
1902
|
-
const out = {
|
|
1903
|
-
color: colorName(pos.turn),
|
|
1904
|
-
from: squareName(mv.from),
|
|
1905
|
-
to: landingSq !== null ? squareName(landingSq) : squareName(mv.to),
|
|
1906
|
-
piece: ROLE_CHARS[piece.role],
|
|
1907
|
-
flags: flags.join(""),
|
|
1908
|
-
san,
|
|
1909
|
-
lan,
|
|
1910
|
-
before: __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, pos),
|
|
1911
|
-
after: __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_fenOf).call(this, after),
|
|
1912
|
-
};
|
|
1913
|
-
if (isCapture || isEp)
|
|
1914
|
-
out.captured = isEp || !target ? "p" : ROLE_CHARS[target.role];
|
|
1915
|
-
if (mv.promotion)
|
|
1916
|
-
out.promotion = ROLE_CHARS[mv.promotion];
|
|
1917
|
-
return out;
|
|
1918
|
-
}, _Chess_fenOf = function _Chess_fenOf(pos) {
|
|
1919
|
-
const fen = makeFen(pos);
|
|
1920
|
-
const ep = pos.epSquare;
|
|
1921
|
-
if (ep === null || ep === undefined)
|
|
1922
|
-
return fen;
|
|
1923
|
-
const fields = fen.split(" ");
|
|
1924
|
-
if (fields[3] !== squareName(ep))
|
|
1925
|
-
return fen; // engine already suppressed it
|
|
1926
|
-
if (!hasLegalEpCapture(pos)) {
|
|
1927
|
-
fields[3] = "-";
|
|
1928
|
-
}
|
|
1929
|
-
return fields.join(" ");
|
|
1930
|
-
};
|