我正在尝试创建用于在游戏中的每个节点中创建具有游戏状态的决策树的功能(无论什么游戏)。我写了这样的递归函数(DFS):
function makeTree(anchor,count,player){
var subTree=null;
var nodes=[];
if(player)var newPlayer=false;
else var newPlayer=true;
for (var i = 0; i <= 9; i++) {
for (var j = 0; j <= 9; j++) {
if(anchor["state"][i][j]==0){
var newState=anchor["state"];
if(player)newState[i][j]=1;
else newState[i][j]=2;
var node={name:i+"_"+j, contents:[],state:newState, value:null, player:newPlayer};
if(count>0){
var newCount=count-1;
subTree=makeTree(node,newCount,newPlayer);
node["contents"]=subTree;
}
nodes.push(node);
}else{
continue;
}
}
}
return nodes;
}
通过电话:
var tree={};
var hrac=true;
var plocha=[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0]];
var state=plocha;
tree={name: "root",
contents:[],
state:state,
value:null,
player: hrac};
tree["contents"]=makeTree(tree,3,hrac);
但是函数改变了不同范围内的变量,所以输出树将是这样的:
"root" - node - node - node
- node
- node
- node
- node
我无法弄清楚该函数中变量newState
的情况,因为在完成递归后,原始变量plocha
具有最新node["state"]
的值。有什么建议吗?
答案 0 :(得分:0)
您的state
属性是一个可变的数组。在每个赋值中,您更改一个多维数组,该数组是所有节点的state
。您希望将每个newState
设为一个新数组,而不是递归传递所有函数的plocha
引用:
…
var newState = anchor["state"].slice(); // create copy of the outer array
newState[i] = newState[i].slice(); // copy of the row to be modified
newState[i][j] = player ? 1 : 2;
…