我想在python中實現minimax算法,但我在創建分支樹結構時遇到了一些問題。我仍然是一個業餘程序員,所以請不要介意我的代碼看起來不好。這裏是我的節點結構如何在Python中正確實現具有n分支因子的樹?
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個孩子的本身。每個孩子將在父節點中擁有初始矩陣的修改克隆。
發生錯誤是在添加子級(即第二級子級)後,不會將子級添加到子級列表中,而是會將它們添加到根節點中。
孩子的創造被稱爲如下。
def getBestMove(self):
move =0
maxVal = -1;
i=-1;
#evaluate all the 7 children
self.evaluateChildren(2)
self.evaluateSubChildren(1)
#more calculations go here
我第一次嘗試調用相同evaluateChildren()函數如下:
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,但是它保持加更多的2級的孩子,這是在無限循環中拋出我的程序。
請讓我知道我要去哪裏錯了。請詢問是否需要更多信息。
完美!!非常感謝!!簡單而直接點:) –