I want to know what is wrong with my minmax algorithm for connect4 game?

102 Views Asked by At

iam try to write min max algorithm for connect4 game but when i run this code it go in infinte loop and not return move or result, so i want a help to know what is wrong with it , i work in board of 6*7 cells

private int score()
{
    int x = check_Winner();//i checked it and it work right ot return 1 if player 1 win or 2 if pc win or 0 in tie
    if (x == 1) return 10;
    else if (x == 2) return -10;
    else return 0;
}

public int MinMax(int player_num)
{
    List<pair> possiple_moves = get_possible_moves();// it works will
    int score_so_far = score();
    if (possiple_moves.Count == 0 || score_so_far != 0)
        return score_so_far;

    List<int> scores = new List<int>();
    List<pair> moves = new List<pair>();

    foreach (pair move in possiple_moves)
    {
        if (player_num == 1)
        {
            cells[move.x, move.y].player_num = 1;
            scores.Add(MinMax(2));
        }
        else
        {
            cells[move.x, move.y].player_num = 2;
            scores.Add(MinMax(1));
        }
        moves.Add(move);

        cells[move.x, move.y].player_num = 0;
    }

    if (player_num == 1)
    {
        int max_score_indx = 0, tmp = int.MinValue;
        for (int i = 0; i < scores.Count; i++)
        {
            if (scores[i] > tmp)
            {
                tmp = scores[i];
                max_score_indx = i;
            }
        }
        pc_choise = moves[max_score_indx];
        return scores[max_score_indx];
    }
    //==================
    else
    {
        int min_score_indx = 0, tmp = int.MaxValue;
        for (int i = 0; i < scores.Count; i++)
        {
            if (scores[i] < tmp)
            {
                tmp = scores[i];
                min_score_indx = i;
            }
        }
        pc_choise = moves[min_score_indx];
        return scores[min_score_indx];
    }
}
1

There are 1 best solutions below

1
On

@Equalsk is right, I believe: you are calling MinMax from within the foreach loop, before you reach the code that evaluates the stop conditions. So providing that the method get_possible_moves returns something different to Null, you will get stuck in foreach --> MinMax --> foreach --> MinMax --> foreach...