-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
92 lines (79 loc) · 2.18 KB
/
script.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
const cellElements = document.querySelectorAll('.cell')
let circleTurn = 'x'
const grid = document.querySelector('.grid-container')
const winningMessageElement = document.querySelector('.winning-message')
const winningMessageTextElement = document.querySelector('.winning-message-text')
const restartElement = document.querySelector('.button')
const winningStates = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 4, 8],
[2, 4, 6],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]
]
startGame()
restartElement.addEventListener('click', startGame)
function startGame() {
grid.classList.add('x') //game starts with x
winningMessageElement.classList.remove('show')
for (cell of cellElements) {
cell.classList.remove('o')
cell.classList.remove('x')
cell.removeEventListener('click', handleClick)
cell.addEventListener('click', handleClick, {once: true})
}
}
function handleClick(e) {
const cell = e.target
console.log(circleTurn)
placeMark(cell)
if (checkWin()) {
endGame(false)
} else if (isDraw()) {
endGame(true)
} else {
console.log('swaaping turns!')
swapTurns()
setGrid()
}
}
function isDraw() {
let arrayCellElements = Array.from(cellElements)
return arrayCellElements.every((cell) => {
return cell.classList.contains('x') || cell.classList.contains('o')
})
}
function swapTurns() {
if (circleTurn == 'x') {
circleTurn = 'o'
} else {
circleTurn = 'x'
}
}
function endGame(draw) {
if (draw) {
winningMessageTextElement.innerText = 'Draw!'
} else {
winningMessageTextElement.innerText = `${circleTurn == 'x' ? "X's" : "O's"} Wins!`
}
winningMessageElement.classList.add('show')
}
function placeMark(cell) {
cell.classList.add(circleTurn)
}
function setGrid() {
const grid = document.querySelector('.grid-container')
grid.classList.remove('x')
grid.classList.remove('o')
grid.classList.add(circleTurn)
}
function checkWin() {
return winningStates.some(state => {
return state.every(index => {
return cellElements[index].classList.contains(circleTurn)
})
})
}