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