Search code examples
javascriptfor-loopminimax

i and j of my for loops are getting higher then they should in my minimax algorithm


My current code looks something like this:

let bestScore = -Infinity
let move;
for(i = 0; i < board.length; i++)
{
    for(j = 0; j < board.length; j++)
    {
        if(whiteFrameNumber.includes(board[i][j])) // spot is available
        {
            const fieldBefore = board[i][j]
            board[i][j] = cross
            const score = minimax(board, 0, false)
            board[i][j] = fieldBefore
            if(score > bestScore)
            {
                bestScore = score
                move = {i, j}
            }
        }
    }
}
board[move.i][move.j] = cross

and my minimax algorithm:

function minimax(board, depth, isMaximizing)
{
    const result = checkWinner(board)
    if(result !== 'noone won')
    {
        let score
        if(result === cross) score = 1
        else if(result === circle) score = -1
        else if(result === 'tie') score = 0
    }

    if(isMaximizing)
    {
        const bestScore = -Infinity
        for(i = 0; i < board.length; i++)
        {
            for(j = 0; j < board.length; j++)
            {
                if(whiteFrameNumber.includes(board[i][j]))  // spot is available
                {
                    const fieldBefore = board[i][j]
                    boardi[i][j] = cross
                    const score = minimax(board, depth + 1, false)
                    boardi[i][j] = fieldBefore
                    bestScore = Math.max(score, bestScore)
                }
            }
        }
        return bestScore
    }
    else
    {
        const bestScore = Infinity
        for(i = 0; i < board.length; i++)
        {
            for(j = 0; j < board.length; j++)
            {
                if(whiteFrameNumber.includes(board[i][j])) // spot is available
                {
                    const fieldBefore = board[i][j]
                    boardi[i][j] = circle
                    const score = minimax(board, depth + 1, true)
                    boardi[i][j] = fieldBefore
                    bestScore = Math.min(score, bestScore)
                }
            }
        }
        return bestScore
    }
}

I get the error: TypeError: Cannot set property '0' of undefined

I also got: TypeError: Cannot set property '3' of undefined

Through debugging I found out that 'j' in the main loop gets set to 3 after the minimax function. I have no idea how and why but it would explain the error.

I didn't find any solution through further debugging so I have no idea how to proceed.

Sorry for my bad english ^^


Solution

  • You're using the same i and j variables in the main loop and the minimax() function. So the loops in minimax() are updating the variables in the caller.

    Make the variables local to each function by declaring them with let or var.

    for (let i = ...) {
        for (let j = ...) {
            ...
        }
    }