From a4ea1a2ec853ab86652d440dc0cb5ba69dd103b7 Mon Sep 17 00:00:00 2001 From: Rh17S15 Date: Mon, 22 Sep 2025 19:43:52 +0200 Subject: [PATCH] Added Alpha-Beta-Pruning to Speed up AI to minimax --- MVC/minimax.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/MVC/minimax.py b/MVC/minimax.py index ec7893c..12ef384 100644 --- a/MVC/minimax.py +++ b/MVC/minimax.py @@ -4,7 +4,7 @@ import random class Minimax: - def minimax(self, current_field, is_maximizing, player1_char, player2_char): + def minimax(self, current_field, is_maximizing, player1_char, player2_char, alpha=float('-inf'), beta=float('inf')): checkwin = self.check_win(current_field, player1_char, player2_char) if checkwin == (1, 1): # Draw return 0, 0, 0 @@ -20,15 +20,20 @@ class Minimax: for k in range(0, len(current_field), 2): if current_field[j][k] == " ": current_field[j][k] = player1_char if not is_maximizing else player2_char - score = self.minimax(current_field, not is_maximizing, player1_char, player2_char)[0] + score = self.minimax(current_field, not is_maximizing, player1_char, player2_char, alpha, beta)[0] current_field[j][k] = " " if is_maximizing and score > best_score: best_score = score best_move = j, k + alpha = max(alpha, best_score) elif not is_maximizing and score < best_score: best_score = score best_move = j, k + beta = min(beta, best_score) + + if beta <= alpha: + break # Beta cutoff if best_score == 0 and best_move == (0, 0): # is None: empty_cells = [(j, k) for j in range(0, len(current_field), 2) for k in range(0, len(current_field), 2) if @@ -40,7 +45,6 @@ class Minimax: if best_move is None: return 0, -1, -1 # No available moves else: - # print('The next best move is:', best_move, "score: ", best_score) return best_score, best_move[1], best_move[0] def check_win(self, ifield, player1_char, player2_char):