-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
84 lines (74 loc) · 2.48 KB
/
script.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
let boxes = document.querySelectorAll(".box");
let turn = "X";
let isGameOver = false;
boxes.forEach(e => {
e.innerHTML = "";
e.addEventListener("click", () => {
if (!isGameOver && e.innerHTML === "") {
e.innerHTML = turn;
e.style.backgroundColor = turn === "X" ? "#009FBD" : "#EB455F";
// color for X and O
cheakWin();
cheakDraw();
changeTurn();
}
});
});
function changeTurn() {
if (turn === "X") {
turn = "O";
document.querySelector(".bg").style.background = "#EB455F"; //color for O turn
document.querySelector(".bg").style.left = "85px";
} else {
turn = "X";
document.querySelector(".bg").style.background = "#009FBD";
document.querySelector(".bg").style.left = "0"; //color for X turn
}
}
function cheakWin() {
let winConditions = [
[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 < winConditions.length; i++) {
let v0 = boxes[winConditions[i][0]].innerHTML;
let v1 = boxes[winConditions[i][1]].innerHTML;
let v2 = boxes[winConditions[i][2]].innerHTML;
if (v0 !== "" && v0 === v1 && v0 === v2) {
isGameOver = true;
document.querySelector("#results").innerHTML = turn + " wins";
document.querySelector("#play-again").style.display = "inline";
for (j = 0; j < 3; j++) {
boxes[winConditions[i][j]].style.backgroundColor = "lime";
// color for wining
boxes[winConditions[i][j]].style.color = "#000";
}
}
}
}
function cheakDraw() {
if (!isGameOver) {
let isDraw = true;
boxes.forEach(e => {
if (e.innerHTML === "") isDraw = false;
});
if (isDraw) {
isGameOver = true;
document.querySelector("#results").innerHTML = "Draw";
document.querySelector("#play-again").style.display = "inline";
}
}
}
document.querySelector("#play-again").addEventListener("click", () => {
isGameOver = false;
turn = "X";
document.querySelector(".bg").style.left = "0";
document.querySelector("#results").innerHTML = "";
document.querySelector("#play-again").style.display = "none";
boxes.forEach(e => {
e.innerHTML = "";
e.style.removeProperty("background-color");
e.style.color = "#fff";
});
});