-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_logic.js
80 lines (65 loc) · 1.85 KB
/
game_logic.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
let playerText = document.getElementById('playerText')
let restartBtn = document.getElementById('restartBtn')
let boxes =Array.from(document.getElementsByClassName('box'))
let winnerIndicator = getComputedStyle(document.body).getPropertyValue('--winner_blocks')
const O_TEXT = "O"
const X_TEXT = "X"
let currentPlayer = X_TEXT
let spaces = Array(9).fill(null)
let count_plays = 0
console.log(spaces)
const startGame = () => {
boxes.forEach(box => box.addEventListener('click',boxClicked))
}
function boxClicked(e){
const id = e.target.id
if(!spaces[id] && count_plays < 9){
spaces[id] = currentPlayer
e.target.innerText = currentPlayer
if(playerHasWon() != false){
playerText.innerText = `${currentPlayer} has won!`
let winner_blocks = playerHasWon()
count_plays = 10
winner_blocks.map( box => boxes[box].style.backgroundColor=winnerIndicator)
return
}
count_plays++
currentPlayer = currentPlayer == X_TEXT ? O_TEXT : X_TEXT
}
if(count_plays == 9) {
playerText.innerHTML = 'Draw Game!'
boxes.forEach(box => box.style.color = drawIndicator)
}
}
const winning = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,6],
[0,4,8],
[2,4,6]
]
function playerHasWon() {
for(const condition of winning) {
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)
count_plays = 0
boxes.forEach(box => {
box.innerText = ''
box.style.backgroundColor=''
box.style.color = '#F2C14E'
})
playerText.innerText = `Tic Tac Toe`
currentPlayer = X_TEXT
}
startGame()