【发布时间】:2013-12-23 07:14:40
【问题描述】:
我正在尝试创建一个创建树的递归函数。每个节点都持有井字游戏的状态,每个节点的子节点是下一个可能的移动。
我将棋盘的状态传递给递归函数。对于每一个可能的移动,我都会创建一个状态副本,然后进行移动。这个新状态被传递给递归函数。
#XXX
#O O = state [1,1,1,-1,0,-1,1,1,1]
#XXX
playerX = 1
playerO = -1
class node:
children = [] #holds all the children
state = [] #holds the state of the board as a list of ints
def __init__(self,st):
self.state = st
def addChild(self,child):
self.children.append(child) #if only giving birth was this easy
#returns a node with all it's children filled in
#cState is the state for this node
#currentPlayer flips sign every function call
#stateSize is the size of the board
def makeTreeXO(cState,currentPlayer,stateSize):
newNode = node(cState)
for i in range(stateSize):
print "looking at", i, "in", cState
if(cState[i] == 0): #found an open space
print "found an empty space"
newState = cState #create copy of state
newState[i] = currentPlayer #make the available move
print "made new state"
newNode.addChild(makeTreeXO(newState,currentPlayer*-1,stateSize))
print "Done with this instance"
return newNode
root = makeTreeXO([1,0,0,1,1,1,1,1,1],playerX,9)
输出:
looking at 0 in [1, 0, 0, 1, 1, 1, 1, 1, 1]
looking at 1 in [1, 0, 0, 1, 1, 1, 1, 1, 1]
found an empty space
made new state
looking at 0 in [1, 1, 0, 1, 1, 1, 1, 1, 1]
looking at 1 in [1, 1, 0, 1, 1, 1, 1, 1, 1]
looking at 2 in [1, 1, 0, 1, 1, 1, 1, 1, 1]
found an empty space
made new state
looking at 0 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 1 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 2 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 3 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 4 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 5 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 6 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 7 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 8 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
Done with this instance
looking at 3 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 4 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 5 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 6 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 7 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 8 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
Done with this instance
looking at 2 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 3 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 4 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 5 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 6 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 7 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
looking at 8 in [1, 1, -1, 1, 1, 1, 1, 1, 1]
Done with this instance
从打印语句中可以清楚地看出,对状态所做的更改正在被带回函数的父实例。有谁知道为什么?
【问题讨论】:
标签: python recursion tree tic-tac-toe