-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
97 lines (87 loc) · 2.75 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
85
86
87
88
89
90
91
92
93
94
95
96
97
let boxes = document.querySelectorAll(".box");
let turn = "X"; // Player starts
let isGameOver = false;
boxes.forEach(e => {
e.innerHTML = ""
e.addEventListener("click", () => {
if (!isGameOver && e.innerHTML === "" && turn === "X") { // Player's turn
e.innerHTML = turn;
checkWin();
checkDraw();
if (!isGameOver) {
turn = "O";
computerTurn();
}
}
});
});
function computerTurn() {
setTimeout(() => {
let emptyBoxes = Array.from(boxes).filter(box => box.innerHTML === "");
if (emptyBoxes.length > 0) {
let randomBox = emptyBoxes[Math.floor(Math.random() * emptyBoxes.length)];
randomBox.innerHTML = turn;
checkWin();
checkDraw();
if (!isGameOver) {
turn = "X";
}
}
}, 500);
}
function changeTurn() {
if (turn === "X") {
turn = "O";
document.querySelector(".bg").style.left = "85px";
} else {
turn = "X";
document.querySelector(".bg").style.left = "0";
}
}
function checkWin() {
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 (let j = 0; j < 3; j++) {
boxes[winConditions[i][j]].style.backgroundColor = "white";
boxes[winConditions[i][j]].style.color = "#000";
}
return;
}
}
}
function checkDraw() {
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";
});
});