迷住井字游戏中的MiniMax算法

时间:2019-05-13 15:20:22

标签: java tic-tac-toe minimax

我想制作一个国际象棋AI,所以我认为我应该先从一个井字游戏AI开始。由于其受欢迎程度,我的代码使用了minimax算法。

我将其应用于代码,但是无法正常工作。

以这个为例:

x x -
- o -
- o x

O(人工智能)的明显选择是右上方,从而阻止X赢得最高排名。相反,该机器人在这里播放:

x x -
o o -
- o x

注意:这不是机器人犯错误的唯一例子,它在其他几个位置失败。

很明显,我在某个地方犯了一个错误,但我找不到它。

    private int getBestMove() {
        int bestValue = -10000000;
        Button returnValue = null;//todo change this to int

        Tree tree = new Tree(0, deepCopy(board));

        for (Button button: tree.getEmptyPositions()) {
            System.out.println("Calculating. . .");

            int value = getValue(new Tree(0, deepCopy(board)), button, getOp(turn));

            if (value > bestValue) {
                bestValue = value;
                returnValue = button;
            }
        }

        if (returnValue == null) {
            System.err.println(" *** Critical Error: Failed to find available move.");
        }
        return returnValue.id; // Each button has an id
    }


    private static int getValue(Tree tree, Button button, int turn) {
        int returnValue = 0;

        tree.board[button.y][button.x].cell = turn; // What is in the tile

        if (isWin(tree.board, AI.id)) returnValue += WIN - tree.depth;
        else if (isWin(tree.board, HUMAN.id)) returnValue += LOOSE + tree.depth;
        else if (isFullBoard(tree.board)) returnValue += TIE;
        else {
            for (Button cell : tree.getEmptyPositions()) { // Possible moves
                returnValue += getValue(new Tree(tree.depth + 1, deepCopy(tree.board)), cell, getOp(turn)); // getOp = getEnemy 
            }

            //if (tree.depth % 2 == 0) returnValue += 10;
            //else returnValue -= 10; // Many people use this, not sure if I'll need this
        }
        return returnValue;
    }

我的问题:我到底在做什么错了?

0 个答案:

没有答案