I'am creating a tik tak toe game with javascript. So right now i'am making it that you can play vs the computer. And i got it to work but right now it does fill in a field on the board, and i also have a array with the gameState to track which fields on the board are already filled in. But what it does right now is that in that array the move of the computer gets in a wrong position SOMETIMES. Not always but like 50/50 and sometimes it doesn't even showup in the array. Ill put my code for the computer down below. The fields variable is just a querySelectorAll for the fiels of the board.
function handleComputerMove() {
const emptyFields = [];
let randomField;
if (!gameActive || !gameState.includes("")) {
return;
}
fields.forEach(function(cell){
if (cell.textContent == '') {
emptyFields.push(cell);
}
});
randomField = Math.ceil(Math.random() * emptyFields.length -1);
emptyFields[randomField].innerHTML = currentPlayer;
handleCellPlayed(randomField);
handleResultValidation();
}
CodePudding user response:
The problem is that the index in emptyFields
is not (necessarily) the index of the cell that is free.
So you should translate that back to the cell's index, which is what you could store in emptyFields
(instead of the cell element).
Not your issue, but you should use the more common way to generate a random integer, because Math.random()
can in theory return 0.
So:
fields.forEach(function(cell, i){
if (cell.innerHTML == '') {
emptyFields.push(i); // Store i, instead of cell
}
});
randomField = emptyFields[Math.floor(Math.random() * emptyFields.length)];
fields[randomField].innerHTML = currentPlayer;