-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
68 lines (60 loc) · 1.64 KB
/
script.js
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
const cells = document.querySelectorAll('td');
let player = 'X';
// Add click event to each cell
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener('click', function() {
if (this.textContent === '') {
this.textContent = player;
checkForWin();
switchPlayer();
}
});
}
function switchPlayer() {
if (player === 'X') {
player = 'O';
} else {
player = 'X';
}
}
function checkForWin() {
// Check rows
for (let i = 0; i <= 6; i += 3) {
if (cells[i].textContent === player && cells[i+1].textContent === player && cells[i+2].textContent === player) {
alert(`Player ${player} wins!`);
resetBoard();
}
}
// Check columns
for (let i = 0; i <= 2; i++) {
if (cells[i].textContent === player && cells[i+3].textContent === player && cells[i+6].textContent === player) {
alert(`Player ${player} wins!`);
resetBoard();
}
}
// Check diagonals
if (cells[0].textContent === player && cells[4].textContent === player && cells[8].textContent === player) {
alert(`Player ${player} wins!`);
resetBoard();
}
if (cells[2].textContent === player && cells[4].textContent === player && cells[6].textContent === player) {
alert(`Player ${player} wins!`);
resetBoard();
}
let isDraw = true;
for (let i = 0; i < cells.length; i++) {
if (cells[i].textContent === "") {
isDraw = false;
break;
}
}
if(isDraw) {
alert(`Its a Draw!!`);
resetBoard();
}
}
function resetBoard() {
for (let i = 0; i < cells.length; i++) {
cells[i].textContent = '';
}
}