I have a question regarding my implementation of the minimax algorithm for the game called "nim game" in kotlin. It is based on the minimax algorithm that is described in wikipedia.
I do not really know why it is not working. I think the problem is in the evaluate method. If the player is +1 the algorithm should link a great move with a high value and if the player is -1 it should link a great move with a low value.
To understand the Code you may need to know what some methods and variables do:
rows -> IntArray of the current board. If rows = (2,3) the board has 2 matches in the first row and 3 in the second
createAllMoves -> takes rows and creates all possible Moves. If rows = (1,1) there are two Moves: (0,1) take one match out of the first row, or (1,0) take one match out of the second row
play(Move) -> if Move = (3,1) and rows (1,2,3) the output is: rows = (1,2,2) because the Move took 1 match out of the third row
desiredDepth = 5
I'd be pleased if you know how to improve my code. Thanks in advance.
fun evaluate(player: Int) : Int {
if (player == 1) {
return 1
} else if (player == -1) {
return -1
}
return 0
}
fun max(player: Int, depth: Int): Int{
var tmpAllMoves: MutableList<Move> = createAllMoves(rows)
if(depth == 0 || tmpAllMoves.isEmpty()){
return evaluate(player)
}
var maxValue: Int = Int.MIN_VALUE
while(!tmpAllMoves.isEmpty()){
var randomMove: Move = tmpAllMoves.random();
play(randomMove)
tmpAllMoves.remove(randomMove)
var value: Int = min(-1*player, depth-1)
undoMove()
if(value > maxValue){
maxValue = value
if(depth == desiredDepth){
var savedMove: Move = randomMove
}
}
}
return maxValue
}
fun min(player: Int, depth: Int): Int{
var tmpAllMoves: MutableList<Move> = createAllMoves(rows)
if(depth == 0 || tmpAllMoves.isEmpty()){
return evaluate(player)
}
var minValue: Int = Int.MAX_VALUE
while(!tmpAllMoves.isEmpty()){
var randomMove: Move = tmpAllMoves.random();
play(randomMove)
tmpAllMoves.remove(randomMove)
var value: Int = max(-1*player, depth-1)
undoMove()
if(value < minValue){
minValue = value
}
}
return minValue
}