-2

Could you please help me to find a proper way to fix it?

Why is there an error "TypeError: Cannot read properties of undefined" for the row with gameState[move.i] = playerAi? What did I do wrong?

let scoreCounter = function() {
  //....
  return scores
}

function bestMove() {
  let bestScore = -Infinity;
  let move;
  for (let i = 0; i < gameState.length; i++) {
    if (gameState[i] === "") {
      gameState[i] = playerAi;
      let score = minimax(gameState, 0, false)
      gameState[i] = "";
      if (score > bestScore) {
        bestScore = score;
        move = {
          i
        };
      }
    }
  }
  gameState[move.i] = playerAi;
  document.getElementById(move.i).innerHTML = playerAi;
}

//actual minimax
function minimax(gameState, depth, maximization) {
  let result = scoreCounter();
  if (result !== null) {
    return scores;
  }

  if (maximization) {
    let bestScore = -Infinity;
    for (let i = 0; i < gameState.length; i++) {
      if (gameState[i] === "") {
        gameState[i] = playerAi;
        let score = minimax(gameState, depth + 1, false)
        gameState[i] = "";
        bestScore = Math.max(score, bestScore)
      }
    }
    return bestScore
  } else {
    let bestScore = Infinity;
    for (let i = 0; i < gameState.length; i++) {
      if (gameState[i] === "") {
        gameState[i] = playerX;
        let score = minimax(gameState, depth + 1, true)
        gameState[i] = "";
        bestScore = Math.min(score, bestScore)
      }
    }
    return bestScore

  }
}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
justice81
  • 31
  • 3

1 Answers1

0

You need to initialize the move variable, I suggest setting it to the first possible move, which in your case would be 0.

eligolf
  • 1,682
  • 1
  • 6
  • 22