====== Tic Tac Toe Game in HTML, CSS and Java Script ====== Tic-Tac-Toe

Tic-Tac-Toe

body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; margin: 0; } .container { text-align: center; } .board { display: grid; grid-template-columns: repeat(3, 100px); grid-gap: 5px; margin: 20px 0; } .cell { width: 100px; height: 100px; background-color: white; display: flex; justify-content: center; align-items: center; font-size: 36px; cursor: pointer; border: 2px solid #333; } .cell:hover { background-color: #e0e0e0; } .status { margin-top: 20px; font-size: 18px; } button { padding: 10px 20px; font-size: 16px; cursor: pointer; } const cells = document.querySelectorAll('.cell'); const statusDisplay = document.getElementById('status'); const restartButton = document.getElementById('restart'); let currentPlayer = 'X'; let gameActive = true; let gameState = ['', '', '', '', '', '', '', '', '']; const winningConditions = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; const handleCellClick = (event) => { const clickedCell = event.target; const clickedCellIndex = parseInt(clickedCell.getAttribute('data-cell-index')); if (gameState[clickedCellIndex] !== '' || !gameActive) { return; } gameState[clickedCellIndex] = currentPlayer; clickedCell.textContent = currentPlayer; checkResult(); }; const checkResult = () => { let roundWon = false; for (let i = 0; i < winningConditions.length; i++) { const [a, b, c] = winningConditions[i]; if (gameState[a] === '' || gameState[b] === '' || gameState[c] === '') { continue; } if (gameState[a] === gameState[b] && gameState[a] === gameState[c]) { roundWon = true; break; } } if (roundWon) { statusDisplay.textContent = `Player ${currentPlayer} has won!`; gameActive = false; return; } if (!gameState.includes('')) { statusDisplay.textContent = 'Game ended in a draw!'; gameActive = false; return; } currentPlayer = currentPlayer === 'X' ? 'O' : 'X'; statusDisplay.textContent = `It's ${currentPlayer}'s turn`; }; const restartGame = () => { gameActive = true; currentPlayer = 'X'; gameState = ['', '', '', '', '', '', '', '', '']; statusDisplay.textContent = `It's ${currentPlayer}'s turn`; cells.forEach(cell => { cell.textContent = ''; }); }; cells.forEach(cell => cell.addEventListener('click', handleCellClick)); restartButton.addEventListener('click', restartGame); statusDisplay.textContent = `It's ${currentPlayer}'s turn`; {{:java-script:games:pasted:20240814-035347.png}}