无限递归 - Javascript minimax

时间:2014-03-07 03:54:55

标签: javascript recursion minimax

我正在尝试使用chess.js库创建国际象棋AI。我正在使用带有Alpha-Beta修剪的minimax解决方案,但出于某种原因,当程序运行时,即使在深度达到0后它仍然继续。任何人都可以告诉我为什么?

var Buddha = function() {

  this.movehistory = 0;
  this.color = "b";
  this.opp = "w";


  this.minimax = function(board, depth, alpha, beta) {
    console.log(depth);
    if(depth === 0 || board.game_over() === true) {
      console.log("Depth == 0");
      return [this.eval_board(board), null]
    } else {
      if(board.turn() === this.color) {
        var bestmove = null

        var possible_moves = board.moves()
        for (index = 0; index < possible_moves.length; ++index) {
          var new_board = new Chess(board.fen());
          new_board.move(possible_moves[index])

          var mini = this.minimax(new_board, --depth, alpha, beta)
          var score = mini[0];
          var move = mini[1];

          if(score > alpha) {
            alpha = score;
            bestmove = possible_moves[index];
            if(alpha >= beta) {
              break;
            }
          }
        }
        return [alpha, bestmove]
      } else if(board.turn() === this.opp) {
        var bestmove = null

        var possible_moves = board.moves()
        for (index = 0; index < possible_moves.length; ++index) {
          var new_board = new Chess(board.fen());
          new_board.move(possible_moves[index])

          var mini = this.minimax(new_board, --depth, alpha, beta)
          var score = mini[0];
          var move = mini[1];

          if(score < beta) {
            beta = score;
            bestmove = possible_moves[index];
            if(alpha >= beta) {
              break;
            }
          }
        }
        return [beta, bestmove]
      }
    }
  }

  this.eval_board = function(board) {
    if(board.in_check()) {
      if(board.turn() == this.opp) {
        return Number.POSITIVE_INFINITY;
      } else {
        return Number.NEGATIVE_INFINITY;
      }
    } else if(board.in_checkmate()) {
      if(board.turn() == this.opp) {
        return Number.POSITIVE_INFINITY;
      } else {
        return Number.NEGATIVE_INFINITY;
      }
    } else if(board.in_stalemate()) {
      if(board.turn() == this.opp) {
        return Number.POSITIVE_INFINITY;
      } else {
        return Number.NEGATIVE_INFINITY;
      }
    }
  }

  this.move = function(board) {
    var bestmove = this.minimax(board, 1, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY)
  }

}

1 个答案:

答案 0 :(得分:2)

function minimax(board, depth, alpha, beta) {
  if(depth === 0 …) { …
    return …
  } else {
    …
    for (index = 0; index < possible_moves.length; ++index) {
      … minimax(new_board, --depth, alpha, beta)
//                         ^^
    …
    }
  }
}

这里你在循环中递减depth。使用depth <= 0作为基本情况,和/或传递depth - 1作为参数或将减量语句放在循环之前。