-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
108 lines (87 loc) · 2.46 KB
/
scripts.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
const cellElements = document.querySelectorAll("[data-cell]");
const board = document.querySelector("[data-board]");
const winningMessageTextElement = document.querySelector(
"[data-winning-message-text]"
);
const winningMessage = document.querySelector("[data-winning-message]");
const restartButton = document.querySelector("[data-restart-button]");
let isCircleTurn;
const winningCombinations = [
[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 startGame = () => {
isCircleTurn = false;
for (const cell of cellElements) {
cell.classList.remove("circle");
cell.classList.remove("x");
cell.removeEventListener("click", handleClick);
cell.addEventListener("click", handleClick, { once: true });
}
setBoardHoverClass();
winningMessage.classList.remove("show-winning-message");
};
const endGame = (isDraw) => {
if (isDraw) {
winningMessageTextElement.innerText = "Empate!";
} else {
winningMessageTextElement.innerText = isCircleTurn
? "O Venceu!"
: "X Venceu!";
}
winningMessage.classList.add("show-winning-message");
};
const checkForWin = (currentPlayer) => {
return winningCombinations.some((combination) => {
return combination.every((index) => {
return cellElements[index].classList.contains(currentPlayer);
});
});
};
const checkForDraw = () => {
return [...cellElements].every((cell) => {
return cell.classList.contains("x") || cell.classList.contains("circle");
});
};
const placeMark = (cell, classToAdd) => {
cell.classList.add(classToAdd);
};
const setBoardHoverClass = () => {
board.classList.remove("circle");
board.classList.remove("x");
if (isCircleTurn) {
board.classList.add("circle");
} else {
board.classList.add("x");
}
};
const swapTurns = () => {
isCircleTurn = !isCircleTurn;
setBoardHoverClass();
};
const handleClick = (e) => {
// Colocar a marca (X ou Círculo)
const cell = e.target;
const classToAdd = isCircleTurn ? "circle" : "x";
placeMark(cell, classToAdd);
// Verificar por vitória
const isWin = checkForWin(classToAdd);
// Verificar por empate
const isDraw = checkForDraw();
if (isWin) {
endGame(false);
} else if (isDraw) {
endGame(true);
} else {
// Mudar símbolo
swapTurns();
}
};
startGame();
restartButton.addEventListener("click", startGame);