feat: minimax algorighm

This commit is contained in:
snsd0805 2024-04-09 18:02:17 +08:00
parent 05d32500b2
commit e7464ceeb4
Signed by: snsd0805
GPG Key ID: 569349933C77A854

View File

@ -162,7 +162,29 @@ class MinimaxAgent(MultiAgentSearchAgent):
Returns whether or not the game state is a losing state
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
return self.result(gameState, 0, self.depth)[1]
def result(self, state, agentIndex, depth):
if depth == 0 or state.isLose() or state.isWin():
return self.evaluationFunction(state), None
elif agentIndex == 0: # maximize
(nextAgentIndex, nextDepth) = (0, depth-1) if agentIndex == (state.getNumAgents()-1) else (agentIndex+1, depth)
max_reward, max_action = -1e9, None
for action in state.getLegalActions(agentIndex):
reward = self.result(state.generateSuccessor(agentIndex, action), nextAgentIndex, nextDepth)[0]
if reward > max_reward:
max_reward, max_action = reward, action
return max_reward, max_action
else: # minimize
(nextAgentIndex, nextDepth) = (0, depth-1) if agentIndex == (state.getNumAgents()-1) else (agentIndex+1, depth)
min_reward, min_action = 1e9, None
for action in state.getLegalActions(agentIndex):
reward = self.result(state.generateSuccessor(agentIndex, action), nextAgentIndex, nextDepth)[0]
if reward < min_reward:
min_reward, min_action = reward, action
return min_reward, min_action
class AlphaBetaAgent(MultiAgentSearchAgent):
"""