-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
110 lines (93 loc) · 2.67 KB
/
Copy pathapp.js
File metadata and controls
110 lines (93 loc) · 2.67 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Access elements
let boxes = document.querySelectorAll(".box");
let resetBtn = document.querySelector("#reset-btn");
let newGameBtn = document.querySelector("#new-btn");
let msgContainer = document.querySelector(".msg-container");
let msg = document.querySelector("#msg");
// Who goes first
let turnA = true;
// Using 2D array to create winning conditions
let winningPatterns = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8], // Fixed pattern 3 from [5,6,7] to [6,7,8]
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
const resetGame = () => {
turnA = true;
enableBoxes();
msgContainer.classList.add("hide");
msg.innerText = ""; // Clear the message text on reset
}
/** Event - clicking */
boxes.forEach((box) => {
box.addEventListener("click", () => {
console.log("clicked");
/* Add O or X depending on Turn */
if (turnA) {
box.innerText = "O";
turnA = false;
} else {
box.innerText = "X";
turnA = true;
}
box.disabled = true;
checkWinner();
})
})
const enableBoxes = () => {
boxes.forEach((box) => {
box.disabled = false;
box.innerText = "";
});
}
const disableBoxes = () => {
boxes.forEach((box) => {
box.disabled = true;
});
}
const showWinner = (winner) => {
msg.innerText = `Congratulations! Winner is ${winner}`;
msgContainer.classList.remove("hide");
disableBoxes();
}
const showTie = () => {
msg.innerText = "Oh no, It's a TIE! You Both Lose!";
msgContainer.classList.remove("hide");
disableBoxes();
}
const checkWinner = () => {
let isWinnerFound = false;
for (let pattern of winningPatterns) {
let positionOfValue1 = boxes[pattern[0]].innerText;
let positionOfValue2 = boxes[pattern[1]].innerText;
let positionOfValue3 = boxes[pattern[2]].innerText;
if (positionOfValue1 !== "" && positionOfValue2 !== "" && positionOfValue3 !== "") {
if (positionOfValue1 === positionOfValue2 && positionOfValue2 === positionOfValue3) {
showWinner(positionOfValue1);
isWinnerFound = true;
break;
}
}
}
// Check for tie if no winner found and all boxes are filled
if (!isWinnerFound) {
let allFilled = true;
for (let box of boxes) {
if (box.innerText === "") {
allFilled = false;
break;
}
}
if (allFilled) {
showTie();
}
}
}
// Event listeners for reset buttons
newGameBtn.addEventListener("click", resetGame);
resetBtn.addEventListener("click", resetGame);