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