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