Commit | Line | Data |
---|---|---|
92342261 BA |
1 | // (Orthodox) Chess rules are defined in ChessRules class. |
2 | // Variants generally inherit from it, and modify some parts. | |
3 | ||
e2732923 | 4 | import { ArrayFun } from "@/utils/array"; |
0c3fe8a6 | 5 | import { randInt, shuffle } from "@/utils/alea"; |
e2732923 | 6 | |
910d631b | 7 | // class "PiPo": Piece + Position |
6808d7a1 | 8 | export const PiPo = class PiPo { |
1c9f093d | 9 | // o: {piece[p], color[c], posX[x], posY[y]} |
6808d7a1 | 10 | constructor(o) { |
1c9f093d BA |
11 | this.p = o.p; |
12 | this.c = o.c; | |
13 | this.x = o.x; | |
14 | this.y = o.y; | |
15 | } | |
6808d7a1 | 16 | }; |
1d184b4c | 17 | |
6808d7a1 | 18 | export const Move = class Move { |
1c9f093d BA |
19 | // o: {appear, vanish, [start,] [end,]} |
20 | // appear,vanish = arrays of PiPo | |
21 | // start,end = coordinates to apply to trigger move visually (think castle) | |
6808d7a1 | 22 | constructor(o) { |
1c9f093d BA |
23 | this.appear = o.appear; |
24 | this.vanish = o.vanish; | |
6808d7a1 BA |
25 | this.start = o.start ? o.start : { x: o.vanish[0].x, y: o.vanish[0].y }; |
26 | this.end = o.end ? o.end : { x: o.appear[0].x, y: o.appear[0].y }; | |
1c9f093d | 27 | } |
6808d7a1 | 28 | }; |
1d184b4c | 29 | |
2c5d7b20 BA |
30 | // NOTE: x coords = top to bottom; y = left to right |
31 | // (from white player perspective) | |
6808d7a1 | 32 | export const ChessRules = class ChessRules { |
1c9f093d BA |
33 | ////////////// |
34 | // MISC UTILS | |
35 | ||
20620465 | 36 | // Some variants don't have flags: |
6808d7a1 BA |
37 | static get HasFlags() { |
38 | return true; | |
20620465 | 39 | } |
1c9f093d | 40 | |
3a2a7b5f BA |
41 | // Or castle |
42 | static get HasCastle() { | |
43 | return V.HasFlags; | |
44 | } | |
45 | ||
32f6285e BA |
46 | // Pawns specifications |
47 | static get PawnSpecs() { | |
48 | return { | |
49 | directions: { 'w': -1, 'b': 1 }, | |
472c0c4f | 50 | initShift: { w: 1, b: 1 }, |
32f6285e | 51 | twoSquares: true, |
472c0c4f | 52 | threeSquares: false, |
32f6285e BA |
53 | promotions: [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN], |
54 | canCapture: true, | |
55 | captureBackward: false, | |
56 | bidirectional: false | |
57 | }; | |
58 | } | |
59 | ||
60 | // En-passant captures need a stack of squares: | |
6808d7a1 BA |
61 | static get HasEnpassant() { |
62 | return true; | |
20620465 BA |
63 | } |
64 | ||
65 | // Some variants cannot have analyse mode | |
8477e53d | 66 | static get CanAnalyze() { |
20620465 BA |
67 | return true; |
68 | } | |
933fd1f9 BA |
69 | // Patch: issues with javascript OOP, objects can't access static fields. |
70 | get canAnalyze() { | |
71 | return V.CanAnalyze; | |
72 | } | |
20620465 BA |
73 | |
74 | // Some variants show incomplete information, | |
75 | // and thus show only a partial moves list or no list at all. | |
76 | static get ShowMoves() { | |
77 | return "all"; | |
78 | } | |
933fd1f9 BA |
79 | get showMoves() { |
80 | return V.ShowMoves; | |
81 | } | |
1c9f093d | 82 | |
00eef1ca BA |
83 | // Sometimes moves must remain hidden until game ends |
84 | static get SomeHiddenMoves() { | |
85 | return false; | |
86 | } | |
87 | get someHiddenMoves() { | |
88 | return V.SomeHiddenMoves; | |
89 | } | |
90 | ||
ad030c7d BA |
91 | // Generally true, unless the variant includes random effects |
92 | static get CorrConfirm() { | |
93 | return true; | |
94 | } | |
95 | ||
5246b49d BA |
96 | // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn) |
97 | get showFirstTurn() { | |
98 | return false; | |
99 | } | |
100 | ||
71ef1664 BA |
101 | // Some variants always show the same orientation |
102 | static get CanFlip() { | |
103 | return true; | |
104 | } | |
105 | get canFlip() { | |
106 | return V.CanFlip; | |
107 | } | |
108 | ||
107dc1bd BA |
109 | // For (generally old) variants without checkered board |
110 | static get Monochrome() { | |
111 | return false; | |
112 | } | |
113 | ||
114 | // Some variants require lines drawing | |
115 | static get Lines() { | |
116 | if (V.Monochrome) { | |
117 | let lines = []; | |
118 | // Draw all inter-squares lines | |
119 | for (let i = 0; i <= V.size.x; i++) | |
120 | lines.push([[i, 0], [i, V.size.y]]); | |
121 | for (let j = 0; j <= V.size.y; j++) | |
122 | lines.push([[0, j], [V.size.x, j]]); | |
123 | return lines; | |
124 | } | |
125 | return null; | |
126 | } | |
127 | ||
61656127 BA |
128 | // Some variants use click infos: |
129 | doClick() { | |
130 | return null; | |
131 | } | |
132 | ||
90df90bc BA |
133 | // Some variants may need to highlight squares on hover (Hamilton, Weiqi...) |
134 | hoverHighlight() { | |
135 | return false; | |
136 | } | |
137 | ||
14edde72 BA |
138 | static get IMAGE_EXTENSION() { |
139 | // All pieces should be in the SVG format | |
140 | return ".svg"; | |
141 | } | |
142 | ||
1c9f093d | 143 | // Turn "wb" into "B" (for FEN) |
6808d7a1 BA |
144 | static board2fen(b) { |
145 | return b[0] == "w" ? b[1].toUpperCase() : b[1]; | |
1c9f093d BA |
146 | } |
147 | ||
148 | // Turn "p" into "bp" (for board) | |
6808d7a1 BA |
149 | static fen2board(f) { |
150 | return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f; | |
1c9f093d BA |
151 | } |
152 | ||
68e19a44 | 153 | // Check if FEN describes a board situation correctly |
6808d7a1 | 154 | static IsGoodFen(fen) { |
1c9f093d BA |
155 | const fenParsed = V.ParseFen(fen); |
156 | // 1) Check position | |
6808d7a1 | 157 | if (!V.IsGoodPosition(fenParsed.position)) return false; |
1c9f093d | 158 | // 2) Check turn |
6808d7a1 | 159 | if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false; |
1c9f093d | 160 | // 3) Check moves count |
e50a8025 | 161 | if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount, 10) >= 0)) |
1c9f093d BA |
162 | return false; |
163 | // 4) Check flags | |
164 | if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags))) | |
165 | return false; | |
166 | // 5) Check enpassant | |
6808d7a1 BA |
167 | if ( |
168 | V.HasEnpassant && | |
169 | (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant)) | |
170 | ) { | |
1c9f093d BA |
171 | return false; |
172 | } | |
173 | return true; | |
174 | } | |
175 | ||
176 | // Is position part of the FEN a priori correct? | |
6808d7a1 BA |
177 | static IsGoodPosition(position) { |
178 | if (position.length == 0) return false; | |
1c9f093d | 179 | const rows = position.split("/"); |
6808d7a1 | 180 | if (rows.length != V.size.x) return false; |
6f2f9437 | 181 | let kings = { "k": 0, "K": 0 }; |
6808d7a1 | 182 | for (let row of rows) { |
1c9f093d | 183 | let sumElts = 0; |
6808d7a1 | 184 | for (let i = 0; i < row.length; i++) { |
6f2f9437 | 185 | if (['K','k'].includes(row[i])) kings[row[i]]++; |
6808d7a1 BA |
186 | if (V.PIECES.includes(row[i].toLowerCase())) sumElts++; |
187 | else { | |
e50a8025 | 188 | const num = parseInt(row[i], 10); |
6808d7a1 | 189 | if (isNaN(num)) return false; |
1c9f093d BA |
190 | sumElts += num; |
191 | } | |
192 | } | |
6808d7a1 | 193 | if (sumElts != V.size.y) return false; |
1c9f093d | 194 | } |
6f2f9437 BA |
195 | // Both kings should be on board. Exactly one per color. |
196 | if (Object.values(kings).some(v => v != 1)) return false; | |
1c9f093d BA |
197 | return true; |
198 | } | |
199 | ||
200 | // For FEN checking | |
6808d7a1 BA |
201 | static IsGoodTurn(turn) { |
202 | return ["w", "b"].includes(turn); | |
1c9f093d BA |
203 | } |
204 | ||
205 | // For FEN checking | |
6808d7a1 | 206 | static IsGoodFlags(flags) { |
3a2a7b5f BA |
207 | // NOTE: a little too permissive to work with more variants |
208 | return !!flags.match(/^[a-z]{4,4}$/); | |
1c9f093d BA |
209 | } |
210 | ||
472c0c4f | 211 | // NOTE: not with regexp to adapt to different board sizes. (TODO?) |
6808d7a1 BA |
212 | static IsGoodEnpassant(enpassant) { |
213 | if (enpassant != "-") { | |
214 | const ep = V.SquareToCoords(enpassant); | |
215 | if (isNaN(ep.x) || !V.OnBoard(ep)) return false; | |
1c9f093d BA |
216 | } |
217 | return true; | |
218 | } | |
219 | ||
220 | // 3 --> d (column number to letter) | |
6808d7a1 | 221 | static CoordToColumn(colnum) { |
1c9f093d BA |
222 | return String.fromCharCode(97 + colnum); |
223 | } | |
224 | ||
225 | // d --> 3 (column letter to number) | |
6808d7a1 | 226 | static ColumnToCoord(column) { |
1c9f093d BA |
227 | return column.charCodeAt(0) - 97; |
228 | } | |
229 | ||
230 | // a4 --> {x:3,y:0} | |
6808d7a1 | 231 | static SquareToCoords(sq) { |
1c9f093d BA |
232 | return { |
233 | // NOTE: column is always one char => max 26 columns | |
234 | // row is counted from black side => subtraction | |
e50a8025 | 235 | x: V.size.x - parseInt(sq.substr(1), 10), |
1c9f093d BA |
236 | y: sq[0].charCodeAt() - 97 |
237 | }; | |
238 | } | |
239 | ||
240 | // {x:0,y:4} --> e8 | |
6808d7a1 | 241 | static CoordsToSquare(coords) { |
1c9f093d BA |
242 | return V.CoordToColumn(coords.y) + (V.size.x - coords.x); |
243 | } | |
244 | ||
305ede7e | 245 | // Path to pieces (standard ones in pieces/ folder) |
241bf8f2 | 246 | getPpath(b) { |
305ede7e | 247 | return b; |
241bf8f2 BA |
248 | } |
249 | ||
3a2a7b5f | 250 | // Path to promotion pieces (usually the same) |
c7550017 BA |
251 | getPPpath(m) { |
252 | return this.getPpath(m.appear[0].c + m.appear[0].p); | |
3a2a7b5f BA |
253 | } |
254 | ||
1c9f093d | 255 | // Aggregates flags into one object |
6808d7a1 | 256 | aggregateFlags() { |
1c9f093d BA |
257 | return this.castleFlags; |
258 | } | |
259 | ||
260 | // Reverse operation | |
6808d7a1 | 261 | disaggregateFlags(flags) { |
1c9f093d BA |
262 | this.castleFlags = flags; |
263 | } | |
264 | ||
265 | // En-passant square, if any | |
6808d7a1 BA |
266 | getEpSquare(moveOrSquare) { |
267 | if (!moveOrSquare) return undefined; | |
268 | if (typeof moveOrSquare === "string") { | |
1c9f093d | 269 | const square = moveOrSquare; |
6808d7a1 | 270 | if (square == "-") return undefined; |
1c9f093d BA |
271 | return V.SquareToCoords(square); |
272 | } | |
273 | // Argument is a move: | |
274 | const move = moveOrSquare; | |
1c5bfdf2 BA |
275 | const s = move.start, |
276 | e = move.end; | |
6808d7a1 | 277 | if ( |
1c5bfdf2 | 278 | s.y == e.y && |
0d5335de BA |
279 | Math.abs(s.x - e.x) == 2 && |
280 | // Next conditions for variants like Atomic or Rifle, Recycle... | |
281 | (move.appear.length > 0 && move.appear[0].p == V.PAWN) && | |
282 | (move.vanish.length > 0 && move.vanish[0].p == V.PAWN) | |
6808d7a1 | 283 | ) { |
1c9f093d | 284 | return { |
1c5bfdf2 BA |
285 | x: (s.x + e.x) / 2, |
286 | y: s.y | |
1c9f093d BA |
287 | }; |
288 | } | |
289 | return undefined; //default | |
290 | } | |
291 | ||
292 | // Can thing on square1 take thing on square2 | |
6808d7a1 BA |
293 | canTake([x1, y1], [x2, y2]) { |
294 | return this.getColor(x1, y1) !== this.getColor(x2, y2); | |
1c9f093d BA |
295 | } |
296 | ||
297 | // Is (x,y) on the chessboard? | |
6808d7a1 BA |
298 | static OnBoard(x, y) { |
299 | return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y; | |
1c9f093d BA |
300 | } |
301 | ||
302 | // Used in interface: 'side' arg == player color | |
6808d7a1 BA |
303 | canIplay(side, [x, y]) { |
304 | return this.turn == side && this.getColor(x, y) == side; | |
1c9f093d BA |
305 | } |
306 | ||
307 | // On which squares is color under check ? (for interface) | |
af34341d BA |
308 | getCheckSquares() { |
309 | const color = this.turn; | |
b0a0468a BA |
310 | return ( |
311 | this.underCheck(color) | |
2c5d7b20 BA |
312 | // kingPos must be duplicated, because it may change: |
313 | ? [JSON.parse(JSON.stringify(this.kingPos[color]))] | |
b0a0468a BA |
314 | : [] |
315 | ); | |
1c9f093d BA |
316 | } |
317 | ||
318 | ///////////// | |
319 | // FEN UTILS | |
320 | ||
7ba4a5bc BA |
321 | // Setup the initial random (asymmetric) position |
322 | static GenRandInitFen(randomness) { | |
7ba4a5bc BA |
323 | if (randomness == 0) |
324 | // Deterministic: | |
3a2a7b5f | 325 | return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -"; |
7ba4a5bc | 326 | |
6808d7a1 | 327 | let pieces = { w: new Array(8), b: new Array(8) }; |
3a2a7b5f | 328 | let flags = ""; |
7ba4a5bc | 329 | // Shuffle pieces on first (and last rank if randomness == 2) |
6808d7a1 | 330 | for (let c of ["w", "b"]) { |
7ba4a5bc BA |
331 | if (c == 'b' && randomness == 1) { |
332 | pieces['b'] = pieces['w']; | |
3a2a7b5f | 333 | flags += flags; |
7ba4a5bc BA |
334 | break; |
335 | } | |
336 | ||
1c9f093d BA |
337 | let positions = ArrayFun.range(8); |
338 | ||
339 | // Get random squares for bishops | |
656b1878 | 340 | let randIndex = 2 * randInt(4); |
1c9f093d BA |
341 | const bishop1Pos = positions[randIndex]; |
342 | // The second bishop must be on a square of different color | |
656b1878 | 343 | let randIndex_tmp = 2 * randInt(4) + 1; |
1c9f093d BA |
344 | const bishop2Pos = positions[randIndex_tmp]; |
345 | // Remove chosen squares | |
6808d7a1 BA |
346 | positions.splice(Math.max(randIndex, randIndex_tmp), 1); |
347 | positions.splice(Math.min(randIndex, randIndex_tmp), 1); | |
1c9f093d BA |
348 | |
349 | // Get random squares for knights | |
656b1878 | 350 | randIndex = randInt(6); |
1c9f093d BA |
351 | const knight1Pos = positions[randIndex]; |
352 | positions.splice(randIndex, 1); | |
656b1878 | 353 | randIndex = randInt(5); |
1c9f093d BA |
354 | const knight2Pos = positions[randIndex]; |
355 | positions.splice(randIndex, 1); | |
356 | ||
357 | // Get random square for queen | |
656b1878 | 358 | randIndex = randInt(4); |
1c9f093d BA |
359 | const queenPos = positions[randIndex]; |
360 | positions.splice(randIndex, 1); | |
361 | ||
362 | // Rooks and king positions are now fixed, | |
363 | // because of the ordering rook-king-rook | |
364 | const rook1Pos = positions[0]; | |
365 | const kingPos = positions[1]; | |
366 | const rook2Pos = positions[2]; | |
367 | ||
368 | // Finally put the shuffled pieces in the board array | |
6808d7a1 BA |
369 | pieces[c][rook1Pos] = "r"; |
370 | pieces[c][knight1Pos] = "n"; | |
371 | pieces[c][bishop1Pos] = "b"; | |
372 | pieces[c][queenPos] = "q"; | |
373 | pieces[c][kingPos] = "k"; | |
374 | pieces[c][bishop2Pos] = "b"; | |
375 | pieces[c][knight2Pos] = "n"; | |
376 | pieces[c][rook2Pos] = "r"; | |
3a2a7b5f | 377 | flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos); |
1c9f093d | 378 | } |
e3e2cc44 | 379 | // Add turn + flags + enpassant |
6808d7a1 BA |
380 | return ( |
381 | pieces["b"].join("") + | |
1c9f093d BA |
382 | "/pppppppp/8/8/8/8/PPPPPPPP/" + |
383 | pieces["w"].join("").toUpperCase() + | |
3a2a7b5f | 384 | " w 0 " + flags + " -" |
e3e2cc44 | 385 | ); |
1c9f093d BA |
386 | } |
387 | ||
388 | // "Parse" FEN: just return untransformed string data | |
6808d7a1 | 389 | static ParseFen(fen) { |
1c9f093d | 390 | const fenParts = fen.split(" "); |
6808d7a1 | 391 | let res = { |
1c9f093d BA |
392 | position: fenParts[0], |
393 | turn: fenParts[1], | |
6808d7a1 | 394 | movesCount: fenParts[2] |
1c9f093d BA |
395 | }; |
396 | let nextIdx = 3; | |
6808d7a1 BA |
397 | if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] }); |
398 | if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] }); | |
1c9f093d BA |
399 | return res; |
400 | } | |
401 | ||
402 | // Return current fen (game state) | |
6808d7a1 BA |
403 | getFen() { |
404 | return ( | |
f9c36b2d BA |
405 | this.getBaseFen() + " " + |
406 | this.getTurnFen() + " " + | |
6808d7a1 BA |
407 | this.movesCount + |
408 | (V.HasFlags ? " " + this.getFlagsFen() : "") + | |
409 | (V.HasEnpassant ? " " + this.getEnpassantFen() : "") | |
410 | ); | |
1c9f093d BA |
411 | } |
412 | ||
f9c36b2d BA |
413 | getFenForRepeat() { |
414 | // Omit movesCount, only variable allowed to differ | |
415 | return ( | |
416 | this.getBaseFen() + "_" + | |
417 | this.getTurnFen() + | |
418 | (V.HasFlags ? "_" + this.getFlagsFen() : "") + | |
419 | (V.HasEnpassant ? "_" + this.getEnpassantFen() : "") | |
420 | ); | |
421 | } | |
422 | ||
1c9f093d | 423 | // Position part of the FEN string |
6808d7a1 | 424 | getBaseFen() { |
6f2f9437 BA |
425 | const format = (count) => { |
426 | // if more than 9 consecutive free spaces, break the integer, | |
427 | // otherwise FEN parsing will fail. | |
428 | if (count <= 9) return count; | |
429 | // Currently only boards of size up to 11 or 12: | |
430 | return "9" + (count - 9); | |
431 | }; | |
1c9f093d | 432 | let position = ""; |
6808d7a1 | 433 | for (let i = 0; i < V.size.x; i++) { |
1c9f093d | 434 | let emptyCount = 0; |
6808d7a1 BA |
435 | for (let j = 0; j < V.size.y; j++) { |
436 | if (this.board[i][j] == V.EMPTY) emptyCount++; | |
437 | else { | |
438 | if (emptyCount > 0) { | |
1c9f093d | 439 | // Add empty squares in-between |
6f2f9437 | 440 | position += format(emptyCount); |
1c9f093d BA |
441 | emptyCount = 0; |
442 | } | |
443 | position += V.board2fen(this.board[i][j]); | |
444 | } | |
445 | } | |
6808d7a1 | 446 | if (emptyCount > 0) { |
1c9f093d | 447 | // "Flush remainder" |
6f2f9437 | 448 | position += format(emptyCount); |
1c9f093d | 449 | } |
6808d7a1 | 450 | if (i < V.size.x - 1) position += "/"; //separate rows |
1c9f093d BA |
451 | } |
452 | return position; | |
453 | } | |
454 | ||
6808d7a1 | 455 | getTurnFen() { |
1c9f093d BA |
456 | return this.turn; |
457 | } | |
458 | ||
459 | // Flags part of the FEN string | |
6808d7a1 | 460 | getFlagsFen() { |
1c9f093d | 461 | let flags = ""; |
3a2a7b5f BA |
462 | // Castling flags |
463 | for (let c of ["w", "b"]) | |
464 | flags += this.castleFlags[c].map(V.CoordToColumn).join(""); | |
1c9f093d BA |
465 | return flags; |
466 | } | |
467 | ||
468 | // Enpassant part of the FEN string | |
6808d7a1 | 469 | getEnpassantFen() { |
1c9f093d | 470 | const L = this.epSquares.length; |
6808d7a1 BA |
471 | if (!this.epSquares[L - 1]) return "-"; //no en-passant |
472 | return V.CoordsToSquare(this.epSquares[L - 1]); | |
1c9f093d BA |
473 | } |
474 | ||
475 | // Turn position fen into double array ["wb","wp","bk",...] | |
6808d7a1 | 476 | static GetBoard(position) { |
1c9f093d BA |
477 | const rows = position.split("/"); |
478 | let board = ArrayFun.init(V.size.x, V.size.y, ""); | |
6808d7a1 | 479 | for (let i = 0; i < rows.length; i++) { |
1c9f093d | 480 | let j = 0; |
6808d7a1 | 481 | for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) { |
1c9f093d | 482 | const character = rows[i][indexInRow]; |
e50a8025 | 483 | const num = parseInt(character, 10); |
a13cbc0f | 484 | // If num is a number, just shift j: |
6808d7a1 | 485 | if (!isNaN(num)) j += num; |
a13cbc0f | 486 | // Else: something at position i,j |
6808d7a1 | 487 | else board[i][j++] = V.fen2board(character); |
1c9f093d BA |
488 | } |
489 | } | |
490 | return board; | |
491 | } | |
492 | ||
493 | // Extract (relevant) flags from fen | |
6808d7a1 | 494 | setFlags(fenflags) { |
1c9f093d | 495 | // white a-castle, h-castle, black a-castle, h-castle |
bb688df5 | 496 | this.castleFlags = { w: [-1, -1], b: [-1, -1] }; |
3a2a7b5f BA |
497 | for (let i = 0; i < 4; i++) { |
498 | this.castleFlags[i < 2 ? "w" : "b"][i % 2] = | |
499 | V.ColumnToCoord(fenflags.charAt(i)); | |
500 | } | |
1c9f093d BA |
501 | } |
502 | ||
503 | ////////////////// | |
504 | // INITIALIZATION | |
505 | ||
37cdcbf3 | 506 | // Fen string fully describes the game state |
b627d118 BA |
507 | constructor(fen) { |
508 | if (!fen) | |
509 | // In printDiagram() fen isn't supply because only getPpath() is used | |
510 | // TODO: find a better solution! | |
511 | return; | |
1c9f093d BA |
512 | const fenParsed = V.ParseFen(fen); |
513 | this.board = V.GetBoard(fenParsed.position); | |
af34341d | 514 | this.turn = fenParsed.turn; |
e50a8025 | 515 | this.movesCount = parseInt(fenParsed.movesCount, 10); |
1c9f093d BA |
516 | this.setOtherVariables(fen); |
517 | } | |
518 | ||
3a2a7b5f BA |
519 | // Scan board for kings positions |
520 | scanKings(fen) { | |
6808d7a1 | 521 | this.INIT_COL_KING = { w: -1, b: -1 }; |
2c5d7b20 BA |
522 | // Squares of white and black king: |
523 | this.kingPos = { w: [-1, -1], b: [-1, -1] }; | |
1c9f093d | 524 | const fenRows = V.ParseFen(fen).position.split("/"); |
90e814b6 | 525 | const startRow = { 'w': V.size.x - 1, 'b': 0 }; |
6808d7a1 | 526 | for (let i = 0; i < fenRows.length; i++) { |
1c9f093d | 527 | let k = 0; //column index on board |
6808d7a1 BA |
528 | for (let j = 0; j < fenRows[i].length; j++) { |
529 | switch (fenRows[i].charAt(j)) { | |
530 | case "k": | |
531 | this.kingPos["b"] = [i, k]; | |
532 | this.INIT_COL_KING["b"] = k; | |
1c9f093d | 533 | break; |
6808d7a1 BA |
534 | case "K": |
535 | this.kingPos["w"] = [i, k]; | |
536 | this.INIT_COL_KING["w"] = k; | |
1c9f093d | 537 | break; |
6808d7a1 | 538 | default: { |
e50a8025 | 539 | const num = parseInt(fenRows[i].charAt(j), 10); |
6808d7a1 BA |
540 | if (!isNaN(num)) k += num - 1; |
541 | } | |
1c9f093d BA |
542 | } |
543 | k++; | |
544 | } | |
545 | } | |
546 | } | |
547 | ||
548 | // Some additional variables from FEN (variant dependant) | |
6808d7a1 | 549 | setOtherVariables(fen) { |
1c9f093d BA |
550 | // Set flags and enpassant: |
551 | const parsedFen = V.ParseFen(fen); | |
6808d7a1 BA |
552 | if (V.HasFlags) this.setFlags(parsedFen.flags); |
553 | if (V.HasEnpassant) { | |
554 | const epSq = | |
555 | parsedFen.enpassant != "-" | |
9bd6786b | 556 | ? this.getEpSquare(parsedFen.enpassant) |
6808d7a1 BA |
557 | : undefined; |
558 | this.epSquares = [epSq]; | |
1c9f093d | 559 | } |
3a2a7b5f BA |
560 | // Search for kings positions: |
561 | this.scanKings(fen); | |
1c9f093d BA |
562 | } |
563 | ||
564 | ///////////////////// | |
565 | // GETTERS & SETTERS | |
566 | ||
6808d7a1 BA |
567 | static get size() { |
568 | return { x: 8, y: 8 }; | |
1c9f093d BA |
569 | } |
570 | ||
0ba6420d | 571 | // Color of thing on square (i,j). 'undefined' if square is empty |
6808d7a1 | 572 | getColor(i, j) { |
1c9f093d BA |
573 | return this.board[i][j].charAt(0); |
574 | } | |
575 | ||
576 | // Piece type on square (i,j). 'undefined' if square is empty | |
6808d7a1 | 577 | getPiece(i, j) { |
1c9f093d BA |
578 | return this.board[i][j].charAt(1); |
579 | } | |
580 | ||
581 | // Get opponent color | |
6808d7a1 BA |
582 | static GetOppCol(color) { |
583 | return color == "w" ? "b" : "w"; | |
1c9f093d BA |
584 | } |
585 | ||
1c9f093d | 586 | // Pieces codes (for a clearer code) |
6808d7a1 BA |
587 | static get PAWN() { |
588 | return "p"; | |
589 | } | |
590 | static get ROOK() { | |
591 | return "r"; | |
592 | } | |
593 | static get KNIGHT() { | |
594 | return "n"; | |
595 | } | |
596 | static get BISHOP() { | |
597 | return "b"; | |
598 | } | |
599 | static get QUEEN() { | |
600 | return "q"; | |
601 | } | |
602 | static get KING() { | |
603 | return "k"; | |
604 | } | |
1c9f093d BA |
605 | |
606 | // For FEN checking: | |
6808d7a1 BA |
607 | static get PIECES() { |
608 | return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING]; | |
1c9f093d BA |
609 | } |
610 | ||
611 | // Empty square | |
6808d7a1 BA |
612 | static get EMPTY() { |
613 | return ""; | |
614 | } | |
1c9f093d BA |
615 | |
616 | // Some pieces movements | |
6808d7a1 | 617 | static get steps() { |
1c9f093d | 618 | return { |
6808d7a1 BA |
619 | r: [ |
620 | [-1, 0], | |
621 | [1, 0], | |
622 | [0, -1], | |
623 | [0, 1] | |
624 | ], | |
625 | n: [ | |
626 | [-1, -2], | |
627 | [-1, 2], | |
628 | [1, -2], | |
629 | [1, 2], | |
630 | [-2, -1], | |
631 | [-2, 1], | |
632 | [2, -1], | |
633 | [2, 1] | |
634 | ], | |
635 | b: [ | |
636 | [-1, -1], | |
637 | [-1, 1], | |
638 | [1, -1], | |
639 | [1, 1] | |
640 | ] | |
1c9f093d BA |
641 | }; |
642 | } | |
643 | ||
644 | //////////////////// | |
645 | // MOVES GENERATION | |
646 | ||
0ba6420d | 647 | // All possible moves from selected square |
6808d7a1 BA |
648 | getPotentialMovesFrom([x, y]) { |
649 | switch (this.getPiece(x, y)) { | |
1c9f093d | 650 | case V.PAWN: |
6808d7a1 | 651 | return this.getPotentialPawnMoves([x, y]); |
1c9f093d | 652 | case V.ROOK: |
6808d7a1 | 653 | return this.getPotentialRookMoves([x, y]); |
1c9f093d | 654 | case V.KNIGHT: |
6808d7a1 | 655 | return this.getPotentialKnightMoves([x, y]); |
1c9f093d | 656 | case V.BISHOP: |
6808d7a1 | 657 | return this.getPotentialBishopMoves([x, y]); |
1c9f093d | 658 | case V.QUEEN: |
6808d7a1 | 659 | return this.getPotentialQueenMoves([x, y]); |
1c9f093d | 660 | case V.KING: |
6808d7a1 | 661 | return this.getPotentialKingMoves([x, y]); |
1c9f093d | 662 | } |
6808d7a1 | 663 | return []; //never reached |
1c9f093d BA |
664 | } |
665 | ||
666 | // Build a regular move from its initial and destination squares. | |
667 | // tr: transformation | |
6808d7a1 | 668 | getBasicMove([sx, sy], [ex, ey], tr) { |
1c58eb76 BA |
669 | const initColor = this.getColor(sx, sy); |
670 | const initPiece = this.getPiece(sx, sy); | |
1c9f093d BA |
671 | let mv = new Move({ |
672 | appear: [ | |
673 | new PiPo({ | |
674 | x: ex, | |
675 | y: ey, | |
1c58eb76 BA |
676 | c: tr ? tr.c : initColor, |
677 | p: tr ? tr.p : initPiece | |
1c9f093d BA |
678 | }) |
679 | ], | |
680 | vanish: [ | |
681 | new PiPo({ | |
682 | x: sx, | |
683 | y: sy, | |
1c58eb76 BA |
684 | c: initColor, |
685 | p: initPiece | |
1c9f093d BA |
686 | }) |
687 | ] | |
688 | }); | |
689 | ||
690 | // The opponent piece disappears if we take it | |
6808d7a1 | 691 | if (this.board[ex][ey] != V.EMPTY) { |
1c9f093d BA |
692 | mv.vanish.push( |
693 | new PiPo({ | |
694 | x: ex, | |
695 | y: ey, | |
6808d7a1 BA |
696 | c: this.getColor(ex, ey), |
697 | p: this.getPiece(ex, ey) | |
1c9f093d BA |
698 | }) |
699 | ); | |
700 | } | |
1c5bfdf2 | 701 | |
1c9f093d BA |
702 | return mv; |
703 | } | |
704 | ||
705 | // Generic method to find possible moves of non-pawn pieces: | |
706 | // "sliding or jumping" | |
6808d7a1 | 707 | getSlideNJumpMoves([x, y], steps, oneStep) { |
1c9f093d | 708 | let moves = []; |
6808d7a1 | 709 | outerLoop: for (let step of steps) { |
1c9f093d BA |
710 | let i = x + step[0]; |
711 | let j = y + step[1]; | |
6808d7a1 BA |
712 | while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) { |
713 | moves.push(this.getBasicMove([x, y], [i, j])); | |
d1be8046 | 714 | if (oneStep) continue outerLoop; |
1c9f093d BA |
715 | i += step[0]; |
716 | j += step[1]; | |
717 | } | |
6808d7a1 BA |
718 | if (V.OnBoard(i, j) && this.canTake([x, y], [i, j])) |
719 | moves.push(this.getBasicMove([x, y], [i, j])); | |
1c9f093d BA |
720 | } |
721 | return moves; | |
722 | } | |
723 | ||
32f6285e BA |
724 | // Special case of en-passant captures: treated separately |
725 | getEnpassantCaptures([x, y], shiftX) { | |
726 | const Lep = this.epSquares.length; | |
727 | const epSquare = this.epSquares[Lep - 1]; //always at least one element | |
728 | let enpassantMove = null; | |
729 | if ( | |
730 | !!epSquare && | |
731 | epSquare.x == x + shiftX && | |
732 | Math.abs(epSquare.y - y) == 1 | |
733 | ) { | |
734 | enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]); | |
735 | enpassantMove.vanish.push({ | |
736 | x: x, | |
737 | y: epSquare.y, | |
8c1ec210 | 738 | // Captured piece is usually a pawn, but next line seems harmless |
6f2f9437 | 739 | p: this.getPiece(x, epSquare.y), |
32f6285e BA |
740 | c: this.getColor(x, epSquare.y) |
741 | }); | |
742 | } | |
743 | return !!enpassantMove ? [enpassantMove] : []; | |
744 | } | |
745 | ||
1c58eb76 BA |
746 | // Consider all potential promotions: |
747 | addPawnMoves([x1, y1], [x2, y2], moves, promotions) { | |
748 | let finalPieces = [V.PAWN]; | |
af34341d | 749 | const color = this.turn; //this.getColor(x1, y1); |
1c58eb76 BA |
750 | const lastRank = (color == "w" ? 0 : V.size.x - 1); |
751 | if (x2 == lastRank) { | |
752 | // promotions arg: special override for Hiddenqueen variant | |
753 | if (!!promotions) finalPieces = promotions; | |
15d69043 | 754 | else if (!!V.PawnSpecs.promotions) finalPieces = V.PawnSpecs.promotions; |
1c58eb76 BA |
755 | } |
756 | let tr = null; | |
757 | for (let piece of finalPieces) { | |
758 | tr = (piece != V.PAWN ? { c: color, p: piece } : null); | |
759 | moves.push(this.getBasicMove([x1, y1], [x2, y2], tr)); | |
760 | } | |
761 | } | |
762 | ||
1c9f093d | 763 | // What are the pawn moves from square x,y ? |
32f6285e | 764 | getPotentialPawnMoves([x, y], promotions) { |
af34341d | 765 | const color = this.turn; //this.getColor(x, y); |
6808d7a1 | 766 | const [sizeX, sizeY] = [V.size.x, V.size.y]; |
32f6285e | 767 | const pawnShiftX = V.PawnSpecs.directions[color]; |
1c58eb76 | 768 | const firstRank = (color == "w" ? sizeX - 1 : 0); |
0b8bd121 | 769 | const forward = (color == 'w' ? -1 : 1); |
32f6285e BA |
770 | |
771 | // Pawn movements in shiftX direction: | |
772 | const getPawnMoves = (shiftX) => { | |
773 | let moves = []; | |
774 | // NOTE: next condition is generally true (no pawn on last rank) | |
775 | if (x + shiftX >= 0 && x + shiftX < sizeX) { | |
776 | if (this.board[x + shiftX][y] == V.EMPTY) { | |
0b8bd121 | 777 | // One square forward (or backward) |
1c58eb76 | 778 | this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions); |
32f6285e BA |
779 | // Next condition because pawns on 1st rank can generally jump |
780 | if ( | |
781 | V.PawnSpecs.twoSquares && | |
472c0c4f BA |
782 | ( |
783 | (color == 'w' && x >= V.size.x - 1 - V.PawnSpecs.initShift['w']) | |
784 | || | |
785 | (color == 'b' && x <= V.PawnSpecs.initShift['b']) | |
786 | ) | |
32f6285e | 787 | ) { |
0b8bd121 BA |
788 | if ( |
789 | shiftX == forward && | |
790 | this.board[x + 2 * shiftX][y] == V.EMPTY | |
791 | ) { | |
472c0c4f BA |
792 | // Two squares jump |
793 | moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y])); | |
794 | if ( | |
795 | V.PawnSpecs.threeSquares && | |
796 | this.board[x + 3 * shiftX][y] == V.EMPTY | |
797 | ) { | |
798 | // Three squares jump | |
799 | moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y])); | |
800 | } | |
801 | } | |
32f6285e BA |
802 | } |
803 | } | |
804 | // Captures | |
805 | if (V.PawnSpecs.canCapture) { | |
806 | for (let shiftY of [-1, 1]) { | |
15d69043 | 807 | if (y + shiftY >= 0 && y + shiftY < sizeY) { |
32f6285e BA |
808 | if ( |
809 | this.board[x + shiftX][y + shiftY] != V.EMPTY && | |
810 | this.canTake([x, y], [x + shiftX, y + shiftY]) | |
811 | ) { | |
1c58eb76 BA |
812 | this.addPawnMoves( |
813 | [x, y], [x + shiftX, y + shiftY], | |
814 | moves, promotions | |
815 | ); | |
32f6285e BA |
816 | } |
817 | if ( | |
0b8bd121 | 818 | V.PawnSpecs.captureBackward && shiftX == forward && |
32f6285e BA |
819 | x - shiftX >= 0 && x - shiftX < V.size.x && |
820 | this.board[x - shiftX][y + shiftY] != V.EMPTY && | |
821 | this.canTake([x, y], [x - shiftX, y + shiftY]) | |
822 | ) { | |
1c58eb76 | 823 | this.addPawnMoves( |
0b8bd121 | 824 | [x, y], [x - shiftX, y + shiftY], |
1c58eb76 BA |
825 | moves, promotions |
826 | ); | |
32f6285e BA |
827 | } |
828 | } | |
1c9f093d BA |
829 | } |
830 | } | |
831 | } | |
32f6285e | 832 | return moves; |
1c9f093d BA |
833 | } |
834 | ||
32f6285e BA |
835 | let pMoves = getPawnMoves(pawnShiftX); |
836 | if (V.PawnSpecs.bidirectional) | |
837 | pMoves = pMoves.concat(getPawnMoves(-pawnShiftX)); | |
838 | ||
6808d7a1 | 839 | if (V.HasEnpassant) { |
32f6285e BA |
840 | // NOTE: backward en-passant captures are not considered |
841 | // because no rules define them (for now). | |
842 | Array.prototype.push.apply( | |
843 | pMoves, | |
844 | this.getEnpassantCaptures([x, y], pawnShiftX) | |
845 | ); | |
1c9f093d | 846 | } |
294fe29f | 847 | |
32f6285e | 848 | return pMoves; |
1c9f093d BA |
849 | } |
850 | ||
851 | // What are the rook moves from square x,y ? | |
6808d7a1 | 852 | getPotentialRookMoves(sq) { |
1c9f093d BA |
853 | return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]); |
854 | } | |
855 | ||
856 | // What are the knight moves from square x,y ? | |
6808d7a1 | 857 | getPotentialKnightMoves(sq) { |
1c9f093d BA |
858 | return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep"); |
859 | } | |
860 | ||
861 | // What are the bishop moves from square x,y ? | |
6808d7a1 | 862 | getPotentialBishopMoves(sq) { |
1c9f093d BA |
863 | return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]); |
864 | } | |
865 | ||
866 | // What are the queen moves from square x,y ? | |
6808d7a1 BA |
867 | getPotentialQueenMoves(sq) { |
868 | return this.getSlideNJumpMoves( | |
869 | sq, | |
870 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]) | |
871 | ); | |
1c9f093d BA |
872 | } |
873 | ||
874 | // What are the king moves from square x,y ? | |
6808d7a1 | 875 | getPotentialKingMoves(sq) { |
1c9f093d | 876 | // Initialize with normal moves |
c583ef1c | 877 | let moves = this.getSlideNJumpMoves( |
6808d7a1 BA |
878 | sq, |
879 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), | |
880 | "oneStep" | |
881 | ); | |
c583ef1c BA |
882 | if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq)); |
883 | return moves; | |
1c9f093d BA |
884 | } |
885 | ||
a6836242 | 886 | // "castleInCheck" arg to let some variants castle under check |
85a1dcba | 887 | getCastleMoves([x, y], castleInCheck, castleWith) { |
6808d7a1 BA |
888 | const c = this.getColor(x, y); |
889 | if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c]) | |
1c9f093d BA |
890 | return []; //x isn't first rank, or king has moved (shortcut) |
891 | ||
892 | // Castling ? | |
893 | const oppCol = V.GetOppCol(c); | |
894 | let moves = []; | |
895 | let i = 0; | |
9bd6786b | 896 | // King, then rook: |
6808d7a1 BA |
897 | const finalSquares = [ |
898 | [2, 3], | |
899 | [V.size.y - 2, V.size.y - 3] | |
9bd6786b | 900 | ]; |
6808d7a1 BA |
901 | castlingCheck: for ( |
902 | let castleSide = 0; | |
903 | castleSide < 2; | |
904 | castleSide++ //large, then small | |
905 | ) { | |
3a2a7b5f | 906 | if (this.castleFlags[c][castleSide] >= V.size.y) continue; |
3f22c2c3 | 907 | // If this code is reached, rook and king are on initial position |
1c9f093d | 908 | |
2c5d7b20 | 909 | // NOTE: in some variants this is not a rook |
32f6285e | 910 | const rookPos = this.castleFlags[c][castleSide]; |
85a1dcba BA |
911 | if ( |
912 | this.board[x][rookPos] == V.EMPTY || | |
913 | this.getColor(x, rookPos) != c || | |
914 | (!!castleWith && !castleWith.includes(this.getPiece(x, rookPos))) | |
915 | ) { | |
61656127 | 916 | // Rook is not here, or changed color (see Benedict) |
32f6285e | 917 | continue; |
85a1dcba | 918 | } |
32f6285e | 919 | |
2beba6db | 920 | // Nothing on the path of the king ? (and no checks) |
61656127 | 921 | const castlingPiece = this.getPiece(x, rookPos); |
2beba6db BA |
922 | const finDist = finalSquares[castleSide][0] - y; |
923 | let step = finDist / Math.max(1, Math.abs(finDist)); | |
924 | i = y; | |
6808d7a1 BA |
925 | do { |
926 | if ( | |
5e1bc651 BA |
927 | // NOTE: "castling" arg is used by some variants (Monster), |
928 | // where "isAttacked" is overloaded in an infinite-recursive way. | |
34bfe151 | 929 | // TODO: not used anymore (Monster + Doublemove2 are simplified). |
5e1bc651 | 930 | (!castleInCheck && this.isAttacked([x, i], oppCol, "castling")) || |
6808d7a1 BA |
931 | (this.board[x][i] != V.EMPTY && |
932 | // NOTE: next check is enough, because of chessboard constraints | |
933 | (this.getColor(x, i) != c || | |
a6836242 | 934 | ![V.KING, castlingPiece].includes(this.getPiece(x, i)))) |
6808d7a1 | 935 | ) { |
1c9f093d BA |
936 | continue castlingCheck; |
937 | } | |
2beba6db | 938 | i += step; |
6808d7a1 | 939 | } while (i != finalSquares[castleSide][0]); |
1c9f093d BA |
940 | |
941 | // Nothing on the path to the rook? | |
6808d7a1 | 942 | step = castleSide == 0 ? -1 : 1; |
3a2a7b5f | 943 | for (i = y + step; i != rookPos; i += step) { |
6808d7a1 | 944 | if (this.board[x][i] != V.EMPTY) continue castlingCheck; |
1c9f093d | 945 | } |
1c9f093d BA |
946 | |
947 | // Nothing on final squares, except maybe king and castling rook? | |
6808d7a1 BA |
948 | for (i = 0; i < 2; i++) { |
949 | if ( | |
5e1bc651 | 950 | finalSquares[castleSide][i] != rookPos && |
6808d7a1 | 951 | this.board[x][finalSquares[castleSide][i]] != V.EMPTY && |
5e1bc651 BA |
952 | ( |
953 | this.getPiece(x, finalSquares[castleSide][i]) != V.KING || | |
954 | this.getColor(x, finalSquares[castleSide][i]) != c | |
955 | ) | |
6808d7a1 | 956 | ) { |
1c9f093d BA |
957 | continue castlingCheck; |
958 | } | |
959 | } | |
960 | ||
961 | // If this code is reached, castle is valid | |
6808d7a1 BA |
962 | moves.push( |
963 | new Move({ | |
964 | appear: [ | |
2c5d7b20 BA |
965 | new PiPo({ |
966 | x: x, | |
967 | y: finalSquares[castleSide][0], | |
968 | p: V.KING, | |
969 | c: c | |
970 | }), | |
971 | new PiPo({ | |
972 | x: x, | |
973 | y: finalSquares[castleSide][1], | |
974 | p: castlingPiece, | |
975 | c: c | |
976 | }) | |
6808d7a1 BA |
977 | ], |
978 | vanish: [ | |
979 | new PiPo({ x: x, y: y, p: V.KING, c: c }), | |
a6836242 | 980 | new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c }) |
6808d7a1 BA |
981 | ], |
982 | end: | |
983 | Math.abs(y - rookPos) <= 2 | |
984 | ? { x: x, y: rookPos } | |
985 | : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) } | |
986 | }) | |
987 | ); | |
1c9f093d BA |
988 | } |
989 | ||
990 | return moves; | |
991 | } | |
992 | ||
993 | //////////////////// | |
994 | // MOVES VALIDATION | |
995 | ||
996 | // For the interface: possible moves for the current turn from square sq | |
6808d7a1 BA |
997 | getPossibleMovesFrom(sq) { |
998 | return this.filterValid(this.getPotentialMovesFrom(sq)); | |
1c9f093d BA |
999 | } |
1000 | ||
1001 | // TODO: promotions (into R,B,N,Q) should be filtered only once | |
6808d7a1 BA |
1002 | filterValid(moves) { |
1003 | if (moves.length == 0) return []; | |
1c9f093d BA |
1004 | const color = this.turn; |
1005 | return moves.filter(m => { | |
1006 | this.play(m); | |
1007 | const res = !this.underCheck(color); | |
1008 | this.undo(m); | |
1009 | return res; | |
1010 | }); | |
1011 | } | |
1012 | ||
5e1bc651 | 1013 | getAllPotentialMoves() { |
1c9f093d | 1014 | const color = this.turn; |
1c9f093d | 1015 | let potentialMoves = []; |
6808d7a1 BA |
1016 | for (let i = 0; i < V.size.x; i++) { |
1017 | for (let j = 0; j < V.size.y; j++) { | |
156986e6 | 1018 | if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) { |
6808d7a1 BA |
1019 | Array.prototype.push.apply( |
1020 | potentialMoves, | |
1021 | this.getPotentialMovesFrom([i, j]) | |
1022 | ); | |
1c9f093d BA |
1023 | } |
1024 | } | |
1025 | } | |
5e1bc651 BA |
1026 | return potentialMoves; |
1027 | } | |
1028 | ||
1029 | // Search for all valid moves considering current turn | |
1030 | // (for engine and game end) | |
1031 | getAllValidMoves() { | |
1032 | return this.filterValid(this.getAllPotentialMoves()); | |
1c9f093d BA |
1033 | } |
1034 | ||
1035 | // Stop at the first move found | |
2c5d7b20 | 1036 | // TODO: not really, it explores all moves from a square (one is enough). |
6808d7a1 | 1037 | atLeastOneMove() { |
1c9f093d | 1038 | const color = this.turn; |
6808d7a1 BA |
1039 | for (let i = 0; i < V.size.x; i++) { |
1040 | for (let j = 0; j < V.size.y; j++) { | |
665eed90 | 1041 | if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) { |
6808d7a1 BA |
1042 | const moves = this.getPotentialMovesFrom([i, j]); |
1043 | if (moves.length > 0) { | |
107dc1bd | 1044 | for (let k = 0; k < moves.length; k++) |
6808d7a1 | 1045 | if (this.filterValid([moves[k]]).length > 0) return true; |
1c9f093d BA |
1046 | } |
1047 | } | |
1048 | } | |
1049 | } | |
1050 | return false; | |
1051 | } | |
1052 | ||
68e19a44 BA |
1053 | // Check if pieces of given color are attacking (king) on square x,y |
1054 | isAttacked(sq, color) { | |
6808d7a1 | 1055 | return ( |
68e19a44 BA |
1056 | this.isAttackedByPawn(sq, color) || |
1057 | this.isAttackedByRook(sq, color) || | |
1058 | this.isAttackedByKnight(sq, color) || | |
1059 | this.isAttackedByBishop(sq, color) || | |
1060 | this.isAttackedByQueen(sq, color) || | |
1061 | this.isAttackedByKing(sq, color) | |
6808d7a1 | 1062 | ); |
1c9f093d BA |
1063 | } |
1064 | ||
d1be8046 | 1065 | // Generic method for non-pawn pieces ("sliding or jumping"): |
68e19a44 BA |
1066 | // is x,y attacked by a piece of given color ? |
1067 | isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) { | |
d1be8046 BA |
1068 | for (let step of steps) { |
1069 | let rx = x + step[0], | |
1070 | ry = y + step[1]; | |
1071 | while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) { | |
1072 | rx += step[0]; | |
1073 | ry += step[1]; | |
1074 | } | |
1075 | if ( | |
1076 | V.OnBoard(rx, ry) && | |
68e19a44 BA |
1077 | this.getPiece(rx, ry) == piece && |
1078 | this.getColor(rx, ry) == color | |
d1be8046 BA |
1079 | ) { |
1080 | return true; | |
1081 | } | |
1082 | } | |
1083 | return false; | |
1084 | } | |
1085 | ||
68e19a44 | 1086 | // Is square x,y attacked by 'color' pawns ? |
107dc1bd | 1087 | isAttackedByPawn(sq, color) { |
68e19a44 | 1088 | const pawnShift = (color == "w" ? 1 : -1); |
107dc1bd BA |
1089 | return this.isAttackedBySlideNJump( |
1090 | sq, | |
1091 | color, | |
1092 | V.PAWN, | |
1093 | [[pawnShift, 1], [pawnShift, -1]], | |
1094 | "oneStep" | |
1095 | ); | |
1c9f093d BA |
1096 | } |
1097 | ||
68e19a44 BA |
1098 | // Is square x,y attacked by 'color' rooks ? |
1099 | isAttackedByRook(sq, color) { | |
1100 | return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]); | |
1c9f093d BA |
1101 | } |
1102 | ||
68e19a44 BA |
1103 | // Is square x,y attacked by 'color' knights ? |
1104 | isAttackedByKnight(sq, color) { | |
6808d7a1 BA |
1105 | return this.isAttackedBySlideNJump( |
1106 | sq, | |
68e19a44 | 1107 | color, |
6808d7a1 BA |
1108 | V.KNIGHT, |
1109 | V.steps[V.KNIGHT], | |
1110 | "oneStep" | |
1111 | ); | |
1c9f093d BA |
1112 | } |
1113 | ||
68e19a44 BA |
1114 | // Is square x,y attacked by 'color' bishops ? |
1115 | isAttackedByBishop(sq, color) { | |
1116 | return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]); | |
1c9f093d BA |
1117 | } |
1118 | ||
68e19a44 BA |
1119 | // Is square x,y attacked by 'color' queens ? |
1120 | isAttackedByQueen(sq, color) { | |
6808d7a1 BA |
1121 | return this.isAttackedBySlideNJump( |
1122 | sq, | |
68e19a44 | 1123 | color, |
6808d7a1 BA |
1124 | V.QUEEN, |
1125 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]) | |
1126 | ); | |
1c9f093d BA |
1127 | } |
1128 | ||
68e19a44 BA |
1129 | // Is square x,y attacked by 'color' king(s) ? |
1130 | isAttackedByKing(sq, color) { | |
6808d7a1 BA |
1131 | return this.isAttackedBySlideNJump( |
1132 | sq, | |
68e19a44 | 1133 | color, |
6808d7a1 BA |
1134 | V.KING, |
1135 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), | |
1136 | "oneStep" | |
1137 | ); | |
1c9f093d BA |
1138 | } |
1139 | ||
1c9f093d | 1140 | // Is color under check after his move ? |
6808d7a1 | 1141 | underCheck(color) { |
1c58eb76 | 1142 | return this.isAttacked(this.kingPos[color], V.GetOppCol(color)); |
1c9f093d BA |
1143 | } |
1144 | ||
1145 | ///////////////// | |
1146 | // MOVES PLAYING | |
1147 | ||
1148 | // Apply a move on board | |
6808d7a1 BA |
1149 | static PlayOnBoard(board, move) { |
1150 | for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY; | |
1151 | for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p; | |
1c9f093d BA |
1152 | } |
1153 | // Un-apply the played move | |
6808d7a1 BA |
1154 | static UndoOnBoard(board, move) { |
1155 | for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY; | |
1156 | for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p; | |
1c9f093d BA |
1157 | } |
1158 | ||
3a2a7b5f BA |
1159 | prePlay() {} |
1160 | ||
1161 | play(move) { | |
1162 | // DEBUG: | |
1163 | // if (!this.states) this.states = []; | |
1c58eb76 | 1164 | // const stateFen = this.getFen() + JSON.stringify(this.kingPos); |
3a2a7b5f BA |
1165 | // this.states.push(stateFen); |
1166 | ||
1167 | this.prePlay(move); | |
2c5d7b20 BA |
1168 | // Save flags (for undo) |
1169 | if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags()); | |
3a2a7b5f BA |
1170 | if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move)); |
1171 | V.PlayOnBoard(this.board, move); | |
1172 | this.turn = V.GetOppCol(this.turn); | |
1173 | this.movesCount++; | |
1174 | this.postPlay(move); | |
1175 | } | |
1176 | ||
a9e1202b BA |
1177 | updateCastleFlags(move, piece, color) { |
1178 | const c = color || V.GetOppCol(this.turn); | |
1c58eb76 BA |
1179 | const firstRank = (c == "w" ? V.size.x - 1 : 0); |
1180 | // Update castling flags if rooks are moved | |
c7550017 | 1181 | const oppCol = this.turn; |
1c58eb76 | 1182 | const oppFirstRank = V.size.x - 1 - firstRank; |
bb688df5 BA |
1183 | if (piece == V.KING && move.appear.length > 0) |
1184 | this.castleFlags[c] = [V.size.y, V.size.y]; | |
1185 | else if ( | |
1c58eb76 BA |
1186 | move.start.x == firstRank && //our rook moves? |
1187 | this.castleFlags[c].includes(move.start.y) | |
1188 | ) { | |
1189 | const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1); | |
1190 | this.castleFlags[c][flagIdx] = V.size.y; | |
305ede7e BA |
1191 | } |
1192 | // NOTE: not "else if" because a rook could take an opposing rook | |
1193 | if ( | |
1c58eb76 BA |
1194 | move.end.x == oppFirstRank && //we took opponent rook? |
1195 | this.castleFlags[oppCol].includes(move.end.y) | |
1196 | ) { | |
1197 | const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1); | |
1198 | this.castleFlags[oppCol][flagIdx] = V.size.y; | |
1199 | } | |
1200 | } | |
1201 | ||
1c9f093d | 1202 | // After move is played, update variables + flags |
3a2a7b5f BA |
1203 | postPlay(move) { |
1204 | const c = V.GetOppCol(this.turn); | |
1c9f093d | 1205 | let piece = undefined; |
3a2a7b5f | 1206 | if (move.vanish.length >= 1) |
1c9f093d BA |
1207 | // Usual case, something is moved |
1208 | piece = move.vanish[0].p; | |
3a2a7b5f | 1209 | else |
1c9f093d BA |
1210 | // Crazyhouse-like variants |
1211 | piece = move.appear[0].p; | |
1c9f093d BA |
1212 | |
1213 | // Update king position + flags | |
964eda04 BA |
1214 | if (piece == V.KING && move.appear.length > 0) |
1215 | this.kingPos[c] = [move.appear[0].x, move.appear[0].y]; | |
bb688df5 | 1216 | if (V.HasCastle) this.updateCastleFlags(move, piece); |
1c9f093d BA |
1217 | } |
1218 | ||
3a2a7b5f | 1219 | preUndo() {} |
1c9f093d | 1220 | |
6808d7a1 | 1221 | undo(move) { |
3a2a7b5f | 1222 | this.preUndo(move); |
6808d7a1 BA |
1223 | if (V.HasEnpassant) this.epSquares.pop(); |
1224 | if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags)); | |
1c9f093d BA |
1225 | V.UndoOnBoard(this.board, move); |
1226 | this.turn = V.GetOppCol(this.turn); | |
1227 | this.movesCount--; | |
3a2a7b5f | 1228 | this.postUndo(move); |
1c9f093d BA |
1229 | |
1230 | // DEBUG: | |
1c58eb76 | 1231 | // const stateFen = this.getFen() + JSON.stringify(this.kingPos); |
9bd6786b BA |
1232 | // if (stateFen != this.states[this.states.length-1]) debugger; |
1233 | // this.states.pop(); | |
1c9f093d BA |
1234 | } |
1235 | ||
3a2a7b5f BA |
1236 | // After move is undo-ed *and flags resetted*, un-update other variables |
1237 | // TODO: more symmetry, by storing flags increment in move (?!) | |
1238 | postUndo(move) { | |
1239 | // (Potentially) Reset king position | |
1240 | const c = this.getColor(move.start.x, move.start.y); | |
1241 | if (this.getPiece(move.start.x, move.start.y) == V.KING) | |
1242 | this.kingPos[c] = [move.start.x, move.start.y]; | |
1243 | } | |
1244 | ||
1c9f093d BA |
1245 | /////////////// |
1246 | // END OF GAME | |
1247 | ||
1248 | // What is the score ? (Interesting if game is over) | |
6808d7a1 | 1249 | getCurrentScore() { |
bb688df5 | 1250 | if (this.atLeastOneMove()) return "*"; |
1c9f093d BA |
1251 | // Game over |
1252 | const color = this.turn; | |
1253 | // No valid move: stalemate or checkmate? | |
bb688df5 | 1254 | if (!this.underCheck(color)) return "1/2"; |
1c9f093d | 1255 | // OK, checkmate |
68e19a44 | 1256 | return (color == "w" ? "0-1" : "1-0"); |
1c9f093d BA |
1257 | } |
1258 | ||
1259 | /////////////// | |
1260 | // ENGINE PLAY | |
1261 | ||
1262 | // Pieces values | |
6808d7a1 | 1263 | static get VALUES() { |
1c9f093d | 1264 | return { |
6808d7a1 BA |
1265 | p: 1, |
1266 | r: 5, | |
1267 | n: 3, | |
1268 | b: 3, | |
1269 | q: 9, | |
1270 | k: 1000 | |
1c9f093d BA |
1271 | }; |
1272 | } | |
1273 | ||
1274 | // "Checkmate" (unreachable eval) | |
6808d7a1 BA |
1275 | static get INFINITY() { |
1276 | return 9999; | |
1277 | } | |
1c9f093d BA |
1278 | |
1279 | // At this value or above, the game is over | |
6808d7a1 BA |
1280 | static get THRESHOLD_MATE() { |
1281 | return V.INFINITY; | |
1282 | } | |
1c9f093d | 1283 | |
2c5d7b20 | 1284 | // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller |
6808d7a1 BA |
1285 | static get SEARCH_DEPTH() { |
1286 | return 3; | |
1287 | } | |
1c9f093d | 1288 | |
af34341d BA |
1289 | // 'movesList' arg for some variants to provide a custom list |
1290 | getComputerMove(movesList) { | |
1c9f093d BA |
1291 | const maxeval = V.INFINITY; |
1292 | const color = this.turn; | |
af34341d | 1293 | let moves1 = movesList || this.getAllValidMoves(); |
c322a844 | 1294 | |
6808d7a1 | 1295 | if (moves1.length == 0) |
e71161fb | 1296 | // TODO: this situation should not happen |
41cb9b94 | 1297 | return null; |
1c9f093d | 1298 | |
b83a675a | 1299 | // Rank moves using a min-max at depth 2 (if search_depth >= 2!) |
6808d7a1 | 1300 | for (let i = 0; i < moves1.length; i++) { |
afbf3ca7 BA |
1301 | this.play(moves1[i]); |
1302 | const score1 = this.getCurrentScore(); | |
1303 | if (score1 != "*") { | |
1304 | moves1[i].eval = | |
1305 | score1 == "1/2" | |
1306 | ? 0 | |
1307 | : (score1 == "1-0" ? 1 : -1) * maxeval; | |
1308 | } | |
1309 | if (V.SEARCH_DEPTH == 1 || score1 != "*") { | |
1310 | if (!moves1[i].eval) moves1[i].eval = this.evalPosition(); | |
1311 | this.undo(moves1[i]); | |
b83a675a BA |
1312 | continue; |
1313 | } | |
1c9f093d | 1314 | // Initial self evaluation is very low: "I'm checkmated" |
6808d7a1 | 1315 | moves1[i].eval = (color == "w" ? -1 : 1) * maxeval; |
afbf3ca7 BA |
1316 | // Initial enemy evaluation is very low too, for him |
1317 | let eval2 = (color == "w" ? 1 : -1) * maxeval; | |
1318 | // Second half-move: | |
1319 | let moves2 = this.getAllValidMoves(); | |
1320 | for (let j = 0; j < moves2.length; j++) { | |
1321 | this.play(moves2[j]); | |
1322 | const score2 = this.getCurrentScore(); | |
1323 | let evalPos = 0; //1/2 value | |
1324 | switch (score2) { | |
1325 | case "*": | |
1326 | evalPos = this.evalPosition(); | |
1327 | break; | |
1328 | case "1-0": | |
1329 | evalPos = maxeval; | |
1330 | break; | |
1331 | case "0-1": | |
1332 | evalPos = -maxeval; | |
1333 | break; | |
1c9f093d | 1334 | } |
afbf3ca7 BA |
1335 | if ( |
1336 | (color == "w" && evalPos < eval2) || | |
1337 | (color == "b" && evalPos > eval2) | |
1338 | ) { | |
1339 | eval2 = evalPos; | |
1340 | } | |
1341 | this.undo(moves2[j]); | |
1342 | } | |
6808d7a1 BA |
1343 | if ( |
1344 | (color == "w" && eval2 > moves1[i].eval) || | |
1345 | (color == "b" && eval2 < moves1[i].eval) | |
1346 | ) { | |
1c9f093d BA |
1347 | moves1[i].eval = eval2; |
1348 | } | |
1349 | this.undo(moves1[i]); | |
1350 | } | |
6808d7a1 BA |
1351 | moves1.sort((a, b) => { |
1352 | return (color == "w" ? 1 : -1) * (b.eval - a.eval); | |
1353 | }); | |
a97bdbda | 1354 | // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; })); |
1c9f093d | 1355 | |
1c9f093d | 1356 | // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...) |
6808d7a1 | 1357 | if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) { |
6808d7a1 | 1358 | for (let i = 0; i < moves1.length; i++) { |
1c9f093d BA |
1359 | this.play(moves1[i]); |
1360 | // 0.1 * oldEval : heuristic to avoid some bad moves (not all...) | |
6808d7a1 BA |
1361 | moves1[i].eval = |
1362 | 0.1 * moves1[i].eval + | |
1363 | this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval); | |
1c9f093d BA |
1364 | this.undo(moves1[i]); |
1365 | } | |
6808d7a1 BA |
1366 | moves1.sort((a, b) => { |
1367 | return (color == "w" ? 1 : -1) * (b.eval - a.eval); | |
1368 | }); | |
b83a675a | 1369 | } |
1c9f093d | 1370 | |
b83a675a | 1371 | let candidates = [0]; |
d54f6261 BA |
1372 | for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++) |
1373 | candidates.push(i); | |
656b1878 | 1374 | return moves1[candidates[randInt(candidates.length)]]; |
1c9f093d BA |
1375 | } |
1376 | ||
6808d7a1 | 1377 | alphabeta(depth, alpha, beta) { |
1c9f093d BA |
1378 | const maxeval = V.INFINITY; |
1379 | const color = this.turn; | |
1380 | const score = this.getCurrentScore(); | |
1381 | if (score != "*") | |
6808d7a1 BA |
1382 | return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval; |
1383 | if (depth == 0) return this.evalPosition(); | |
a97bdbda | 1384 | const moves = this.getAllValidMoves(); |
6808d7a1 BA |
1385 | let v = color == "w" ? -maxeval : maxeval; |
1386 | if (color == "w") { | |
1387 | for (let i = 0; i < moves.length; i++) { | |
1c9f093d | 1388 | this.play(moves[i]); |
6808d7a1 | 1389 | v = Math.max(v, this.alphabeta(depth - 1, alpha, beta)); |
1c9f093d BA |
1390 | this.undo(moves[i]); |
1391 | alpha = Math.max(alpha, v); | |
6808d7a1 | 1392 | if (alpha >= beta) break; //beta cutoff |
1c9f093d | 1393 | } |
1c5bfdf2 | 1394 | } |
6808d7a1 | 1395 | else { |
1c5bfdf2 | 1396 | // color=="b" |
6808d7a1 | 1397 | for (let i = 0; i < moves.length; i++) { |
1c9f093d | 1398 | this.play(moves[i]); |
6808d7a1 | 1399 | v = Math.min(v, this.alphabeta(depth - 1, alpha, beta)); |
1c9f093d BA |
1400 | this.undo(moves[i]); |
1401 | beta = Math.min(beta, v); | |
6808d7a1 | 1402 | if (alpha >= beta) break; //alpha cutoff |
1c9f093d BA |
1403 | } |
1404 | } | |
1405 | return v; | |
1406 | } | |
1407 | ||
6808d7a1 | 1408 | evalPosition() { |
1c9f093d BA |
1409 | let evaluation = 0; |
1410 | // Just count material for now | |
6808d7a1 BA |
1411 | for (let i = 0; i < V.size.x; i++) { |
1412 | for (let j = 0; j < V.size.y; j++) { | |
1413 | if (this.board[i][j] != V.EMPTY) { | |
1414 | const sign = this.getColor(i, j) == "w" ? 1 : -1; | |
1415 | evaluation += sign * V.VALUES[this.getPiece(i, j)]; | |
1c9f093d BA |
1416 | } |
1417 | } | |
1418 | } | |
1419 | return evaluation; | |
1420 | } | |
1421 | ||
1422 | ///////////////////////// | |
1423 | // MOVES + GAME NOTATION | |
1424 | ///////////////////////// | |
1425 | ||
1426 | // Context: just before move is played, turn hasn't changed | |
1427 | // TODO: un-ambiguous notation (switch on piece type, check directions...) | |
6808d7a1 BA |
1428 | getNotation(move) { |
1429 | if (move.appear.length == 2 && move.appear[0].p == V.KING) | |
1cd3e362 | 1430 | // Castle |
6808d7a1 | 1431 | return move.end.y < move.start.y ? "0-0-0" : "0-0"; |
1c9f093d BA |
1432 | |
1433 | // Translate final square | |
1434 | const finalSquare = V.CoordsToSquare(move.end); | |
1435 | ||
1436 | const piece = this.getPiece(move.start.x, move.start.y); | |
6808d7a1 | 1437 | if (piece == V.PAWN) { |
1c9f093d BA |
1438 | // Pawn move |
1439 | let notation = ""; | |
6808d7a1 | 1440 | if (move.vanish.length > move.appear.length) { |
1c9f093d BA |
1441 | // Capture |
1442 | const startColumn = V.CoordToColumn(move.start.y); | |
1443 | notation = startColumn + "x" + finalSquare; | |
78d64531 | 1444 | } |
6808d7a1 BA |
1445 | else notation = finalSquare; |
1446 | if (move.appear.length > 0 && move.appear[0].p != V.PAWN) | |
78d64531 | 1447 | // Promotion |
1c9f093d BA |
1448 | notation += "=" + move.appear[0].p.toUpperCase(); |
1449 | return notation; | |
1450 | } | |
6808d7a1 BA |
1451 | // Piece movement |
1452 | return ( | |
1453 | piece.toUpperCase() + | |
1454 | (move.vanish.length > move.appear.length ? "x" : "") + | |
1455 | finalSquare | |
1456 | ); | |
1457 | } | |
2c5d7b20 BA |
1458 | |
1459 | static GetUnambiguousNotation(move) { | |
1460 | // Machine-readable format with all the informations about the move | |
1461 | return ( | |
1462 | (!!move.start && V.OnBoard(move.start.x, move.start.y) | |
1463 | ? V.CoordsToSquare(move.start) | |
1464 | : "-" | |
1465 | ) + "." + | |
1466 | (!!move.end && V.OnBoard(move.end.x, move.end.y) | |
1467 | ? V.CoordsToSquare(move.end) | |
1468 | : "-" | |
1469 | ) + " " + | |
1470 | (!!move.appear && move.appear.length > 0 | |
1471 | ? move.appear.map(a => | |
1472 | a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".") | |
1473 | : "-" | |
1474 | ) + "/" + | |
1475 | (!!move.vanish && move.vanish.length > 0 | |
1476 | ? move.vanish.map(a => | |
1477 | a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".") | |
1478 | : "-" | |
1479 | ) | |
1480 | ); | |
1481 | } | |
6808d7a1 | 1482 | }; |