-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtictactoe.js
More file actions
63 lines (53 loc) · 1.77 KB
/
tictactoe.js
File metadata and controls
63 lines (53 loc) · 1.77 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
const cells = document.querySelectorAll("[data-cell]");
const statusText = document.getElementById("status");
const restartButton = document.getElementById("restart");
let currentPlayer = "X";
let board = Array(9).fill(null);
function checkWinner() {
const winningCombinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
[0, 4, 8], [2, 4, 6] // Diagonals
];
for (const combination of winningCombinations) {
const [a, b, c] = combination;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
return board[a];
}
}
return null;
}
function updateStatus(winner) {
if (winner) {
statusText.textContent = `Player ${winner} wins!`;
cells.forEach(cell => cell.removeEventListener("click", onClick));
} else if (board.every(cell => cell)) {
statusText.textContent = "It's a tie!";
} else {
statusText.textContent = `Player ${currentPlayer}'s turn`;
}
}
function onClick(e) {
const cell = e.target;
const index = Array.from(cells).indexOf(cell);
if (board[index] || checkWinner()) return;
board[index] = currentPlayer;
cell.textContent = currentPlayer;
cell.classList.add("taken");
const winner = checkWinner();
updateStatus(winner);
currentPlayer = currentPlayer === "X" ? "O" : "X";
}
function resetGame() {
board.fill(null);
cells.forEach(cell => {
cell.textContent = "";
cell.classList.remove("taken");
cell.addEventListener("click", onClick);
});
currentPlayer = "X";
updateStatus(null);
}
cells.forEach(cell => cell.addEventListener("click", onClick));
restartButton.addEventListener("click", resetGame);
updateStatus(null);