一层的情况就不讨论了,直接就是走一步后,当前局面的最高分
第二层情况
第三层情况
现在分析一下为什么会出现最大最小值算法:
因为走棋是你一步我一步的来。
作为我来说,我肯定愿意选当前局面分值最大的一步。
作为对方来说,对方肯定不是傻子,肯定选你局面分最小的情况。
这样就形成了,最大,最小值算法,最大(我),最小(你)。
理想的情况,计算机是不会输的,因为他可以选择出最优的路径,前提是层数最够多。
当然每加一层,是指数式增长。所以计算机是不可能真的有无限层。所以计算机可能输。
int AI::getMaxScore(Game* game, int level, int curMaxScore)
{
if (level == 0)
return calcScore(game);
CCArray* allMove = allPossibleMove(game);
int maxScore = -20000;//用来记录当前局面最大分
for (int i = 0; i < allMove->count(); i++)
{
Step* step = (Step*)allMove->objectAtIndex(i);//获取走法
fakeMove(game, step);//假走
int score = getMinScore(game, level - 1, maxScore);//获取这一局面下的最小值,如果在计算最小值时有某个score比max小,那么肯定不选他,就剪枝
unfakeMove(game, step);
// 减枝:用大于等于号来剪枝效率更高
if (score >= curMaxScore)
return score;
if (score > maxScore)
{
maxScore = score;
// 在计算的顶层循环要记录要走的步骤
if (level == _level)
{
_step = step;
}
}
}
return maxScore;
}
int AI::getMinScore(Game* game, int level, int curMinScore)
{
if (level == 0)
return calcScore(game);
CCArray* allMove = allPossibleMove(game);
int minScore = 100000;
for (int i = 0; i < allMove->count(); i++)
{
Step* step = (Step*)allMove->objectAtIndex(i);
fakeMove(game, step);
int score = getMaxScore(game, level - 1, minScore);//如果在计算最大值时有某个score比min还大,那么肯定不选他,就剪枝
unfakeMove(game, step);
// 减枝:用小于等于号来剪枝效率更高
if (score <= curMinScore)
return score;
if (score < minScore)
{
minScore = score;
// 在计算的顶层循环要记录要走的步骤
if (level == _level)
{
_step = step;
}
}
}
return minScore;
}