Reputation: 35
I'm trying to implement this turn-based "Fighting game" using a minimax algorithm. However, I ran into some problems. THe code worked the first time running it but after running it the second time It gave an error.
I thought applying alpha-beta pruning would solve the issue but it's still the same.
RecursionError: maximum recursion depth exceeded while calling a Python object.
This is the minimax algorithm that's causing the error
def minimax(self, depth, is_maximizing, alpha, beta):
if depth == 0 or self.is_winning(self.computer) or self.is_winning(self.player) or self.is_draw():
if self.is_winning(self.computer):
return self.computer_score - depth
if self.is_winning(self.player):
return -self.player_score + depth
if self.is_draw():
return 0
if is_maximizing:
best_value = float('-inf')
for move in ["slash", "thrust"]:
self.attack = move
value = self.minimax(depth - 1, False, alpha, beta)
best_value = max(best_value, value)
alpha = max(alpha, best_value)
if beta <= alpha:
break
return best_value
else:
best_value = float('inf')
for move in ["block", "dodge"]:
self.defend = move
value = self.minimax(depth - 1, True, alpha, beta)
best_value = min(best_value, value)
beta = min(beta, best_value)
if beta <= alpha:
break
return best_value
What am I missing here? Any answer that's helpful is appreciated.
Upvotes: 1
Views: 187
Reputation: 76
The problem is here:
if depth == 0 or self.is_winning(self.computer) or self.is_winning(self.player) or self.is_draw():
if self.is_winning(self.computer):
return self.computer_score - depth
if self.is_winning(self.player):
return -self.player_score + depth
if self.is_draw():
return 0
There is no default condition, so it is possible for your minmax function to go to past depth=0
. You can fix this easily by adding a return at the end.
if depth == 0 or self.is_winning(self.computer) or self.is_winning(self.player) or self.is_draw():
if self.is_winning(self.computer):
return self.computer_score - depth
if self.is_winning(self.player):
return -self.player_score + depth
if self.is_draw():
return 0
return 0 # Or replace with an evaluation function
Upvotes: 2