-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
109 lines (90 loc) · 2.21 KB
/
main.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
let board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "x";
let gameOver = false;
const status = document.querySelector(".status");
const resetButton = document.querySelector("button");
const td = document.querySelectorAll("td");
document.querySelectorAll(".square").forEach(function (square) {
square.addEventListener("click", handleSquareChoice);
});
function handleSquareChoice(event) {
if (gameOver) {
return;
}
const square = event.target;
const index = square.dataset.squareIndex;
if (board[index] !== "") {
return;
}
board[index] = currentPlayer;
square.innerHTML = currentPlayer;
// CHECK IF THERE IS A WINNER
// 0 1 2
// 3 4 5
// 6 7 8
const winConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
let roundWon = false;
for (let i = 0; i < winConditions.length; i++) {
const condition = winConditions[i];
const a = board[condition[0]];
const b = board[condition[1]];
const c = board[condition[2]];
//checking the winner
if (a === "" || b === "" || c === "") {
continue;
}
if (a === b && b === c) {
roundWon = true;
break;
}
}
if (roundWon) {
gameOver = true;
if (currentPlayer === "o") {
square.className = "nought";
} else {
square.className = "cross";
}
status.innerHTML = `WINNER IS ${currentPlayer}`;
return;
}
let roundDraw = !board.includes("");
if (roundDraw) {
gameOver = true;
if (currentPlayer === "o") {
square.className = "nought";
} else {
square.className = "cross";
}
status.innerHTML = "IT'S A DRAW";
return;
}
// result = condition ? value1 : value2;
currentPlayer = currentPlayer === "x" ? "o" : "x";
if (currentPlayer === "x") {
square.className = "nought";
} else {
square.className = "cross";
}
resetButton.addEventListener("click", () => {
reset();
});
function reset() {
gameOver = false;
board = ["", "", "", "", "", "", "", "", ""];
td.forEach((square) => {
square.innerText = "";
status.innerHTML = "";
square.classList.remove('nought', 'cross');
});
}
}