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
- pick a random number
- put the token in the column corresponding to that number
- 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!