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