Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!