-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
110 lines (93 loc) · 2.73 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
98
99
100
101
102
103
104
105
106
107
108
109
110
"use strict";
const statusDisplay = document.querySelector("#status");
const count = document.querySelector("#numberTurns");
let gameActive = true;
let currentPlayer = "X";
let gameState = ["", "", "", "", "", "", "", "", ""];
const winnMessage = () => `${currentPlayer} has won!`;
const drawMessage = () => `it's a draw!`;
const winnLines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
function handlePlayerTurn() {
const p1 = document.querySelector("#player1"),
p2 = document.querySelector("#player2");
if (currentPlayer === "X") {
p1.style.background = "#8458B3";
p2.style.background = "#d0bdf4";
} else {
p1.style.background = "#d0bdf4";
p2.style.background = "#8458B3";
}
}
function handleClick(event) {
let clickedIndex = Number(event.target.getAttribute("id"));
if (gameState[clickedIndex] !== "" || !gameActive) return;
gameState[clickedIndex] = currentPlayer;
event.target.innerHTML = currentPlayer;
count.innerHTML = +count.innerHTML + 1;
handleResult();
}
function handleResult() {
let roundWon = false,
winLine,
a,
b,
c,
i;
for (i = 0; i < 8; ++i) {
winLine = winnLines[i];
a = gameState[winLine[0]];
b = gameState[winLine[1]];
c = gameState[winLine[2]];
if (a === b && b === c && c !== "") {
roundWon = true;
break;
}
}
if (roundWon || !gameState.includes("")) {
if (roundWon) {
statusDisplay.innerHTML = winnMessage();
statusDisplay.style.color = "#139de2";
winColors(winLine);
} else statusDisplay.innerHTML = drawMessage();
gameActive = false;
return;
}
currentPlayer = currentPlayer === "X" ? "O" : "X";
handlePlayerTurn();
}
function winColors(line) {
console.log(`${line}`);
for (let i = 0; i < 3; ++i) {
let cell = document.getElementById(`${line[i]}`);
cell.style.color = "#139de2";
cell.style.fontSize = "80px";
}
}
function handleRestart() {
gameActive = true;
currentPlayer = "X";
count.innerHTML = "0";
statusDisplay.innerHTML = "";
statusDisplay.style.color = "black";
gameState = ["", "", "", "", "", "", "", "", ""];
handlePlayerTurn();
document.querySelectorAll(".cell").forEach((cell) => {
cell.innerHTML = "";
cell.style.color = "#232d55";
cell.style.fontSize = "60px";
});
}
handlePlayerTurn();
document
.querySelectorAll(".cell")
.forEach((cell) => cell.addEventListener("click", handleClick));
document.querySelector("#restart").addEventListener("click", handleRestart);