首页 > 解决方案 > TicTacToe 极小极大算法与 Java

问题描述

我正在用 Java 实现极小极大算法。我遵循了 Codding Trains 教程。问题是人工智能总是选择下一个可用的位置,而不是最好的。

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;
    }

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

标签: javatic-tac-toeminimax

解决方案


2 如果玩家赢了,您不检查该值。立即检查有-1什么问题。


推荐阅读