I have implemented a NegaMax algorithm (which is just a shorter version of minimax algorithm) with alpha beta pruning . Now I want to implement Iterative Deepening so that I can find a best move for every depth and then reorder the the nodes under the tree based on the scores of the previous layers so that my alphabeta pruning works more efficiently.
Here's what I have done so far:
InitialDEPTH = 1
def findBestMove(gs, validMoves):
global nextMove
global InitialDEPTH
nextMove = None
for d in range(2):
CurrentDEPTH = InitialDEPTH + d
findMoveNegaMaxAlphaBeta(gs, validMoves, CurrentDEPTH, -CHECKMATE, CHECKMATE, 1 if gs.whiteToMove else -1)
return nextMove
Here gs is the gamestate that changes with everymove and contains all the information about the game at t hat point like if castling is possible or whether there is a enpassant move possible. My negamax algorithm looks like this :
def findMoveNegaMaxAlphaBeta(gs, validMoves, depth, alpha, beta, turnMultiplier):
global nextMove
if depth == 0 :
return turnMultiplier * scoreBoard(gs)
maxScore = -CHECKMATE
# I have a felling i need to add some code here to make it work
for move in validMoves :
gs.makeMove(move)
nextMoves = gs.getValidMoves()
score = -findMoveNegaMaxAlphaBeta(gs, nextMoves, depth - 1 , -beta, -alpha, -turnMultiplier)
if score > maxScore:
maxScore = score
if depth == DEPTH :
nextMove = move
gs.undoMove()
if maxScore > alpha: # This is were pruning happens
alpha = maxScore
if alpha >= beta :
break
return maxScore
How can I add the time constraint function to this code so that it only returns the best move when the the mentioned time gets over and not before that.
Also how can I reorder the nodes after each depth for efficient pruning in the next depth. I have written some sort of function for that , but I do not know how to implement this. The function that I wrote :
def sorting(move):
gs.makeMove(move)
score = scoreBoard(gs)
gs.undoMove()
return turnMultiplier * score
validMoves.sort(key = sorting)