const boardElement = document.getElementById('board'); const size = 7; // -1 = invalid, 1 = marble, 0 = empty const board = [ [-1, -1, 1, 1, 1, -1, -1], [-1, -1, 1, 1, 1, -1, -1], [ 1, 1, 1, 1, 1, 1, 1], [ 1, 1, 1, 0, 1, 1, 1], [ 1, 1, 1, 1, 1, 1, 1], [-1, -1, 1, 1, 1, -1, -1], [-1, -1, 1, 1, 1, -1, -1] ]; let selectedCell = null; function drawBoard() { boardElement.innerHTML = ''; for (let row = 0; row < size; row++) { for (let col = 0; col < size; col++) { const cell = document.createElement('div'); cell.classList.add('cell'); if (board[row][col] === 1) { cell.classList.add('marble'); } else if (board[row][col] === 0) { cell.classList.add('empty'); } else { cell.classList.add('invalid'); } if (selectedCell && selectedCell.row === row && selectedCell.col === col) { cell.classList.add('selected'); } cell.dataset.row = row; cell.dataset.col = col; cell.addEventListener('click', () => handleClick(row, col)); boardElement.appendChild(cell); } } } // Handle cell click function handleClick(row, col) { if (selectedCell) { if (isValidMove(selectedCell.row, selectedCell.col, row, col)) { makeMove(selectedCell.row, selectedCell.col, row, col); selectedCell = null; } else { selectedCell = null; } } else if (board[row][col] === 1) { selectedCell = { row, col }; } drawBoard(); } // Check if the move is valid function isValidMove(fromRow, fromCol, toRow, toCol) { if (board[toRow][toCol] !== 0) return false; const rowDiff = Math.abs(fromRow - toRow); const colDiff = Math.abs(fromCol - toCol); if ((rowDiff === 2 && colDiff === 0) || (rowDiff === 0 && colDiff === 2)) { const midRow = (fromRow + toRow) / 2; const midCol = (fromCol + toCol) / 2; return board[midRow][midCol] === 1; } return false; } function makeMove(fromRow, fromCol, toRow, toCol) { const midRow = (fromRow + toRow) / 2; const midCol = (fromCol + toCol) / 2; board[fromRow][fromCol] = 0; board[midRow][midCol] = 0; board[toRow][toCol] = 1; drawBoard(); checkWinCondition(); } function checkWinCondition() { let marbleCount = 0; for (let row = 0; row < size; row++) { for (let col = 0; col < size; col++) { if (board[row][col] === 1) { marbleCount++; } } } if (marbleCount === 1) { alert("Congratulations! You've won the game!"); } } drawBoard();