-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchessCheck.js
More file actions
55 lines (45 loc) · 1.33 KB
/
chessCheck.js
File metadata and controls
55 lines (45 loc) · 1.33 KB
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
'use strict';
module.exports = chessCheck;
/**
* Checks if a given chess board is in check, only for Rook and Knight.
*
* k = king, one in any direction
* kn = knight, L shape, 2 in UDLR, 1 LR
* q = queen, any amount in any single direction
* b = bishop, any amount in diagonal
* r = rook, any amount UDLR
*
* @param {Array} board : 2D array, 8x8
*/
function chessCheck(board) {
const kingPos = _getKingPosition(board);
return _checkRook(board, kingPos) || _checkKnight(board, kingPos);
}
function _checkKnight(board, king) {
const knightSpots = [board[king.row + 2][king.column + 1]];
if (king.row >= 2) {
if (king.column >= 1) {
knightSpots.push(board[king.row - 2][king.column - 1]);
}
knightSpots.push(board[king.row - 2][king.column + 1]);
}
if (king.column >= 1) {
knightSpots.push(board[king.row + 2][king.column - 1]);
}
return knightSpots.includes('kn');
}
function _checkRook(board, kingPos) {
const kingRow = board[kingPos.row];
const kingColumn = board.map((row) => row[kingPos.column]);
return kingRow.includes('r') || kingColumn.includes('r');
}
function _getKingPosition(board) {
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
if (board[i][j] === 'k') {
return { row: i, column: j };
}
}
}
return null;
}