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