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