2016-06-15 32 views
0

我找不到可用于创建国际象棋开头树形结构的蟒蛇树,所以我试图写我自己的。为了进一步深入树中,我尝试在添加新位置时返回一个子根,但似乎所有位置都已添加到根,并且没有像我期望的那样给出对某个子根的引用,尽管我做检查,根也有很多孙子。因为你已经滥用class variables.没有通过蟒树的期望值

基本上,当你声明children外面在类级别范围的任何功能,并且所有Node对象共享同一个列表

import chess.pgn 

class Node(object): 
    children = [] 
    score = None 
    def __init__(self, fen): 
     self.fen = fen 
    def add(self, fen): 
     for c in self.children: 
      if c.fen == (fen): 
       print("working") 
       return c 
     self.children.append(Node(fen)) 
     return self.children[-1] 

root = Node('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') 
def createTree(fileName): 
    pgn = open(fileName) 
    game = chess.pgn.read_game(pgn) 
    while(game):  
     next_move = game.variations[0] 
     fen = next_move.board().fen() 
     global root 
     currentRoot = root.add(fen) 

     while(not next_move.is_end() and next_move.board().fullmove_number <= 5): 
      next_move = next_move.variations[0] 
      fen = next_move.board().fen() 
      currentRoot = currentRoot.add(fen) 
      print(currentRoot.children) 
     game = chess.pgn.read_game(pgn) 

file = r"C:\all.pgn" 
createTree(file) 
for n in root.children: 
    print(n.fen) 
+0

请提供您正在使用的'chess.pgn'库的下载链接。 –

+0

https://pypi.python.org/pypi/python-chess – Josh

回答

0

你的代码失败。您希望在__init__中将其定义为self.children,以便它在实例级别进行作用域。

class Node: 
    def __init__(self, fen): 
     self.fen = fen 
     self.score = None 
     self.children = [] 
    ... 
+0

这很有道理。希望它修复它! – Josh

+0

@Josh请记住,如果代码为您工作,请选择它作为接受的答案。谢谢! –

+0

它确实修复了它。而且我能够制作一些递归方法来遍历它 – Josh