script.js
script.js
js
document.addEventListener("DOMContentLoaded", () => {
const cells = document.querySelectorAll(".cell");
const statusDisplay = document.getElementById("status");
const restartButton = document.getElementById("restart");
function handleCellClick(event) {
const cell = event.target;
const cellIndex = cell.getAttribute("data-index");
// 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);