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