2011-12-02 29 views
0

我一直在尝试在java中创建并填充一棵树,然后使用minimax算法找到AI的最佳路线。树的递归人口

递归函数生成的树:

public void gen(Node n, int depth){ 
    if(depth == 6){ 
     n = new Node(); 
     n.depth = height; 
    } 
    else{ 
     n = new Node(); 
     n.depth = depth;    
     gen(n.e1, depth+1); 
     gen(n.e2, depth+1); 
     gen(n.e3, depth+1); 
     gen(n.p1, depth+1); 
     gen(n.p2, depth+1); 
     gen(n.p3, depth+1); 
     } 
    } 

功能来填充树值:

public void score(Node node, char a){  
    //Assigning scores to states to find utility value 
    //Changing state strings to reflect current state of nodes and phase 
    if(node!=null && node.depth!=6){ 
      if(node.depth%2==1){ 
      //Player's turn 
      node.state = node.state.substring(0, node.depth))+a+node.state.substring((node.depth+2));   
      score(node.e1, 'a'); 
      score(node.e2, 'b'); 
      score(node.e3, 'a'); 
      score(node.p1, 'b'); 
      score(node.p2, 'a'); 
      score(node.p3, 'b'); 
      } 
      else if(node.depth%2==0){ 
      //AI's turn 
      node.state = node.state.substring(0,(node.depth+4))+a+node.state.substring((node.depth+6)); 
      score(node.e1, 'a'); 
      score(node.e2, 'b'); 
      score(node.e3, 'a'); 
      score(node.p1, 'b'); 
      score(node.p2, 'a'); 
      score(node.p3, 'b'); 
      } 
     }  
    } 

测试功能,看看是否一切工作,通过打印内容:

public void printTree(Node node){   
     if(node!=null){ 
      System.out.println(node.depth + " " + node.state); 
      printTree(node.e1); 
      printTree(node.e2); 
      printTree(node.e3); 
      printTree(node.p1); 
      printTree(node.p2); 
      printTree(node.p3); 
     } 
    } 

而且,节点类本身: 最终类节点 {
public String state =“BCXXXCXXX”;

//utility value 
public int score; 
public int oscore; 
public int utility; 
public int min; 
public int max; 
public int depth; 

Node p1; 
Node p2; 
Node p3;  
Node e1; 
Node e2; 
Node e3; 

public Node() 
{ 

} 

}

我跑了打印功能,其打印 1 BxXXCXXX 其中我预期的第一个节点。我用一个空节点调用它,深度为1.为什么它不生成(或打印)树的其余部分,深度为6?

虽然我认为这可能是不相关的,但这个代码最终会在Android游戏中使用。

+1

对于最小最大化算法,你根本不应该构建树。它应该隐含在递归模式中。 –

+0

你是什么意思? – zigzag90

+0

您应该一次生成路径,就像您在递归DFS中一样。 –

回答

2

Java按值通过Node,因此您的分配n = new Node();不起作用。您的gen函数应该返回它创建的节点,而不是将其作为参数。

public Node gen(int depth){ 
    Node n = new Node(); 
    if (depth == 6){ 
     n.depth = height; 
    } else { 
     n.depth = depth;    
     n.e1 = gen(depth+1); 
     n.e2 = gen(depth+1); 
     n.e3 = gen(depth+1); 
     n.p1 = gen(depth+1); 
     n.p2 = gen(depth+1); 
     n.p3 = gen(depth+1); 
    } 
    return n; 
} 
+0

输出确实发生了变化,但我无法确认这是否有窍门,因为我的打印功能现在显示无限循环。我是Java的新手,所以有什么我做错了吗? – zigzag90

+0

@ zigzag90这是意想不到的。你可以分享打印输出的第30..40行吗? – dasblinkenlight

+0

我的歉意,我使用的是旧版本的功能。这次运行良好。我会尝试将它添加到整个项目中,谢谢! – zigzag90