html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tic Tac Toe</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}
#game {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
justify-content: center;
margin: 20px auto;
}
.cell {
background-color: #fff;
border: 2px solid #333;
font-size: 2.5rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background-color 0.3s;
}
.cell:hover {
background-color: #e6e6e6;
}
#status {
font-size: 1.2rem;
margin-top: 15px;
}
button {
margin-top: 15px;
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Tic Tac Toe</h1>
<div id="game"></div>
<div id="status"></div>
<button onclick="resetGame()">Restart Game</button>
<script>
const game = document.getElementById('game');
const statusText = document.getElementById('status');
let board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameActive = true;
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 checkWinner() {
for (let condition of winningConditions) {
const [a, b, c] = condition;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
gameActive = false;
statusText.textContent = `Player ${board[a]} wins!`;
return;
}
}
if (!board.includes("")) {
gameActive = false;
statusText.textContent = "It's a draw!";
return;
}
}
function handleCellClick(index) {
if (!gameActive || board[index]) return;
board[index] = currentPlayer;
renderBoard();
checkWinner();
if (gameActive) {
currentPlayer = currentPlayer === "X" ? "O" : "X";
statusText.textContent = `Player ${currentPlayer}'s turn`;
}
}
function renderBoard() {
game.innerHTML = "";
board.forEach((cell, index) => {
const cellDiv = document.createElement("div");
cellDiv.classList.add("cell");
cellDiv.textContent = cell;
cellDiv.addEventListener("click", () => handleCellClick(index));
game.appendChild(cellDiv);
});
}
function resetGame() {
board = ["", "", "", "", "", "", "", "", ""];
currentPlayer = "X";
gameActive = true;
statusText.textContent = `Player ${currentPlayer}'s turn`;
renderBoard();
}
// Initialize the game
resetGame();
</script>
</body>
</html>