I am trying to implement a minmax algorithm that I found in javascript to my c# tic Tac toe game. I have done my best, but in my opinion the problem seems to be in the recursive function that I have been debugging for ages. This is my first time using recursive function so it is confusing for me.
So I implement the algorithm this way and it is giving me move that is not with the best score so the problem could be in returning score for the move.
Link to the javascript code: https://medium.freecodecamp.org/how-to-make-your-tic-tac-toe-game-unbeatable-by-using-the-minimax-algorithm-9d690bad4b37
public int Minimax(string[] reboard, bool player) {
// board looks like this [] {"0","1","2","3","4","5","6","7","8"}
//player X == true and player O == false
//X is human O is an AI
//array of possible moves
var array = Avail(reboard);
//check if current position of the board, true/false is the current player
if (WinningMinMax(reboard, true)) {
return -10;
}
else if (WinningMinMax(reboard, false)) {
return 10;
}
// or it is a draw
else if (DrawMinMax(reboard)) {
return 0;
}
//MoveS is an object with two parameters: index and score
List<MoveS> moves = new List<MoveS>();
for (var i = 0; i < array.Length; i++)
{
var move = new MoveS();
move.index = Convert.ToInt32(reboard[Convert.ToInt32(array[i])]);
if (player)
{
reboard[Convert.ToInt32(array[i])] = "X";
}
else
{
reboard[Convert.ToInt32(array[i])] = "O";
}
if (!player) {
var g = new MoveS();
//recursive call for building the tree of possible moves
g.score = Minimax(reboard, true);
move.score = g.score;
} else {
var g = new MoveS();
g.score = Minimax(reboard, false);
move.score = g.score;
}
//resets the board value
reboard[Convert.ToInt32(array[i])] = move.index.ToString();
// adding the final object move to a List of moves with score for every move
moves.Add(move);
}
//finding the best move of possible moves
int bestMove = 0;
if (player == false) {
var bestScore = -10000;
for (var i = 0; i < moves.Count; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
var bestScore = 10000;
for (var i = 0; i < moves.Count; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
//returning the best move's index for an Ai to play
return moves[bestMove].index;
}