Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
Tic tac toe move shows up in other slot in array then on the board. javascript

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();
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda