-
Notifications
You must be signed in to change notification settings - Fork 1
/
game.js
69 lines (57 loc) · 2.06 KB
/
game.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
const game = {
xTurn: true,
xState: [],
oState: [],
winningStates: [
// Rows
['0', '1', '2'],
['3', '4', '5'],
['6', '7', '8'],
// Columns
['0', '3', '6'],
['1', '4', '7'],
['2', '5', '8'],
// Diagonal
['0', '4', '8'],
['2', '4', '6']
]
}
document.addEventListener('click', event => {
const target = event.target
const isCell = target.classList.contains('grid-cell')
const isDisabled = target.classList.contains('disabled')
if (isCell && !isDisabled) {
const cellValue = target.dataset.value
game.xTurn === true
? game.xState.push(cellValue)
: game.oState.push(cellValue)
target.classList.add('disabled')
target.classList.add(game.xTurn ? 'x' : 'o')
game.xTurn = !game.xTurn
// If all cells are disabled, then its draw
if (!document.querySelectorAll('.grid-cell:not(.disabled)').length) {
document.querySelector('.game-over').classList.add('visible')
document.querySelector('.game-over-text').textContent = 'Draw!'
}
game.winningStates.forEach(winningState => {
const xWins = winningState.every(state => game.xState.includes(state))
const oWins = winningState.every(state => game.oState.includes(state))
if (xWins || oWins) {
document.querySelectorAll('.grid-cell').forEach(cell => cell.classList.add('disabled'))
document.querySelector('.game-over').classList.add('visible')
document.querySelector('.game-over-text').textContent = xWins
? 'X wins!'
: 'O wins!'
}
})
}
})
document.querySelector('.restart').addEventListener('click', () => {
document.querySelector('.game-over').classList.remove('visible')
document.querySelectorAll('.grid-cell').forEach(cell => {
cell.classList.remove('disabled', 'x', 'o')
})
game.xTurn = true
game.xState = []
game.oState = []
})