-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
54 lines (49 loc) · 1.66 KB
/
Copy pathscript.js
File metadata and controls
54 lines (49 loc) · 1.66 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
let btn = document.querySelectorAll(".tile");
let res = document.querySelector(".res");
let filled = [false,false,false,false,false,false,false,false,false]; //To store the button click status
let turn = "X";
let gameOver = false;
for(let i =0;i<btn.length;i++){
btn[i].addEventListener('click',()=>{
if(!filled[i] && !gameOver){
btn[i].innerText=turn;
filled[i] = true;
let win = checkWin();
if(win==="X"||win==="O"){
finish( `
<h1>Congrats</h1>
<h2>${win} is the winner</h2>
<button class="playAgain">Play Again</button>
`);
}
else if(filled.every(Boolean)){
finish(`<h2>This Match was a Draw</h2>
<button class="playAgain">Play Again</button>
`);
}
if(turn==="X")
turn = "O";
else
turn = "X";
}
});
}
function finish(message){
gameOver = true;
res.style.zIndex = '200';
res.style.opacity = '0.75';
res.innerHTML = message;
const playAgainBtn = document.querySelector(".playAgain");
playAgainBtn.addEventListener("click", () => {
window.location.reload();
});
}
function checkWin(){
let mat = [[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]];
for(let i = 0;i<mat.length;i++){
if(btn[mat[i][0]].innerText!="" && btn[mat[i][0]].innerText==btn[mat[i][1]].innerText&&btn[mat[i][1]].innerText===btn[mat[i][2]].innerText)
return btn[mat[i][0]].innerText;
}
}