All files boardValidation.js

94.69% Statements 107/113
90% Branches 81/90
88.88% Functions 16/18
95.53% Lines 107/112

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                                                              408x 408x       408x         403x 50x   50x 366x 50x       403x   403x 403x                       403x           295x         270x         26x 26x 17x 17x   17x 17x     26x         295x         277x   34x 34x 33x 33x   33x 33x     34x               403x 403x 403x 403x 403x 403x   403x 4355x   4355x   11327x     11327x 10772x   555x       11327x   11327x 10528x       4355x 4097x             403x       12548x                 12548x   100384x 100384x   100384x 103306x             103306x   1792x     1792x 101514x 54575x   46939x       100384x   12548x     100384x   100384x             100384x     2408x         100384x   12548x 12548x 4200x 4200x 4200x 4200x 17763x 966x 966x         3234x       12548x                                   200768x       12145x         404x                 404x 404x 404x 5857x 5857x       5857x 4355x             404x 404x   404x   403x   403x   5857x 403x     5857x 5857x             403x     403x     403x 33x 11x           11x     22x             1x     403x        
/**
	BoardValidation determines viable move options for all pieces
	given the current state of the board. If it's the White sides turn
	to attack, only White piece move options are evaluated (and visa versa).
 
	BoardValidation is intended to be the 2nd phase of move
	validation that is capable of taking into account factors across pieces
	on the board (and not just the pieces themselves). For example, King
	castle eligibility is determined based on whether or not both the candidate
	King and Rook pieces have not moved and whether or not the path of travel
	for the King would result in the King being placed in check at any
	point during the travel. Individual Piece validation wouldn't be sufficient
	to determine whether or not this move is possible.
 
	Additionally, isSquareAttacked exists on the BoardValidation object. While
	this method could have easily existed within the PieceValidation object
	I've kept it in BoardValidation so that PieceValidation remains truly
	agnostic of the other pieces on the same board.
 
	Due to how BoardValidation actually functions, the client only needs to
	instantiate a BoardValidation for the Game and call the start method
	in order to evaluate every Piece's valid move options. There is no need
	to call PieceValidation (and doing so wouldn't give an accurate picture
	of what is possible anyway).
*/
import { PieceType, SideType } from './piece.js';
import { NeighborType } from './board.js';
import { PieceValidation } from './pieceValidation.js';
 
export class BoardValidation {
	constructor (game) {
		this.board = game ? game.board : null;
		this.game = game;
	}
 
	static create (game) {
		return new BoardValidation(game);
	}
 
	evaluateCastle (validMoves) {
		let
			getValidSquares = (sq) => {
				let i = 0;
 
				for (i = 0; i < validMoves.length; i++) {
					if (validMoves[i].src === sq) {
						return validMoves[i].squares;
					}
				}
			},
			interimMove = null,
			// eslint-disable-next-line no-magic-numbers
			rank = this.game.getCurrentSide() === SideType.White ? 1 : 8,
			squares = {
				'a' : this.board.getSquare('a', rank),
				'b' : this.board.getSquare('b', rank),
				'c' : this.board.getSquare('c', rank),
				'd' : this.board.getSquare('d', rank),
				'e' : this.board.getSquare('e', rank),
				'f' : this.board.getSquare('f', rank),
				'g' : this.board.getSquare('g', rank),
				'h' : this.board.getSquare('h', rank)
			};
 
		// is king eligible
		if (squares.e.piece &&
				squares.e.piece.type === PieceType.King &&
				squares.e.piece.moveCount === 0 &&
				!this.isSquareAttacked(squares.e)) {
 
			// is left rook eligible
			if (squares.a.piece &&
					squares.a.piece.type === PieceType.Rook &&
					squares.a.piece.moveCount === 0) {
 
				// are the squares between king and rook clear
				if (!squares.b.piece &&
						!squares.c.piece &&
						!squares.d.piece) {
 
					// when king moves through squares between, is it in check
					interimMove = this.board.move(squares.e, squares.d, true);
					if (!this.isSquareAttacked(squares.d)) {
						interimMove.undo();
						interimMove = this.board.move(squares.e, squares.c, true);
 
						Eif (!this.isSquareAttacked(squares.c)) {
							getValidSquares(squares.e).push(squares.c);
						}
					}
					interimMove.undo();
				}
			}
 
			// is right rook eligible
			if (squares.h.piece &&
					squares.h.piece.type === PieceType.Rook &&
					squares.h.piece.moveCount === 0) {
 
				// are the squares between king and rook clear
				if (!squares.g.piece && !squares.f.piece) {
					// when king moves through squares between, is it in check
					interimMove = this.board.move(squares.e, squares.f, true);
					if (!this.isSquareAttacked(squares.f)) {
						interimMove.undo();
						interimMove = this.board.move(squares.e, squares.g, true);
 
						Eif (!this.isSquareAttacked(squares.g)) {
							getValidSquares(squares.e).push(squares.g);
						}
					}
					interimMove.undo();
				}
			}
		}
	}
 
	filterKingAttack (kingSquare, moves) {
		let
			filteredMoves = [],
			i = 0,
			isCheck = false,
			n = 0,
			r = null,
			squares = [];
 
		for (i = 0; i < moves.length; i++) {
			squares = [];
 
			for (n = 0; n < moves[i].squares.length; n++) {
				// simulate move on the board
				r = this.board.move(moves[i].src, moves[i].squares[n], true);
 
				// check if king is attacked
				if (moves[i].squares[n].piece.type !== PieceType.King) {
					isCheck = this.isSquareAttacked(kingSquare);
				} else {
					isCheck = this.isSquareAttacked(moves[i].squares[n]);
				}
 
				// reverse the move
				r.undo();
 
				if (!isCheck) {
					squares.push(moves[i].squares[n]);
				}
			}
 
			if (squares && squares.length > 0) {
				filteredMoves.push({
					squares,
					src : moves[i].src
				});
			}
		}
 
		return filteredMoves;
	}
 
	findAttackers (sq) {
		Iif (!sq || !sq.piece) {
			return {
				attacked : false,
				blocked : false
			};
		}
 
		let
			/* eslint no-invalid-this: 0 */
			isAttacked = (b, n) => {
				let
					context = {},
					currentSquare = b.getNeighborSquare(sq, n);
 
				while (currentSquare) {
					context = {
						attacked : currentSquare.piece && currentSquare.piece.side !== sq.piece.side,
						blocked : currentSquare.piece && currentSquare.piece.side === sq.piece.side,
						piece : currentSquare.piece,
						square : currentSquare
					};
 
					if (context.attacked) {
						// verify that the square is actually attacked
						PieceValidation
							.create(context.piece.type, b)
							.start(currentSquare, setAttacked(context));
						currentSquare = null;
					} else if (context.blocked) {
						currentSquare = null;
					} else {
						currentSquare = b.getNeighborSquare(currentSquare, n);
					}
				}
 
				return context;
			},
			isAttackedByKnight = (b, n) => {
				let
					context,
					currentSquare = b.getNeighborSquare(sq, n);
 
				context = {
					attacked : false,
					blocked : false,
					piece : currentSquare ? currentSquare.piece : currentSquare,
					square : currentSquare
				};
 
				if (currentSquare &&
					currentSquare.piece &&
					currentSquare.piece.type === PieceType.Knight) {
					PieceValidation
						.create(PieceType.Knight, b)
						.start(currentSquare, setAttacked(context));
				}
 
				return context;
			},
			self = this,
			setAttacked = (c) => {
				return (err, squares) => {
					Eif (!err) {
						let i = 0;
						for (i = 0; i < squares.length; i++) {
							if (squares[i] === sq) {
								c.attacked = true;
								return;
							}
						}
					}
 
					c.attacked = false;
				};
			};
 
		return [
			isAttacked(self.board, NeighborType.Above),
			isAttacked(self.board, NeighborType.AboveRight),
			isAttacked(self.board, NeighborType.Right),
			isAttacked(self.board, NeighborType.BelowRight),
			isAttacked(self.board, NeighborType.Below),
			isAttacked(self.board, NeighborType.BelowLeft),
			isAttacked(self.board, NeighborType.Left),
			isAttacked(self.board, NeighborType.AboveLeft),
			// fix for issue #4
			isAttackedByKnight(self.board, NeighborType.KnightAboveRight),
			isAttackedByKnight(self.board, NeighborType.KnightRightAbove),
			isAttackedByKnight(self.board, NeighborType.KnightBelowRight),
			isAttackedByKnight(self.board, NeighborType.KnightRightBelow),
			isAttackedByKnight(self.board, NeighborType.KnightBelowLeft),
			isAttackedByKnight(self.board, NeighborType.KnightLeftBelow),
			isAttackedByKnight(self.board, NeighborType.KnightAboveLeft),
			isAttackedByKnight(self.board, NeighborType.KnightLeftAbove)
		].filter((result) => result.attacked);
	}
 
	isSquareAttacked (sq) {
		return this.findAttackers(sq).length !== 0;
	}
 
	start (callback) {
		// ensure callback is set
		callback = callback || ((err, validMoves) => new Promise((resolve, reject) => {
			if (err) {
				return reject(err);
			}
 
			return resolve(validMoves);
		}));
 
		let
			i = 0,
			kingSquare = null,
			setValidMoves = (v, sq) => {
				return (err, squares) => {
					Iif (err) {
						return callback(err);
					}
 
					if (squares && squares.length > 0) {
						v.push({
							squares,
							src : sq
						});
					}
				};
			},
			squares = [],
			validMoves = [];
 
		if (this.board) {
			// get squares with pieces for which to evaluate move options
			squares = this.board.getSquares(this.game.getCurrentSide());
 
			for (i = 0; i < squares.length; i++) {
				// set king to refer to later
				if (squares[i].piece.type === PieceType.King) {
					kingSquare = squares[i];
				}
 
				Eif (squares[i] && squares[i].piece) {
					PieceValidation
						.create(squares[i].piece.type, this.board)
						.start(squares[i], setValidMoves(validMoves, squares[i]));
				}
			}
 
			// perform king castle validation
			this.evaluateCastle(validMoves);
 
			// make sure moves only contain escape & non-check options
			validMoves = this.filterKingAttack(kingSquare, validMoves);
 
			// find any pieces attacking the king
			this.findAttackers(kingSquare).forEach((attacker) => {
				if (!validMoves.length) {
					this.game.emit(
						'checkmate', {
							attackingSquare : attacker.square,
							kingSquare
						});
 
					return;
				}
 
				this.game.emit(
					'check', {
						attackingSquare : attacker.square,
						kingSquare
					});
			});
		} else {
			return callback(new Error('board is invalid'));
		}
 
		return callback(null, validMoves);
	}
}
 
export default { BoardValidation };