-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
108 lines (101 loc) · 2.72 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
101
102
103
104
105
106
107
108
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");
//Winning Pattern Array
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],
];
//Player 'X' plays first
let xTurn = true;
let count = 0;
//Disable All Buttons
const disableButtons = () => {
btnRef.forEach((element) => (element.disabled = true));
//enable popup
popupRef.classList.remove("hide");
};
//Enable all buttons (For New Game and Restart)
const enableButtons = () => {
btnRef.forEach((element) => {
element.innerText = "";
element.disabled = false;
});
//disable popup
popupRef.classList.add("hide");
};
//This function is executed when a player wins
const winFunction = (letter) => {
disableButtons();
if (letter == "X") {
msgRef.innerHTML = "😎 <br> Congratulations <br> 🎊 'X' Wins 🎊";
} else {
msgRef.innerHTML = "😎 <br> Congratulations <br> 🎊 'O' Wins 🎊";
}
};
//Function for draw
const drawFunction = () => {
disableButtons();
msgRef.innerHTML = "😬 <br> It's a Draw";
};
//New Game
newgameBtn.addEventListener("click", () => {
count = 0;
enableButtons();
});
restartBtn.addEventListener("click", () => {
count = 0;
enableButtons();
});
//Win Logic
const winChecker = () => {
//Loop through all win patterns
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);
}
}
}
};
//Display X/O on click
btnRef.forEach((element) => {
element.addEventListener("click", () => {
if (xTurn) {
xTurn = false;
//Display X
element.innerText = "X";
element.disabled = true;
} else {
xTurn = true;
//Display Y
element.innerText = "O";
element.disabled = true;
}
//Increment count on each click
count += 1;
if (count == 9) {
drawFunction();
}
//Check for win on every click
winChecker();
});
});
//Enable Buttons and disable popup on page load
window.onload = enableButtons;