// winningCombinationsState is an array of 8 integers ranging from 0 to 3.
// Game.winningCombinations is an array of 8 arrays containing 3 integers each ranging from 0 to 8.
// Game.state is an array of 9 strings. It keeps the record of the 2 player's position on the board.
function bestMove () {
let index;
while (index == undefined) {
// Find index of first Math.max(...array)
let max = winningCombinationsState.indexOf(Math.max(...winningCombinationsState));
// Check for the first empty slot within Game.state at indexes Game.winningCombinations[max]
for (let slot in Game.winningCombinations[max]) {
if (Game.state[slot] == "") {
index = slot;
break;
}
}
// Remove the best array if no empty slot were found.
if (index == undefined) {
delete winningCombinationsState[max];
}
// While Game.state[slot] isn't an empty string then keep searching.
}
return index;
}
It works well but sometimes it gets stuck.
When index’s left undefined
I have this error Game.winningCombinations[max] is not iterable
Tried using a for ... in
which lift the error message but it still get stuck and sometimes runs into an infinite loop …
console.log(typeof Game.winningCombinations[max])
tells me it’s an object but it’s defined as an array of arrays within an object.
2
Answers
First error: the array winninCombinationsState has 9 object; if the index of the first max integer is 8, then the next code won’t work, because it has only 8 array making its max index to be 7 (counting from 0)
Actualy, the Game.winningCombinations[max] should be an Array, then
is same than
while it is expecting an integer as index;
You have little confused at using
delete winningCombinationsState[max]
, I think.You can test at google console like this.
So, you should remade the array named
winningCombinationsState
by this code:Then use this array variable!
Good luck.