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