变量重新分配自己 - Javascript

时间:2014-03-07 05:41:28

标签: javascript recursion minimax

我正在运行这个国际象棋AI,它正确地分配了bestmove变量,但是当它进行最后的递归并返回得分时,最好的移动,即使先前已设置,最好的移动总是未定义的。那是为什么?

var Buddha = function() {

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

  this.minimax = function(board, depth, alpha, beta) {
    if(depth <= 0 || board.game_over() === true) {
      return [this.eval_board(board), this.bestmove]
    } else {
      if(board.turn() === this.color) {

        var possible_moves = board.moves();
        for (index = 0; index < possible_moves.length; ++index) {
          if(possible_moves[index] != undefined) {
            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],
                move = mini[1];

           if(score > alpha) {
              alpha = score;
              this.bestmove = possible_moves[index];
              console.log(this.bestmove);
              if(alpha >= beta) {
                break;
              }
            }
          }
        }
        return [alpha, this.bestmove]

      } else if(board.turn() === this.opp) {

        var possible_moves = board.moves();
        for (index = 0; index < possible_moves.length; ++index) {
          if(possible_moves[index] != undefined) {
            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],
                move = mini[1];

            if(score < beta) {
              beta = score;
              this.bestmove = possible_moves[index];

              if(alpha >= beta) {
                break;
              }
            }
          }
        }
        return [beta, this.bestmove]
      }
    }
  }

  this.eval_board = function(board) {
    if(board.in_check()) {
      if(board.turn() == this.opp) {
        return 999999999;
      } else {
        return -999999999;
      }
    } else if(board.in_checkmate()) {
      if(board.turn() == this.opp) {
        return 999999999;
      } else {
        return -999999999;
      }
    } else if(board.in_stalemate()) {
      if(board.turn() == this.opp) {
        return 999999999;
      } else {
        return -999999999;
      }
    } else {
      return 0;
    }
  }

  this.move = function(board) {
    console.log(this.minimax(board, 16, -999999999, 999999998));
  }

}

我的程序使用此处的chess.js API:https://github.com/jhlywa/chess.js

0 个答案:

没有答案