Minimax in Scala

706 views Asked by At

I'm trying to adapt the minimax algorithm from Wikipedia for my implementation of TicTacToe in Scala. I want the X player, -1, to try and maximize his score. I found a cool static evaluation function here which I would like to use. It returns positive numbers if the board is a good board for the player, and negative numbers if the board is bad for the player. I've tried a few variations and X continues to just make the first move available. The method is below, the method and evaluation function can be found here.

Is there something glaringly obvious about this that I'm missing?

// player X = -1, player O = 1
def minmax(board:Array[Int], height:Int, player:Int):Double={
  if(height == 0)
    evaluatePosition(board, player)

  var alpha = -player * Double.PositiveInfinity;

  val allBoards = makeAllPossibleMoves(board, player) // array of child boards
  for(b <- allBoards){
    val score = minmax(b, height-1, -player)
    alpha = if (player == -1) Math.max(alpha, score) else Math.min(alpha, score)
  }

  alpha
}
1

There are 1 answers

1
Roland Ewald On BEST ANSWER

It seems that alpha is initialized with the wrong value:

var alpha = -player * Double.PositiveInfinity

means that in case of the X player (-1) alpha is initialized as

var alpha = - (-1) * Double.PositiveInfinity

which can be simplified to

var alpha = Double.PositiveInfinity

Thus, alpha cannot increase anymore, i.e.

alpha = if (player == -1) Math.max(alpha, score) else //...

will have no effect. The reverse should be true for the other player (1), where alpha is initialized as negative infinity and thus cannot be mimized anymore. Thus, you should be able to fix this by simply removing the -1 factor from the initialization of alpha:

var alpha = player * Double.PositiveInfinity