-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.html
More file actions
70 lines (64 loc) · 2.15 KB
/
Copy pathcode.html
File metadata and controls
70 lines (64 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tic-Tac-Toe</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin: 0; padding: 0; }
h1 { margin: 10px; }
#board { display: grid; grid-template: repeat(3, 1fr) / repeat(3, 1fr); width: 180px; height: 180px; margin: 10px auto; gap: 2px; }
.cell { width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background: #eee; font-size: 24px; cursor: pointer; }
.cell.taken { cursor: not-allowed; }
#reset { margin-top: 10px; padding: 5px 10px; background: #007bff; color: #fff; border: none; border-radius: 3px; cursor: pointer; }
#reset:hover { background: #0056b3; }
</style>
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div id="board"></div>
<button id="reset">Reset</button>
<script>
const board = document.getElementById("board");
const reset = document.getElementById("reset");
let currentPlayer = "X", gameActive = true, grid = Array(9).fill("");
const winPatterns = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // cols
[0, 4, 8], [2, 4, 6] // diagonals
];
function checkWin() {
for (let pattern of winPatterns) {
const [a, b, c] = pattern;
if (grid[a] && grid[a] === grid[b] && grid[a] === grid[c]) return grid[a];
}
return grid.includes("") ? null : "Draw";
}
function renderBoard() {
board.innerHTML = grid.map((cell, i) =>
`<div class="cell ${cell ? "taken" : ""}" data-index="${i}">${cell}</div>`
).join("");
}
board.addEventListener("click", (e) => {
if (!gameActive) return;
const index = e.target.dataset.index;
if (index && !grid[index]) {
grid[index] = currentPlayer;
const winner = checkWin();
if (winner) {
gameActive = false;
setTimeout(() => alert(winner === "Draw" ? "It's a draw!" : `${winner} wins!`), 10);
}
currentPlayer = currentPlayer === "X" ? "O" : "X";
renderBoard();
}
});
reset.addEventListener("click", () => {
grid = Array(9).fill("");
currentPlayer = "X";
gameActive = true;
renderBoard();
});
renderBoard();
</script>
</body>
</html>