-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
87 lines (77 loc) · 2.24 KB
/
script.js
File metadata and controls
87 lines (77 loc) · 2.24 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
78
79
80
81
82
83
84
85
86
87
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 disableBtns = () => {
btnRef.forEach((element) => (element.disabled = true));
popupRef.classList.remove("hide");
}
const enableBtns = () => {
btnRef.forEach((element) => {
element.innerText = "";
element.disabled = false;
});
popupRef.classList.add("hide");
xTurn = true;
}
newgameBtn.addEventListener("click", () => {
count = 0;
enableBtns();
});
restartBtn.addEventListener("click", () => {
count = 0;
enableBtns();
});
const winningFunction = (winner) => {
disableBtns();
if (winner == "X"){
msgRef.innerHTML = "🎉 <br><br> 'X' Wins";
} else {
msgRef.innerHTML = "🎉 <br><br> 'O' Wins";}
}
const winChecker = () => {
for(let i of winningPattern){
let [e1, e2, e3] = [btnRef[i[0]].innerText,btnRef[i[1]].innerText,btnRef[i[2]].innerText];
if(e1 != "" && e2 != "" && e3 != ""){
if(e1 == e2 && e2 == e3){
winningFunction(e1);
}
}
}
}
const drawFunction = () => {
disableBtns();
msgRef.innerHTML = "😎 <br><br> It's a Draw";
}
btnRef.forEach((element) => {
element.addEventListener("click", () => {
element.innerText = "X";
element.disabled = true;
let remainingButtons = Array.from(btnRef).filter(btn => btn.innerText === "");
if (remainingButtons.length > 0) {
const randomIndex = Math.floor(Math.random() * remainingButtons.length);
const randomButton = remainingButtons[randomIndex];
count += 1;
randomButton.innerText = "O";
randomButton.disabled = true;
}
count += 1;
if(count == 9){
drawFunction();
}
winChecker();
})
})