-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
116 lines (97 loc) · 3.03 KB
/
index.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
109
110
111
112
113
114
115
116
const boxes = document.querySelectorAll(".box");
const gameInfo = document.querySelector(".game-info");
const newGameBtn = document.querySelector(".btn");
let currentPlayer;
let gameGrid;
const winningPositions = [
[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's create a function to initialise the game
function initGame() {
currentPlayer = "X";
gameGrid = ["","","","","","","","",""];
//UI pr empty bhi karna padega boxes ko
boxes.forEach((box, index) => {
box.innerText = "";
boxes[index].style.pointerEvents = "all";
//one more thing is missing, initialise box with css properties again
box.classList = `box box${index+1}`;
});
newGameBtn.classList.remove("active");
gameInfo.innerText = `Current Player - ${currentPlayer}`;
}
initGame();
function swapTurn() {
if(currentPlayer === "X") {
currentPlayer = "O";
}
else {
currentPlayer = "X";
}
//UI Update
gameInfo.innerText = `Current Player - ${currentPlayer}`;
}
function checkGameOver() {
let answer = "";
winningPositions.forEach((position) => {
//all 3 boxes should be non-empty and exactly same in value
if( (gameGrid[position[0]] !== "" || gameGrid[position[1]] !== "" || gameGrid[position[2]] !== "")
&& (gameGrid[position[0]] === gameGrid[position[1]] ) && (gameGrid[position[1]] === gameGrid[position[2]])) {
//check if winner is X
if(gameGrid[position[0]] === "X")
answer = "X";
else {
answer = "O";
}
//disable pointer events
boxes.forEach((box) => {
box.style.pointerEvents = "none";
})
//now we know X/O is a winner
boxes[position[0]].classList.add("win");
boxes[position[1]].classList.add("win");
boxes[position[2]].classList.add("win");
}
});
//it means we have a winner
if(answer !== "" ) {
gameInfo.innerText = `Winner Player - ${answer}`;
newGameBtn.classList.add("active");
return;
}
//We know, NO Winner Found, let's check whether there is tie
let fillCount = 0;
gameGrid.forEach((box) => {
if(box !== "" )
fillCount++;
});
//board is Filled, game is TIE
if(fillCount === 9) {
gameInfo.innerText = "Game Tied !";
newGameBtn.classList.add("active");
}
}
function handleClick(index) {
if(gameGrid[index] === "" ) {
boxes[index].innerText = currentPlayer;
gameGrid[index] = currentPlayer;
boxes[index].style.pointerEvents = "none";
//swap karo turn ko
swapTurn();
//check koi jeet toh nahi gya
checkGameOver();
}
}
boxes.forEach((box, index) => {
box.addEventListener("click", () => {
handleClick(index);
})
});
newGameBtn.addEventListener("click", initGame);