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 BA |
29 | |
30 | // NOTE: x coords = top to bottom; y = left to right (from white player perspective) | |
6808d7a1 | 31 | export const ChessRules = class ChessRules { |
1c9f093d BA |
32 | ////////////// |
33 | // MISC UTILS | |
34 | ||
20620465 | 35 | // Some variants don't have flags: |
6808d7a1 BA |
36 | static get HasFlags() { |
37 | return true; | |
20620465 | 38 | } |
1c9f093d | 39 | |
20620465 | 40 | // Some variants don't have en-passant |
6808d7a1 BA |
41 | static get HasEnpassant() { |
42 | return true; | |
20620465 BA |
43 | } |
44 | ||
45 | // Some variants cannot have analyse mode | |
8477e53d | 46 | static get CanAnalyze() { |
20620465 BA |
47 | return true; |
48 | } | |
49 | ||
50 | // Some variants show incomplete information, | |
51 | // and thus show only a partial moves list or no list at all. | |
52 | static get ShowMoves() { | |
53 | return "all"; | |
54 | } | |
1c9f093d BA |
55 | |
56 | // Path to pieces | |
6808d7a1 | 57 | static getPpath(b) { |
1c9f093d BA |
58 | return b; //usual pieces in pieces/ folder |
59 | } | |
60 | ||
61 | // Turn "wb" into "B" (for FEN) | |
6808d7a1 BA |
62 | static board2fen(b) { |
63 | return b[0] == "w" ? b[1].toUpperCase() : b[1]; | |
1c9f093d BA |
64 | } |
65 | ||
66 | // Turn "p" into "bp" (for board) | |
6808d7a1 BA |
67 | static fen2board(f) { |
68 | return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f; | |
1c9f093d BA |
69 | } |
70 | ||
89021f18 | 71 | // Check if FEN describe a board situation correctly |
6808d7a1 | 72 | static IsGoodFen(fen) { |
1c9f093d BA |
73 | const fenParsed = V.ParseFen(fen); |
74 | // 1) Check position | |
6808d7a1 | 75 | if (!V.IsGoodPosition(fenParsed.position)) return false; |
1c9f093d | 76 | // 2) Check turn |
6808d7a1 | 77 | if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false; |
1c9f093d BA |
78 | // 3) Check moves count |
79 | if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0)) | |
80 | return false; | |
81 | // 4) Check flags | |
82 | if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags))) | |
83 | return false; | |
84 | // 5) Check enpassant | |
6808d7a1 BA |
85 | if ( |
86 | V.HasEnpassant && | |
87 | (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant)) | |
88 | ) { | |
1c9f093d BA |
89 | return false; |
90 | } | |
91 | return true; | |
92 | } | |
93 | ||
94 | // Is position part of the FEN a priori correct? | |
6808d7a1 BA |
95 | static IsGoodPosition(position) { |
96 | if (position.length == 0) return false; | |
1c9f093d | 97 | const rows = position.split("/"); |
6808d7a1 BA |
98 | if (rows.length != V.size.x) return false; |
99 | for (let row of rows) { | |
1c9f093d | 100 | let sumElts = 0; |
6808d7a1 BA |
101 | for (let i = 0; i < row.length; i++) { |
102 | if (V.PIECES.includes(row[i].toLowerCase())) sumElts++; | |
103 | else { | |
1c9f093d | 104 | const num = parseInt(row[i]); |
6808d7a1 | 105 | if (isNaN(num)) return false; |
1c9f093d BA |
106 | sumElts += num; |
107 | } | |
108 | } | |
6808d7a1 | 109 | if (sumElts != V.size.y) return false; |
1c9f093d BA |
110 | } |
111 | return true; | |
112 | } | |
113 | ||
114 | // For FEN checking | |
6808d7a1 BA |
115 | static IsGoodTurn(turn) { |
116 | return ["w", "b"].includes(turn); | |
1c9f093d BA |
117 | } |
118 | ||
119 | // For FEN checking | |
6808d7a1 | 120 | static IsGoodFlags(flags) { |
1c9f093d BA |
121 | return !!flags.match(/^[01]{4,4}$/); |
122 | } | |
123 | ||
6808d7a1 BA |
124 | static IsGoodEnpassant(enpassant) { |
125 | if (enpassant != "-") { | |
126 | const ep = V.SquareToCoords(enpassant); | |
127 | if (isNaN(ep.x) || !V.OnBoard(ep)) return false; | |
1c9f093d BA |
128 | } |
129 | return true; | |
130 | } | |
131 | ||
132 | // 3 --> d (column number to letter) | |
6808d7a1 | 133 | static CoordToColumn(colnum) { |
1c9f093d BA |
134 | return String.fromCharCode(97 + colnum); |
135 | } | |
136 | ||
137 | // d --> 3 (column letter to number) | |
6808d7a1 | 138 | static ColumnToCoord(column) { |
1c9f093d BA |
139 | return column.charCodeAt(0) - 97; |
140 | } | |
141 | ||
142 | // a4 --> {x:3,y:0} | |
6808d7a1 | 143 | static SquareToCoords(sq) { |
1c9f093d BA |
144 | return { |
145 | // NOTE: column is always one char => max 26 columns | |
146 | // row is counted from black side => subtraction | |
147 | x: V.size.x - parseInt(sq.substr(1)), | |
148 | y: sq[0].charCodeAt() - 97 | |
149 | }; | |
150 | } | |
151 | ||
152 | // {x:0,y:4} --> e8 | |
6808d7a1 | 153 | static CoordsToSquare(coords) { |
1c9f093d BA |
154 | return V.CoordToColumn(coords.y) + (V.size.x - coords.x); |
155 | } | |
156 | ||
157 | // Aggregates flags into one object | |
6808d7a1 | 158 | aggregateFlags() { |
1c9f093d BA |
159 | return this.castleFlags; |
160 | } | |
161 | ||
162 | // Reverse operation | |
6808d7a1 | 163 | disaggregateFlags(flags) { |
1c9f093d BA |
164 | this.castleFlags = flags; |
165 | } | |
166 | ||
167 | // En-passant square, if any | |
6808d7a1 BA |
168 | getEpSquare(moveOrSquare) { |
169 | if (!moveOrSquare) return undefined; | |
170 | if (typeof moveOrSquare === "string") { | |
1c9f093d | 171 | const square = moveOrSquare; |
6808d7a1 | 172 | if (square == "-") return undefined; |
1c9f093d BA |
173 | return V.SquareToCoords(square); |
174 | } | |
175 | // Argument is a move: | |
176 | const move = moveOrSquare; | |
6808d7a1 | 177 | const [sx, sy, ex] = [move.start.x, move.start.y, move.end.x]; |
41cb9b94 | 178 | // NOTE: next conditions are first for Atomic, and last for Checkered |
6808d7a1 BA |
179 | if ( |
180 | move.appear.length > 0 && | |
181 | Math.abs(sx - ex) == 2 && | |
182 | move.appear[0].p == V.PAWN && | |
183 | ["w", "b"].includes(move.appear[0].c) | |
184 | ) { | |
1c9f093d | 185 | return { |
6808d7a1 | 186 | x: (sx + ex) / 2, |
1c9f093d BA |
187 | y: sy |
188 | }; | |
189 | } | |
190 | return undefined; //default | |
191 | } | |
192 | ||
193 | // Can thing on square1 take thing on square2 | |
6808d7a1 BA |
194 | canTake([x1, y1], [x2, y2]) { |
195 | return this.getColor(x1, y1) !== this.getColor(x2, y2); | |
1c9f093d BA |
196 | } |
197 | ||
198 | // Is (x,y) on the chessboard? | |
6808d7a1 BA |
199 | static OnBoard(x, y) { |
200 | return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y; | |
1c9f093d BA |
201 | } |
202 | ||
203 | // Used in interface: 'side' arg == player color | |
6808d7a1 BA |
204 | canIplay(side, [x, y]) { |
205 | return this.turn == side && this.getColor(x, y) == side; | |
1c9f093d BA |
206 | } |
207 | ||
208 | // On which squares is color under check ? (for interface) | |
6808d7a1 | 209 | getCheckSquares(color) { |
1c9f093d BA |
210 | return this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]) |
211 | ? [JSON.parse(JSON.stringify(this.kingPos[color]))] //need to duplicate! | |
212 | : []; | |
213 | } | |
214 | ||
215 | ///////////// | |
216 | // FEN UTILS | |
217 | ||
218 | // Setup the initial random (assymetric) position | |
6808d7a1 BA |
219 | static GenRandInitFen() { |
220 | let pieces = { w: new Array(8), b: new Array(8) }; | |
1c9f093d | 221 | // Shuffle pieces on first and last rank |
6808d7a1 | 222 | for (let c of ["w", "b"]) { |
1c9f093d BA |
223 | let positions = ArrayFun.range(8); |
224 | ||
225 | // Get random squares for bishops | |
656b1878 | 226 | let randIndex = 2 * randInt(4); |
1c9f093d BA |
227 | const bishop1Pos = positions[randIndex]; |
228 | // The second bishop must be on a square of different color | |
656b1878 | 229 | let randIndex_tmp = 2 * randInt(4) + 1; |
1c9f093d BA |
230 | const bishop2Pos = positions[randIndex_tmp]; |
231 | // Remove chosen squares | |
6808d7a1 BA |
232 | positions.splice(Math.max(randIndex, randIndex_tmp), 1); |
233 | positions.splice(Math.min(randIndex, randIndex_tmp), 1); | |
1c9f093d BA |
234 | |
235 | // Get random squares for knights | |
656b1878 | 236 | randIndex = randInt(6); |
1c9f093d BA |
237 | const knight1Pos = positions[randIndex]; |
238 | positions.splice(randIndex, 1); | |
656b1878 | 239 | randIndex = randInt(5); |
1c9f093d BA |
240 | const knight2Pos = positions[randIndex]; |
241 | positions.splice(randIndex, 1); | |
242 | ||
243 | // Get random square for queen | |
656b1878 | 244 | randIndex = randInt(4); |
1c9f093d BA |
245 | const queenPos = positions[randIndex]; |
246 | positions.splice(randIndex, 1); | |
247 | ||
248 | // Rooks and king positions are now fixed, | |
249 | // because of the ordering rook-king-rook | |
250 | const rook1Pos = positions[0]; | |
251 | const kingPos = positions[1]; | |
252 | const rook2Pos = positions[2]; | |
253 | ||
254 | // Finally put the shuffled pieces in the board array | |
6808d7a1 BA |
255 | pieces[c][rook1Pos] = "r"; |
256 | pieces[c][knight1Pos] = "n"; | |
257 | pieces[c][bishop1Pos] = "b"; | |
258 | pieces[c][queenPos] = "q"; | |
259 | pieces[c][kingPos] = "k"; | |
260 | pieces[c][bishop2Pos] = "b"; | |
261 | pieces[c][knight2Pos] = "n"; | |
262 | pieces[c][rook2Pos] = "r"; | |
1c9f093d | 263 | } |
6808d7a1 BA |
264 | return ( |
265 | pieces["b"].join("") + | |
1c9f093d BA |
266 | "/pppppppp/8/8/8/8/PPPPPPPP/" + |
267 | pieces["w"].join("").toUpperCase() + | |
6808d7a1 BA |
268 | " w 0 1111 -" |
269 | ); //add turn + flags + enpassant | |
1c9f093d BA |
270 | } |
271 | ||
272 | // "Parse" FEN: just return untransformed string data | |
6808d7a1 | 273 | static ParseFen(fen) { |
1c9f093d | 274 | const fenParts = fen.split(" "); |
6808d7a1 | 275 | let res = { |
1c9f093d BA |
276 | position: fenParts[0], |
277 | turn: fenParts[1], | |
6808d7a1 | 278 | movesCount: fenParts[2] |
1c9f093d BA |
279 | }; |
280 | let nextIdx = 3; | |
6808d7a1 BA |
281 | if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] }); |
282 | if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] }); | |
1c9f093d BA |
283 | return res; |
284 | } | |
285 | ||
286 | // Return current fen (game state) | |
6808d7a1 BA |
287 | getFen() { |
288 | return ( | |
289 | this.getBaseFen() + | |
290 | " " + | |
291 | this.getTurnFen() + | |
292 | " " + | |
293 | this.movesCount + | |
294 | (V.HasFlags ? " " + this.getFlagsFen() : "") + | |
295 | (V.HasEnpassant ? " " + this.getEnpassantFen() : "") | |
296 | ); | |
1c9f093d BA |
297 | } |
298 | ||
299 | // Position part of the FEN string | |
6808d7a1 | 300 | getBaseFen() { |
1c9f093d | 301 | let position = ""; |
6808d7a1 | 302 | for (let i = 0; i < V.size.x; i++) { |
1c9f093d | 303 | let emptyCount = 0; |
6808d7a1 BA |
304 | for (let j = 0; j < V.size.y; j++) { |
305 | if (this.board[i][j] == V.EMPTY) emptyCount++; | |
306 | else { | |
307 | if (emptyCount > 0) { | |
1c9f093d BA |
308 | // Add empty squares in-between |
309 | position += emptyCount; | |
310 | emptyCount = 0; | |
311 | } | |
312 | position += V.board2fen(this.board[i][j]); | |
313 | } | |
314 | } | |
6808d7a1 | 315 | if (emptyCount > 0) { |
1c9f093d BA |
316 | // "Flush remainder" |
317 | position += emptyCount; | |
318 | } | |
6808d7a1 | 319 | if (i < V.size.x - 1) position += "/"; //separate rows |
1c9f093d BA |
320 | } |
321 | return position; | |
322 | } | |
323 | ||
6808d7a1 | 324 | getTurnFen() { |
1c9f093d BA |
325 | return this.turn; |
326 | } | |
327 | ||
328 | // Flags part of the FEN string | |
6808d7a1 | 329 | getFlagsFen() { |
1c9f093d BA |
330 | let flags = ""; |
331 | // Add castling flags | |
6808d7a1 BA |
332 | for (let i of ["w", "b"]) { |
333 | for (let j = 0; j < 2; j++) flags += this.castleFlags[i][j] ? "1" : "0"; | |
1c9f093d BA |
334 | } |
335 | return flags; | |
336 | } | |
337 | ||
338 | // Enpassant part of the FEN string | |
6808d7a1 | 339 | getEnpassantFen() { |
1c9f093d | 340 | const L = this.epSquares.length; |
6808d7a1 BA |
341 | if (!this.epSquares[L - 1]) return "-"; //no en-passant |
342 | return V.CoordsToSquare(this.epSquares[L - 1]); | |
1c9f093d BA |
343 | } |
344 | ||
345 | // Turn position fen into double array ["wb","wp","bk",...] | |
6808d7a1 | 346 | static GetBoard(position) { |
1c9f093d BA |
347 | const rows = position.split("/"); |
348 | let board = ArrayFun.init(V.size.x, V.size.y, ""); | |
6808d7a1 | 349 | for (let i = 0; i < rows.length; i++) { |
1c9f093d | 350 | let j = 0; |
6808d7a1 | 351 | for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) { |
1c9f093d BA |
352 | const character = rows[i][indexInRow]; |
353 | const num = parseInt(character); | |
6808d7a1 BA |
354 | if (!isNaN(num)) j += num; |
355 | //just shift j | |
356 | //something at position i,j | |
357 | else board[i][j++] = V.fen2board(character); | |
1c9f093d BA |
358 | } |
359 | } | |
360 | return board; | |
361 | } | |
362 | ||
363 | // Extract (relevant) flags from fen | |
6808d7a1 | 364 | setFlags(fenflags) { |
1c9f093d | 365 | // white a-castle, h-castle, black a-castle, h-castle |
6808d7a1 BA |
366 | this.castleFlags = { w: [true, true], b: [true, true] }; |
367 | if (!fenflags) return; | |
368 | for (let i = 0; i < 4; i++) | |
369 | this.castleFlags[i < 2 ? "w" : "b"][i % 2] = fenflags.charAt(i) == "1"; | |
1c9f093d BA |
370 | } |
371 | ||
372 | ////////////////// | |
373 | // INITIALIZATION | |
374 | ||
6808d7a1 | 375 | constructor(fen) { |
37cdcbf3 BA |
376 | this.re_init(fen); |
377 | } | |
378 | ||
379 | // Fen string fully describes the game state | |
6808d7a1 | 380 | re_init(fen) { |
1c9f093d BA |
381 | const fenParsed = V.ParseFen(fen); |
382 | this.board = V.GetBoard(fenParsed.position); | |
383 | this.turn = fenParsed.turn[0]; //[0] to work with MarseilleRules | |
384 | this.movesCount = parseInt(fenParsed.movesCount); | |
385 | this.setOtherVariables(fen); | |
386 | } | |
387 | ||
388 | // Scan board for kings and rooks positions | |
6808d7a1 BA |
389 | scanKingsRooks(fen) { |
390 | this.INIT_COL_KING = { w: -1, b: -1 }; | |
391 | this.INIT_COL_ROOK = { w: [-1, -1], b: [-1, -1] }; | |
392 | this.kingPos = { w: [-1, -1], b: [-1, -1] }; //squares of white and black king | |
1c9f093d | 393 | const fenRows = V.ParseFen(fen).position.split("/"); |
6808d7a1 | 394 | for (let i = 0; i < fenRows.length; i++) { |
1c9f093d | 395 | let k = 0; //column index on board |
6808d7a1 BA |
396 | for (let j = 0; j < fenRows[i].length; j++) { |
397 | switch (fenRows[i].charAt(j)) { | |
398 | case "k": | |
399 | this.kingPos["b"] = [i, k]; | |
400 | this.INIT_COL_KING["b"] = k; | |
1c9f093d | 401 | break; |
6808d7a1 BA |
402 | case "K": |
403 | this.kingPos["w"] = [i, k]; | |
404 | this.INIT_COL_KING["w"] = k; | |
1c9f093d | 405 | break; |
6808d7a1 BA |
406 | case "r": |
407 | if (this.INIT_COL_ROOK["b"][0] < 0) this.INIT_COL_ROOK["b"][0] = k; | |
408 | else this.INIT_COL_ROOK["b"][1] = k; | |
1c9f093d | 409 | break; |
6808d7a1 BA |
410 | case "R": |
411 | if (this.INIT_COL_ROOK["w"][0] < 0) this.INIT_COL_ROOK["w"][0] = k; | |
412 | else this.INIT_COL_ROOK["w"][1] = k; | |
1c9f093d | 413 | break; |
6808d7a1 | 414 | default: { |
1c9f093d | 415 | const num = parseInt(fenRows[i].charAt(j)); |
6808d7a1 BA |
416 | if (!isNaN(num)) k += num - 1; |
417 | } | |
1c9f093d BA |
418 | } |
419 | k++; | |
420 | } | |
421 | } | |
422 | } | |
423 | ||
424 | // Some additional variables from FEN (variant dependant) | |
6808d7a1 | 425 | setOtherVariables(fen) { |
1c9f093d BA |
426 | // Set flags and enpassant: |
427 | const parsedFen = V.ParseFen(fen); | |
6808d7a1 BA |
428 | if (V.HasFlags) this.setFlags(parsedFen.flags); |
429 | if (V.HasEnpassant) { | |
430 | const epSq = | |
431 | parsedFen.enpassant != "-" | |
432 | ? V.SquareToCoords(parsedFen.enpassant) | |
433 | : undefined; | |
434 | this.epSquares = [epSq]; | |
1c9f093d BA |
435 | } |
436 | // Search for king and rooks positions: | |
437 | this.scanKingsRooks(fen); | |
438 | } | |
439 | ||
440 | ///////////////////// | |
441 | // GETTERS & SETTERS | |
442 | ||
6808d7a1 BA |
443 | static get size() { |
444 | return { x: 8, y: 8 }; | |
1c9f093d BA |
445 | } |
446 | ||
447 | // Color of thing on suqare (i,j). 'undefined' if square is empty | |
6808d7a1 | 448 | getColor(i, j) { |
1c9f093d BA |
449 | return this.board[i][j].charAt(0); |
450 | } | |
451 | ||
452 | // Piece type on square (i,j). 'undefined' if square is empty | |
6808d7a1 | 453 | getPiece(i, j) { |
1c9f093d BA |
454 | return this.board[i][j].charAt(1); |
455 | } | |
456 | ||
457 | // Get opponent color | |
6808d7a1 BA |
458 | static GetOppCol(color) { |
459 | return color == "w" ? "b" : "w"; | |
1c9f093d BA |
460 | } |
461 | ||
1c9f093d | 462 | // Pieces codes (for a clearer code) |
6808d7a1 BA |
463 | static get PAWN() { |
464 | return "p"; | |
465 | } | |
466 | static get ROOK() { | |
467 | return "r"; | |
468 | } | |
469 | static get KNIGHT() { | |
470 | return "n"; | |
471 | } | |
472 | static get BISHOP() { | |
473 | return "b"; | |
474 | } | |
475 | static get QUEEN() { | |
476 | return "q"; | |
477 | } | |
478 | static get KING() { | |
479 | return "k"; | |
480 | } | |
1c9f093d BA |
481 | |
482 | // For FEN checking: | |
6808d7a1 BA |
483 | static get PIECES() { |
484 | return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING]; | |
1c9f093d BA |
485 | } |
486 | ||
487 | // Empty square | |
6808d7a1 BA |
488 | static get EMPTY() { |
489 | return ""; | |
490 | } | |
1c9f093d BA |
491 | |
492 | // Some pieces movements | |
6808d7a1 | 493 | static get steps() { |
1c9f093d | 494 | return { |
6808d7a1 BA |
495 | r: [ |
496 | [-1, 0], | |
497 | [1, 0], | |
498 | [0, -1], | |
499 | [0, 1] | |
500 | ], | |
501 | n: [ | |
502 | [-1, -2], | |
503 | [-1, 2], | |
504 | [1, -2], | |
505 | [1, 2], | |
506 | [-2, -1], | |
507 | [-2, 1], | |
508 | [2, -1], | |
509 | [2, 1] | |
510 | ], | |
511 | b: [ | |
512 | [-1, -1], | |
513 | [-1, 1], | |
514 | [1, -1], | |
515 | [1, 1] | |
516 | ] | |
1c9f093d BA |
517 | }; |
518 | } | |
519 | ||
520 | //////////////////// | |
521 | // MOVES GENERATION | |
522 | ||
523 | // All possible moves from selected square (assumption: color is OK) | |
6808d7a1 BA |
524 | getPotentialMovesFrom([x, y]) { |
525 | switch (this.getPiece(x, y)) { | |
1c9f093d | 526 | case V.PAWN: |
6808d7a1 | 527 | return this.getPotentialPawnMoves([x, y]); |
1c9f093d | 528 | case V.ROOK: |
6808d7a1 | 529 | return this.getPotentialRookMoves([x, y]); |
1c9f093d | 530 | case V.KNIGHT: |
6808d7a1 | 531 | return this.getPotentialKnightMoves([x, y]); |
1c9f093d | 532 | case V.BISHOP: |
6808d7a1 | 533 | return this.getPotentialBishopMoves([x, y]); |
1c9f093d | 534 | case V.QUEEN: |
6808d7a1 | 535 | return this.getPotentialQueenMoves([x, y]); |
1c9f093d | 536 | case V.KING: |
6808d7a1 | 537 | return this.getPotentialKingMoves([x, y]); |
1c9f093d | 538 | } |
6808d7a1 | 539 | return []; //never reached |
1c9f093d BA |
540 | } |
541 | ||
542 | // Build a regular move from its initial and destination squares. | |
543 | // tr: transformation | |
6808d7a1 | 544 | getBasicMove([sx, sy], [ex, ey], tr) { |
1c9f093d BA |
545 | let mv = new Move({ |
546 | appear: [ | |
547 | new PiPo({ | |
548 | x: ex, | |
549 | y: ey, | |
6808d7a1 BA |
550 | c: tr ? tr.c : this.getColor(sx, sy), |
551 | p: tr ? tr.p : this.getPiece(sx, sy) | |
1c9f093d BA |
552 | }) |
553 | ], | |
554 | vanish: [ | |
555 | new PiPo({ | |
556 | x: sx, | |
557 | y: sy, | |
6808d7a1 BA |
558 | c: this.getColor(sx, sy), |
559 | p: this.getPiece(sx, sy) | |
1c9f093d BA |
560 | }) |
561 | ] | |
562 | }); | |
563 | ||
564 | // The opponent piece disappears if we take it | |
6808d7a1 | 565 | if (this.board[ex][ey] != V.EMPTY) { |
1c9f093d BA |
566 | mv.vanish.push( |
567 | new PiPo({ | |
568 | x: ex, | |
569 | y: ey, | |
6808d7a1 BA |
570 | c: this.getColor(ex, ey), |
571 | p: this.getPiece(ex, ey) | |
1c9f093d BA |
572 | }) |
573 | ); | |
574 | } | |
575 | return mv; | |
576 | } | |
577 | ||
578 | // Generic method to find possible moves of non-pawn pieces: | |
579 | // "sliding or jumping" | |
6808d7a1 | 580 | getSlideNJumpMoves([x, y], steps, oneStep) { |
1c9f093d | 581 | let moves = []; |
6808d7a1 | 582 | outerLoop: for (let step of steps) { |
1c9f093d BA |
583 | let i = x + step[0]; |
584 | let j = y + step[1]; | |
6808d7a1 BA |
585 | while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) { |
586 | moves.push(this.getBasicMove([x, y], [i, j])); | |
587 | if (oneStep !== undefined) continue outerLoop; | |
1c9f093d BA |
588 | i += step[0]; |
589 | j += step[1]; | |
590 | } | |
6808d7a1 BA |
591 | if (V.OnBoard(i, j) && this.canTake([x, y], [i, j])) |
592 | moves.push(this.getBasicMove([x, y], [i, j])); | |
1c9f093d BA |
593 | } |
594 | return moves; | |
595 | } | |
596 | ||
597 | // What are the pawn moves from square x,y ? | |
6808d7a1 | 598 | getPotentialPawnMoves([x, y]) { |
1c9f093d BA |
599 | const color = this.turn; |
600 | let moves = []; | |
6808d7a1 BA |
601 | const [sizeX, sizeY] = [V.size.x, V.size.y]; |
602 | const shiftX = color == "w" ? -1 : 1; | |
603 | const firstRank = color == "w" ? sizeX - 1 : 0; | |
604 | const startRank = color == "w" ? sizeX - 2 : 1; | |
605 | const lastRank = color == "w" ? 0 : sizeX - 1; | |
606 | const pawnColor = this.getColor(x, y); //can be different for checkered | |
1c9f093d BA |
607 | |
608 | // NOTE: next condition is generally true (no pawn on last rank) | |
6808d7a1 BA |
609 | if (x + shiftX >= 0 && x + shiftX < sizeX) { |
610 | const finalPieces = | |
611 | x + shiftX == lastRank | |
612 | ? [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN] | |
613 | : [V.PAWN]; | |
1c9f093d | 614 | // One square forward |
6808d7a1 BA |
615 | if (this.board[x + shiftX][y] == V.EMPTY) { |
616 | for (let piece of finalPieces) { | |
617 | moves.push( | |
618 | this.getBasicMove([x, y], [x + shiftX, y], { | |
619 | c: pawnColor, | |
620 | p: piece | |
621 | }) | |
622 | ); | |
1c9f093d BA |
623 | } |
624 | // Next condition because pawns on 1st rank can generally jump | |
6808d7a1 BA |
625 | if ( |
626 | [startRank, firstRank].includes(x) && | |
627 | this.board[x + 2 * shiftX][y] == V.EMPTY | |
628 | ) { | |
1c9f093d | 629 | // Two squares jump |
6808d7a1 | 630 | moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y])); |
1c9f093d BA |
631 | } |
632 | } | |
633 | // Captures | |
6808d7a1 BA |
634 | for (let shiftY of [-1, 1]) { |
635 | if ( | |
636 | y + shiftY >= 0 && | |
637 | y + shiftY < sizeY && | |
638 | this.board[x + shiftX][y + shiftY] != V.EMPTY && | |
639 | this.canTake([x, y], [x + shiftX, y + shiftY]) | |
640 | ) { | |
641 | for (let piece of finalPieces) { | |
642 | moves.push( | |
643 | this.getBasicMove([x, y], [x + shiftX, y + shiftY], { | |
644 | c: pawnColor, | |
645 | p: piece | |
646 | }) | |
647 | ); | |
1c9f093d BA |
648 | } |
649 | } | |
650 | } | |
651 | } | |
652 | ||
6808d7a1 | 653 | if (V.HasEnpassant) { |
1c9f093d BA |
654 | // En passant |
655 | const Lep = this.epSquares.length; | |
6808d7a1 BA |
656 | const epSquare = this.epSquares[Lep - 1]; //always at least one element |
657 | if ( | |
658 | !!epSquare && | |
659 | epSquare.x == x + shiftX && | |
660 | Math.abs(epSquare.y - y) == 1 | |
661 | ) { | |
662 | let enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]); | |
1c9f093d BA |
663 | enpassantMove.vanish.push({ |
664 | x: x, | |
665 | y: epSquare.y, | |
6808d7a1 BA |
666 | p: "p", |
667 | c: this.getColor(x, epSquare.y) | |
1c9f093d BA |
668 | }); |
669 | moves.push(enpassantMove); | |
670 | } | |
671 | } | |
672 | ||
673 | return moves; | |
674 | } | |
675 | ||
676 | // What are the rook moves from square x,y ? | |
6808d7a1 | 677 | getPotentialRookMoves(sq) { |
1c9f093d BA |
678 | return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]); |
679 | } | |
680 | ||
681 | // What are the knight moves from square x,y ? | |
6808d7a1 | 682 | getPotentialKnightMoves(sq) { |
1c9f093d BA |
683 | return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep"); |
684 | } | |
685 | ||
686 | // What are the bishop moves from square x,y ? | |
6808d7a1 | 687 | getPotentialBishopMoves(sq) { |
1c9f093d BA |
688 | return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]); |
689 | } | |
690 | ||
691 | // What are the queen moves from square x,y ? | |
6808d7a1 BA |
692 | getPotentialQueenMoves(sq) { |
693 | return this.getSlideNJumpMoves( | |
694 | sq, | |
695 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]) | |
696 | ); | |
1c9f093d BA |
697 | } |
698 | ||
699 | // What are the king moves from square x,y ? | |
6808d7a1 | 700 | getPotentialKingMoves(sq) { |
1c9f093d | 701 | // Initialize with normal moves |
6808d7a1 BA |
702 | let moves = this.getSlideNJumpMoves( |
703 | sq, | |
704 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), | |
705 | "oneStep" | |
706 | ); | |
1c9f093d BA |
707 | return moves.concat(this.getCastleMoves(sq)); |
708 | } | |
709 | ||
6808d7a1 BA |
710 | getCastleMoves([x, y]) { |
711 | const c = this.getColor(x, y); | |
712 | if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c]) | |
1c9f093d BA |
713 | return []; //x isn't first rank, or king has moved (shortcut) |
714 | ||
715 | // Castling ? | |
716 | const oppCol = V.GetOppCol(c); | |
717 | let moves = []; | |
718 | let i = 0; | |
6808d7a1 BA |
719 | const finalSquares = [ |
720 | [2, 3], | |
721 | [V.size.y - 2, V.size.y - 3] | |
722 | ]; //king, then rook | |
723 | castlingCheck: for ( | |
724 | let castleSide = 0; | |
725 | castleSide < 2; | |
726 | castleSide++ //large, then small | |
727 | ) { | |
728 | if (!this.castleFlags[c][castleSide]) continue; | |
1c9f093d BA |
729 | // If this code is reached, rooks and king are on initial position |
730 | ||
2beba6db BA |
731 | // Nothing on the path of the king ? (and no checks) |
732 | const finDist = finalSquares[castleSide][0] - y; | |
733 | let step = finDist / Math.max(1, Math.abs(finDist)); | |
734 | i = y; | |
6808d7a1 BA |
735 | do { |
736 | if ( | |
737 | this.isAttacked([x, i], [oppCol]) || | |
738 | (this.board[x][i] != V.EMPTY && | |
739 | // NOTE: next check is enough, because of chessboard constraints | |
740 | (this.getColor(x, i) != c || | |
741 | ![V.KING, V.ROOK].includes(this.getPiece(x, i)))) | |
742 | ) { | |
1c9f093d BA |
743 | continue castlingCheck; |
744 | } | |
2beba6db | 745 | i += step; |
6808d7a1 | 746 | } while (i != finalSquares[castleSide][0]); |
1c9f093d BA |
747 | |
748 | // Nothing on the path to the rook? | |
6808d7a1 BA |
749 | step = castleSide == 0 ? -1 : 1; |
750 | for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step) { | |
751 | if (this.board[x][i] != V.EMPTY) continue castlingCheck; | |
1c9f093d BA |
752 | } |
753 | const rookPos = this.INIT_COL_ROOK[c][castleSide]; | |
754 | ||
755 | // Nothing on final squares, except maybe king and castling rook? | |
6808d7a1 BA |
756 | for (i = 0; i < 2; i++) { |
757 | if ( | |
758 | this.board[x][finalSquares[castleSide][i]] != V.EMPTY && | |
759 | this.getPiece(x, finalSquares[castleSide][i]) != V.KING && | |
760 | finalSquares[castleSide][i] != rookPos | |
761 | ) { | |
1c9f093d BA |
762 | continue castlingCheck; |
763 | } | |
764 | } | |
765 | ||
766 | // If this code is reached, castle is valid | |
6808d7a1 BA |
767 | moves.push( |
768 | new Move({ | |
769 | appear: [ | |
770 | new PiPo({ x: x, y: finalSquares[castleSide][0], p: V.KING, c: c }), | |
771 | new PiPo({ x: x, y: finalSquares[castleSide][1], p: V.ROOK, c: c }) | |
772 | ], | |
773 | vanish: [ | |
774 | new PiPo({ x: x, y: y, p: V.KING, c: c }), | |
775 | new PiPo({ x: x, y: rookPos, p: V.ROOK, c: c }) | |
776 | ], | |
777 | end: | |
778 | Math.abs(y - rookPos) <= 2 | |
779 | ? { x: x, y: rookPos } | |
780 | : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) } | |
781 | }) | |
782 | ); | |
1c9f093d BA |
783 | } |
784 | ||
785 | return moves; | |
786 | } | |
787 | ||
788 | //////////////////// | |
789 | // MOVES VALIDATION | |
790 | ||
791 | // For the interface: possible moves for the current turn from square sq | |
6808d7a1 BA |
792 | getPossibleMovesFrom(sq) { |
793 | return this.filterValid(this.getPotentialMovesFrom(sq)); | |
1c9f093d BA |
794 | } |
795 | ||
796 | // TODO: promotions (into R,B,N,Q) should be filtered only once | |
6808d7a1 BA |
797 | filterValid(moves) { |
798 | if (moves.length == 0) return []; | |
1c9f093d BA |
799 | const color = this.turn; |
800 | return moves.filter(m => { | |
801 | this.play(m); | |
802 | const res = !this.underCheck(color); | |
803 | this.undo(m); | |
804 | return res; | |
805 | }); | |
806 | } | |
807 | ||
808 | // Search for all valid moves considering current turn | |
809 | // (for engine and game end) | |
6808d7a1 | 810 | getAllValidMoves() { |
1c9f093d BA |
811 | const color = this.turn; |
812 | const oppCol = V.GetOppCol(color); | |
813 | let potentialMoves = []; | |
6808d7a1 BA |
814 | for (let i = 0; i < V.size.x; i++) { |
815 | for (let j = 0; j < V.size.y; j++) { | |
1c9f093d | 816 | // Next condition "!= oppCol" to work with checkered variant |
6808d7a1 BA |
817 | if (this.board[i][j] != V.EMPTY && this.getColor(i, j) != oppCol) { |
818 | Array.prototype.push.apply( | |
819 | potentialMoves, | |
820 | this.getPotentialMovesFrom([i, j]) | |
821 | ); | |
1c9f093d BA |
822 | } |
823 | } | |
824 | } | |
825 | return this.filterValid(potentialMoves); | |
826 | } | |
827 | ||
828 | // Stop at the first move found | |
6808d7a1 | 829 | atLeastOneMove() { |
1c9f093d BA |
830 | const color = this.turn; |
831 | const oppCol = V.GetOppCol(color); | |
6808d7a1 BA |
832 | for (let i = 0; i < V.size.x; i++) { |
833 | for (let j = 0; j < V.size.y; j++) { | |
834 | if (this.board[i][j] != V.EMPTY && this.getColor(i, j) != oppCol) { | |
835 | const moves = this.getPotentialMovesFrom([i, j]); | |
836 | if (moves.length > 0) { | |
837 | for (let k = 0; k < moves.length; k++) { | |
838 | if (this.filterValid([moves[k]]).length > 0) return true; | |
1c9f093d BA |
839 | } |
840 | } | |
841 | } | |
842 | } | |
843 | } | |
844 | return false; | |
845 | } | |
846 | ||
847 | // Check if pieces of color in 'colors' are attacking (king) on square x,y | |
6808d7a1 BA |
848 | isAttacked(sq, colors) { |
849 | return ( | |
850 | this.isAttackedByPawn(sq, colors) || | |
851 | this.isAttackedByRook(sq, colors) || | |
852 | this.isAttackedByKnight(sq, colors) || | |
853 | this.isAttackedByBishop(sq, colors) || | |
854 | this.isAttackedByQueen(sq, colors) || | |
855 | this.isAttackedByKing(sq, colors) | |
856 | ); | |
1c9f093d BA |
857 | } |
858 | ||
859 | // Is square x,y attacked by 'colors' pawns ? | |
6808d7a1 BA |
860 | isAttackedByPawn([x, y], colors) { |
861 | for (let c of colors) { | |
862 | let pawnShift = c == "w" ? 1 : -1; | |
863 | if (x + pawnShift >= 0 && x + pawnShift < V.size.x) { | |
864 | for (let i of [-1, 1]) { | |
865 | if ( | |
866 | y + i >= 0 && | |
867 | y + i < V.size.y && | |
868 | this.getPiece(x + pawnShift, y + i) == V.PAWN && | |
869 | this.getColor(x + pawnShift, y + i) == c | |
870 | ) { | |
1c9f093d BA |
871 | return true; |
872 | } | |
873 | } | |
874 | } | |
875 | } | |
876 | return false; | |
877 | } | |
878 | ||
879 | // Is square x,y attacked by 'colors' rooks ? | |
6808d7a1 | 880 | isAttackedByRook(sq, colors) { |
1c9f093d BA |
881 | return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]); |
882 | } | |
883 | ||
884 | // Is square x,y attacked by 'colors' knights ? | |
6808d7a1 BA |
885 | isAttackedByKnight(sq, colors) { |
886 | return this.isAttackedBySlideNJump( | |
887 | sq, | |
888 | colors, | |
889 | V.KNIGHT, | |
890 | V.steps[V.KNIGHT], | |
891 | "oneStep" | |
892 | ); | |
1c9f093d BA |
893 | } |
894 | ||
895 | // Is square x,y attacked by 'colors' bishops ? | |
6808d7a1 | 896 | isAttackedByBishop(sq, colors) { |
1c9f093d BA |
897 | return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]); |
898 | } | |
899 | ||
900 | // Is square x,y attacked by 'colors' queens ? | |
6808d7a1 BA |
901 | isAttackedByQueen(sq, colors) { |
902 | return this.isAttackedBySlideNJump( | |
903 | sq, | |
904 | colors, | |
905 | V.QUEEN, | |
906 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]) | |
907 | ); | |
1c9f093d BA |
908 | } |
909 | ||
910 | // Is square x,y attacked by 'colors' king(s) ? | |
6808d7a1 BA |
911 | isAttackedByKing(sq, colors) { |
912 | return this.isAttackedBySlideNJump( | |
913 | sq, | |
914 | colors, | |
915 | V.KING, | |
916 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), | |
917 | "oneStep" | |
918 | ); | |
1c9f093d BA |
919 | } |
920 | ||
921 | // Generic method for non-pawn pieces ("sliding or jumping"): | |
922 | // is x,y attacked by a piece of color in array 'colors' ? | |
6808d7a1 BA |
923 | isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) { |
924 | for (let step of steps) { | |
925 | let rx = x + step[0], | |
926 | ry = y + step[1]; | |
927 | while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) { | |
1c9f093d BA |
928 | rx += step[0]; |
929 | ry += step[1]; | |
930 | } | |
6808d7a1 BA |
931 | if ( |
932 | V.OnBoard(rx, ry) && | |
933 | this.getPiece(rx, ry) === piece && | |
934 | colors.includes(this.getColor(rx, ry)) | |
935 | ) { | |
1c9f093d BA |
936 | return true; |
937 | } | |
938 | } | |
939 | return false; | |
940 | } | |
941 | ||
942 | // Is color under check after his move ? | |
6808d7a1 | 943 | underCheck(color) { |
1c9f093d BA |
944 | return this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]); |
945 | } | |
946 | ||
947 | ///////////////// | |
948 | // MOVES PLAYING | |
949 | ||
950 | // Apply a move on board | |
6808d7a1 BA |
951 | static PlayOnBoard(board, move) { |
952 | for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY; | |
953 | for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p; | |
1c9f093d BA |
954 | } |
955 | // Un-apply the played move | |
6808d7a1 BA |
956 | static UndoOnBoard(board, move) { |
957 | for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY; | |
958 | for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p; | |
1c9f093d BA |
959 | } |
960 | ||
961 | // After move is played, update variables + flags | |
6808d7a1 | 962 | updateVariables(move) { |
1c9f093d BA |
963 | let piece = undefined; |
964 | let c = undefined; | |
6808d7a1 | 965 | if (move.vanish.length >= 1) { |
1c9f093d BA |
966 | // Usual case, something is moved |
967 | piece = move.vanish[0].p; | |
968 | c = move.vanish[0].c; | |
6808d7a1 | 969 | } else { |
1c9f093d BA |
970 | // Crazyhouse-like variants |
971 | piece = move.appear[0].p; | |
972 | c = move.appear[0].c; | |
973 | } | |
6808d7a1 BA |
974 | if (c == "c") { |
975 | //if (!["w","b"].includes(c)) | |
1c9f093d BA |
976 | // 'c = move.vanish[0].c' doesn't work for Checkered |
977 | c = V.GetOppCol(this.turn); | |
978 | } | |
6808d7a1 | 979 | const firstRank = c == "w" ? V.size.x - 1 : 0; |
1c9f093d BA |
980 | |
981 | // Update king position + flags | |
6808d7a1 | 982 | if (piece == V.KING && move.appear.length > 0) { |
1c9f093d BA |
983 | this.kingPos[c][0] = move.appear[0].x; |
984 | this.kingPos[c][1] = move.appear[0].y; | |
6808d7a1 | 985 | if (V.HasFlags) this.castleFlags[c] = [false, false]; |
1c9f093d BA |
986 | return; |
987 | } | |
6808d7a1 | 988 | if (V.HasFlags) { |
1c9f093d BA |
989 | // Update castling flags if rooks are moved |
990 | const oppCol = V.GetOppCol(c); | |
6808d7a1 BA |
991 | const oppFirstRank = V.size.x - 1 - firstRank; |
992 | if ( | |
993 | move.start.x == firstRank && //our rook moves? | |
994 | this.INIT_COL_ROOK[c].includes(move.start.y) | |
995 | ) { | |
996 | const flagIdx = move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1; | |
1c9f093d | 997 | this.castleFlags[c][flagIdx] = false; |
6808d7a1 BA |
998 | } else if ( |
999 | move.end.x == oppFirstRank && //we took opponent rook? | |
1000 | this.INIT_COL_ROOK[oppCol].includes(move.end.y) | |
1001 | ) { | |
1002 | const flagIdx = move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1; | |
1c9f093d BA |
1003 | this.castleFlags[oppCol][flagIdx] = false; |
1004 | } | |
1005 | } | |
1006 | } | |
1007 | ||
1008 | // After move is undo-ed *and flags resetted*, un-update other variables | |
1009 | // TODO: more symmetry, by storing flags increment in move (?!) | |
6808d7a1 | 1010 | unupdateVariables(move) { |
1c9f093d | 1011 | // (Potentially) Reset king position |
6808d7a1 BA |
1012 | const c = this.getColor(move.start.x, move.start.y); |
1013 | if (this.getPiece(move.start.x, move.start.y) == V.KING) | |
1c9f093d BA |
1014 | this.kingPos[c] = [move.start.x, move.start.y]; |
1015 | } | |
1016 | ||
6808d7a1 | 1017 | play(move) { |
1c9f093d | 1018 | // DEBUG: |
6808d7a1 BA |
1019 | // if (!this.states) this.states = []; |
1020 | // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen(); | |
1021 | // this.states.push(stateFen); | |
1022 | ||
1023 | if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo) | |
1024 | if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move)); | |
1c9f093d BA |
1025 | V.PlayOnBoard(this.board, move); |
1026 | this.turn = V.GetOppCol(this.turn); | |
1027 | this.movesCount++; | |
1028 | this.updateVariables(move); | |
1029 | } | |
1030 | ||
6808d7a1 BA |
1031 | undo(move) { |
1032 | if (V.HasEnpassant) this.epSquares.pop(); | |
1033 | if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags)); | |
1c9f093d BA |
1034 | V.UndoOnBoard(this.board, move); |
1035 | this.turn = V.GetOppCol(this.turn); | |
1036 | this.movesCount--; | |
1037 | this.unupdateVariables(move); | |
1038 | ||
1039 | // DEBUG: | |
6808d7a1 BA |
1040 | // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen(); |
1041 | // if (stateFen != this.states[this.states.length-1]) debugger; | |
1042 | // this.states.pop(); | |
1c9f093d BA |
1043 | } |
1044 | ||
1045 | /////////////// | |
1046 | // END OF GAME | |
1047 | ||
1048 | // What is the score ? (Interesting if game is over) | |
6808d7a1 BA |
1049 | getCurrentScore() { |
1050 | if (this.atLeastOneMove()) | |
1051 | // game not over | |
1c9f093d BA |
1052 | return "*"; |
1053 | ||
1054 | // Game over | |
1055 | const color = this.turn; | |
1056 | // No valid move: stalemate or checkmate? | |
1057 | if (!this.isAttacked(this.kingPos[color], [V.GetOppCol(color)])) | |
1058 | return "1/2"; | |
1059 | // OK, checkmate | |
6808d7a1 | 1060 | return color == "w" ? "0-1" : "1-0"; |
1c9f093d BA |
1061 | } |
1062 | ||
1063 | /////////////// | |
1064 | // ENGINE PLAY | |
1065 | ||
1066 | // Pieces values | |
6808d7a1 | 1067 | static get VALUES() { |
1c9f093d | 1068 | return { |
6808d7a1 BA |
1069 | p: 1, |
1070 | r: 5, | |
1071 | n: 3, | |
1072 | b: 3, | |
1073 | q: 9, | |
1074 | k: 1000 | |
1c9f093d BA |
1075 | }; |
1076 | } | |
1077 | ||
1078 | // "Checkmate" (unreachable eval) | |
6808d7a1 BA |
1079 | static get INFINITY() { |
1080 | return 9999; | |
1081 | } | |
1c9f093d BA |
1082 | |
1083 | // At this value or above, the game is over | |
6808d7a1 BA |
1084 | static get THRESHOLD_MATE() { |
1085 | return V.INFINITY; | |
1086 | } | |
1c9f093d BA |
1087 | |
1088 | // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.) | |
6808d7a1 BA |
1089 | static get SEARCH_DEPTH() { |
1090 | return 3; | |
1091 | } | |
1c9f093d | 1092 | |
1c9f093d | 1093 | // NOTE: works also for extinction chess because depth is 3... |
6808d7a1 | 1094 | getComputerMove() { |
1c9f093d BA |
1095 | const maxeval = V.INFINITY; |
1096 | const color = this.turn; | |
1097 | // Some variants may show a bigger moves list to the human (Switching), | |
1098 | // thus the argument "computer" below (which is generally ignored) | |
1099 | let moves1 = this.getAllValidMoves("computer"); | |
6808d7a1 BA |
1100 | if (moves1.length == 0) |
1101 | //TODO: this situation should not happen | |
41cb9b94 | 1102 | return null; |
1c9f093d BA |
1103 | |
1104 | // Can I mate in 1 ? (for Magnetic & Extinction) | |
6808d7a1 | 1105 | for (let i of shuffle(ArrayFun.range(moves1.length))) { |
1c9f093d | 1106 | this.play(moves1[i]); |
6808d7a1 BA |
1107 | let finish = Math.abs(this.evalPosition()) >= V.THRESHOLD_MATE; |
1108 | if (!finish) { | |
1c9f093d | 1109 | const score = this.getCurrentScore(); |
6808d7a1 | 1110 | if (["1-0", "0-1"].includes(score)) finish = true; |
1c9f093d BA |
1111 | } |
1112 | this.undo(moves1[i]); | |
6808d7a1 | 1113 | if (finish) return moves1[i]; |
1c9f093d BA |
1114 | } |
1115 | ||
1116 | // Rank moves using a min-max at depth 2 | |
6808d7a1 | 1117 | for (let i = 0; i < moves1.length; i++) { |
1c9f093d | 1118 | // Initial self evaluation is very low: "I'm checkmated" |
6808d7a1 | 1119 | moves1[i].eval = (color == "w" ? -1 : 1) * maxeval; |
1c9f093d BA |
1120 | this.play(moves1[i]); |
1121 | const score1 = this.getCurrentScore(); | |
1122 | let eval2 = undefined; | |
6808d7a1 | 1123 | if (score1 == "*") { |
1c9f093d | 1124 | // Initial enemy evaluation is very low too, for him |
6808d7a1 | 1125 | eval2 = (color == "w" ? 1 : -1) * maxeval; |
1c9f093d BA |
1126 | // Second half-move: |
1127 | let moves2 = this.getAllValidMoves("computer"); | |
6808d7a1 | 1128 | for (let j = 0; j < moves2.length; j++) { |
1c9f093d BA |
1129 | this.play(moves2[j]); |
1130 | const score2 = this.getCurrentScore(); | |
6808d7a1 BA |
1131 | let evalPos = 0; //1/2 value |
1132 | switch (score2) { | |
1133 | case "*": | |
1134 | evalPos = this.evalPosition(); | |
1135 | break; | |
1136 | case "1-0": | |
1137 | evalPos = maxeval; | |
1138 | break; | |
1139 | case "0-1": | |
1140 | evalPos = -maxeval; | |
1141 | break; | |
1142 | } | |
1143 | if ( | |
1144 | (color == "w" && evalPos < eval2) || | |
1145 | (color == "b" && evalPos > eval2) | |
1146 | ) { | |
1c9f093d BA |
1147 | eval2 = evalPos; |
1148 | } | |
1149 | this.undo(moves2[j]); | |
1150 | } | |
6808d7a1 BA |
1151 | } else eval2 = score1 == "1/2" ? 0 : (score1 == "1-0" ? 1 : -1) * maxeval; |
1152 | if ( | |
1153 | (color == "w" && eval2 > moves1[i].eval) || | |
1154 | (color == "b" && eval2 < moves1[i].eval) | |
1155 | ) { | |
1c9f093d BA |
1156 | moves1[i].eval = eval2; |
1157 | } | |
1158 | this.undo(moves1[i]); | |
1159 | } | |
6808d7a1 BA |
1160 | moves1.sort((a, b) => { |
1161 | return (color == "w" ? 1 : -1) * (b.eval - a.eval); | |
1162 | }); | |
1c9f093d BA |
1163 | |
1164 | let candidates = [0]; //indices of candidates moves | |
6808d7a1 | 1165 | for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++) |
1c9f093d | 1166 | candidates.push(j); |
0c3fe8a6 | 1167 | let currentBest = moves1[candidates[randInt(candidates.length)]]; |
1c9f093d | 1168 | |
1c9f093d | 1169 | // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...) |
6808d7a1 | 1170 | if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) { |
656b1878 BA |
1171 | // From here, depth >= 3: may take a while, so we control time |
1172 | const timeStart = Date.now(); | |
6808d7a1 BA |
1173 | for (let i = 0; i < moves1.length; i++) { |
1174 | if (Date.now() - timeStart >= 5000) | |
1175 | //more than 5 seconds | |
1c9f093d BA |
1176 | return currentBest; //depth 2 at least |
1177 | this.play(moves1[i]); | |
1178 | // 0.1 * oldEval : heuristic to avoid some bad moves (not all...) | |
6808d7a1 BA |
1179 | moves1[i].eval = |
1180 | 0.1 * moves1[i].eval + | |
1181 | this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval); | |
1c9f093d BA |
1182 | this.undo(moves1[i]); |
1183 | } | |
6808d7a1 BA |
1184 | moves1.sort((a, b) => { |
1185 | return (color == "w" ? 1 : -1) * (b.eval - a.eval); | |
1186 | }); | |
1187 | } else return currentBest; | |
1188 | // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; })); | |
1c9f093d BA |
1189 | |
1190 | candidates = [0]; | |
6808d7a1 | 1191 | for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++) |
1c9f093d | 1192 | candidates.push(j); |
656b1878 | 1193 | return moves1[candidates[randInt(candidates.length)]]; |
1c9f093d BA |
1194 | } |
1195 | ||
6808d7a1 | 1196 | alphabeta(depth, alpha, beta) { |
1c9f093d BA |
1197 | const maxeval = V.INFINITY; |
1198 | const color = this.turn; | |
1199 | const score = this.getCurrentScore(); | |
1200 | if (score != "*") | |
6808d7a1 BA |
1201 | return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval; |
1202 | if (depth == 0) return this.evalPosition(); | |
1c9f093d | 1203 | const moves = this.getAllValidMoves("computer"); |
6808d7a1 BA |
1204 | let v = color == "w" ? -maxeval : maxeval; |
1205 | if (color == "w") { | |
1206 | for (let i = 0; i < moves.length; i++) { | |
1c9f093d | 1207 | this.play(moves[i]); |
6808d7a1 | 1208 | v = Math.max(v, this.alphabeta(depth - 1, alpha, beta)); |
1c9f093d BA |
1209 | this.undo(moves[i]); |
1210 | alpha = Math.max(alpha, v); | |
6808d7a1 | 1211 | if (alpha >= beta) break; //beta cutoff |
1c9f093d | 1212 | } |
6808d7a1 BA |
1213 | } //color=="b" |
1214 | else { | |
1215 | for (let i = 0; i < moves.length; i++) { | |
1c9f093d | 1216 | this.play(moves[i]); |
6808d7a1 | 1217 | v = Math.min(v, this.alphabeta(depth - 1, alpha, beta)); |
1c9f093d BA |
1218 | this.undo(moves[i]); |
1219 | beta = Math.min(beta, v); | |
6808d7a1 | 1220 | if (alpha >= beta) break; //alpha cutoff |
1c9f093d BA |
1221 | } |
1222 | } | |
1223 | return v; | |
1224 | } | |
1225 | ||
6808d7a1 | 1226 | evalPosition() { |
1c9f093d BA |
1227 | let evaluation = 0; |
1228 | // Just count material for now | |
6808d7a1 BA |
1229 | for (let i = 0; i < V.size.x; i++) { |
1230 | for (let j = 0; j < V.size.y; j++) { | |
1231 | if (this.board[i][j] != V.EMPTY) { | |
1232 | const sign = this.getColor(i, j) == "w" ? 1 : -1; | |
1233 | evaluation += sign * V.VALUES[this.getPiece(i, j)]; | |
1c9f093d BA |
1234 | } |
1235 | } | |
1236 | } | |
1237 | return evaluation; | |
1238 | } | |
1239 | ||
1240 | ///////////////////////// | |
1241 | // MOVES + GAME NOTATION | |
1242 | ///////////////////////// | |
1243 | ||
1244 | // Context: just before move is played, turn hasn't changed | |
1245 | // TODO: un-ambiguous notation (switch on piece type, check directions...) | |
6808d7a1 BA |
1246 | getNotation(move) { |
1247 | if (move.appear.length == 2 && move.appear[0].p == V.KING) | |
1248 | //castle | |
1249 | return move.end.y < move.start.y ? "0-0-0" : "0-0"; | |
1c9f093d BA |
1250 | |
1251 | // Translate final square | |
1252 | const finalSquare = V.CoordsToSquare(move.end); | |
1253 | ||
1254 | const piece = this.getPiece(move.start.x, move.start.y); | |
6808d7a1 | 1255 | if (piece == V.PAWN) { |
1c9f093d BA |
1256 | // Pawn move |
1257 | let notation = ""; | |
6808d7a1 | 1258 | if (move.vanish.length > move.appear.length) { |
1c9f093d BA |
1259 | // Capture |
1260 | const startColumn = V.CoordToColumn(move.start.y); | |
1261 | notation = startColumn + "x" + finalSquare; | |
6808d7a1 BA |
1262 | } //no capture |
1263 | else notation = finalSquare; | |
1264 | if (move.appear.length > 0 && move.appear[0].p != V.PAWN) | |
1265 | //promotion | |
1c9f093d BA |
1266 | notation += "=" + move.appear[0].p.toUpperCase(); |
1267 | return notation; | |
1268 | } | |
6808d7a1 BA |
1269 | // Piece movement |
1270 | return ( | |
1271 | piece.toUpperCase() + | |
1272 | (move.vanish.length > move.appear.length ? "x" : "") + | |
1273 | finalSquare | |
1274 | ); | |
1275 | } | |
1276 | }; |