Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. class AlphaBetaAgent(MultiAgentSearchAgent):
  2. """
  3. Your minimax agent with alpha-beta pruning (question 3)
  4. """
  5.  
  6. def get_action(self, game_state):
  7. """
  8. Returns the minimax action using self.depth and self.evaluationFunction
  9. """
  10. """*** YOUR CODE HERE ***"""
  11. return self.alphabeta(game_state, self.depth * 2, 0 , -float('inf'), float('inf'))[1]
  12.  
  13. def alphabeta(self, state, curr_depth, player, alpha, beta):
  14. if curr_depth == 0:
  15. return self.evaluation_function(state), Action.STOP
  16.  
  17. if player == 0: # max
  18. best_value = -float('inf')
  19. actions = state.get_legal_actions(player)
  20. succ_states = [state.generate_successor(player, action) for action in actions]
  21.  
  22. if len(actions) == 0:
  23. return self.evaluation_function(state), Action.STOP
  24. best_action = actions[0]
  25.  
  26. for index, succ in enumerate(succ_states):
  27. value, drop = self.alphabeta(succ, curr_depth - 1, 1, alpha, beta)
  28. if value > best_value:
  29. best_value = value
  30. best_action = actions[index]
  31.  
  32. if value >= beta:
  33. return (best_value, best_action)
  34.  
  35. alpha = max(alpha, value)
  36.  
  37.  
  38. else: # min
  39. best_value = float('inf')
  40. actions = state.get_legal_actions(player)
  41. succ_states = [state.generate_successor(player, action) for action in actions]
  42.  
  43. if len(actions) == 0:
  44. return self.evaluation_function(state), Action.STOP
  45. best_action = actions[0]
  46.  
  47. for index, succ in enumerate(succ_states):
  48. value, drop = self.alphabeta(succ, curr_depth - 1, 0, alpha, beta)
  49. if value < best_value:
  50. best_value = value
  51. best_action = actions[index]
  52.  
  53. if value <= alpha:
  54. return (best_value, best_action)
  55.  
  56. beta = min(beta, value)
  57.  
  58. return (best_value, best_action)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement