I am building a chess game , I am now implementing a check. here is my implementation:
export function check(position, color) {
let king;
position.forEach((row) => {
row.forEach((piece) => {
if (piece.symbol == "k" && piece.color == color) king = piece;
});
});
getAllLegalMoves(position, color === "w" ? "b" : "w").forEach((el) => {
if (el.row == king.row && el.col == king.col) {
return true;
}
});
return false;
}
the function do the following:
here is the code for dropping the piece in the new square:
document.addEventListener("drop", function (event) {
const { row, col } = dragged.parentNode.dataset;
const piece = position[row][col];
if (!piece.canMoveTo(position, event.target.dataset) || piece.color != turn)
return;
piece.movePiece(position, event.target.dataset);
if (check(position, turn)) console.log("check");
dragged.parentNode.removeChild(dragged);
event.target.appendChild(dragged);
if (turn == "w") turn = "b";
else turn = "w";
});
first I check if the piece can move to the new square, If so I move the piece and I check the player who moved the piece is in check , if so I log check , but it is always logging false. Can you help me please. Thank you.
My first observation would be that you are returning true from your forEach function, which does nothing. Then you are returning false always no matter what. Try this:
export function check(position, color) {
let king;
position.forEach((row) => {
row.forEach((piece) => {
if (piece.symbol == "k" && piece.color == color) king = piece;
});
});
return getAllLegalMoves(position, color === "w" ? "b" : "w").reduce((carry, el) => {
if (carry) return carry;
return el.row == king.row && el.col == king.col;
}, false);
}
here is the answer:
export function check(position, color) {
let king,
inCheck = false;
position.forEach((row) => {
row.forEach((piece) => {
if (piece.symbol == "k" && piece.color == color) king = piece;
});
});
getAllLegalMoves(position, color === "w" ? "b" : "w").forEach((el) => {
if (el.row == king.row && el.col == king.col) {
inCheck = true;
}
});
return inCheck;
}