I was thinking to do a simple tic tac toe game, but instead of adding X and 0, I was thinking when a square is clicked, that square should become red, then next click on another square to make it blue.
All was ok, until the squares turn only into red when I click on them and on next click they don't became blue. I tried different ways, without success. Finally I wrote the code like so, to be very clear that after .red class was added on the div that was clicked, the value of current player should change, and then because it changed, on next click to add the .blue class on clicked div. But it's becoming red, not blue. What should I do, so on next click the div should turn into blue? Thanks
let score=0
let blue ='blue',red = 'red'
let currentPlayer = red
const cells = [] // to keep all cell to iterate over them
for(let i=0;i<9;i++){
const divCell = document.createElement('div')
divCell.setAttribute('class', 'cell')
divCell.setAttribute('id', i)
gridWrapper.appendChild(divCell)
cells.push(divCell)
}
cells.forEach( cell => {
cell.addEventListener('click', (e)=> {
let id = e.currentTarget.id
if(!cells.id && currentPlayer === red){
cells[id] = currentPlayer
e.target.classList.add('red')
currentPlayer = blue
console.log(currentPlayer);
}
if(!cells.id && currentPlayer === blue){
cells[id] = currentPlayer
e.target.classList.add('blue')
currentPlayer = red
console.log(currentPlayer);
}
})
})```
I think you have a logical error with the cells array check see in pic
suppose to be cells[id] and not cells.id
On each click, both if blocks are being invoked. Because changes made in the first if block are satisfying the second condition. Make the second if an else if:
if (!cells.id && currentPlayer === red) {
//...
} else if (!cells.id && currentPlayer === blue) {
//...
}
That way each click only invokes one player's turn rather than both.