I’m new to JavaScript and I’m trying to make a tic tac toe game, but it’s not even doing anything, and I don’t know why. I tried to find solution, but I couldn’t.
I tried changing the content in “cellItems.forEach” in several ways but it didn’t work out.
const cellItems = document.querySelectorAll('.cell');
const winner = document.getElementById("winner");
let nextTurn = false;
let winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
cellItems.forEach(cell => {
cell.addEventListener('click', function() {
turn(cell)
checkWin();
}, {
once: true
});
});
function turn() {
if (nextTurn === false) {
cell = 'X';
nextTurn = true;
} else if (nextTurn === true) {
cell = 'O';
nextTurn = false;
}
};
function checkWin() {
for (let winCondition of winningConditions) {
if (winCondition.every(i => cellItems[i].innerHTML == "X")) {
winner.innerHTML = "X won";
} else if (winCondition.every(i => cellItems[i].innerHTML == "O")) {
winner.innerHTML = "O won";
} else {
winner.innerHTML = "DRAW";
}
}
};