-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
71 lines (63 loc) · 1.55 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
const winingConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
const cells = document.querySelectorAll(".board > *");
const gameState = [];
let isFinished = false;
let isUserTurn = true;
const move = (player, number) => {
gameState[number] = player;
cells[number].textContent = player;
for (let i = 0; i < winingConditions.length; i++) {
const condition = winingConditions[i];
if (condition.every((n) => gameState[n] === player)) {
const h1 = document.querySelector("h1");
h1.textContent = player + " برنده شد!";
h1.style.color = player === "X" ? "green" : "red";
isFinished = true;
setInterval(() => {
i++;
condition.forEach((n) => {
cells[n].style.color = i % 2 ? "blue" : "red";
});
}, 200);
break;
}
}
};
const findRandom = () => {
const emptyNums = [];
for (let num = 0; num < 9; num++) {
if (!gameState[num]) {
emptyNums.push(num);
}
}
return emptyNums[Math.floor(Math.random() * emptyNums.length)];
};
const playComputer = () => {
const random = findRandom();
move("O", random);
isUserTurn = true;
};
cells.forEach((cell, number) => {
cell.addEventListener("click", () => {
if (isFinished || !isUserTurn || gameState[number]) {
return;
}
isUserTurn = false;
move("X", number);
if (!isFinished) {
setTimeout(playComputer, 500);
}
});
});
document
.querySelector("button")
.addEventListener("click", () => location.reload());