-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
94 lines (78 loc) · 3.01 KB
/
app.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
const gameBoard = document.querySelector('.gameboard');
const gameInfo = document.querySelector('.info');
gameInfo.innerHTML = '<span style="color: rgb(35, 165, 90)">Circle</span> plays first';
const gameBoxs = ["","","","","","","","",""];
let start = "circle";
function gameBox () {
gameBoxs.forEach((_cell, index) => {
const box = document.createElement('div');
box.classList.add('box');
box.id = index;
box.addEventListener('click', addGo);
gameBoard.append(box);
})
}
gameBox()
function addGo (e) {
const goDisay = document.createElement('div');
goDisay.classList.add(start);
e.target.append(goDisay);
start = start === 'circle' ? 'cross' : 'circle';
gameInfo.innerHTML = `It is now <span style="color: ${start === 'cross' ? 'rgb(242, 63, 67)' : 'rgb(35, 165, 90)'}">${start}</span>'s turn`;
e.target.removeEventListener("click", addGo);
checkScore();
}
let gameOver = false;
function checkScore() {
const allBox = document.querySelectorAll('.box')
const winningCombos = [
[0,1,2],[3,4,5],[6,7,8],
[0,3,6,],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]
]
if (!gameOver) {
winningCombos.forEach(array => {
const circleWins = array.every(cell => allBox[cell].firstChild?.classList.contains('circle'))
if (circleWins) {
gameInfo.innerHTML = "<span style='color: rgb(35, 165, 90)'>Circle</span> Wins!";
allBox.forEach(box => box.replaceWith(box.cloneNode(true)));
document.querySelector('#gameOver').classList.remove('smoothHide');
gameOver = true;
}
});
}
if (!gameOver) {
winningCombos.forEach(array => {
const crossWins = array.every(cell => allBox[cell].firstChild?.classList.contains('cross'))
if (crossWins) {
gameInfo.innerHTML = "<span style='color: rgb(242, 63, 67)'>Cross</span> Wins!";
allBox.forEach(box => box.replaceWith(box.cloneNode(true)));
document.querySelector('#gameOver').classList.remove('smoothHide');
gameOver = true;
}
});
}
if (!gameOver) {
const isDraw = [...allBox].every(box => box.firstChild);
if (isDraw) {
gameInfo.innerHTML = "<span style='color: rgb(226 219 85);'>Draw</span>!";
allBox.forEach(box => box.replaceWith(box.cloneNode(true)));
document.querySelector('#gameOver').classList.remove('smoothHide');
gameOver = true;
};
}
}
function restartGame() {
for (let i = 0; i < gameBoxs.length; i++) {
gameBoxs[i] = "";
}
gameOver = false;
start = "circle";
gameBoard.innerHTML = "";
gameInfo.innerHTML = '<span style="color: rgb(35, 165, 90)">Circle</span> plays first';
gameBox();
setTimeout(() => {
document.querySelector('#gameOver').classList.add('smoothHide');
}, 300)
}
document.querySelector('#restartGame').addEventListener('click', restartGame);