import random from math import inf from utilities.constants import GREEN, WHITE from utilities.gameManager import GameManager class MiniMax: def AI(self, depth: int, maxPlayer: int, gameManager: GameManager) -> tuple: """ The minimax algorithm :param depth: How deep the algorithm should go :param maxPlayer: The current player :param gameManager: The game manager :return: the best evaluation and board """ if depth == 0 or gameManager.board.winner() is not None: return gameManager.board.scoreOfTheBoard(), gameManager.board if type(maxPlayer) == int: maxEval = -inf bestMove = None for move in gameManager.board.getAllMoves(maxPlayer): evaluation = self.AI(depth - 1, False, gameManager)[0] maxEval = max(maxEval, evaluation) if maxEval > evaluation: bestMove = move if maxEval == evaluation: # bestMove = move bestMove = bestMove if random.choice([True, False]) else move return maxEval, bestMove else: minEval = inf bestMove = None colour = WHITE if gameManager.turn == GREEN else GREEN for move in gameManager.board.getAllMoves(colour): evaluation = self.AI(depth - 1, True, gameManager)[0] minEval = min(minEval, evaluation) if minEval < evaluation: bestMove = move if minEval == evaluation: # bestMove = move bestMove = bestMove if random.choice([True, False]) else move return minEval, bestMove