【发布时间】:2020-08-06 10:40:38
【问题描述】:
我在 python 中使用 minimax 算法开发了一个国际象棋引擎,并且我还使用 Alpha-Beta Pruning 对其进行了进一步优化。目前我正在搜索 4 的深度,虽然不是很多,但仍然需要 10 - 60 秒才能想到一个动作。
减慢程序的主要因素是一次又一次地迭代。我首先在deque.collection() 中生成所有可能的移动,然后我遍历它一次以验证它。现在我再次遍历它以评估这些动作,然后比较它们以获得最佳可能的动作。我在整个过程中都使用 for 循环,所有可能的移动的格式是集合(移动)的集合(mainmoves)
我可以做些什么来优化它并减少生成移动所需的时间。
def minimaxRoot(depth,isMaximizing):
global board
possibleMoves = gen(False)
bestMove = -math.inf
bestMoveFinal = None
for move in possibleMoves:
orig = normperform(move)
value = max(bestMove, minimax(depth - 1,not isMaximizing,-math.inf,math.inf))
undo(move,orig)
if value > bestMove:
bestMove = value
bestMoveFinal = move
return bestMoveFinal
def minimax(depth,ismax,alpha,beta):
global board
if depth == 0:
return calcpoints()
maxeval = -math.inf
mineval = math.inf
if ismax == True:
mainmoves = gen(False)
if mainmoves == 'mate':
return 8000
for move in mainmoves:
orig = normperform(move)
eval = minimax(depth-1,False,alpha,beta)
undo(move,orig)
maxeval=max(eval,maxeval)
alpha = max(alpha,eval)
if beta <= alpha:
break
return maxeval
elif ismax == False:
mainmoves2 = gen(True)
if mainmoves2 == 'mate':
return 8000
for move2 in mainmoves2:
orig2 = normperform(move2)
eval2 = minimax(depth-1,True,alpha,beta)
undo(move2,orig2)
mineval = min(mineval,eval2)
if eval2 < beta:
beta = eval2
if beta <= alpha:
break
return mineval
【问题讨论】:
标签: python loops optimization chess minimax