-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
68 lines (57 loc) · 1.62 KB
/
app.ts
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
enum Player {
None = '',
X = 'X',
O = 'O',
}
type Board = Player[];
let currentPlayer: Player = Player.X;
let board: Board = Array(9).fill(Player.None);
const winningCombinations: number[][] = [
[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
];
function cellClick(index: number) {
if (board[index] === Player.None) {
board[index] = currentPlayer;
renderBoard();
checkWinner();
currentPlayer = currentPlayer === Player.X ? Player.O : Player.X;
}
}
function checkWinner() {
for (const combination of winningCombinations) {
const [a, b, c] = combination;
if (board[a] !== Player.None &&
board[a] === board[b] &&
board[a] === board[c]) {
alert(`${board[a]} wins!`);
resetGame();
return;
}
}
if (!board.includes(Player.None)) {
alert("It's a draw!");
resetGame();
}
}
function resetGame() {
board = Array(9).fill(Player.None);
currentPlayer = Player.X;
renderBoard();
}
function renderBoard() {
const cells = document.querySelectorAll('.cell');
cells.forEach((cell, index) => {
cell.textContent = board[index];
});
}
document.addEventListener('DOMContentLoaded', () => {
const cells = document.querySelectorAll('.cell');
cells.forEach((cell, index) => {
cell.addEventListener('click', () => cellClick(index));
});
const resetButton = document.getElementById('resetBtn');
resetButton?.addEventListener('click', resetGame);
renderBoard();
});