【发布时间】:2017-05-05 00:17:21
【问题描述】:
iam 尝试为 connect4 游戏编写 min max 算法,但是当我运行此代码时,它进入无限循环并且不返回移动或结果,所以我需要帮助以了解它有什么问题,我在 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];
}
}
【问题讨论】:
-
你从内部递归调用
MinMax,所以它会永远持续下去。 -
为什么永远,有停止条件
-
使用您的调试器逐步执行
MinMax方法,找出为什么您的停止条件从未被命中,然后您可以修复它。 -
我已经成功了,当 score_sofar !=0 或没有可能移动时,它已经达到了我的停止条件
-
你的代码丢失了一半,所以很难猜出哪里出了问题。我只能告诉你,这是我能看到的唯一递归,这就是导致你的错误的原因。