0
我有一个Javascript类,我需要克隆来创建与alpha beta beta修剪在javascript中的极小算法。但是,当我将电路板对象传递给极小极小函数时,它应该深度复制电路板对象然后进行更改,但它会更改原始电路板。它为什么这样做?对象没有得到克隆 - Javascript
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
我模块使用chess.js API来自:https://github.com/jhlywa/chess.js。
编辑:我已经缩小到克隆功能克隆棋功能正确。是否因为国际象棋函数没有用this
装饰器声明变量?
它不应该做一个深层复制。它应该像所有对象一样工作,并传递参考。 –
我怎样才能做出深层次的复制?我不想修改原始对象。 – TimCPogue
查看**相关**标题下的某些右侧链接。 –