// Chess game initialization const chess = new Chess(); const boardElement = document.getElementById('chessboard'); const fenDisplay = document.getElementById('fen-display'); const moveHistory = document.getElementById('move-history'); const currentTurn = document.getElementById('current-turn'); const moveCount = document.getElementById('move-count'); const newGameBtn = document.getElementById('new-game'); const flipBoardBtn = document.getElementById('flip-board'); const aiMoveBtn = document.getElementById('ai-move'); const toggleAiBtn = document.getElementById('toggle-ai'); const aiLevelSelect = document.getElementById('ai-level'); const undoMoveBtn = document.getElementById('undo-move'); const gameStatus = document.getElementById('game-status'); const whiteScore = document.getElementById('white-score'); const blackScore = document.getElementById('black-score'); // Stockfish AI const stockfish = new Worker('https://cdnjs.cloudflare.com/ajax/libs/stockfish.js/10.0.2/stockfish.js'); let isPlayerTurn = true; let isAiGame = false; let aiLevel = 2; // Initialize the board function initializeBoard() { boardElement.innerHTML = ''; let isWhite = true; for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { const square = document.createElement('div'); square.className = `square ${isWhite ? 'white-square' : 'black-square'}`; square.dataset.row = i; square.dataset.col = j; square.addEventListener('click', () => handleSquareClick(i, j)); boardElement.appendChild(square); isWhite = !isWhite; } isWhite = !isWhite; } updateBoard(); updateScores(); } // Update the board with current pieces function updateBoard() { const squares = boardElement.querySelectorAll('.square'); squares.forEach(square => { square.innerHTML = ''; square.classList.remove('highlight', 'selected', 'possible-move', 'check'); }); // Highlight king in check if (chess.in_check()) { const kingPos = chess.board().flat().find(p => p && p.type === 'k' && p.color === chess.turn()); if (kingPos) { const square = document.querySelector(`.square[data-row="${kingPos.square[1] - 1}"][data-col="${kingPos.square.charCodeAt(0) - 97}"]`); square.classList.add('check'); } } // Place pieces on board for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { const piece = chess.get(String.fromCharCode(97 + j) + (8 - i)); if (piece) { const square = document.querySelector(`.square[data-row="${i}"][data-col="${j}"]`); const pieceElement = document.createElement('div'); pieceElement.className = 'piece'; pieceElement.textContent = getPieceSymbol(piece); square.appendChild(pieceElement); } } } // Update game info fenDisplay.textContent = chess.fen(); currentTurn.textContent = chess.turn() === 'w' ? 'White' : 'Black'; moveCount.textContent = chess.history().length; } // Get Unicode chess piece symbols function getPieceSymbol(piece) { const symbols = { 'p': '♟', 'n': '♞', 'b': '♝', 'r': '♜', 'q': '♛', 'k': '♚', 'P': '♙', 'N': '♘', 'B': '♗', 'R': '♖', 'Q': '♕', 'K': '♔' }; return symbols[piece.type] || ''; } // Handle square clicks let selectedSquare = null; let possibleMoves = []; function showPieceMovement(piece, fromSquare) { clearSelection(); const moves = chess.moves({ square: fromSquare, verbose: true }); // Highlight the selected piece const [file, rank] = fromSquare.split(''); const col = file.charCodeAt(0) - 97; const row = 8 - parseInt(rank); const square = document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`); square.classList.add('selected'); // Highlight possible moves moves.forEach(move => { const toRow = 8 - parseInt(move.to[1]); const toCol = move.to.charCodeAt(0) - 97; const square = document.querySelector(`.square[data-row="${toRow}"][data-col="${toCol}"]`); square.classList.add('possible-move'); }); } function handleSquareClick(row, col) { if (!isPlayerTurn) return; const squareNotation = String.fromCharCode(97 + col) + (8 - row); const clickedSquare = document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`); // If a piece is selected and user clicks on a possible move if (selectedSquare && possibleMoves.some(move => move.to === squareNotation)) { const move = possibleMoves.find(move => move.to === squareNotation); makeMove(move); return; } // Clear previous selection clearSelection(); // Select new piece if it's the current player's turn const piece = chess.get(squareNotation); if (piece && piece.color === chess.turn()) { selectedSquare = { row, col, notation: squareNotation }; clickedSquare.classList.add('selected'); // Highlight possible moves possibleMoves = chess.moves({ square: squareNotation, verbose: true }); possibleMoves.forEach(move => { const toRow = 8 - parseInt(move.to[1]); const toCol = move.to.charCodeAt(0) - 97; const square = document.querySelector(`.square[data-row="${toRow}"][data-col="${toCol}"]`); square.classList.add('possible-move'); }); } } function clearSelection() { document.querySelectorAll('.square').forEach(sq => { sq.classList.remove('selected', 'possible-move'); }); selectedSquare = null; possibleMoves = []; } // Make a move function makeMove(move) { chess.move(move); updateBoard(); addToMoveHistory(move); clearSelection(); updateGameStatus(); if (isAiGame && chess.turn() === 'b') { isPlayerTurn = false; getAiMove(); } } // Add move to history function addToMoveHistory(move) { const moveElement = document.createElement('div'); moveElement.className = 'flex justify-between py-1 px-2 hover:bg-gray-600 rounded'; moveElement.textContent = `${move.piece.toUpperCase()} ${move.from} → ${move.to}`; moveHistory.appendChild(moveElement); moveHistory.scrollTop = moveHistory.scrollHeight; } // AI move using Stockfish function getAiMove() { stockfish.postMessage(`uci`); stockfish.postMessage(`position fen ${chess.fen()}`); stockfish.postMessage(`go depth ${aiLevel}`); stockfish.onmessage = (event) => { if (event.data.startsWith('bestmove')) { const moveStr = event.data.split(' ')[1]; const move = { from: moveStr.substring(0, 2), to: moveStr.substring(2, 4), promotion: moveStr.length > 4 ? moveStr.substring(4, 5) : undefined }; setTimeout(() => { makeMove(move); isPlayerTurn = true; }, 500); } }; } // Event listeners newGameBtn.addEventListener('click', () => { chess.reset(); updateBoard(); moveHistory.innerHTML = ''; if (isAiGame && chess.turn() === 'b') { isPlayerTurn = false; getAiMove(); } else { isPlayerTurn = true; } }); flipBoardBtn.addEventListener('click', () => { boardElement.classList.toggle('flipped'); }); aiMoveBtn.addEventListener('click', () => { if (!isAiGame && chess.turn() === 'b') { getAiMove(); } }); toggleAiBtn.addEventListener('click', () => { isAiGame = !isAiGame; toggleAiBtn.textContent = isAiGame ? 'Playing vs AI' : 'Play vs AI'; toggleAiBtn.classList.toggle('bg-purple-600', !isAiGame); toggleAiBtn.classList.toggle('bg-purple-800', isAiGame); }); undoMoveBtn.addEventListener('click', () => { if (chess.history().length > 0) { chess.undo(); updateBoard(); moveHistory.innerHTML = ''; chess.history().forEach(move => { addToMoveHistory(move); }); isPlayerTurn = chess.turn() === 'w'; updateGameStatus(); } }); aiLevelSelect.addEventListener('change', (e) => { aiLevel = parseInt(e.target.value); }); // Update game status and scores function updateGameStatus() { if (chess.in_checkmate()) { gameStatus.textContent = `Checkmate! ${chess.turn() === 'w' ? 'Black' : 'White'} wins!`; gameStatus.className = 'text-sm font-medium text-red-400'; updateScores(); } else if (chess.in_stalemate()) { gameStatus.textContent = 'Stalemate! Game is a draw.'; gameStatus.className = 'text-sm font-medium text-yellow-400'; } else if (chess.in_check()) { gameStatus.textContent = `${chess.turn() === 'w' ? 'White' : 'Black'} is in check!'; gameStatus.className = 'text-sm font-medium text-orange-400'; } else { gameStatus.textContent = 'Game in Progress'; gameStatus.className = 'text-sm font-medium text-green-400'; } } function updateScores() { if (chess.in_checkmate()) { if (chess.turn() === 'w') { whiteScore.textContent = parseInt(whiteScore.textContent) + 1; } else { blackScore.textContent = parseInt(blackScore.textContent) + 1; } } // Initialize the game initializeBoard();