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