我正在编写一个 minmax 算法作为井字游戏的人工智能,我在这里遵循了类似的指令,但是该算法似乎不够智能,即使我尝试在树中进行更深的搜索,任何人都可以帮助分析哪里出了问题?非常感谢你!
- (int) miniMax:(int)depth : (UIImage*) player {
NSMutableArray *steps = [self generateMoves];
if (depth == 0 || [steps count] == 0) {
return [self evaluate];
}
int bestScore = player == myImg ? -1000000 : 1000000;
int currentScore = 0;
for (UIImageView *step in steps) {
step.image = player;
if (player == myImg) {
UIImage *opp = player == xImg ? oImg : xImg;
currentScore = [self miniMax:depth - 1 :opp];
if (currentScore > bestScore) {
bestScore = currentScore;
nextStep = step;
}
} else {
UIImage *opp = player == xImg ? oImg : xImg;
currentScore = [self miniMax:depth - 1 :opp];
if (currentScore < bestScore) {
bestScore = currentScore;
nextStep = step;
}
}
step.image = NULL;
}
return bestScore;
}
- (int) evaluate {
int score = 0;
score += [self evaluateLine:img0 :img1 :img2];
score += [self evaluateLine:img3 :img4 :img5];
score += [self evaluateLine:img6 :img7 :img8];
score += [self evaluateLine:img0 :img3 :img6];
score += [self evaluateLine:img1 :img4 :img7];
score += [self evaluateLine:img2 :img5 :img8];
score += [self evaluateLine:img2 :img4 :img6];
score += [self evaluateLine:img0 :img4 :img8];
return score;
}
- (int) evaluateLine:(UIImageView*)img1 :(UIImageView*)img2 :(UIImageView*)img3 {
int score = 0;
// first cell
if ([img1 image] == myImg) {
score = 1;
} else if ([img1 image] == oppImg){
score = -1;
}
// second cell
if ([img2 image] == myImg) {
if (score == 1) {
score = 10;
} else if (score == -1) {
return 0;
} else {
score = -1;
}
} else if ([img2 image] == oppImg){
if (score == -1) {
score = -10;
} else if (score == 1) {
return 0;
} else {
score = -1;
}
}
// third cell
if ([img3 image] == myImg) {
if (score > 0) {
score *= 10;
} else if (score < 0) {
return 0;
} else {
score = -1;
}
} else if ([img3 image] == oppImg){
if (score < 0) {
score *= 10;
} else if (score > 1) {
return 0;
} else {
score = -1;
}
}
return score;
}
我这里使用的是:如果存在与人类玩家持有的相同图像,则得分加1。如果一行或一行或对角线有两个或三个玩家的图像,则总分分别为10和100。如果在同一行、同一列或同一对角线中同时存在“X”和“O”,则得分为 0。计算机保留上述这些的负分。