let currentPlayer = 'X'; // X starts
let gameBoard = ['', '', '', '', '', '', '', '', '']; // 9 cells empty
let gameActive = true;
const cells = document.querySelectorAll('.cell');
const message = document.getElementById('message');
const board = document.getElementById('board');
function handleClick(index) {
if (!gameActive || gameBoard[index] !== '') return;
gameBoard[index] = currentPlayer;
cells[index].textContent = currentPlayer;
if (checkWinner()) {
message.textContent = `${currentPlayer} wins!`;
message.classList.add('winner-message');
gameActive = false;
return;
}
if (gameBoard.every(cell => cell !== '')) {
message.textContent = 'It\'s a draw!';
message.classList.add('draw-message');
gameActive = false;
return;
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
function checkWinner() {
const winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let combination of winningCombinations) {
const [a, b, c] = combination;
if (gameBoard[a] && gameBoard[a] === gameBoard[b] && gameBoard[a] === gameBoard[c]) {
return true;
}
}
return false;
}
function resetGame() {
gameBoard = ['', '', '', '', '', '', '', '', ''];
gameActive = true;
currentPlayer = 'X';
message.textContent = '';
message.classList.remove('winner-message', 'draw-message');
cells.forEach(cell => cell.textContent = '');
}
cells.forEach((cell, index) => {
cell.addEventListener('click', () => handleClick(index));
});