Your current implementation includes a basic mechanism for detecting checks and displaying a "Check!" message. However, to ensure it works flawlessly and meets your specific requirements—automatically detecting checks based on the current player's turn and displaying the message appropriately—I recommend the following enhancements and refinements:
-
Ensure Accurate Check Detection:
The isKingInCheck function should accurately determine if the current player's king is under threat by any of the opponent's pieces. We'll refine this function to ensure it comprehensively checks all possible threats.
-
Display "Check!" Message Appropriately:
Modify the logic to display the "Check!" message in red for two seconds whenever a check is detected. This includes ensuring the message appears correctly during both human vs. human and human vs. AI games.
-
Handle Check After All Move Types:
Ensure that checks are detected after any type of move, including pawn promotions and AI moves.
Below are the detailed modifications and the complete updated code.
1. Refining the isKingInCheck Function
The existing isKingInCheck function checks if the king is under threat by simulating potential attacks from all opposing pieces. We'll enhance this function to cover all possible capturing moves and ensure accuracy.
function isKingInCheck(player, boardState) {
const kingSymbol = player === 'white' ? '♔' : '♚';
let kingRow, kingCol;
// Locate the king on the board
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (boardState[row][col] === kingSymbol) {
kingRow = row;
kingCol = col;
break;
}
}
if (kingRow !== undefined) break;
}
if (kingRow === undefined) {
console.error(`King for ${player} not found on the board.`);
return false;
}
// Iterate through all opponent pieces to see if any can attack the king
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = boardState[row][col];
if (piece && !isPieceOfCurrentPlayer(piece, player)) {
if (isValidMove(row, col, kingRow, kingCol, boardState, player)) {
return true;
}
}
}
}
return false;
}
Notes:
- Parameter Adjustment: Modified
isPieceOfCurrentPlayer to accept a player parameter for clarity.
- Error Handling: Added an error log if the king isn't found, which is crucial for debugging.
- Board State Parameter: Passed
boardState to isValidMove to allow the function to work with simulated board states.
2. Updating isPieceOfCurrentPlayer Function
Update the isPieceOfCurrentPlayer function to accurately determine ownership based on the player parameter.
function isPieceOfCurrentPlayer(piece, player) {
if (player === 'white') {
// White pieces Unicode: ♖ ♘ ♗ ♕ ♔ ♙
return ['♖', '♘', '♗', '♕', '♔', '♙'].includes(piece);
} else {
// Black pieces Unicode: ♜ ♞ ♝ ♛ ♚ ♟
return ['♜', '♞', '♝', '♛', '♚', '♟'].includes(piece);
}
}
3. Enhancing isValidMove Function
Ensure that isValidMove accurately validates moves based on the current board state and player.
function isValidMove(fromRow, fromCol, toRow, toCol, boardState = board, player = currentPlayer) {
const piece = boardState[fromRow][fromCol];
const targetPiece = boardState[toRow][toCol];
if (!piece) return false;
// Prevent capturing own pieces
if (targetPiece && isPieceOfCurrentPlayer(targetPiece, player)) {
return false;
}
// Piece-specific movement logic
switch (piece) {
case '♙': // White pawn
// Implement white pawn movement
return validatePawnMove(fromRow, fromCol, toRow, toCol, boardState, 'white');
case '♟': // Black pawn
// Implement black pawn movement
return validatePawnMove(fromRow, fromCol, toRow, toCol, boardState, 'black');
case '♖': case '♜': // Rook
return validateRookMove(fromRow, fromCol, toRow, toCol, boardState);
case '♘': case '♞': // Knight
return validateKnightMove(fromRow, fromCol, toRow, toCol);
case '♗': case '♝': // Bishop
return validateBishopMove(fromRow, fromCol, toRow, toCol, boardState);
case '♕': case '♛': // Queen
return validateQueenMove(fromRow, fromCol, toRow, toCol, boardState);
case '♔': case '♚': // King
return validateKingMove(fromRow, fromCol, toRow, toCol);
default:
return false;
}
}
Notes:
- Function Parameters: Added
boardState and player parameters for flexibility.
- Delegating to Specific Validators: To improve readability and maintainability, delegate validation to specific functions for each piece type.
4. Implementing Specific Move Validators
Implement dedicated functions for each piece type to handle their unique movement logic.
function validatePawnMove(fromRow, fromCol, toRow, toCol, boardState, player) {
const direction = player === 'white' ? -1 : 1;
const startRow = player === 'white' ? 6 : 1;
// Move forward
if (fromCol === toCol) {
if (boardState[toRow][toCol] !== '') return false;
if (toRow === fromRow + direction) return true;
if (fromRow === startRow && toRow === fromRow + 2 * direction && boardState[fromRow + direction][fromCol] === '') return true;
}
// Capture diagonally
if (Math.abs(toCol - fromCol) === 1 && toRow === fromRow + direction) {
if (boardState[toRow][toCol] !== '' && !isPieceOfCurrentPlayer(boardState[toRow][toCol], player)) {
return true;
}
}
return false;
}
function validateRookMove(fromRow, fromCol, toRow, toCol, boardState) {
if (fromRow !== toRow && fromCol !== toCol) return false;
return checkClearPath(fromRow, fromCol, toRow, toCol, boardState);
}
function validateKnightMove(fromRow, fromCol, toRow, toCol) {
const rowDiff = Math.abs(fromRow - toRow);
const colDiff = Math.abs(fromCol - toCol);
return (rowDiff === 2 && colDiff === 1) || (rowDiff === 1 && colDiff === 2);
}
function validateBishopMove(fromRow, fromCol, toRow, toCol, boardState) {
if (Math.abs(fromRow - toRow) !== Math.abs(fromCol - toCol)) return false;
return checkClearPath(fromRow, fromCol, toRow, toCol, boardState);
}
function validateQueenMove(fromRow, fromCol, toRow, toCol, boardState) {
if (fromRow === toRow || fromCol === toCol || Math.abs(fromRow - toRow) === Math.abs(fromCol - toCol)) {
return checkClearPath(fromRow, fromCol, toRow, toCol, boardState);
}
return false;
}
function validateKingMove(fromRow, fromCol, toRow, toCol) {
const rowDiff = Math.abs(fromRow - toRow);
const colDiff = Math.abs(fromCol - toCol);
return rowDiff <= 1 && colDiff <= 1;
}
Notes:
- Pawn Movement: Differentiates between white and black pawns based on direction.
- Rook, Bishop, Queen: Utilize the
checkClearPath function to ensure no pieces obstruct their movement.
- Knight and King: Have unique movement patterns that don't require path obstruction checks (except for the king moving into check, which is handled elsewhere).
5. Refining the checkClearPath Function
Ensure that the path between the source and destination squares is unobstructed for sliding pieces.
function checkClearPath(fromRow, fromCol, toRow, toCol, boardState) {
const rowIncrement = Math.sign(toRow - fromRow);
const colIncrement = Math.sign(toCol - fromCol);
let currentRow = fromRow + rowIncrement;
let currentCol = fromCol + colIncrement;
while (currentRow !== toRow || currentCol !== toCol) {
if (boardState[currentRow][currentCol] !== '') {
return false;
}
currentRow += rowIncrement;
currentCol += colIncrement;
}
return true;
}
6. Displaying the "Check!" Message
Modify the highlightCheck function to display the "Check!" message correctly based on the current player's status.
function highlightCheck() {
const kingSymbol = currentPlayer === 'white' ? '♔' : '♚';
let kingRow, kingCol;
// Locate the king on the board
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (board[row][col] === kingSymbol) {
kingRow = row;
kingCol = col;
break;
}
}
if (kingRow !== undefined) break;
}
const isInCheck = isKingInCheck(currentPlayer, board);
// Highlight the king's square if in check
for (let i = 0; i < chessboard.children.length; i++) {
chessboard.children[i].classList.remove('check');
}
if (isInCheck) {
const kingSquare = chessboard.children[kingRow * 8 + kingCol];
kingSquare.classList.add('check');
showCheckMessage();
}
}
7. Updating the showCheckMessage Function
Ensure the "Check!" message appears in red for two seconds and then disappears.
function showCheckMessage() {
checkMessage.style.display = 'block';
checkMessage.style.color = 'red'; // Ensure the message is red
setTimeout(() => {
checkMessage.style.display = 'none';
}, 2000); // Display for 2 seconds
}
8. Ensuring Check Detection After All Moves
Ensure that after every move—whether by a player or the AI—the check detection logic is invoked correctly.
For Player Moves:
After a player moves a piece, renderBoard() is called, which in turn calls highlightCheck(). This ensures that if the move results in a check, the message is displayed.
For AI Moves:
Ensure that after the AI makes a move, renderBoard() is called to detect any resulting check.
function makeAIMove() {
const moves = getAvailableMoves('black');
if (moves.length > 0) {
const move = selectAIMove(moves);
movePiece(move.fromRow, move.fromCol, move.toRow, move.toCol);
currentPlayer = 'white';
renderBoard();
if (isKingInCheck('white', board)) {
showCheckMessage();
}
}
}
Note: The renderBoard() function already calls highlightCheck(), which handles the check message. The additional isKingInCheck call ensures that the message appears immediately after the AI's move if necessary.
9. Complete Updated JavaScript Code
Below is the complete updated JavaScript code with all the enhancements integrated:
const gameContainer = document.getElementById('game-container');
const menu = document.getElementById('menu');
const chessboard = document.getElementById('chessboard');
const checkMessage = document.getElementById('check-message');
const promotionBox = document.getElementById('promotion-box');
let gameMode = '';
let aiDifficulty = 'hard';
let selectedPiece = null;
let currentPlayer = 'white';
let promotionRow = null;
let promotionCol = null;
const initialBoard = [
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖']
];
let board = JSON.parse(JSON.stringify(initialBoard));
function showMainMenu() {
menu.innerHTML = `
<button onclick="showGameModes()">Play</button>
<button onclick="showSettings()">Settings</button>
`;
}
function showGameModes() {
menu.innerHTML = `
<button onclick="startGame('1v1')">1 vs 1</button>
<button onclick="showAIDifficulty()">AI vs 1</button>
<button onclick="showMainMenu()">Home</button>
`;
}
function showSettings() {
menu.innerHTML = `
<h2>Settings</h2>
<button onclick="showMainMenu()">Home</button>
`;
}
function showAIDifficulty() {
menu.innerHTML = `
<button onclick="startGame('ai', 'easy')">Easy</button>
<button onclick="startGame('ai', 'medium')">Medium</button>
<button onclick="startGame('ai', 'hard')">Hard</button>
<button onclick="showGameModes()">Back</button>
`;
}
function startGame(mode, difficulty = 'hard') {
gameMode = mode;
aiDifficulty = difficulty;
menu.style.display = 'none';
chessboard.style.display = 'inline-grid';
renderBoard();
if (gameMode === 'ai') {
menu.innerHTML = `<button onclick="giveUp()">Give Up</button>`;
}
}
function renderBoard() {
chessboard.innerHTML = '';
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const square = document.createElement('div');
square.className = `square ${(row + col) % 2 === 0 ? 'white' : 'black'}`;
square.textContent = board[row][col];
square.addEventListener('click', () => handleSquareClick(row, col));
chessboard.appendChild(square);
}
}
highlightCheck();
}
function handleSquareClick(row, col) {
const piece = board[row][col];
if (selectedPiece) {
if (isValidMove(selectedPiece.row, selectedPiece.col, row, col)) {
movePiece(selectedPiece.row, selectedPiece.col, row, col);
selectedPiece = null;
currentPlayer = currentPlayer === 'white' ? 'black' : 'white';
renderBoard();
if (gameMode === 'ai' && currentPlayer === 'black') {
setTimeout(makeAIMove, 500);
}
} else {
selectedPiece = null;
renderBoard();
}
} else if (piece && isPieceOfCurrentPlayer(piece, currentPlayer)) {
selectedPiece = { row, col };
highlightSquare(row, col);
}
}
function isPieceOfCurrentPlayer(piece, player = currentPlayer) {
if (player === 'white') {
return ['♖', '♘', '♗', '♕', '♔', '♙'].includes(piece);
} else {
return ['♜', '♞', '♝', '♛', '♚', '♟'].includes(piece);
}
}
function isValidMove(fromRow, fromCol, toRow, toCol, boardState = board, player = currentPlayer) {
const piece = boardState[fromRow][fromCol];
const targetPiece = boardState[toRow][toCol];
if (!piece) return false;
// Prevent capturing own pieces
if (targetPiece && isPieceOfCurrentPlayer(targetPiece, player)) {
return false;
}
// Piece-specific movement logic
switch (piece) {
case '♙': // White pawn
return validatePawnMove(fromRow, fromCol, toRow, toCol, boardState, 'white');
case '♟': // Black pawn
return validatePawnMove(fromRow, fromCol, toRow, toCol, boardState, 'black');
case '♖': case '♜': // Rook
return validateRookMove(fromRow, fromCol, toRow, toCol, boardState);
case '♘': case '♞': // Knight
return validateKnightMove(fromRow, fromCol, toRow, toCol);
case '♗': case '♝': // Bishop
return validateBishopMove(fromRow, fromCol, toRow, toCol, boardState);
case '♕': case '♛': // Queen
return validateQueenMove(fromRow, fromCol, toRow, toCol, boardState);
case '♔': case '♚': // King
return validateKingMove(fromRow, fromCol, toRow, toCol);
default:
return false;
}
}
function validatePawnMove(fromRow, fromCol, toRow, toCol, boardState, player) {
const direction = player === 'white' ? -1 : 1;
const startRow = player === 'white' ? 6 : 1;
// Move forward
if (fromCol === toCol) {
if (boardState[toRow][toCol] !== '') return false;
if (toRow === fromRow + direction) return true;
if (fromRow === startRow && toRow === fromRow + 2 * direction && boardState[fromRow + direction][fromCol] === '') return true;
}
// Capture diagonally
if (Math.abs(toCol - fromCol) === 1 && toRow === fromRow + direction) {
if (boardState[toRow][toCol] !== '' && !isPieceOfCurrentPlayer(boardState[toRow][toCol], player)) {
return true;
}
}
// Handle Promotion Trigger
if ((player === 'white' && toRow === 0) || (player === 'black' && toRow === 7)) {
promotionRow = toRow;
promotionCol = toCol;
showPromotionBox();
}
return false;
}
function validateRookMove(fromRow, fromCol, toRow, toCol, boardState) {
if (fromRow !== toRow && fromCol !== toCol) return false;
return checkClearPath(fromRow, fromCol, toRow, toCol, boardState);
}
function validateKnightMove(fromRow, fromCol, toRow, toCol) {
const rowDiff = Math.abs(fromRow - toRow);
const colDiff = Math.abs(fromCol - toCol);
return (rowDiff === 2 && colDiff === 1) || (rowDiff === 1 && colDiff === 2);
}
function validateBishopMove(fromRow, fromCol, toRow, toCol, boardState) {
if (Math.abs(fromRow - toRow) !== Math.abs(fromCol - toCol)) return false;
return checkClearPath(fromRow, fromCol, toRow, toCol, boardState);
}
function validateQueenMove(fromRow, fromCol, toRow, toCol, boardState) {
if (fromRow === toRow || fromCol === toCol || Math.abs(fromRow - toRow) === Math.abs(fromCol - toCol)) {
return checkClearPath(fromRow, fromCol, toRow, toCol, boardState);
}
return false;
}
function validateKingMove(fromRow, fromCol, toRow, toCol) {
const rowDiff = Math.abs(fromRow - toRow);
const colDiff = Math.abs(fromCol - toCol);
return rowDiff <= 1 && colDiff <= 1;
}
function checkClearPath(fromRow, fromCol, toRow, toCol, boardState) {
const rowIncrement = Math.sign(toRow - fromRow);
const colIncrement = Math.sign(toCol - fromCol);
let currentRow = fromRow + rowIncrement;
let currentCol = fromCol + colIncrement;
while (currentRow !== toRow || currentCol !== toCol) {
if (boardState[currentRow][currentCol] !== '') {
return false;
}
currentRow += rowIncrement;
currentCol += colIncrement;
}
return true;
}
function movePiece(fromRow, fromCol, toRow, toCol) {
board[toRow][toCol] = board[fromRow][fromCol];
board[fromRow][fromCol] = '';
if ((toRow === 0 && board[toRow][toCol] === '♙') || (toRow === 7 && board[toRow][toCol] === '♟')) {
promotionRow = toRow;
promotionCol = toCol;
showPromotionBox();
}
}
function highlightSquare(row, col) {
const square = chessboard.children[row * 8 + col];
square.style.backgroundColor = 'yellow';
}
function makeAIMove() {
const moves = getAvailableMoves('black');
if (moves.length > 0) {
const move = selectAIMove(moves);
movePiece(move.fromRow, move.fromCol, move.toRow, move.toCol);
currentPlayer = 'white';
renderBoard();
// After AI moves, check if White is in check
if (isKingInCheck('white', board)) {
showCheckMessage();
}
}
}
function getAvailableMoves(player) {
const moves = [];
for (let fromRow = 0; fromRow < 8; fromRow++) {
for (let fromCol = 0; fromCol < 8; fromCol++) {
if (board[fromRow][fromCol] && isPieceOfCurrentPlayer(board[fromRow][fromCol], player)) {
for (let toRow = 0; toRow < 8; toRow++) {
for (let toCol = 0; toCol < 8; toCol++) {
if (isValidMove(fromRow, fromCol, toRow, toCol)) {
const tempBoard = JSON.parse(JSON.stringify(board));
tempBoard[toRow][toCol] = tempBoard[fromRow][fromCol];
tempBoard[fromRow][fromCol] = '';
if (!isKingInCheck(player, tempBoard)) {
moves.push({ fromRow, fromCol, toRow, toCol });
}
}
}
}
}
}
}
return moves;
}
function selectAIMove(moves) {
const capturingMoves = moves.filter(move => board[move.toRow][move.toCol] !== '');
const checkingMoves = moves.filter(move => {
const tempBoard = JSON.parse(JSON.stringify(board));
tempBoard[move.toRow][move.toCol] = tempBoard[move.fromRow][move.fromCol];
tempBoard[move.fromRow][move.fromCol] = '';
return isKingInCheck('white', tempBoard);
});
if (checkingMoves.length > 0) {
return checkingMoves[Math.floor(Math.random() * checkingMoves.length)];
} else if (capturingMoves.length > 0) {
return capturingMoves[Math.floor(Math.random() * capturingMoves.length)];
} else {
return moves[Math.floor(Math.random() * moves.length)];
}
}
function isKingInCheck(player, boardState) {
const kingSymbol = player === 'white' ? '♔' : '♚';
let kingRow, kingCol;
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (boardState[row][col] === kingSymbol) {
kingRow = row;
kingCol = col;
break;
}
}
if (kingRow !== undefined) break;
}
if (kingRow === undefined) {
console.error(`King for ${player} not found on the board.`);
return false;
}
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = boardState[row][col];
if (piece && !isPieceOfCurrentPlayer(piece, player)) {
if (isValidMove(row, col, kingRow, kingCol, boardState, player)) {
return true;
}
}
}
}
return false;
}
function highlightCheck() {
const kingSymbol = currentPlayer === 'white' ? '♔' : '♚';
let kingRow, kingCol;
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (board[row][col] === kingSymbol) {
kingRow = row;
kingCol = col;
break;
}
}
if (kingRow !== undefined) break;
}
const isInCheck = isKingInCheck(currentPlayer, board);
// Remove any existing check highlights
for (let i = 0; i < chessboard.children.length; i++) {
chessboard.children[i].classList.remove('check');
}
if (isInCheck) {
const kingSquare = chessboard.children[kingRow * 8 + kingCol];
kingSquare.classList.add('check');
showCheckMessage();
}
}
function showCheckMessage() {
checkMessage.style.display = 'block';
checkMessage.style.color = 'red';
setTimeout(() => {
checkMessage.style.display = 'none';
}, 2000);
}
function showPromotionBox() {
promotionBox.style.display = 'block';
}
function promotePawn(pieceType) {
const whitePieces = { queen: '♕', rook: '♖', bishop: '♗', knight: '♘' };
const blackPieces = { queen: '♛', rook: '♜', bishop: '♝', knight: '♞' };
const pieces = board[promotionRow][promotionCol] === '♙' ? whitePieces : blackPieces;
board[promotionRow][promotionCol] = pieces[pieceType];
promotionBox.style.display = 'none';
renderBoard();
}
function giveUp() {
chessboard.style.display = 'none';
showGameModes();
}
showMainMenu();
10. Testing the Implementation
After integrating the above changes, thoroughly test the game to ensure:
-
Check Detection:
Move pieces to create scenarios where a king is in check. Verify that the "Check!" message appears in red for two seconds and that the king's square is highlighted.
-
AI Behavior:
In AI vs. 1 mode, ensure that the AI does not make illegal moves that leave its king in check and that it responds appropriately when in check.
-
Pawn Promotion:
Promote pawns and verify that check detection works post-promotion.
-
Edge Cases:
Test edge cases, such as when the king is under double check or when no legal moves are available (checkmate scenarios).
11. Additional Enhancements (Optional)
To further enhance your chess game, consider implementing:
-
Checkmate and Stalemate Detection:
Currently, the game detects checks but doesn't handle checkmates or stalemates. Implement logic to recognize these game-ending states and display appropriate messages.
-
Move Validation Enhancements:
Incorporate more robust move validations, such as castling, en passant captures, and pawn promotion under specific conditions.
-
User Interface Improvements:
Enhance visual indicators for selected pieces, possible moves, and endgame states to provide a better user experience.
-
AI Improvement:
Implement more sophisticated AI algorithms (e.g., Minimax with alpha-beta pruning) to provide a challenging opponent.
By implementing the above modifications, your chess game should now accurately detect checks based on the current player's turn and display the "Check!" message in red for two seconds when applicable. Ensure to perform comprehensive testing to validate the functionality and address any potential issues.