我找不到一个我可以用来为国际象棋开口创建树形结构的python树,所以我试着写自己的。为了更深入地进入树,我尝试在添加新位置时返回子根,但似乎所有位置都被添加到根目录中,并且我没有像我期望的那样获得对子根的引用,尽管我做了检查,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)
答案 0 :(得分:0)
您的代码失败,因为您误用了class variables.
基本上,当您在任何函数之外声明children
时,它在类级别作用域,并且所有Node
个对象共享相同的列表。您希望在__init__
中将其定义为self.children
,以便它在实例级别定义。
class Node:
def __init__(self, fen):
self.fen = fen
self.score = None
self.children = []
...