【问题标题】:Alpha-beta pruning with clone doesnt work Java带有克隆的 Alpha-beta 修剪不起作用 Java
【发布时间】:2016-09-29 16:57:00
【问题描述】:

想在我的黑白棋游戏中为我的 AI 模拟下一步动作,但不是只返回下一步动作,而是在原始棋盘上进行所有动作,而不是仅仅在克隆上模拟,然后游戏结束。

public class GameState implements Cloneable{
private Node[][] board;                 // Game board
private int scorePlayer, scoreAI;       // Player scores ( will start at 0 )
private ArrayList<Node> validNodes;     // List holding all nodes possible to add pieces to 

/**
 * Creates the game state
 */
public GameState(){
    // create size x size board
    this.board = new Node[Setting.BOARD_SIZE][Setting.BOARD_SIZE];
    validNodes = new ArrayList<>();
    scorePlayer = 0;
    scoreAI = 0;

protected GameState clone() {
    return new GameState(this);
}------------------------ CLONE METHOD----------------



public int search(GameState board, Player player, int alpha, int beta, int depth, ScoreEval function) {
    int record = Integer.MIN_VALUE;
    Node maxMove = null;
    int result;

    GameState subBoard = board.clone();
    if (depth <= 0 || board.getValidMoves().size()==0) {
        record = function.evaluate(board, player);
    } else {
    ArrayList<Node> possibleMoves = board.getValidMoves();
        if (!possibleMoves.isEmpty()) {
            for (int i =0; i<possibleMoves.size();i++) {
                Node nod = possibleMoves.get(i);
                subBoard = board.clone();
                subBoard.setPiece(nod.x,nod.y, player.type);
                if(player.type==Setting.TILE_AI){
                    result = -search(subBoard, aiAss1.Controller.pHum, alpha, beta, depth - 1, function);
                }
                else{
                    result = -search(subBoard, aiAss1.Controller.pAI, alpha, beta, depth - 1, function);
                }

            if (result > record) {
                    record = result;
                    maxMove = nod;
                }
            }
        } else {
            record = -search(subBoard, player, alpha, beta, depth - 1, function);
        }
    }
    bestMove = maxMove;
    return record;
}

【问题讨论】:

  • 您确定要复制董事会的内部状态吗? (所有可变对象)
  • 您的 clone() 方法看起来已损坏。您很可能正在创建浅拷贝。
  • GameState添加clone的实现
  • @Kayaman 可能是对的。但是你真的需要克隆整个板子吗?反向移动不是更高效吗?
  • 尝试使用 ---- protected GameState clone() throws CloneNotSupportedException { GameState state = (GameState)super.clone();返回状态; } 但也可以工作

标签: java algorithm alpha-beta-pruning


【解决方案1】:

尝试将您的逻辑分解为多个部分,将每个部分放入一个单独的方法中。然后为每个部分编写一个单元测试,并检查每个部分是否符合您的要求。

这就是你应该如何编写软件。

【讨论】:

  • 我只是分享一些与我的问题相关的代码,问题似乎是克隆只返回一个浅拷贝,
  • clone的语义不清楚,最好避免。如果你想要一个深度克隆,写一个 deepClone() 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多