未通过 python 树的期望值

Not being passed desired value for python tree

我找不到可用于为国际象棋开局创建树结构的 python 树,因此我尝试编写自己的树。为了深入到树中,我在添加新位置时尝试 return 一个子根,但似乎所有位置都被添加到根中,而且我没有像我一样得到对子根的引用期待,虽然我确实检查过并且 root 也有很多孙子。

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)

您的代码失败是因为您误用了 class variables.

基本上,当您在任何函数之外声明 children 时,它的作用域在 class 级别,并且所有 Node 对象共享同一个列表。您希望在 __init__ 中将其定义为 self.children,以便它在实例级别范围内。

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