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