-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
64 lines (54 loc) · 1.64 KB
/
script.js
File metadata and controls
64 lines (54 loc) · 1.64 KB
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
const board = document.querySelector('.board');
const cells = document.querySelectorAll('.cell');
const status = document.querySelector('.status');
const restartBtn = document.querySelector('.restart-btn');
let currentPlayer = 'X';
let gameFinished = false;
const checkForWin = () => {
const 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++) {
const [a, b, c] = winConditions[i];
if (cells[a].textContent === currentPlayer &&
cells[b].textContent === currentPlayer &&
cells[c].textContent === currentPlayer) {
return true;
}
}
return false;
}
const switchPlayer = () => {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
status.textContent = `Vez do jogador ${currentPlayer}`;
}
const handleCellClick = (e) => {
if (gameFinished || e.target.textContent !== '') {
return;
}
e.target.textContent = currentPlayer;
if (checkForWin()) {
status.textContent = `O jogador ${currentPlayer} ganhou!`;
gameFinished = true;
} else if ([...cells].every(cell => cell.textContent !== '')) {
status.textContent = 'Empate!';
gameFinished = true;
} else {
switchPlayer();
}
}
const handleRestartClick = () => {
cells.forEach(cell => cell.textContent = '');
currentPlayer = 'X';
gameFinished = false;
status.textContent = `Vez do jogador ${currentPlayer}`;
}
cells.forEach(cell => cell.addEventListener('click', handleCellClick));
restartBtn.addEventListener('click', handleRestartClick);