我正在使用 Unity3D (C#) 中的 AI 开发 Connect Four 游戏。我根据this (German) Pseudocode使用 MiniMax 算法。
AI的表现仍然很糟糕。它试图连续获得 4 个,尽管只有三个空闲字段。AI 总是在需要时穿过行并阻塞。不幸的是,它也不总是阻塞。
哪里隐藏问题?我忘记了什么?
当下一步没有人赢或输时,我如何整合人工智能的随机动作。
这是我的源代码:
最小最大深度 = 4
函数调用:Max (minimaxDepth, fieldCopy);
int Max (int depth, int[,] fieldCopy)
{
int maxValue = -9999;
int moveValue;
bool winAI = false;
bool winHuman = false;
bool isStoneBelow = false;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
if (y > 0) {
//is a stone under it?
if (fieldCopy [x, y - 1] == 1 || fieldCopy [x, y - 1] == 2) {
isStoneBelow = true;
} else {
isStoneBelow = false;
}
} else {
isStoneBelow = true;
}
// possible move?
if (fieldCopy [x, y] != 1 && fieldCopy [x, y] != 2 && isStoneBelow == true) {
isStoneBelow = false;
fieldCopy [x, y] = 2; //simulate move
winAI = false;
winHuman = false;
//Is there a winner?
if (CheckWin (x, y, 2, fieldCopy)) {
winAI = true;
winHuman = false;
}
//No more moves possible?
if (depth <= 1 || winAI == true) {
moveValue = evaluationFunction (winAI, winHuman); //evaluate the move
} else {
moveValue = Min (depth - 1, fieldCopy);
}
fieldCopy [x, y] = 0; //Reset simulated move
if (moveValue > maxValue) {
maxValue = moveValue;
if (depth == minimaxDepth) {
aiMoveX = x; // next move
}
}
}
}
}
return maxValue;
}
int Min (int depth, int[,] fieldCopy)
{
int minValue = 9999;
int moveValue;
bool winAI = false;
bool winHuman = false;
bool isStoneBelow = false;
bool loopBreak = false;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
if (y > 0) {
//is a stone under it?
if (fieldCopy [x, y - 1] == 1 || fieldCopy [x, y - 1] == 2) {
isStoneBelow = true;
} else {
isStoneBelow = false;
}
} else {
isStoneBelow = true;
}
// possible move?
if (fieldCopy [x, y] != 1 && fieldCopy [x, y] != 2 && isStoneBelow == true) {
isStoneBelow = false;
fieldCopy [x, y] = 1; //simulate move
winHuman = false;
winAI = false;
//Is there a winner?
if (CheckWin (x, y, 1, fieldCopy)) {
winHuman = true;
winAI = false;
}
//No more moves possible?
if (depth <= 1 || winHuman == true) {
moveValue = evaluationFunction (winAI, winHuman); //evaluate the move
} else {
moveValue = Max (depth - 1, fieldCopy);
}
fieldCopy [x, y] = 0; //Reset simulated move
if (moveValue < minValue) {
minValue = moveValue;
}
}
}
}
return minValue;
}
int evaluationFunction (bool winAI, bool winHuman)
{
if (winAI) {
return 1;
} else if (winHuman) {
return -1;
} else {
return 0;
}
}
谢谢你的帮助!