-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
100 lines (84 loc) · 2.2 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
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
let btnRef = document.querySelectorAll(".button-option");
let popupRef = document.querySelector(".popup");
let newgameBtn = document.getElementById("new-game");
let restartBtn = document.getElementById("restart");
let msgRef = document.getElementById("message");
let winningPattern = [
[0, 1, 2],
[0, 3, 6],
[2, 5, 8],
[6, 7, 8],
[3, 4, 5],
[1, 4, 7],
[0, 4, 8],
[2, 4, 6],
];
let xTurn = true;
let count = 0;
const disableButtons = () => {
btnRef.forEach((element) => (element.disabled = true));
popupRef.classList.remove("hide");
};
const enableButtons = () => {
btnRef.forEach((element) => {
element.innerText = "";
element.disabled = false;
});
popupRef.classList.add("hide");
};
const winFunction = (letter) => {
disableButtons();
if (letter == "X") {
msgRef.innerHTML = " <br> '1st player X ' Wins";
} else {
msgRef.innerHTML = " <br> '2st player O' Wins";
}
};
const drawFunction = () => {
disableButtons();
msgRef.innerHTML = " <br> It's a Draw";
};
newgameBtn.addEventListener("click", () => {
count = 0;
enableButtons();
});
restartBtn.addEventListener("click", () => {
count = 0;
enableButtons();
});
const winChecker = () => {
for (let i of winningPattern) {
let [element1, element2, element3] = [
btnRef[i[0]].innerText,
btnRef[i[1]].innerText,
btnRef[i[2]].innerText,
];
//Check if elements are filled
//If 3 empty elements are same and would give win as would
if (element1 != "" && (element2 != "") & (element3 != "")) {
if (element1 == element2 && element2 == element3) {
//If all 3 buttons have same values then pass the value to winFunction
winFunction(element1);
}
}
}
};
btnRef.forEach((element) => {
element.addEventListener("click", () => {
if (xTurn) {
xTurn = false;
element.innerText = "X";
element.disabled = true;
} else {
xTurn = true;
element.innerText = "O";
element.disabled = true;
}
count += 1;
if (count == 9) {
drawFunction();
}
winChecker();
});
});
window.onload = enableButtons;