All files board.js

99.36% Statements 156/157
97.63% Branches 165/169
100% Functions 16/16
99.35% Lines 153/154

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 404 405                  9x                                           170x   170x         168x 168x 168x 168x 168x     168x 10752x 10752x 10752x   10752x   10752x 2688x 672x     2016x 672x     1344x 672x     672x 336x       336x       8064x 2688x           168x         2x                             2x 2x   16x 16x   16x 72x 8x 64x 64x     64x 64x 64x 64x   72x       2x 16x 16x         2x 2x   128x 128x 128x 128x   16x     2x 128x   128x 14x     128x 64x 64x   64x 8x   56x         2x       329371x   329371x     6022x     323349x     5828x     317521x     24538x     292983x     19646x         273337x 273337x   273337x   273337x 273337x 226082x         47255x         4532x 400x 400x         4532x 4532x   4532x   4530x 4530x 4529x       3x       792x   792x 50688x 11512x       792x       11966x 126x     11966x 126x         11966x 11450x 11450x     11966x   11966x               11966x 11966x 11966x 11966x 11455x   11x 1x         11454x 11454x     11454x 11449x       11454x 5x               5x       11454x 102x       102x       102x       11454x   10x     10x     10x         11966x 11966x     11966x     11966x     11966x 9x 9x 9x       11966x 123x         123x     123x       123x       11966x 516x 516x   516x 76x     516x 21x     516x 4x     516x     11966x                 5x 5x     5x   5x   5x            
/**
	The Board is the representation of the current position of the pieces on
	the squares it contains.
*/
import { Piece, PieceType, SideType } from './piece.js';
import { EventEmitter } from 'events';
import { Square } from './square.js';
 
// types
export var NeighborType = {
	Above : { offset : 8 },
	AboveLeft : { offset : 7 },
	AboveRight : { offset : 9 },
	Below : { offset : -8 },
	BelowLeft : { offset : -9 },
	BelowRight : { offset : -7 },
	KnightAboveLeft : { offset : 15 },
	KnightAboveRight : { offset : 17 },
	KnightBelowLeft : { offset : -17 },
	KnightBelowRight : { offset : -15 },
	KnightLeftAbove : { offset : 6 },
	KnightLeftBelow : { offset : -10 },
	KnightRightAbove : { offset : 10 },
	KnightRightBelow : { offset : -6 },
	Left : { offset : -1 },
	Right : { offset : 1 }
};
 
// ctor
export class Board extends EventEmitter {
	constructor (squares) {
		super();
 
		this.squares = squares;
	}
 
	static create () {
		let
			b = new Board([]),
			f = 0,
			i = 0,
			r = 0,
			sq = null;
 
		/* eslint no-magic-numbers:0 */
		for (i = 0; i < 64; i++) {
			f = Math.floor(i % 8);
			r = Math.floor(i / 8) + 1;
			sq = Square.create('abcdefgh'[f], r);
 
			b.squares.push(sq);
 
			if (r === 1 || r === 8) { // Named pieces
				if (f === 0 || f === 7) { // Rookage
					sq.piece = Piece.createRook(
						r === 1 ? SideType.White : SideType.Black
					);
				} else if (f === 1 || f === 6) { // Knights
					sq.piece = Piece.createKnight(
						r === 1 ? SideType.White : SideType.Black
					);
				} else if (f === 2 || f === 5) { // Bish's
					sq.piece = Piece.createBishop(
						r === 1 ? SideType.White : SideType.Black
					);
				} else if (f === 3) {
					sq.piece = Piece.createQueen(
						r === 1 ? SideType.White : SideType.Black
					);
				} else {
					sq.piece = Piece.createKing(
						r === 1 ? SideType.White : SideType.Black
					);
				}
			} else if (r === 2 || r === 7) { // Pawns
				sq.piece = Piece.createPawn(
					r === 2 ? SideType.White : SideType.Black
				);
			}
		}
 
		return b;
	}
 
	static load (fen) {
		/* eslint sort-keys: 0 */
		const pieces = {
			b: { arg: SideType.Black, method: 'createBishop' },
			B: { arg: SideType.White, method: 'createBishop' },
			k: { arg: SideType.Black, method: 'createKing' },
			K: { arg: SideType.White, method: 'createKing' },
			n: { arg: SideType.Black, method: 'createKnight' },
			N: { arg: SideType.White, method: 'createKnight' },
			p: { arg: SideType.Black, method: 'createPawn' },
			P: { arg: SideType.White, method: 'createPawn' },
			q: { arg: SideType.Black, method: 'createQueen' },
			Q: { arg: SideType.White, method: 'createQueen' },
			r: { arg: SideType.Black, method: 'createRook' },
			R: { arg: SideType.White, method: 'createRook' }
		};
 
		const [board/* , turn, castling, enPassant, halfs, moves */] = fen.split(' ');
		const lines = board.split('/')
			.map((line, rank) => {
				const arr = line.split('');
				let file = 0;
 
				return arr.reduce((acc, cur) => {
					if (!isNaN(Number(cur))) {
						for (let i = 0; i < Number(cur); i += 1) {
							acc.push(Square.create('abcdefgh'[file], 8 - rank));
							file = file < 7 ? file + 1 : 0;
						}
					} else {
						const square = Square.create('abcdefgh'[file], 8 - rank);
						square.piece = Piece[pieces[cur].method](pieces[cur].arg);
						acc.push(square);
						file = file < 7 ? file + 1 : 0;
					}
					return acc;
				}, []);
			});
 
		return new Board(lines.reduce((acc, cur) => {
			acc.push(...cur);
			return acc;
		}, []));
	}
 
	getFen () {
		const fen = [];
		const squares = this.squares
			.reduce((acc, cur, idx) => {
				const outerIdx = parseInt(idx / 8, 10);
				acc[outerIdx] = acc[outerIdx] || [];
				acc[outerIdx].push(cur);
				return acc;
			}, [])
			.flatMap((row) => row.reverse())
			.reverse();
 
		for (let i = 0; i < squares.length; i += 1) {
			const square = squares[i];
 
			if (square.file === 'a' && square.rank < 8) {
				fen.push('/');
			}
 
			if (square.piece) {
				const transform = `to${square.piece.side.name === 'white' ? 'Upp' : 'Low'}erCase`;
				fen.push((square.piece.notation || 'p')[transform]());
			} else {
				if (isNaN(Number(fen[fen.length - 1]))) {
					fen.push(1);
				} else {
					fen[fen.length - 1] += 1;
				}
			}
		}
 
		return fen.join('');
	}
 
	getNeighborSquare (sq, n) {
		Eif (sq && n) {
			// validate boundaries of board
			if (sq.file === 'a' && (n === NeighborType.AboveLeft ||
					n === NeighborType.BelowLeft ||
					n === NeighborType.Left)) {
				return null;
			}
 
			if (sq.file === 'h' && (n === NeighborType.AboveRight ||
					n === NeighborType.BelowRight ||
					n === NeighborType.Right)) {
				return null;
			}
 
			if (sq.rank === 1 && (n === NeighborType.Below ||
					n === NeighborType.BelowLeft ||
					n === NeighborType.BelowRight)) {
				return null;
			}
 
			if (sq.rank === 8 && (n === NeighborType.Above ||
					n === NeighborType.AboveLeft ||
					n === NeighborType.AboveRight)) {
				return null;
			}
 
			// validate file
			let
				fIndex = 'abcdefgh'.indexOf(sq.file),
				i = 0;
 
			Eif (fIndex !== -1 && sq.rank > 0 && sq.rank < 9) {
				// find the index
				i = 8 * (sq.rank - 1) + fIndex + n.offset;
				if (this.squares && this.squares.length > i && i > -1) {
					return this.squares[i];
				}
			}
		}
 
		return null;
	}
 
	getSquare (f, r) {
		// check for shorthand
		if (typeof f === 'string' && f.length === 2 && !r) {
			r = parseInt(f.charAt(1), 10);
			f = f.charAt(0);
		}
 
		// validate file
		let
			fIndex = 'abcdefgh'.indexOf(f),
			i = 0;
 
		if (fIndex !== -1 && r > 0 && r < 9) {
			// Find the index
			i = 8 * (r - 1) + fIndex;
			if (this.squares && this.squares.length > i) {
				return this.squares[i];
			}
		}
 
		return null;
	}
 
	getSquares (side) {
		const list = [];
 
		for (let i = 0; i < this.squares.length; i++) {
			if (this.squares[i].piece && this.squares[i].piece.side === side) {
				list.push(this.squares[i]);
			}
		}
 
		return list;
	}
 
	move (src, dest, n) {
		if (typeof src === 'string' && src.length === 2) {
			src = this.getSquare(src);
		}
 
		if (typeof dest === 'string' && dest.length === 2) {
			dest = this.getSquare(dest);
		}
 
		let simulate;
 
		if (typeof n === 'boolean') {
			simulate = n;
			n = null;
		}
 
		Eif (src && src.file && src.rank && dest && dest.file && dest.rank) {
			let
				move = {
					algebraic : n,
					capturedPiece : dest.piece,
					castle : false,
					enPassant : false,
					postSquare : dest,
					prevSquare : src
				},
				p = src.piece,
				sq = null,
				undo = (b, m) => {
					return () => {
						if (!simulate) {
							// ensure no harm can be done if called multiple times
							if (m.undone) {
								throw new Error('cannot undo a move multiple times');
							}
						}
 
						// backout move by returning the squares to their state prior to the move
						m.prevSquare.piece = m.postSquare.piece;
						m.postSquare.piece = m.capturedPiece;
 
						// handle standard scenario
						if (!m.enPassant) {
							m.postSquare.piece = m.capturedPiece;
						}
 
						// handle en-passant scenario
						if (m.enPassant) {
							b.getSquare(
								m.postSquare.file,
								m.prevSquare.rank
							).piece = m.capturedPiece;
 
							// there is no piece on the post square in the event of
							// an en-passant, clear anything that me be present as
							// a result of the move (fix for issue #8)
							m.postSquare.piece = null;
						}
 
						// handle castle scenario
						if (m.castle) {
							sq = b.getSquare(
								move.postSquare.file === 'g' ? 'f' : 'd',
								move.postSquare.rank);
								
							b.getSquare(
								move.postSquare.file === 'g' ? 'h' : 'a',
								move.postSquare.rank
							).piece = sq.piece;
							sq.piece = null;
						}
 
						// if not a simulation, reset the move count
						if (!simulate) {
							// correct the moveCount for the piece
							m.prevSquare.piece.moveCount = m.prevSquare.piece.moveCount - 1;
 
							// indicate move has been undone
							m.undone = true;
 
							// emit an undo event
							b.emit('undo', m);
						}
					};
				};
 
			dest.piece = p;
			move.castle = p.type === PieceType.King &&
				p.moveCount === 0 &&
				(move.postSquare.file === 'g' || move.postSquare.file === 'c');
			move.enPassant = p.type === PieceType.Pawn &&
				move.capturedPiece === null &&
				move.postSquare.file !== move.prevSquare.file;
			move.prevSquare.piece = null;
 
			// check for en-passant
			if (move.enPassant) {
				sq = this.getSquare(move.postSquare.file, move.prevSquare.rank);
				move.capturedPiece = sq.piece;
				sq.piece = null;
			}
 
			// check for castle
			if (move.castle) {
				sq = this.getSquare(
					move.postSquare.file === 'g' ? 'h' : 'a',
					move.postSquare.rank
				);
 
				Iif (sq.piece === null) {
					move.castle = false;
				} else {
					this.getSquare(
						move.postSquare.file === 'g' ? 'f' : 'd',
						move.postSquare.rank
					).piece = sq.piece;
					sq.piece = null;
				}
			}
 
			if (!simulate) {
				p.moveCount++;
				this.lastMovedPiece = p;
 
				if (move.capturedPiece) {
					this.emit('capture', move);
				}
 
				if (move.castle) {
					this.emit('castle', move);
				}
 
				if (move.enPassant) {
					this.emit('enPassant', move);
				}
 
				this.emit('move', move);
			}
 
			return {
				move,
				undo : undo(this, move)
			};
		}
	}
 
	promote (sq, p) {
		// update move count and last piece
		p.moveCount = sq.piece.moveCount;
		this.lastMovedPiece = p;
 
		// set to square
		sq.piece = p;
 
		this.emit('promote', sq);
 
		return sq;
	}
}
 
// exports
export default { Board, NeighborType };