tac-toe-tictactoe minimax算法

hof1towb  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(247)

我正在用java实现minimax算法。我学过编码火车教程。问题是,人工智能总是选择下一个可用的地点,而不是最好的。
game.put()将玩家(或空白点)id放置在给定的点上。
board是游戏类的一个变量,它是字节的二维数组。
game.checkforwin()如果游戏仍然打开,则返回0,如果没有人赢并且没有可能的移动(平局),则返回1,如果ai赢了,则返回1,如果玩家赢了,则返回2。

public Point bestMove(){
        int bestScore = Integer.MIN_VALUE;
        Point move = null;

        for (int i=0; i<board.length; i++){
            for(int j=0; j<board[i].length; j++){
                if (board[i][j] == blank){
                    game.put(ai_id, new Point(i,j));
                    int score = minimax(false);
                    game.put(blank, new Point(i,j));
                    if(score > bestScore){
                        bestScore = score;
                        move = new Point(i, j);
                    }
                }
            }
        }
        return move;
    }

    public int minimax(boolean ai_turn){
        int state = game.checkForWin();
        if (state!=0){ // If game ended
            if(state == -1){
                return 0; //TIE
            }
            if( state == ai_id){
                return 1; //AI wins
            }
            return -1; //Player wins
        }

        int bestScore = 0;

        if(ai_turn){
            bestScore = Integer.MIN_VALUE;
            for (int i=0; i<board.length; i++){
                for(int j=0; j<board[i].length; j++){
                    if (board[i][j] == blank){
                        game.put(ai_id, new Point(i,j));
                        int score = minimax(false);
                        game.put(blank, new Point(i,j));
                        bestScore = Math.max(score, bestScore);
                    }
                }
            }
        }else{
            bestScore = Integer.MAX_VALUE;
            for (int i=0; i<board.length; i++){
                for(int j=0; j<board[i].length; j++){
                    if (board[i][j] == blank){
                        game.put(player_id, new Point(i,j));
                        int score = minimax(true);
                        game.put(blank, new Point(i,j));
                        bestScore = Math.min(score, bestScore);
                    }
                }
            }
        }
        return bestScore;
    }

编辑:我重写了整个游戏的代码和这个函数算法的工作预期。

bqujaahr

bqujaahr1#

不检查值 2 如果玩家赢了。你先检查一下 -1 怎么了?

相关问题