// script.
js
document.addEventListener("DOMContentLoaded", () => {
const cells = document.querySelectorAll(".cell");
const statusDisplay = document.getElementById("status");
const restartButton = document.getElementById("restart");
let currentPlayer = "X";
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],
];
function handleCellClick(event) {
const cell = event.target;
const cellIndex = cell.getAttribute("data-index");
// If cell is already taken or the game is over, return
if (gameState[cellIndex] !== "" || checkWinner()) return;
// Update the cell and game state
gameState[cellIndex] = currentPlayer;
cell.textContent = currentPlayer;
cell.classList.add("taken");
// Check for winner or tie
if (checkWinner()) {
statusDisplay.textContent = `Player ${currentPlayer} Wins!`;
highlightWinningCells();
return;
} else if (gameState.every(cell => cell !== "")) {
statusDisplay.textContent = "It's a Tie!";
return;
}
// Switch player
currentPlayer = currentPlayer === "X" ? "O" : "X";
statusDisplay.textContent = `Player ${currentPlayer}'s Turn`;
}
function checkWinner() {
for (const condition of winningConditions) {
const [a, b, c] = condition;
if (
gameState[a] &&
gameState[a] === gameState[b] &&
gameState[a] === gameState[c]
) {
return condition;
}
}
return null;
}
function highlightWinningCells() {
const winnerCells = checkWinner();
if (winnerCells) {
winnerCells.forEach(index => {
cells[index].style.backgroundColor = "#90ee90";
});
}
}
function restartGame() {
currentPlayer = "X";
gameState = ["", "", "", "", "", "", "", "", ""];
statusDisplay.textContent = `Player ${currentPlayer}'s Turn`;
cells.forEach(cell => {
cell.textContent = "";
cell.style.backgroundColor = "#fff";
cell.classList.remove("taken");
});
}
// Event listeners
cells.forEach(cell => cell.addEventListener("click", handleCellClick));
restartButton.addEventListener("click", restartGame);
// Initialize the status display
statusDisplay.textContent = `Player ${currentPlayer}'s Turn`;
});