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