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

250
Visualizações
Why is this `while` loop not iterating and just exiting?
function aiPick() {
    let aiCell = null;
    while (aiCell == null) {
      let aiColIndex = Math.floor(Math.random() * 7)
      console.log(aiColIndex)
      aiCell = getFirstOpenCellForColumn(aiColIndex) 
      console.log(typeof(aiCell))
      console.log(getClassListArray(aiCell))
    }
    aiCell.classList.add('red')
    checkStatusOfGame(aiCell)
    yellowIsNext = !yellowIsNext
    aiClassList = getClassListArray(aiCell)
    aiColClass = aiClassList.find(className => className.includes('col'));
    let aiColIndex = parseInt(aiColClass[4], 10);
    clearColorFromTop(aiColIndex)
}

I'm working on an opponent for a Connect Four game. I'm having it pick one of seven columns by random, and then the function getFirstOpenCellForColumn will mark the first open cell by adding a class of red to that div.

The code then checks if the move is a win with checkStatusOfGame(aiCell) and swaps the player and removes a token that shows up at the top of the column, outside the gameboard, that serves as a "picker."

I was looking for a way to get the computer to generate a new random number to pick a column when the last space in the column was occupied. I thought this would do it, since when the computer picks a full column, it gives me this error message:

script.js:39 Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at getClassListArray (script.js:39)
    at aiPick (script.js:274)
    at HTMLDivElement.handleCellClick (script.js:258)

But then it seems not to go back to picking a random number, but simply jumps down to yellowIsNext = !yellowIsNext so that I'm now placing the computer's red token instead of my yellow ones.

Basically, I want the code to

  1. pick a random number
  2. put the token in the column corresponding to that number
  3. if that column is full, go back to #1

Do you know why this isn't working? Is there another way to write the while loop, or is let aiCell = null incorrect?

Thanks!

about 4 years ago · Santiago Gelvez
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