我想知道我的minmax算法对于connect4游戏有什么问题?

时间:2016-12-19 21:20:23

标签: c# minmax

我尝试为connect4游戏编写min max算法,但是当我运行此代码时,它会进入infinte循环而不返回移动或结果,所以我想帮助知道它有什么问题,我在6中工作* 7个细胞

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 个答案:

答案 0 :(得分:0)

@Equalsk是对的,我相信:你在foreach循环中调用MinMax,然后才能到达评估停止条件的代码。因此,假设方法get_possible_moves返回与Null不同的东西,你将陷入foreach - &gt; MinMax - &gt; foreach - &gt; MinMax - &gt;的foreach ...