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