Changed around line 1
+ document.addEventListener('DOMContentLoaded', () => {
+ const board = document.querySelector('.game-board');
+ const cells = document.querySelectorAll('[data-cell]');
+ const status = document.getElementById('status');
+ const restartButton = document.getElementById('restartButton');
+ let currentPlayer = 'X';
+ let gameState = ['', '', '', '', '', '', '', '', ''];
+ let gameActive = true;
+
+ const winningCombinations = [
+ [0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
+ [0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
+ [0, 4, 8], [2, 4, 6] // Diagonals
+ ];
+
+ function handleCellClick(e) {
+ const cell = e.target;
+ const index = Array.from(cells).indexOf(cell);
+
+ if (gameState[index] !== '' || !gameActive) return;
+
+ gameState[index] = currentPlayer;
+ cell.textContent = currentPlayer;
+ cell.classList.add(currentPlayer.toLowerCase());
+ cell.setAttribute('aria-label', `${currentPlayer} placed at position ${index + 1}`);
+
+ if (checkWin()) {
+ gameActive = false;
+ status.textContent = `Player ${currentPlayer} Wins!`;
+ highlightWinningCells();
+ return;
+ }
+
+ if (checkDraw()) {
+ gameActive = false;
+ status.textContent = "Game Draw!";
+ return;
+ }
+
+ currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
+ status.textContent = `Player ${currentPlayer}'s Turn`;
+ }
+
+ function checkWin() {
+ return winningCombinations.some(combination => {
+ return combination.every(index => {
+ return gameState[index] === currentPlayer;
+ });
+ });
+ }
+
+ function checkDraw() {
+ return gameState.every(cell => cell !== '');
+ }
+
+ function highlightWinningCells() {
+ winningCombinations.forEach(combination => {
+ if (combination.every(index => gameState[index] === currentPlayer)) {
+ combination.forEach(index => {
+ cells[index].classList.add('win');
+ });
+ }
+ });
+ }
+
+ function restartGame() {
+ gameState = ['', '', '', '', '', '', '', '', ''];
+ gameActive = true;
+ currentPlayer = 'X';
+ status.textContent = `Player ${currentPlayer}'s Turn`;
+
+ cells.forEach(cell => {
+ cell.textContent = '';
+ cell.classList.remove('x', 'o', 'win');
+ cell.setAttribute('aria-label', 'Empty cell');
+ });
+ }
+
+ // Event Listeners
+ cells.forEach(cell => {
+ cell.addEventListener('click', handleCellClick);
+ cell.setAttribute('aria-label', 'Empty cell');
+ });
+
+ restartButton.addEventListener('click', restartGame);
+
+ // Initialize game
+ restartGame();
+ });