-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
77 lines (77 loc) · 1.82 KB
/
Copy pathscript.js
File metadata and controls
77 lines (77 loc) · 1.82 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
72
73
74
75
76
77
let boxes = document.querySelectorAll(".box");
let resetButton = document.querySelector("#reset-btn");
let turn0 = true;
let countClick = 0;
const winPattern = [
[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 newGameBtn = document.querySelector(".new-btn");
let msgPara = document.querySelector(".msg");
let msgContainer = document.querySelector(".msg-container");
boxes.forEach((val) => {
val.addEventListener("click", () => {
if (turn0) {
val.innerText = "O";
turn0 = false;
} else {
val.innerText = "X";
turn0 = true;
}
countClick++;
val.disabled = true;
let isWinner = checkWinner();
if (countClick === 9 && !isWinner) {
showDraw();
}
});
});
const disableBoxes = () => {
for (box of boxes) {
box.disabled = true;
}
};
const enableBoxes = () => {
for (box of boxes) {
box.disabled = false;
box.innerText = "";
}
};
const showWinner = (winner) => {
msgPara.innerText = `Congratulations, winner is ${winner}`;
msgContainer.classList.remove("hide");
disableBoxes();
};
const showDraw = () => {
msgPara.innerText = `Match is draw, well played`;
msgContainer.classList.remove("hide");
disableBoxes();
};
const checkWinner = () => {
for (pattern of winPattern) {
let pos1 = boxes[pattern[0]].innerText;
let pos2 = boxes[pattern[1]].innerText;
let pos3 = boxes[pattern[2]].innerText;
if (pos1 != "" && pos2 != "" && pos3 != "") {
if (pos1 === pos2 && pos2 === pos3) {
disableBoxes();
showWinner(pos1);
return true;
}
}
}
};
const resetGame = () => {
turn0 = true;
countClick = 0;
msgContainer.classList.add("hide");
enableBoxes();
};
newGameBtn.addEventListener("click", resetGame);
resetButton.addEventListener("click", resetGame);