I am trying to write AI for computer player using MinMax in checkers game and i have strange problem. I have that dictionary:
Dictionary<int, Field> gameBoard;
Look at the methods ApplyMove() and RevertMove()
public int MinMax(Dictionary<int, Field> gameBoard, string color, Boolean maximizingPlayer, int depth)
{
int bestValue;
if (0 == depth)
return ((color == myColor) ? 1 : -1) * evaluateGameBoard(gameBoard, color);
int val;
if (maximizingPlayer)
{
bestValue = int.MinValue;
foreach (Move move in GetPossibleMoves(gameBoard, color))
{
gameBoard = ApplyMove(gameBoard, move);
val = MinMax(gameBoard, color, false, depth - 1);
bestValue = Math.Max(bestValue, val);
gameBoard = RevertMove(gameBoard, move);
}
return bestValue;
}
else
{
bestValue = int.MaxValue;
foreach (Move move in GetPossibleMoves(gameBoard, Extend.GetEnemyPlayerColor(color)))
{
gameBoard = ApplyMove(gameBoard, move);
val = MinMax(gameBoard, color, true, depth - 1);
bestValue = Math.Min(bestValue, val);
gameBoard = RevertMove(gameBoard, move);
}
return bestValue;
}
}
Method ApplyMove() working well, ApplyMove() and RevertMove() both of theme returning gameBoard.
ApplyMove()
public Dictionary<int, Field> ApplyMove(Dictionary<int, Field> gameBoard, Move move)
{
gameBoard_old = Extend.CloneGameBoard(gameBoard);
gameBoard = UpdateFieldTo(gameBoard, move);
if (move.indexThrough == 0)
gameBoard = UpdateFieldThrough(gameBoard, move);
gameBoard = UpdateFieldFrom(gameBoard, move);
return gameBoard;
}
RevertMove()
public Dictionary<int, Field> RevertMove(Dictionary<int, Field> gameBoard, Move move)
{
gameBoard[move.indexFrom] = gameBoard_old[move.indexFrom];
if (move.indexThrough != 0)
{
gameBoard[move.indexThrough] = gameBoard_old[move.indexThrough];
}
gameBoard[move.indexTo] = gameBoard_old[move.indexTo];
return gameBoard;
}
The problem is here in RevertMove():
return gameBoard; ---> value is correct
but when that lane is executed in MinMax():
gameBoard = RevertMove(gameBoard, move);
there is 0 effect... GameBoard ignore that value from RevertMove() and keep holding old values.
I dont know what i am doing wrong... I suspect some problems with the reference. Is that operator "=" is bad way to change dictionary values? I have no idea whats going on... Once time this works well, another don't. Please don't blame me, i am newbie in c#
edit(1)
public static Dictionary<int, Field> CloneGameBoard(Dictionary<int, Field> gameBoard)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(gameBoard);
return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, Field>>(json);
}