Marcel Pirlog
Marcel Pirlog

Reputation: 89

Create dynamic tree in python using anytree module

I try to create a implementation for minmax algorithm and need to create a tree with all possible moves. Create a tree using anytree module in python 3.7, but when try to iterate in first tree level and build next level receive a error.

Traceback (most recent call last):
Hello from the pygame community. https://www.pygame.org/contribute.html
  File "C:/Users/User/PycharmProjects/Tema5AI/Main.py", line 217, in <module>
min_max_algorithm(game)
  File "C:/Users/User/PycharmProjects/Tema5AI/Main.py", line 209, in min_max_algorithm
new_node = Node((game, i, 0), parent=(pre, fill, node))
  File "C:\Users\User\PycharmProjects\Tema5AI\venv\lib\site-packages\anytree\node\node.py", line 66, in __init__
    self.parent = parent
  File "C:\Users\User\PycharmProjects\Tema5AI\venv\lib\site-packages\anytree\node\nodemixin.py", line 126, in parent
    msg = "Parent node %r is not of type 'NodeMixin'." % (value)
TypeError: not all arguments converted during string formatting

My code for build tree is:

def min_max_algorithm(game):
    first_black_move = util.get_all_available_black(game)
    root = Node(game)
    for i in first_black_move:
        node = Node((game, i, 0), parent=root)
    for pre, fill, node in RenderTree(root):
        first_white_move = util.get_all_available_white(game)
        for i in first_white_move:
            new_node = Node((game, i, 0), parent=(pre, fill, node))
    for pre, fill, node in RenderTree(root):
        print("%s%s" % (pre, node.name))

More exactly the question is: How can I add children to a node by going through the current tree ?

The following questions didn't helped me: How to specify childrens in anytree and print a tree

Read data from a file and create a tree using anytree in python

How can I implement a tree in Python? Are there any built in data structures in Python like in Java?

Upvotes: 2

Views: 1534

Answers (1)

c0fec0de
c0fec0de

Reputation: 661

The exception is misleading. I created a ticket https://github.com/c0fec0de/anytree/issues/121.

You can add nodes at any time. Please ensure that only node objects are set as parent or children. Maybe it is better to use an iterator instead of the render function, i.e. the PreOrderIter. Please try this

def min_max_algorithm(game):
    first_black_move = util.get_all_available_black(game)
    root = Node(game)
    for i in first_black_move:
        node = Node((game, i, 0), parent=root)
    for n in PreOrderIter(root):
        first_white_move = util.get_all_available_white(game)
        for i in first_white_move:
            new_node = Node((game, i, 0), parent=n)
    for pre, fill, node in RenderTree(root):
        print("%s%s" % (pre, node.name))

Upvotes: 1

Related Questions