【发布时间】:2017-03-28 17:52:24
【问题描述】:
我已经为 tic tac toe 编写了一个带有 alpha-beta 修剪的 minimax 算法(可能是问题所在,之前运行良好),但它并不总是选择最佳移动(例如,没有立即获胜)。 但是,它仍然会阻止您获胜的任何方式。
例子:
Do you want to go first (y/n)? n
Going in: 2,2
...
.X.
...
Where do you want to go (row,col)? 1,2
.O.
.X.
...
Going in: 1,1
XO.
.X.
...
Where do you want to go (row,col)? 1,3
XOO
.X.
...
Going in: 2,3 (?)
XOO
.XX
...
Where do you want to go (row,col)?
代码(全文见here):
def miniMaxScore(self,isComp,alpha=None,beta=None):
"""Get score of current game"""
if self.isFinished(): #if game is complete, score it and return
return self.score()
if alpha==None:
alpha=float('-inf')
if beta==None:
beta=float('+inf')
if isComp:
bestValue=float('-inf')
for move in self.empty():
new=self.fillIn(*move,2)
currValue=new.miniMaxScore(False,alpha,beta)
alpha=max(alpha,currValue)
bestValue=max(currValue,bestValue)
# if beta<=alpha:
# break
return bestValue
else:
bestValue=float('+inf')
for move in self.empty():
new=self.fillIn(*move,2)
currValue=new.miniMaxScore(True,alpha,beta)
beta=min(currValue,beta)
bestValue=min(currValue,bestValue)
# if beta<=alpha:
# break
return bestValue
def getAIMove(self):
"""Return the x and y positions of the optimal AI move"""
scores=[]
for possibleMove in self.empty():
possibleNext=self.fillIn(*possibleMove,2)
scores.append((possibleMove,possibleNext.miniMaxScore(False)))
return max(scores,key=lambda x:x[1])[0] #best move
编辑:删除修剪,但仍然损坏
【问题讨论】:
标签: python-3.x minimax