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