I am creating a chess AI using the minimax method with alpha-beta pruning. I am trying to understand how the alpha-beta pruning works, but I can't get my head around it when it comes to chess where you set a certain search depth.
How do minimax with alpha-beta solve sacrificing a piece for advantage 2-3 moves ahead? Won't it just look at the position at the sacrifice and immediately discard that branch as bad, therefore missing the good "sacrifice"?
My code so far:
def minimax(board, depth, alpha, beta, maximizing_player): board.is_human_turn = not maximizing_player children = board.get_all_possible_moves() if depth == 0 or board.is_draw or board.is_check_mate: return None, evaluate(board) best_move = random.choice(children) if maximizing_player: max_eval = -math.inf for child in children: board_copy = copy.deepcopy(board) board_copy.move(child) current_eval = minimax(board_copy, depth - 1, alpha, beta, False) if current_eval > max_eval: max_eval = current_eval best_move = child alpha = max(alpha, current_eval) if beta <= alpha: break return best_move, max_eval else: min_eval = math.inf for child in children: board_copy = copy.deepcopy(board) board_copy.move(child) current_eval = minimax(board_copy, depth - 1, alpha, beta, True) if current_eval < min_eval: min_eval = current_eval best_move = child beta = min(beta, current_eval) if beta <= alpha: break return best_move, min_eval