skip to Main Content
// 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


  1. 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)

    let max = winningCombinationsState.indexOf(Math.max(...winningCombinationsState))
    

    Actualy, the Game.winningCombinations[max] should be an Array, then

    Game.state[slot] === ""
    

    is same than

    Game.state[[0, 3, 2]] === ""
    

    while it is expecting an integer as index;

    Login or Signup to reply.
  2. You have little confused at using delete winningCombinationsState[max], I think.

    You can test at google console like this.

    a = [1,2,3,4];
    Math.max(...a);   /* result: 4 */
    a.indexOf(Math.max(...a));    /* result: 3 */
    
    delete a[2];   /* result: true */
    a;   /* result: [1,2, undefined, 4] */
    Math.max(...a);   /* result: NaN */
    

    So, you should remade the array named winningCombinationsState by this code:

    winningCombinationsState = winningCombinationsState.filter(i => i != undefined)
    

    Then use this array variable!
    Good luck.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search