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