-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
71 lines (62 loc) · 1.69 KB
/
Copy pathscript.js
File metadata and controls
71 lines (62 loc) · 1.69 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
71
let turnO = true;
let boxes = document.querySelectorAll(".box");
let resultPopup = document.getElementById("result-popup");
let resultText = document.getElementById("result-text");
let restartBtn = document.getElementById("restart");
const patterns = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6],
];
boxes.forEach((box,index) => {
box.addEventListener("click", () => {
if(box.textContent !== "") return;
if(turnO) {
box.textContent = "O";
} else {
box.textContent = "X";
}
box.disabled = true;
checkWinner();
turnO = !turnO;
});
});
const checkWinner = () => {
for(let pattern of patterns) {
let v1 = boxes[pattern[0]].textContent;
let v2 = boxes[pattern[1]].textContent;
let v3 = boxes[pattern[2]].textContent;
if(v1 && v1 === v2 && v2 === v3) {
showResult(v1);
boxes.forEach(box => box.disabled = true);
return;
}
}
// Check for Draw
let draw = true;
boxes.forEach(box => {
if(box.textContent === "") draw = false;
});
if(draw) showResult("Draw");
};
const showResult = (winner) => {
if(winner === "Draw") {
resultText.textContent = "It's a Draw!";
} else {
resultText.textContent = `Winner is: ${winner}`;
}
resultPopup.classList.remove("hidden");
};
restartBtn.addEventListener("click", () => {
boxes.forEach(box => {
box.textContent = "";
box.disabled = false;
});
resultPopup.classList.add("hidden");
turnO = true;
});