Untitled
unknown
plain_text
a year ago
3.4 kB
5
Indexable
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
"""
def minimax(state, agent = 0, play_depth = 0):
'''
A state is considered a terminal state when the the max depth is reached or the game is over
The max depth is defined by the self.depth attribute
The returned value is a dictionary with the score and the action to take
'''
if play_depth == self.depth or state.isWin() or state.isLose():
return {'score': self.evaluationFunction(state), 'action': None}
if agent == 0:
return max_value(state, agent, play_depth)
else:
return min_value(state, agent, play_depth)
def max_value(state, agent, play_depth):
# Initialize the value as negative infinity, get the legal actions and the best action (action to take) as None
value = float('-inf')
actions = state.getLegalActions(agent)
best_action = None
for action in actions:
# Save the previous value to compare with the new value and update the best action if the new value is greater
previous_value = value
successor = state.generateSuccessor(agent, action)
next_agent = (agent + 1) % state.getNumAgents() # Get the next agent
next_depth = play_depth + 1 if next_agent == 0 else play_depth # Increae the depth if an agent roration is completed
value = max(value, minimax(successor, next_agent, next_depth)['score'])
if value > previous_value:
best_action = action
return {'score': value, 'action': best_action}
def min_value(state, agent, play_depth):
# Initialize the value as positive infinity, get the legal actions and the best action (action to take) as None
value = float('inf')
actions = state.getLegalActions(agent)
best_action = None
for action in actions:
# Save the previous value to compare with the new value and update the best action if the new value is greater
previous_value = value
successor = state.generateSuccessor(agent, action) # Get the next agent
next_agent = (agent + 1) % state.getNumAgents() # Increae the depth if an agent roration is completed
next_depth = play_depth + 1 if next_agent == 0 else play_depth
value = min(value, minimax(successor, next_agent, next_depth)['score'])
if value < previous_value:
best_action = action
return {'score': value, 'action': best_action}
return minimax(gameState)['action']
Editor is loading...
Leave a Comment