我有一个Javascript类,我需要克隆以在javascript中使用Alpha beta修剪创建minimax算法。但是当我将board对象传递给minimax函数时,它应该深度复制board对象然后进行更改,但它会对原始板进行更改。为什么要这样做?
var Buddha = function() {
this.movehistory = 0;
this.color = "b";
this.opp = "w";
this.clone = function(board) {
return $.extend(true, {}, board)
}
this.minimax = function(board, depth, alpha, beta) {
if(depth === 0 || board.game_over() === true) {
return [this.eval_board(board), null]
} else {
if(board.turn() === "w") {
var bestmove = null
var possible_moves = board.moves()
for (index = 0; index < possible_moves.length; ++index) {
var new_board = this.clone(board)
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() === "b") {
var bestmove = null
var possible_moves = board.moves()
for (index = 0; index < possible_moves.length; ++index) {
var new_board = this.clone(board)
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) {
console.log(board.fen());
var bestmove = this.minimax(this.clone(board), 8, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY)
console.log(board.fen());
}
}
控制台日志的输出是:
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
R2r1b2/2q1k1p1/2n4n/2P2Q2/8/8/4K2P/1NBQ1BNR b - - 30 55
我的模块使用来自https://github.com/jhlywa/chess.js的chess.js api。
编辑:我已将其缩小到克隆功能,而不是正确克隆国际象棋功能。是因为Chess函数没有使用this
装饰器声明变量吗?
答案 0 :(得分:0)
chess.js库静态创建变量。难以克隆对象。幸运的是,Chess对象允许传递FEN变量。允许我像这样克隆电路板:
var clonedBoard = new Chess(oldBoard.fen());
这可以防止修改原始电路板。