【问题标题】:Stuck on minmax algorithm with alpha beta pruning坚持使用 alpha beta 剪枝的 minmax 算法
【发布时间】:2016-03-08 17:30:23
【问题描述】:

我正在尝试在 java 的井字游戏中实现带有 alpha beta 修剪的 minmax 算法。写完代码我马上发现了ArrayIndexOutOfBounds的异常,于是我试着自己放了一些终端输出来查找错误,我发现这是由于最终返回的错误结果引起的:算法最终返回@ 987654322@ 得分为-2147483646 ,当其余代码尝试移动并将坐标放入该字段时,它会导致异常。我做了一些方案来模拟一些动作和一些可能的树,但我找不到错误。

   /*
   * int field[][] is the board array, it may contains 0(empty), 1(opponent's seed), 2(computer's seed)
   * nComputer = 2 (computer's seed)
   * nPlayer = 1 (opponent's seed)
   * computerMove = new int[3]
   * remainingMoves has been calculated before the main call
   */

   // Main call
   computerMove = cMove(remainingMoves, nComputer,Integer.MIN_VALUE + 1, Integer.MAX_VALUE - 1);
   field[computerMove[1]][computerMove[2]] = nComputer; // This line cause the exception!!
   // MinMax alpha-beta pruning algorithm
   private static int[] cMove(int depth, int player, int alpha, int beta) {

       int[][] moveList = new int[3][10];
       moveList = generateMoves(field); // See below for details

       int temp;
       int score;
       int bestR = -1;
       int bestC = -1;

       // check function retunrns 1(opponent wins), 2(computer wins), 0(draw) or -1(nothing)
       if(moveList[0][0] == 0 || depth == 0) {
           score = cScore(player);

           return new int[] { score, bestR, bestC };
       } else {
           for (int i = 1;i < moveList[0][0]; i++) {
               // Trying to make a move
               field[moveList[1][i]][moveList[2][i]] = player;

               if(player == nComputer) { // Maximazing player
                   score = cMove(depth -1, nPlayer, alpha, beta)[0];
                   if(score > alpha) {
                       alpha = score;
                       bestR = moveList[1][i];
                       bestC = moveList[2][i];
                   } 
               } else { // Minimizing player
                   score = cMove(depth -1, nComputer, alpha, beta)[0];
                   if(score < beta) {
                       beta = score;
                       bestR = moveList[1][i];
                       bestC = moveList[2][i];
                   } 
               }

               field[moveList[1][i]][moveList[2][i]] = 0; // Undo move
               if(alpha >= beta) i = 10; // Cut-off
           }

           if(player == nComputer) temp = alpha; 
           else temp = beta;

           return new int[] { temp, bestR, bestC };

       }
   }

   /*
   * generateMoves function returns an array 3x10 where [0][0] is the number
   * of possible moves and [0,1,2][1-9] are the score and the
   * coordinates(rows and columns) of all the possible moves
   */
   private static int[][] generateMoves(int[][] field) {
       int[][] result = new int[3][10];
       int k = 0;

       if(check(4) != -1) {
           return result;
       }

       for (int i = 0; i < field.length; i++) {
           for (int j = 0; j < field[0].length; j++) {
               if (field[i][j] == 0) {
                   k++;
                   result[1][k] = i;
                   result[2][k] = j;
               }
           }
       }

       result[0][0] = k;

       return result;
   }

   // cScore function assign a score for the actual node with an heuristic evaluation
private static int cScore(int p) {
    int score = 0;
    score += cRow(p, 0, 0, 0, 1, 0, 2);
    score += cRow(p, 1, 0, 1, 1, 1, 2);
    score += cRow(p, 2, 0, 2, 1, 2, 2);
    score += cRow(p, 0, 0, 1, 0, 2, 0);
    score += cRow(p, 0, 1, 1, 1, 2, 1);
    score += cRow(p, 0, 2, 1, 2, 2, 2);
    score += cRow(p, 0, 0, 1, 1, 2, 2);
    score += cRow(p, 0, 2, 1, 1, 2, 0);
    return score;
 }

private static int cRow(int player, int rOne, int cOne, int rTwo, int cTwo, int rThr, int cThr) {
    int score = 0;

    if (field[rOne][cOne] == nComputer) {
        score = 1;
    } else if (field[rOne][cOne] == nPlayer) {
        score = -1;
    }

    if (field[rTwo][cTwo] == nComputer) {
        if (score == 1) {
            score = 10;
        } else if (score == -1) {
            return 0;
        } else {
            score = 1;
        }
    } else if (field[rTwo][cTwo] == nPlayer) {
        if (score == -1) {
            score = -10;
        } else if (score == 1) {
            return 0;
        } else {
            score = -1;
        }
    }

    if (field[rThr][cThr] == nComputer) {
        if (score > 0) {
            score *= 10;
        } else if (score < 0) {
            return 0;
        } else {
            score = 1;
        }
    } else if (field[rThr][cThr] == nPlayer) {
        if (score < 0) {
            score *= 10;
        } else if (score > 1) {
            return 0;
        } else {
            score = -1;
        }
    }

    return score;
}

我在这个问题上被困了一个星期,我快疯了! 在此先感谢并为糟糕的英语感到抱歉,但这不是我的主要语言,我正在慢慢尝试学习它

----------------------------------------------- - - - - - - - - - 编辑 - - - - - - - - - - - - - - - - -----------------------------

按要求添加校验功能:

// check function first check the state of 5 cells that needs to be filled to won([0,0][0,1][0,2][1,0][2,0])
public static int check(int nMove) {
    int state = -1;

    if(field[0][0] != 0) {
        state = col(0,1);
        if(state == 1 || state == 2) return state; // Win on first col
        state = row(0,1);
        if(state == 1 || state == 2) return state; // Win on first row
        state = diagonal(1);
        if(state == 1 || state == 2) return state; // Win on first diagonal
    }
    if (field[0][1] != 0) {
        state = col(1,2);
        if(state == 1 || state == 2) return state; // Win on second col
    }
    if (field[0][2] != 0) {
        state = col(2,3);
        if(state == 1 || state == 2) return state; // Win on third col
        state = diagonal(2);
        if(state == 1 || state == 2) return state; // Win on second diagonal
    }
    if (field[1][0] != 0) {
        state = row(1,2);
        if(state == 1 || state == 2) return state; // Win on second row
    }
    if (field[2][0] != 0) {
        state = row(2,3);
        if(state == 1 || state == 2) return state; // Win on third row
    }

    if(nMove == 8) return 0; // Draw

    return state;
}
// Check if the entire row is filled (check rows from starting to n points)
private static int row(int start, int n) {
    int s = -1;
    int k = 0;
    int h = 0;

    for (int i = start; i < n; i++) {
        for (int j = 0; j < (field[0]).length; j++) {
            if(field[i][j] == 1) {
                k++;
                if(k==3) s = 1;
            } else if(field[i][j] == 2) {
                    h++;
                    if(h==3) s = 2;
            }
        }
        k=0;
        h=0;
    }

    return s;
}
// Check if the entire col is filled (check cols from starting to n points)
private static int col(int start, int n) {
    int s = -1;
    int k = 0;
    int h = 0;

    for (int i = start; i < n; i++) {
        for (int j = 0; j < (field).length; j++) {
            if(field[j][i] == 1) {
                k++;
                if(k==3) s = 1;
            } else if(field[j][i] == 2) {
                    h++;
                    if(h==3) s = 2;
            }
        }
        k=0;
        h=0;
    }

    return s;
}
// Check if the entire diagonal is filled (check first diagonal if n=1 and second diagonal if n=2)
private static int diagonal(int n) {
    int s = -1;
    int k = 0;
    int h = 0;

    if(n == 1) {
        for (int i = 0; i < (field).length; i++) {
            int j = i;
            if(field[i][j]== 1) {
                k++;
                if(k==3) s = 1;
            } else if(field[i][j] == 2) {
                h++;
                if(h==3) s = 2;
            }
        }
    } else if (n == 2) {
        int j = 2;
        for (int i = 0; i < (field).length; i++) {
            if(field[i][j] == 1) {
                k++;
                if(k==3) s = 1;
            }
            else if(field[i][j] == 2) {
                h++;
                if(h==3) s = 2;
            }
            j--;
        }
    } else { }

    return s;
}

【问题讨论】:

  • 我会为你解答这个问题,但你能把你所有的课程都给我吗?有很多东西不见了,我不知道它是什么。只需将它们全部复制并粘贴进去。如果您导入了任何罐子或类似的东西,请告诉我。
  • 这个测试的整个代码很长(大约 1k 行),所以为了更容易理解,我决定只分享感兴趣的部分。这个函数是一个名为 IA 的类的一部分,我成功编译了它。但是整个算法的结果总是[-1][-1],分数约为2 * 10^9。这让我觉得递归有问题,但我不明白在哪里。如果有帮助,我还可以发布检查算法,如有必要,还可以发布整个代码,但我认为它只会让人困惑。感谢您的快速答复
  • 使用调试器。如果您知道故障以及您的代码应该做什么,那么调试器实际上会在您逐步运行代码时为您提供值。我无法在我的脑海中做到这一点。
  • 我找到了生成异常的代码部分,但是由于这种递归,调试起来非常困难,我找不到导致它总是返回 [-1][-1] 的原因,分数为 2147483646
  • 最终结果表明“cMove”只被调用了一次,为此,if (check(8 - depth) != -1 || depth == 0) { 行是可疑的。你能发布“检查”方法吗?

标签: java arrays algorithm minimax minmax


【解决方案1】:

假设您的棋盘大于 3x3,否则以 4 作为获胜条件的 Tick-tack-toe 没有太大意义,您的异常将在这里引发:

for (int i = 0; i < field.length; i++) {
       for (int j = 0; j < field[0].length; j++) {
           if (field[i][j] == 0) {
               k++;
               result[1][k] = i; // out of bounds
               result[2][k] = j; // out of bounds
           }
       }
   }

对于大小为 A x B 的字段,当 board 为空时,k 将变为 A*B - 1 一样大。对于A = B = 7,这将变为 48,大于 9,这是result[i] 中允许的最大索引。

// ======================== 编辑 ===================== =============
我有点困惑,不确定您要优化什么(计算机或播放器的最佳分数?),但我找到了一些可以解释结果的东西。

在每个递归调用中,您都有一个变量 player
根据其值更新alphabeta
在递归步骤结束时,根据 player 的值返回 alphabeta
但是,如果 player == 2 则更新 alpha

if(player == 2) { // Maximazing player
    score = cMove(depth -1, nPlayer, alpha, beta)[0];
    if(score > alpha) {

但是如果player == 2返回beta

if(player == 1) temp = alpha;
    else temp = beta;

所以你总是返回MIN_VALUE + 1alphaMAX_VALUE - 1beta
因此,if(score &lt; alpha) {if(score &lt; beta) { 对于每一步都将始终为 false,这并不称为基本情况。 你的递归看起来像这样:

  • 深度 = 4,调用深度 = 3
    • 深度 = 3,调用深度 = 2
      • depth = 2,player1 获胜,得分为 42
    • 深度 = 3,更新 alpha = 42,返回 beta = MAX_VALUE - 1 作为分数
  • depth = 4,call3 返回 MAX_VALUE - 1 这是我的测试版,所以没有任何变化,bestRbestC 保持 -1

【讨论】:

  • 目前我第一次尝试使其适用于 3x3 板。我包含了 generateMoves 函数,只是因为它可能是异常的起源,当我尝试执行作为 [-1][-1] 它超出范围时,finally 算法的结果界限。在调用函数后澄清我何时执行field[cMove[1]][cMove[2]] = nComputer;。无论如何感谢您的回答,并为缺乏清晰度感到抱歉
  • 我用建议的改进更新了代码,但它仍然返回与以前相同的结果