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