All files algebraicGameClient.js

94.25% Statements 164/174
88.88% Branches 96/108
100% Functions 20/20
94.11% Lines 160/170

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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403                        2672x 5344x   5344x 18055x 2900x       2444x   2672x 2672x 2672x 2672x 2672x 2672x   2672x 5344x 2900x 2900x   2900x 2900x       2672x 224x     2672x 4x     2672x         4827x 4827x   4827x 53172x 7499x       4827x         323x 323x 323x 323x 323x 323x 323x 323x 323x 323x     323x 3364x 3364x     3364x 8944x 8944x     8944x       8944x         8944x 74x         8944x     3x       8944x           4827x 4827x 2672x   2155x         8944x   415x   30x 30x 385x   15x 15x   370x         8944x   14x           14x           14x           14x         8930x               323x         4x 4x     4x   4x   2x       2x     2x       323x 323x       323x 323x 323x 323x 323x 323x           42x   42x 42x 42x 42x 42x 42x       42x 42x 42x     42x 84x     42x 327x     42x 42x   3x           41x 41x   41x   41x       1x           1x 1x     1x 64x     1x 64x 64x 32x 32x       1x     1x 1x 1x     1x     1x 9x         1x 1x   1x       36x 20x     36x                     2x       2x         269x 269x 269x 269x 269x   269x   267x               267x 4x   263x       267x 3x       267x 261x       6x 4x 2x 1x     262x   261x 3x                     3x 3x         3x 3x       261x   261x       3x          
/* eslint sort-imports: 0 */
import { EventEmitter } from 'events';
import { Board } from './board.js';
import { Game } from './game.js';
import { GameValidation } from './gameValidation.js';
import { Piece } from './piece.js';
import { PieceType } from './piece.js';
import { SideType } from './piece.js';
 
// private methods
function getNotationPrefix (src, dest, movesForPiece) {
	let
		containsDest = (squares) => {
			let n = 0;
 
			for (; n < squares.length; n++) {
				if (squares[n] === dest) {
					return true;
				}
			}
 
			return false;
		},
		file = '',
		fileHash = {},
		i = 0,
		prefix = src.piece.notation,
		rank = 0,
		rankHash = {};
 
	for (; i < movesForPiece.length; i++) {
		if (containsDest(movesForPiece[i].squares)) {
			file = movesForPiece[i].src.file;
			rank = movesForPiece[i].src.rank;
 
			fileHash[file] = (typeof fileHash[file] !== 'undefined' ? fileHash[file] + 1 : 1);
			rankHash[rank] = (typeof rankHash[rank] !== 'undefined' ? rankHash[rank] + 1 : 1);
		}
	}
 
	if (Object.keys(fileHash).length > 1) {
		prefix += src.file;
	}
 
	if (Object.keys(rankHash).length > Object.keys(fileHash).length) {
		prefix += src.rank;
	}
 
	return prefix;
}
 
function getValidMovesByPieceType (pieceType, validMoves) {
	let
		byPiece = [],
		i = 0;
 
	for (; i < validMoves.length; i++) {
		if (validMoves[i].src.piece.type === pieceType) {
			byPiece.push(validMoves[i]);
		}
	}
 
	return byPiece;
}
 
function notate (validMoves, gameClient) {
	let
		algebraicNotation = {},
		i = 0,
		isPromotion = false,
		movesForPiece = [],
		n = 0,
		p = null,
		prefix = '',
		sq = null,
		src = null,
		suffix = '';
 
	// iterate through each starting squares valid moves
	for (; i < validMoves.length; i++) {
		src = validMoves[i].src;
		p = src.piece;
 
		// iterate each potential move and build prefix and suffix for notation
		for (n = 0; n < validMoves[i].squares.length; n++) {
			prefix = '';
			sq = validMoves[i].squares[n];
 
			// set suffix for notation
			suffix = (sq.piece ? 'x' : '') + sq.file + sq.rank;
 
			// check for potential promotion
			/* eslint no-magic-numbers: 0 */
			isPromotion =
				(sq.rank === 8 || sq.rank === 1) &&
				p.type === PieceType.Pawn;
 
			// squares with pawns
			if (sq.piece && p.type === PieceType.Pawn) {
				prefix = src.file;
			}
 
			// en passant
			// fix for #53
			if (p.type === PieceType.Pawn &&
				src.file !== sq.file &&
				!sq.piece) {
				prefix = [src.file, 'x'].join('');
			}
 
			// squares with Bishop, Knight, Queen or Rook pieces
			if (p.type === PieceType.Bishop ||
				p.type === PieceType.Knight ||
				p.type === PieceType.Queen ||
				p.type === PieceType.Rook) {
				// if there is more than 1 of the specified piece on the board,
				// can more than 1 land on the specified square?
				movesForPiece = getValidMovesByPieceType(p.type, validMoves);
				if (movesForPiece.length > 1) {
					prefix = getNotationPrefix(src, sq, movesForPiece);
				} else {
					prefix = src.piece.notation;
				}
			}
 
			// squares with a King piece
			if (p.type === PieceType.King) {
				// look for castle left and castle right
				if (src.file === 'e' && sq.file === 'g') {
					// fix for issue #13 - if PGN is specified should be letters, not numbers
					prefix = gameClient.PGN ? 'O-O' : '0-0';
					suffix = '';
				} else if (src.file === 'e' && sq.file === 'c') {
					// fix for issue #13 - if PGN is specified should be letters, not numbers
					prefix = gameClient.PGN ? 'O-O-O' : '0-0-0';
					suffix = '';
				} else {
					prefix = src.piece.notation;
				}
			}
 
			// set the notation
			if (isPromotion) {
				// Rook promotion
				algebraicNotation[prefix + suffix + 'R'] = {
					dest : sq,
					src
				};
 
				// Knight promotion
				algebraicNotation[prefix + suffix + 'N'] = {
					dest : sq,
					src
				};
 
				// Bishop promotion
				algebraicNotation[prefix + suffix + 'B'] = {
					dest : sq,
					src
				};
 
				// Queen promotion
				algebraicNotation[prefix + suffix + 'Q'] = {
					dest : sq,
					src
				};
			} else {
				algebraicNotation[prefix + suffix] = {
					dest : sq,
					src
				};
			}
		}
	}
 
	return algebraicNotation;
}
 
function parseNotation (notation) {
	let
		captureRegex = /^[a-h]x[a-h][1-8]$/,
		parseDest = '';
 
	// try and parse the notation
	parseDest = notation.substring(notation.length - 2);
 
	if (notation.length > 2) {
		// check for preceding pawn capture style notation (i.e. a-h x)
		Iif (captureRegex.test(notation)) {
			return parseDest;
		}
 
		return notation.charAt(0) + parseDest;
	}
 
	return '';
}
 
function updateGameClient (gameClient) {
	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.notatedMoves = notate(result.validMoves, gameClient);
		gameClient.validMoves = result.validMoves;
	});
}
 
export class AlgebraicGameClient extends EventEmitter {
	constructor (game, opts) {
		super();
 
		this.game = game;
		this.isCheck = false;
		this.isCheckmate = false;
		this.isRepetition = false;
		this.isStalemate = false;
		this.notatedMoves = {};
		// for issue #13, adding options allowing consumers to specify
		// PGN (Portable Game Notation)... essentially, this makes castle moves
		// appear as capital letter O rather than the number 0
		this.PGN = (opts && typeof opts.PGN === 'boolean') ? opts.PGN : false;
		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));
		});
 
		let self = this;
		this.on('undo', () => {
			// force an update
			self.getStatus(true);
		});
	}
 
	static create (opts) {
		let
			game = Game.create(),
			gameClient = new AlgebraicGameClient(game, opts);
 
		updateGameClient(gameClient);
 
		return gameClient;
	}
 
	static fromFEN (fen, opts) {
		Iif (!fen || typeof fen !== 'string') {
			throw new Error('FEN must be a non-empty string');
		}
 
		// create a standard game so listeners/history are wired
		let 
			game = Game.create(),
			loadedBoard = Board.load(fen);
 
		// copy piece placement from loaded board to preserve board indexing and listeners
		for (let i = 0; i < game.board.squares.length; i++) {
			game.board.squares[i].piece = null;
		}
 
		for (let i = 0; i < loadedBoard.squares.length; i++) {
			let sq = loadedBoard.squares[i];
			if (sq.piece) {
				let target = game.board.getSquare(sq.file, sq.rank);
				target.piece = sq.piece;
			}
		}
 
		game.board.lastMovedPiece = null;
 
		// derive side to move from FEN (default to White if missing)
		let parts = fen.split(' ');
		let active = parts[1] || 'w';
		let baseSide = active === 'b' ? SideType.Black : SideType.White;
 
		// override getCurrentSide to honor FEN and alternate thereafter
		let whiteFirst = baseSide === SideType.White;
 
		/* eslint no-param-reassign: 0 */
		game.getCurrentSide = function getCurrentSideAfterFENLoad () {
			return (this.moveHistory.length % 2 === 0) ?
				(whiteFirst ? SideType.White : SideType.Black) :
				(whiteFirst ? SideType.Black : SideType.White);
		};
 
		const gameClient = new AlgebraicGameClient(game, opts);
		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,
			notatedMoves : this.notatedMoves
		};
	}
 
	getFen () {
		return this.game.board.getFen();
	}
 
	getCaptureHistory () {
		return this.game.captureHistory;
	}
 
	move (notation, isFuzzy) {
		let
			move = null,
			notationRegex = /^[BKQNR]?[a-h]?[1-8]?[x-]?[a-h][1-8][+#]?$/,
			p = null,
			promo = '',
			side = this.game.getCurrentSide();
 
		if (notation && typeof notation === 'string') {
			// clean notation of extra or alternate chars
			notation = notation
				.replace(/\!/g, '')
				.replace(/\+/g, '')
				.replace(/\#/g, '')
				.replace(/\=/g, '')
				.replace(/\\/g, '');
 
			// fix for issue #13 - if PGN is specified, should be letters not numbers
			if (this.PGN) {
				notation = notation.replace(/0/g, 'O');
			} else {
				notation = notation.replace(/O/g, '0');
			}
 
			// check for pawn promotion
			if (notation.charAt(notation.length - 1).match(/[BNQR]/)) {
				promo = notation.charAt(notation.length - 1);
			}
 
			// use it directly or attempt to parse it if not found
			if (this.notatedMoves[notation]) {
				move = this.game.board.move(
					this.notatedMoves[notation].src,
					this.notatedMoves[notation].dest,
					notation);
			} else if (notation.match(notationRegex) && notation.length > 1 && !isFuzzy) {
				return this.move(parseNotation(notation), true);
			} else if (isFuzzy) {
				throw new Error(`Invalid move (${notation})`);
			}
 
			if (move) {
				// apply pawn promotion
				if (promo) {
					switch (promo) {
						case 'B':
							p = Piece.createBishop(side);
							break;
						case 'N':
							p = Piece.createKnight(side);
							break;
						case 'Q':
							p = Piece.createQueen(side);
							break;
						case 'R':
							p = Piece.createRook(side);
							break;
						default:
							p = Piece.createPawn(side);
					}
 
					Eif (p) {
						this.game.board.promote(move.move.postSquare, p);
					}
				}
 
				updateGameClient(this);
 
				return move;
			}
		}
 
		throw new Error(`Notation is invalid (${notation})`);
	}
}
 
export default { AlgebraicGameClient };