Problem 28.1 - Chess Moves
const { runTests } = require("./tests.js");
function validChessMoves(board, piece, r, c) {
function isMoveValid(board, r, c) {
const rows = board.length;
const cols = board[0].length;
return (
(r >= 0 && r < rows) &&
(c >= 0 && c < cols) &&
board[r][c] != 1
);
}
const knightDirections = [[-2,1],[-2,-1],[2,1],[2,-1],[-1,2],[1,2],[-1,-2],[1,-2]];
const kingDirections = [[0, 1], [0,-1],[-1,0],[1,0],[-1,1], [-1,-1],[1,1], [1,-1]];
const queenDirections = kingDirections;
const moves = [];
if (piece === "knight") {
for (const [rDir, cDir] of knightDirections) {
const [newR, newC] = [r + rDir, c + cDir];
if (isMoveValid(board, newR, newC)) {
moves.push([newR, newC]);
}
}
}
else if (piece === "king") {
for (const [rDir, cDir] of kingDirections) {
const newR = r + rDir;
const newC = c + cDir;
if (isMoveValid(board, newR, newC)) {
moves.push([newR, newC]);
}
}
}
else {
for (const [rDir, cDir] of queenDirections) {
let newR = r + rDir;
let newC = c + cDir;
while (isMoveValid(board, newR, newC)) {
moves.push([newR, newC]);
newR += rDir;
newC += cDir;
}
}
}
return moves;
}
runTests(validChessMoves);INFO