When I set o_Turn to true, I can place a circle, then another one, and so on, and it doesn't swap to a cross, and when I set o_Turn to false, I can place a cross, then another one, and so on, and it doesn't swap to a circle, I'm a total beginner when it comes to JS and I thought making this would be an easy introduction to it, anyone got any idea why it won't turn swap?
tictactoe.js
const X_CLASS = "x"
const O_CLASS = "circle"
const COMBINATIONS = [
[0,1,2],[0,3,6],[0,4,8],
[1,4,7],[2,4,6],[2,5,8],
[0,4,8],[3,4,5],[6,7,8]
]
const cellElements = document.querySelectorAll('[data-cell]')
const boardElement = document.getElementById('board')
const winningMessageElement = document.getElementById('winningMessage')
const restartButton = document.getElementById('restartButton')
const winningMessageTextElement = document.getElementById('winningMessageText')
let o_Turn = false
startGame()
restartButton.addEventListener('click', startGame)
function startGame(){
o_Turn = true
cellElements.forEach(cell => {
cell.classList.remove(X_CLASS)
cell.classList.remove(O_CLASS)
cell.removeEventListener('click', handleCellClick)
cell.addEventListener('click', handleCellClick, {once: true})
})
setBoardHoverClass()
winningMessageElement.classList.remove('show')
}
function handleCellClick(e){
const cell = e.target
const currentClass = o_Turn ? O_CLASS : X_CLASS
placeMark(cell, currentClass)
if (checkWin(currentClass)){
endGame(false) // somebody won
}else if (isDraw()) {
endGame(true) // game is draw
}else {
swapTurns()
setBoardHoverClass()
}
}
function endGame(draw){
if (draw) {
winningMessageTextElement.innerText = "DRAW"
} else {
winningMessageTextElement.innerText = `${o_Turn ? "O" : "X"} wins!`
}
winningMessageElement.classList.add('show')
}
function isDraw() {
return [...cellElements].every(cell => {
return cell.classList.contains(X_CLASS) || cell.classList.contains(O_CLASS)
})
}
function placeMark(cell, currentClass) {
cell.classList.add(currentClass)
}
function swapTurns() {
o_Turn = !o_Turn
}
function setBoardHoverClass() {
boardElement.classList.remove(X_CLASS)
boardElement.classList.remove(O_CLASS)
if (o_Turn) {
boardElement.classList.add(O_CLASS)
} else {
boardElement.classList.add(X_CLASS)
}
}
function checkWin(currentClass) {
return WINNING_COMBINATIONS.some(combination => {
return combination.every(index => {
return cellElements[index].classList.contains(currentClass)
})
})
}