-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
66 lines (53 loc) · 1.43 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
const currentPlayer = document.querySelector(".currentPlayer");//pega a referencia do currentPlayer
let selected;
let player = "X";
//Variáveis
let positions = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7],
]; //Armazena as posições possívéis para ter um ganhador.
function init() {
selected = [];
currentPlayer.innerHTML = `JOGADOR DA VEZ: ${player}`;
document.querySelectorAll(".Game button").forEach((item) => {
item.innerHTML = "";
item.addEventListener("click", newMove);
});
}
init();
function newMove(e) {
const index = e.target.getAttribute("data-i");
e.target.innerHTML = player;
e.target.removeEventListener("click", newMove);
selected[index] = player;
setTimeout(() => {
check();
}, [100]);
player = player === "X" ? "O" : "X";
currentPlayer.innerHTML = `JOGADOR DA VEZ: ${player}`;
}
function check() {
let playerLastMove = player === "X" ? "O" : "X";
const items = selected
.map((item, i) => [item, i])
.filter((item) => item[0] === playerLastMove)
.map((item) => item[1]);
for (pos of positions) {
if (pos.every((item) => items.includes(item))) {
alert("O JOGADOR '" + playerLastMove + "' GANHOU!");
init();
return;
}
}
if (selected.filter((item) => item).length === 9) {
alert("DEU EMPATE!");
init();
return;
}
}