document.addEventListener('DOMContentLoaded', () => {
const playGameBtn = document.getElementById('playGameBtn');
const gamesSection = document.getElementById('gamesSection');
const resetGame = document.getElementById('resetGame');
const cells = document.querySelectorAll('.game-cell');
const gameStatus = document.getElementById('gameStatus');
const gameScore = document.getElementById('gameScore');
let currentPlayer = 'X';
let board = ['', '', '', '', '', '', '', '', ''];
let xWins = 0;
let oWins = 0;
let gameActive = true;
}
// Toggle games section visibility
playGameBtn.addEventListener('click', () => { gamesSection.style.display = gamesSection.style.display === 'none' ? 'block' : 'none'; // Optionally update button text based on state playGameBtn.textContent = gamesSection.style.display === 'block' ? 'Hide Game' : 'Play a Game While You Wait?'; });
// Handle cell click
function handleCellClick(event) {
const cell = event.target;
const index = parseInt(cell.getAttribute('data-index'));
if (board[index] !== '' || !gameActive) return;
board[index] = currentPlayer;
cell.textContent = currentPlayer;
if (checkWinner()) {
gameStatus.textContent = `Player ${currentPlayer} wins!`;
if (currentPlayer === 'X') xWins++;
else oWins++;
gameScore.textContent = `X Wins: ${xWins} | O Wins: ${oWins}`;
gameActive = false;
} else if (board.every(cell => cell !== '')) {
gameStatus.textContent = 'It\'s a draw!';
gameActive = false;
} else {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
gameStatus.textContent = `Player ${currentPlayer}'s turn`;
}
}
// Check for winner
function checkWinner() {
const winPatterns = [
[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
];
return winPatterns.some(pattern => {
return pattern.every(index => board[index] === currentPlayer);
});
}
// Reset game
resetGame.addEventListener('click', () => {
board = ['', '', '', '', '', '', '', '', ''];
gameActive = true;
currentPlayer = 'X';
cells.forEach(cell => {
cell.textContent = '';
});
gameStatus.textContent = `Player ${currentPlayer}'s turn`;
});
// Add event listeners for the game cells
cells.forEach(cell => {
cell.addEventListener('click', handleCellClick);
});
});
fix tis