
First of all, it is the initialized of class tree, but it does not store any data or built a structure of a tree. In addition, there are two different ways to build a tree to store data.
1. Using recursion method to build a tree under a root.
2. Build a bunch of trees and make them up in one tree.
Obviously, the second method is inefficient. Thus I will introduce the first method in the following article. Here is the code of a game-state tree.
def grow(self):
''' (GameStateNode) -> NoneType
Grow the tree of all possible game state nodes that can be reached
starting from this one.
Assume that the game is finite (and so the tree will be finite).
>>> a0 = SubtractSquareState('p1', current_total = 0)
>>> b1 = SubtractSquareState('p2', current_total = 1)
>>> a2 = SubtractSquareState('p1', current_total = 2)
>>> b3 = SubtractSquareState('p2', current_total = 3)
>>> a4 = SubtractSquareState('p1', current_total = 4)
>>> b0 = SubtractSquareState('p2', current_total = 0)
>>> a0_node = GameStateNode(a0)
>>> b1_node = GameStateNode(b1)
>>> b1_node.children = [a0_node]
>>> a2_node = GameStateNode(a2)
>>> a2_node.children = [b1_node]
>>> b3_node = GameStateNode(b3)
>>> b3_node.children = [a2_node]
>>> b0_node = GameStateNode(b0)
>>> a4_node = GameStateNode(a4)
>>> a4_node.children = [b0_node, b3_node]
>>> root = GameStateNode(SubtractSquareState('p1', current_total = 4))
>>> root.grow()
>>> root.__eq__(a4_node)
True
'''
if self.value.possible_next_moves != []:
for move in self.value.possible_next_moves():
new_gamestate = self.value.apply_move(move)
node = GameStateNode(new_gamestate)
self.children.append(node)
for item in self.children:
item.grow()
According to the doctext, I use the second method to build the tree. As I said see before, it is quite inefficient, but it just use to check the following code is right. In the code, we need to build a different trees as the children of the root by using recursion, which is more efficient than the second method.
没有评论:
发表评论