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