我试图在python中实现minimax算法,但是在创建分支树结构时遇到了一些问题。我仍然是一个业余程序员,所以请不要介意我的代码似乎不好。这是我的节点结构class Node:
parent = None
state = None
pmax = 0 #this represents the MAX player symbol; i.e. SELF
pmin = 0 #this represents the MIN player symbol; i.e. OPPONENT
stateCost = 0 #this represents utility cost of leaf nodes based on the matrix state
bestCost = None #this represents the chosen path in the minimax algorithm
children = []
def __init__(self,mat,up,mx,mn):
self.parent = up
self.state = mat
self.pmax = mx
self.pmin = mn
stateCost = 0
def addChild(self,newState,up):
n = Node(newState,up,self.pmax,self.pmin)
self.children.append(n)
def evaluateChildren(self,minmax):
ln = len(self.state[0])
for x in range(ln):
#newState = insertIntoSink(self.state[0],x)
cloneState = cloneMatrix(self.state)
newState = insertIntoSink(cloneState,x,minmax)
print "state being added"
for list in newState:
print list
self.addChild(newState,self)
print "done Evaluating CHILDREN"
def evaluateSubChildren(self,minimax):
ln = len(self.state[0])
for l in self.children:
for x in range(ln):
cloneState = cloneMatrix(self.state)
newState = insertIntoSink(cloneState,x,minimax)
l.addChild(newState,l)
在我所做的事情中,根节点必须有7个子节点,并且每个子节点本身应该有7个子节点。每个子节点在父节点中都有一个修改过的初始矩阵克隆。在
出现的错误是,添加子级(即二级子级)后,不会将其添加到子级列表中,而是将它们添加到根节点。在
儿童的创造被称为如下。在
^{pr2}$
我首先尝试调用同一个evaluateTechChildren()函数,如下所示:def getBestMove(self):
move =0
maxVal = -1;
i=-1;
#evaluate all the 7 children
self.evaluateChildren(2)
#evaluate second level children
for n in self.children:
print "evaluating SECOND LEVEL CHILDREN"
n.evaluateChildren()
如果我在求值后检查根节点的子节点数,它应该是7,但是它不断地向它添加更多的二级子节点,这会使我的程序陷入无限循环。在
请告诉我我哪里做错了。请询问是否需要更多信息。在