I don’t understand what is wrong here, because AI player is making move to next available spot and not the best one. Can anyone please help me?
Vector2 bestMove(){
int bestVal = -1000;
Vector2 bestPosition= new Vector2(0,0);
for (int i=0; i<_width; i++)
{
for(int j=0; j<_height; j++){
Vector2 position = new Vector2(i,j);
if (_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite.name=="tile")
{
_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite=oImage;
int moveVal = Minimax(_tiles,3,true);
_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite=tileImage;
if(moveVal>bestVal){
bestVal=moveVal;
bestPosition=position;
}
}
}
}
return bestPosition;
}
bool isMovesLeft(Dictionary<Vector2, Tile> tiles){
for (int i=0; i<_width; i++)
{
for(int j=0; j<_height; j++){
Vector2 position = new Vector2(i,j);
if (tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite.name=="tile")
{
return true;
}
}
}
return false;
}
int Minimax (Dictionary<Vector2, Tile> tiles,int depth, bool isMaximazingPlayer){
int score = EvaluateBoard(tiles);
if(score==10 || score==-10 || depth==0){
return score;
}
if(isMovesLeft(tiles)==false){
return 0;
}
if(isMaximazingPlayer){
int bestScore = -1000;
for (int i=0; i<_width; i++)
{
for(int j=0; j<_height; j++){
Vector2 position = new Vector2(i,j);
if (_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite.name=="tile")
{
_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite = oImage;
bestScore = Math.Max(bestScore, Minimax(tiles,depth-1,false));
// reset the board
_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite=tileImage;
}
}
}
Debug.Log("bestScore Max Player: "+bestScore);
return bestScore;
} else {
int bestScore = 1000;
for (int i=0; i<_width; i++)
{
for(int j=0; j<_height; j++){
Vector2 position = new Vector2(i,j);
if (_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite.name=="tile")
{
_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite = xImage;
bestScore = Math.Min(bestScore, Minimax(tiles,depth-1,true));
// reset the board
_tiles.GetValueOrDefault(position).GetComponentInChildren<Button>().GetComponent<Image>().sprite=tileImage;
}
}
}
Debug.Log("bestScore Min Player: "+bestScore);
return bestScore;
}
}