def min_value(board, player, alpha, beta, depth): #if terminal state then return utility of leaf node if is_terminal(board): u, alp, bet = utility(board, player) return u, alp, bet, -1 #if reached depth limit then return utility 0 #that is, consider it a draw if depth == 0: u = 0 return u, -1, -1, -1 v = math.inf ret_mov = -1 a, b = alpha, beta #get list of possible moves and shuffle it legal_moves = shuffle(board.generate_moves()) #find a move with minimum utility for mov in legal_moves: board.make_move(mov) min_val, a1, b1, m = max_value(board, player, a, b, depth - 1) if min_val < v: v, ret_mov = min_val, mov board.unmake_last_move() if v <= a: b = v return v, a, b, ret_mov b = min(b, v) return v, a, b, ret_mov
def min_value(self, board, player, alpha, beta, depth): #check if termial state if self.is_terminal(board): u, alp, bet = self.utility(board, player) return u, alp, bet, -1 #check if depth limit is reached if depth == 0: u = 0 return u, -1, -1, -1 v = math.inf ret_mov = -1 a, b = alpha, beta #Get list of all possible moves legal_moves = self.shuffle(board.generate_moves()) #Search for a move with minimum utility for mov in legal_moves: board.make_move(mov) min_val, a1, b1, m = self.max_value(board, player, a, b, depth - 1) if min_val < v: v, ret_mov = min_val, mov board.unmake_last_move() if v <= a: b = v return v, a, b, ret_mov b = min(b, v) return v, a, b, ret_mov
def perft(board, depth): #Get all possible moves legal_moves = board.generate_moves() #Check if last move caused win lmv = board.last_move_won() #if last move won the game or no valid move available if lmv or len(legal_moves) <= 0: #Unmake last move made by calling function board.unmake_last_move() return 1 #if last move did not win the game and valid moves are available, #but depth limit is reached if depth == 1: board.unmake_last_move() return len(legal_moves) #initialize variable to count leaf nodes visited so far count = 0 #For all legal moves from current state, call perft recursively for i in legal_moves: board.make_move(i) count += perft(board, depth - 1) #Unmake last move made by calling function before returning count board.unmake_last_move() #return number of leaf nodes visited return count pass