我找不到可用于创建国际象棋开头树形结构的蟒蛇树,所以我试图写我自己的。为了进一步深入树中,我尝试在添加新位置时返回一个子根,但似乎所有位置都已添加到根,并且没有像我期望的那样给出对某个子根的引用,尽管我做检查,根也有很多孙子。因为你已经滥用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)
请提供您正在使用的'chess.pgn'库的下载链接。 –
https://pypi.python.org/pypi/python-chess – Josh