-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
72 lines (55 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
72
let playerTex = document.getElementById('playerText')
let restartBtn = document.getElementById('restartBtn')
let boxes = Array.from(document.getElementsByClassName('box'))
let winnerIndicator = getComputedStyle(document.body).getPropertyValue('--winning-blocks')
const O_TEXT = "O"
const X_TEXT = "X"
let currentPlayer = X_TEXT
let spaces = Array(9).fill(null)
const startGame = () => {
boxes.forEach(box => box.addEventListener('click', boxClicked))
}
function boxClicked(e) {
const id = e.target.id
if(!spaces[id]){
spaces[id] = currentPlayer
e.target.innerText = currentPlayer
if(playerHasWon() !==false){
playerTex = '${currentPlayer} has won!'
let winning_blocks = playerHasWon()
winning_blocks.map(box => boxes[box].style.backgroundColor=winnerIndicator)
return
}
currentPlayer = currentPlayer == X_TEXT ? O_TEXT : X_TEXT
}
}
const winningCombos = [
[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 playerHasWon() {
for (const condition of winningCombos) {
let [a, b, c] = condition
if(spaces[a] && (spaces[a] == spaces[b] && spaces[a] == spaces[c])){
return [a,b,c]
}
}
return false
}
restartBtn.addEventListener('click', restart)
function restart() {
spaces.fill(null)
boxes.forEach( box => {
box.innerText = ''
box.style.backgroundColor=''
})
playerText = 'Jogo da Velha'
currentPlayer = X_TEXT
}
startGame()