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