All files uciGameClient.js

86.4% Statements 89/103
76.59% Branches 36/47
100% Functions 15/15
86% Lines 86/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239                    12x           12x 12x   12x 2x       10x 10x 12x   12x       20x 20x       20x 20x 20x 20x 20x 20x           20x 20x 20x     20x   206x 206x     206x   437x     437x       437x       437x   1x 4x           1x       436x             20x         7x   7x 7x 7x 7x 7x 7x 7x 7x     7x 14x     7x 42x     7x 7x   1x           7x 7x   7x   7x       5x 3x     5x                     2x         12x 12x 12x 12x 12x 12x 12x 12x 12x   12x 2x       10x     10x         12x         10x     10x 10x       12x       10x         10x 10x   10x   1x               1x 1x                 1x 1x       10x   10x                
/* eslint sort-imports: 0 */
import { EventEmitter } from 'events';
import { Game } from './game.js';
import { GameValidation } from './gameValidation.js';
import { Piece } from './piece.js';
import { PieceType } from './piece.js';
 
// private helpers
 
function parseUCI(uci) {
  Iif (typeof uci !== 'string') {
    return null;
  }
 
  // UCI format: e2e4, e7e8q (promotion), case-insensitive for promo
  let
    formatRegex = /^([a-h][1-8])([a-h][1-8])([qrbnQRBN])?$/,
    uciMove = uci.trim().match(formatRegex);
 
  if (!uciMove) {
    return null;
  }
 
  let
    dest = { file: uciMove[2][0], rank: Number(uciMove[2][1]) },
    promo = uciMove[3] ? uciMove[3].toUpperCase() : '',
    src = { file: uciMove[1][0], rank: Number(uciMove[1][1]) };
 
  return { dest, promo, src };
}
 
function updateGameClient(gameClient) {
  return gameClient.validation.start((err, result) => {
    Iif (err) {
      throw new Error(err);
    }
 
    gameClient.isCheck = result.isCheck;
    gameClient.isCheckmate = result.isCheckmate;
    gameClient.isRepetition = result.isRepetition;
    gameClient.isStalemate = result.isStalemate;
    gameClient.validMoves = result.validMoves;
    gameClient.uciMoves = notateUCI(result.validMoves);
  });
}
 
function notateUCI(validMoves) {
  let 
    i = 0,
    isPromotion = false,
    notation = {};
 
  // iterate through all valid moves and create UCI notation
  for (; i < validMoves.length; i++) {
    let 
      p = validMoves[i].src.piece,
      src = validMoves[i].src;
 
    // reset inner index for each piece's move list
    for (let n = 0; n < validMoves[i].squares.length; n++) {
      // get the destination square for this move
      let sq = validMoves[i].squares[n];
 
      // base notation
      let base = `${src.file}${src.rank}${sq.file}${sq.rank}`;
 
      // check for potential promotion
      /* eslint no-magic-numbers: 0 */
      isPromotion = 
        (sq.rank === 8 || sq.rank === 1) && 
        p.type === PieceType.Pawn;
      
      if (isPromotion) {
        // add all promotion options
        ['q', 'r', 'b', 'n'].forEach((promo) => {
          notation[`${base}${promo}`] = {
            dest: sq,
            src
          };
        });
 
        continue
      }
 
      // regular move
      notation[base] = {
        dest: sq,
        src
      };
    }
  }
 
  return notation;
}
 
export class UCIGameClient extends EventEmitter {
  constructor(game) {
    super();
 
    this.game = game;
    this.isCheck = false;
    this.isCheckmate = false;
    this.isRepetition = false;
    this.isStalemate = false;
    this.uciMoves = {};
    this.validMoves = [];
    this.validation = GameValidation.create(this.game);
 
    // bubble the game and board events
    ['check', 'checkmate'].forEach((ev) => {
      this.game.on(ev, (data) => this.emit(ev, data));
    });
 
    ['capture', 'castle', 'enPassant', 'move', 'promote', 'undo'].forEach((ev) => {
      this.game.board.on(ev, (data) => this.emit(ev, data));
    });
 
    const self = this;
    this.on('undo', () => {
      // force an update
      self.getStatus(true);
    });
  }
 
  static create() {
    let 
      game = Game.create(),
      gameClient = new UCIGameClient(game);
 
    updateGameClient(gameClient);
 
    return gameClient;
  }
 
  getStatus(forceUpdate) {
    if (forceUpdate) {
      updateGameClient(this);
    }
 
    return {
      board: this.game.board,
      isCheck: this.isCheck,
      isCheckmate: this.isCheckmate,
      isRepetition: this.isRepetition,
      isStalemate: this.isStalemate,
      uciMoves: this.uciMoves
    };
  }
 
  getCaptureHistory() {
    return this.game.captureHistory;
  }
 
  move(uci) {
    let 
      canonical = null,
      dest = null,
      move = null,
      parsed = parseUCI(uci),
      promo = null,
      requiresPromotion = false,
      side = null,
      src = null, 
      srcSquare = null;
 
    if (!parsed) {
      throw new Error(`UCI is invalid (${uci})`);
    }
 
    // destructure the parsed UCI move
    ({ src, dest, promo } = parsed);
 
    // normalize UCI key to compare with generated map
    canonical = promo
      ? `${src.file}${src.rank}${dest.file}${dest.rank}${promo.toLowerCase()}`
      : `${src.file}${src.rank}${dest.file}${dest.rank}`;
 
    // ensure move exactly matches a generated UCI move
    Iif (!this.uciMoves || !this.uciMoves[canonical]) {
      throw new Error(`Move is invalid (${uci})`);
    }
 
    // determine the current side
    side = this.game.getCurrentSide();
 
    // additional safety: enforce promotion semantics
    srcSquare = this.game.board.getSquare(src.file, src.rank);
    requiresPromotion =
      srcSquare && srcSquare.piece && srcSquare.piece.type === PieceType.Pawn &&
      (dest.rank === 8 || dest.rank === 1);
 
    Iif (requiresPromotion && !promo) {
      throw new Error(`Promotion required for move (${uci})`);
    }
 
    Iif (promo && !requiresPromotion) {
      throw new Error(`Promotion flag not allowed for move (${uci})`);
    }
 
    // make the move
    move = this.game.board.move(`${src.file}${src.rank}`, `${dest.file}${dest.rank}`);
    Eif (move) {
      // apply pawn promotion if applicable (already validated above)
      if (promo) {
        let piece;
        switch (promo) {
          case 'B':
            piece = Piece.createBishop(side);
            break;
          case 'N':
            piece = Piece.createKnight(side);
            break;
          case 'Q':
            piece = Piece.createQueen(side);
            break;
          case 'R':
            piece = Piece.createRook(side);
            break;
          default:
            piece = null;
            break;
        }
 
        Eif (piece) {
          this.game.board.promote(move.move.postSquare, piece);
        }
      }
 
      updateGameClient(this);
      
      return move;
    }
 
    throw new Error(`Move is invalid (${uci})`);
  }
}
 
export default { UCIGameClient };