<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic-Tac-Toe</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
margin: 20px auto;
width: 320px;
}
.cell {
width: 100px;
height: 100px;
font-size: 2em;
font-weight: bold;
text-align: center;
line-height: 100px;
background-color: #f0f0f0;
border: 2px solid #000;
cursor: pointer;
}
.cell:hover {
background-color: #ddd;
}
.winner {
font-size: 1.5em;
margin-top: 20px;
}
button, select {
margin-top: 10px;
padding: 10px;
font-size: 1em;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<label for="playerSelect">Choose your player:</label>
<select id="playerSelect">
<option value="X">X</option>
<option value="O">O</option>
</select>
<button onclick="startGame()">Start Game</button>
<div class="board" id="board"></div>
<p class="winner" id="winner"></p>
<button onclick="resetGame()">Reset Game</button>
<script>
let board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameOver = false;
let playerChoice = "X";
function startGame() {
playerChoice = document.getElementById("playerSelect").value;
currentPlayer = playerChoice;
resetGame();
}
function createBoard() {
let boardElement = document.getElementById("board");
boardElement.innerHTML = "";
board.forEach((cell, index) => {
let cellElement = document.createElement("div");
cellElement.classList.add("cell");
cellElement.innerText = cell;
cellElement.addEventListener("click", () => makeMove(index));
boardElement.appendChild(cellElement);
});
}
function makeMove(index) {
if (!gameOver && board[index] === "") {
board[index] = currentPlayer;
checkWinner();
currentPlayer = currentPlayer === "X" ? "O" : "X";
createBoard();
}
}
function checkWinner() {
const winningCombinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
];
for (let combination of winningCombinations) {
let [a, b, c] = combination;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
document.getElementById("winner").innerText = `Player ${board[a]} Wins!`;
gameOver = true;
return;
}
}
if (!board.includes("")) {
document.getElementById("winner").innerText = "It's a Draw!";
gameOver = true;
}
}
function resetGame() {
board = ["", "", "", "", "", "", "", "", ""];
gameOver = false;
document.getElementById("winner").innerText = "";
createBoard();
}
createBoard();
</script>
</body>
</html>