class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] closestPos, minDistance = None, 100000 for livingGhostPositionDistribution in livingGhostPositionDistributions: likelyPosition = self.findLikelyPosition(livingGhostPositionDistribution) distance = self.distancer.getDistance(pacmanPosition,likelyPosition) if distance < minDistance: minDistance, closestPos = distance, likelyPosition for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) if self.distancer.getDistance(pacmanPosition,closestPos) > \ self.distancer.getDistance(successorPosition,closestPos): return action def findLikelyPosition(self, livingGhostPositionDistribution): max_prob, max_pos = 0, None for pos, prob in livingGhostPositionDistribution.items(): if prob > max_prob: max_prob, max_pos = prob, pos return max_pos
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closest to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" maxBeliefPos = [max(l, key = l.get) for l in livingGhostPositionDistributions] closestGhost = min(maxBeliefPos, key = lambda pos: self.distancer.getDistance(pacmanPosition, pos)) successorPositions = [(Actions.getSuccessor(pacmanPosition, action), action) for action in legal] closestAction = min([(self.distancer.getDistance(closestGhost, pos), action) for pos, action in successorPositions])[1] return closestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closest to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] distances = inference.DiscreteDistribution() for pos in [x.argMax() for x in livingGhostPositionDistributions]: distances[pos] = -self.distancer.getDistance(pacmanPosition, pos) targetPos = distances.argMax() distances = inference.DiscreteDistribution() for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) distances[action] = -self.distancer.getDistance(targetPos, \ successorPosition) return distances.argMax()
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closest to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" maxPositions = [belief.argMax() for belief in livingGhostPositionDistributions] dist = [self.distancer.getDistance(pos,pacmanPosition) for pos in maxPositions] minPos = maxPositions[dist.index(min(dist))] successorDistance = [self.distancer.getDistance(minPos,Actions.getSuccessor(pacmanPosition, action)) for action in legal] return legal[successorDistance.index(min(successorDistance))]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" closestDist = None closestGhostPos = None for ghost, dist in enumerate(livingGhostPositionDistributions): positions = dist.keys() positions.sort(cmp=lambda a, b: cmp(dist[a], dist[b])) pos = positions[-1] distance = self.distancer.getDistance(pacmanPosition, pos) if distance < closestDist or closestDist is None: closestGhostPos = pos closestDist = distance actionDistances = [(a, self.distancer.getDistance(Actions.getSuccessor(pacmanPosition, a), closestGhostPos)) for a in legal] bestAction = min(actionDistances, key=lambda ad: ad[1])[0] return bestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" ghost_dist = {} for ghost_distribution in livingGhostPositionDistributions: most_likely_spot = max(ghost_distribution, key=ghost_distribution.get) ghost_dist[most_likely_spot] = self.distancer.getDistance(pacmanPosition, most_likely_spot) closest_ghost = min(ghost_dist, key=ghost_dist.get) possible_actions = {} for action in gameState.getLegalActions(): next_pacman_spot = Actions.getSuccessor(pacmanPosition, action) possible_actions[action] = self.distancer.getDistance(next_pacman_spot, closest_ghost) best_action = min(possible_actions, key=possible_actions.get) return best_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" closest=None min = float("inf") for x in livingGhostPositionDistributions: mostProb = x.argMax() dist = self.distancer.getDistance(pacmanPosition,mostProb) if dist<min: min=dist closest=mostProb action=None min = float("inf") for act in legal: dist=self.distancer.getDistance(Actions.getSuccessor(pacmanPosition,act),mostProb) if dist<min: min=dist action=act return action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def mydistance(x, y, pacmanPosition): ghostLocation = (x, y) return self.distancer.getDistance(pacmanPosition, ghostLocation) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [ beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i + 1] ] ghostPositions = [max(distribution, key=distribution.get) for distribution in livingGhostPositionDistributions] print "ghostPositions", ghostPositions closestGhostPosition = min(ghostPositions, key=lambda x: self.distancer.getDistance(pacmanPosition, x)) print "closestGhostPosition", closestGhostPosition successorPositions = [Actions.getSuccessor(pacmanPosition, action) for action in legal] closestSuccessorPosition = min( successorPositions, key=lambda x: self.distancer.getDistance(closestGhostPosition, x) ) move = legal[successorPositions.index(closestSuccessorPosition)] return move
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" # get max position for every ghost def getMaxDictKey(d): maxKeys = [k for k in d.keys() if d[k] == max(d.values())] return maxKeys[0] maxPos = [getMaxDictKey(k) for k in livingGhostPositionDistributions] distances = map(lambda x: self.distancer.getDistance(x, pacmanPosition), maxPos) minDist = min(distances) goalPos = maxPos[distances.index(minDist)] for action in legal: if self.distancer.getDistance(Actions.getSuccessor(pacmanPosition, action), goalPos) < minDist: return action # should not end here! return legal[0]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" mostPossiblePosition = lambda ghostPosDist: max(ghostPosDist.items(), key=lambda x: x[1])[0] mostPossiblePositions = map(mostPossiblePosition, livingGhostPositionDistributions) distToPacman = lambda x: self.distancer.getDistance(pacmanPosition, x) closestGhostPos = min(mostPossiblePositions, key=distToPacman) minDist = self.distancer.getDistance(pacmanPosition, closestGhostPos) delta_pos = set() for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) delta = self.distancer.getDistance(closestGhostPos, successorPosition)-minDist # the more negative the better delta_pos.add((delta, action)) return min(delta_pos)[1] # util.raiseNotDefined()
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] gohstPosition = [dist.argMax() for dist in livingGhostPositionDistributions] gohstDistance = [self.distancer.getDistance(pacmanPosition, pos) for pos in gohstPosition] closestGhostIndex = gohstDistance.index(min(gohstDistance)) allPacPotentialPos = [Actions.getSuccessor(pacmanPosition, action) for action in legal] distanceToClosestCostAfterAllActions = \ [self.distancer.getDistance(newPacPost, gohstPosition[closestGhostIndex])\ for newPacPost in allPacPotentialPos] return legal[distanceToClosestCostAfterAllActions.index(min(distanceToClosestCostAfterAllActions))]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacman = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions() if a != Directions.STOP] ghosts = gameState.getLivingGhosts() distributions = [b for i, b in enumerate(self.ghostBeliefs) if ghosts[i + 1]] successor = [(Actions.getSuccessor(pacman, a), a) for a in legal] positions = [max(d.items(), key=lambda x:x[1])[0] for d in distributions] distances = [(self.distancer.getDistance(pacman, d), d) for d in positions] choice = min(distances)[1] # min distance between current and any ghost actions = [(self.distancer.getDistance(choice, s[0]), s[1]) for s in successor] action = min(actions)[1] # the action that gets us closer to the close ghost return action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) To get a list of booleans, one for each agent, indicating whether or not the agent is alive, use gameState.getLivingGhosts() Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). You may remove Directions.STOP from the list of available actions. """ mostLikelyGhostPositions = util.Counter(); for i in range(0,len(gameState.getLivingGhosts())): if (gameState.getLivingGhosts()[i]): mostLikelyGhostPositions[i] = self.inferenceModules[i-1].getBeliefDistribution().argMax() minDist = 100000000 minIndex = 1 pacmanPosition = gameState.getPacmanPosition() for ghostIndex in mostLikelyGhostPositions: dist = self.distancer.getDistance(pacmanPosition,mostLikelyGhostPositions[ghostIndex]) if (min(dist,minDist) != minDist): minDist = min(dist,minDist); minIndex = ghostIndex; legal = [a for a in gameState.getLegalPacmanActions() if a != Directions.STOP] legalMoves = util.Counter(); minGhostPos = mostLikelyGhostPositions[minIndex] for action in legal: legalMoves[action] = -1*self.distancer.getDistance(minGhostPos,Actions.getSuccessor(pacmanPosition,action)) return legalMoves.argMax()
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] # Get the position of the most likely ghost max_prob_pos = [] for ghost_dist in livingGhostPositionDistributions: best_pos = max(ghost_dist, key = ghost_dist.get) max_prob_pos.append((best_pos,ghost_dist[best_pos])) best_pos = max(max_prob_pos, key=lambda x : x[1])[0] # Find the best move best_dist = float("inf") best_move = None for move in legal: dist = self.distancer.getDistance(best_pos, Actions.getSuccessor(pacmanPosition, move)) if dist < best_dist or not best_move: best_move = move best_dist = dist return best_move
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. You may remove Directions.STOP from the list of available actions. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions() if a != Directions.STOP] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" minDist = 99999999 action = 'Stop' for la in legal: if la == 'North': newPacPos = (pacmanPosition[0],pacmanPosition[1]+1) elif la == 'South': newPacPos = (pacmanPosition[0],pacmanPosition[1]-1) elif la == 'West': newPacPos = (pacmanPosition[0]-1,pacmanPosition[1]) elif la == 'East': newPacPos = (pacmanPosition[0]+1,pacmanPosition[1]) else: print "TESTE" for i in range(0,len(livingGhostPositionDistributions)): ghostPos = livingGhostPositionDistributions[i].argMax() minDist, action = min((minDist,action), (self.distancer.getDistance(newPacPos,ghostPos),la)) return action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" #initialize them to worst value possible closestDis, minMazeDis = float('inf'), float('inf') closestPos = None theAction = None #find the closest ghost for oneSetDistri in livingGhostPositionDistributions: biggestDistriPos = oneSetDistri.argMax() mazeDis = self.distancer.getDistance(pacmanPosition, biggestDistriPos) if (closestDis > mazeDis): closestDis = mazeDis closestPos = biggestDistriPos #greedy approach: always seek for action with closest distance to get to the ghost for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) mazeDis = self.distancer.getDistance(successorPosition, closestPos) if (minMazeDis > mazeDis): minMazeDis = mazeDis theAction = action return theAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" m_dist = lambda pos1, pos2 : self.distancer.getDistance(pos1, pos2) closest = None # closest ghost position best_action = None # best action position for distrib in livingGhostPositionDistributions: mostLikelyPos = max(distrib.items(), \ key=lambda item : item[1])[0] dist = m_dist(pacmanPosition, mostLikelyPos) if closest == None or dist < closest[1]: closest = (mostLikelyPos, dist) for action in legal: succ_pos = Actions.getSuccessor(pacmanPosition, action) dist = m_dist(succ_pos, closest[0]) if best_action == None or dist < best_action[2]: best_action = (action, succ_pos, dist) return best_action[0]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" bestaction = Directions.STOP bestdistance = None for idx, action in enumerate(legal): nextpos = Actions.getSuccessor(pacmanPosition, action) for idx, dist in enumerate(livingGhostPositionDistributions): items = dist.items() ghostpos = sorted(items, cmp=lambda a,b: cmp(b[1], a[1]))[0][0] dist = self.distancer.getDistance(nextpos, ghostpos) if ((bestdistance == None) or (dist < bestdistance)): bestdistance = dist bestaction = action return bestaction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" localMax = [] for belief in livingGhostPositionDistributions: localMax.append(belief.argMax()) goalCoordinate, goalProbability = None, 0 for index, coordinate in enumerate(localMax): if livingGhostPositionDistributions[index][coordinate] >= goalProbability: goalCoordinate, goalProbability = coordinate, livingGhostPositionDistributions[index][coordinate] tempActions = [] for action in legal: nextLocation = Actions.getSuccessor(pacmanPosition, action) tempActions.append((self.distancer.getDistance(nextLocation, goalCoordinate), action)) return min(tempActions)[1]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" mostLikely = util.Counter() for beliefs in livingGhostPositionDistributions: likelyPos = beliefs.argMax() mostLikely[likelyPos] = beliefs[likelyPos] minDist = float('inf') closest = None for key in mostLikely: curDist = self.distancer.getDistance(pacmanPosition,key) if curDist < minDist: minDist = curDist closest = key ghostPos = closest minDist = self.distancer.getDistance(closest,pacmanPosition) bestMove = None for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) dist = self.distancer.getDistance(ghostPos,successorPosition) if dist < minDist: bestMove = action minDist = dist return bestMove
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] distance = float('inf') for ghost in livingGhostPositionDistributions: highest_prob = -1 for key in ghost: if ghost[key] > highest_prob: highest_prob = ghost[key] ghost_loc = key new_dist = self.distancer.getDistance(pacmanPosition, ghost_loc) if new_dist < distance: distance = new_dist closest = ghost_loc distance = float('inf') successors = [] for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) new_dist = self.distancer.getDistance(successorPosition, closest) if new_dist < distance: best_action = action distance = new_dist return best_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] # print legal livingGhosts = gameState.getLivingGhosts() # noisyDistances = gameState.getNoisyGhostDistances() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] for inf_mod in self.inferenceModules: inf_mod.elapseTime(gameState) dist = util.Counter() for belief in livingGhostPositionDistributions: for p, val in belief.items(): dist[p] += val max_prob = max(dist.items(), key = lambda x: x[1])[0] states = [(a, Actions.getSuccessor(pacmanPosition, a)) for a in legal] actions = [(a, self.distancer.getDistance(state, max_prob)) for a, state in states] return min(actions, key = lambda x: x[1])[0]
class GreedyBustersAgent(BustersAgent): """An agent that charges the closest ghost.""" def registerInitialState(self, gameState): """Pre-computes the distance between every two points.""" BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() actions = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" if len(actions) == 1: best_action = actions[0] else: n_ghosts = len(livingGhostPositionDistributions) positions = livingGhostPositionDistributions[0].iterkeys() positionDistributions = {p: max(livingGhostPositionDistributions[i][p] for i in xrange(n_ghosts)) for p in positions} target = max(positionDistributions.iterkeys(), key=positionDistributions.get) def d(action): next_position = Actions.getSuccessor(pacmanPosition, action) return self.distancer.getDistance(next_position, target) best_action = min(actions, key=d) return best_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [ beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i + 1] ] "*** YOUR CODE HERE ***" minDistance = float("inf") for i in range(len(livingGhostPositionDistributions)): ghostPosition = livingGhostPositionDistributions[i].argMax() ghostDistance = self.distancer.getDistance(pacmanPosition, ghostPosition) if minDistance > ghostDistance: minDistance = ghostDistance closestPosition = ghostPosition minDistance = float("inf") for a in legal: successorPosition = Actions.getSuccessor(pacmanPosition, a) ghostDistance = self.distancer.getDistance(closestPosition, successorPosition) if minDistance > ghostDistance: minDistance = ghostDistance action = a return action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] #find closest position minDistance = None for dist in livingGhostPositionDistributions: mostLikelyPosition = dist.argMax() distance = self.distancer.getDistance(pacmanPosition, mostLikelyPosition) if not minDistance or distance < minDistance: minDistance = distance closestPosition = mostLikelyPosition #find best action minDistance = None for action in legal: newPos = Actions.getSuccessor(pacmanPosition, action) distanceAfterAction = self.distancer.getDistance(newPos, closestPosition) if not minDistance or distanceAfterAction < minDistance: minDistance = distanceAfterAction bestAction = action return bestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closest to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" distance = float("inf") ghost_position = None for dist in livingGhostPositionDistributions: temp_pos = dist.argMax() temp_distance = self.distancer.getDistance(pacmanPosition, temp_pos) if temp_distance < distance: distance = temp_distance ghost_position = temp_pos dist = float("inf") action = None for a in legal: succ_pos = Actions.getSuccessor(pacmanPosition, a) temp = self.distancer.getDistance(succ_pos, ghost_position) if temp < dist: dist = temp action = a return action
def observe(self, gameState, selfIndex, agentIndex): noisyAgentDistance = gameState.getAgentDistances()[agentIndex] distribution = Counter() pacmanPosition = gameState.getAgentState(selfIndex).getPosition() distancer = Distancer(gameState.data.layout) for x in xrange(gameState.data.layout.width): for y in xrange(gameState.data.layout.height): if not gameState.hasWall(x, y): position = (x, y) trueDistance = distancer.getDistance(position, pacmanPosition) distribution[position] = gameState.getDistanceProb(trueDistance, noisyAgentDistance) * self.distributions[agentIndex][position] distribution.normalize() self.distributions[agentIndex] = distribution
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" #Get the best distance to each ghost best_positions = [] distances = [] for ghost_distribution in livingGhostPositionDistributions: best_position = ghost_distribution.argMax() distances.append(self.distancer.getDistance(pacmanPosition,best_position)) best_positions.append(best_position) idx = distances.index(min(distances)) target = best_positions.pop(idx) actions = [] distances = [] for action in legal: new_position = Actions.getSuccessor(pacmanPosition,action) distances.append(self.distancer.getDistance(new_position,target)) actions.append(action) idx = distances.index(min(distances)) best_action = actions.pop(idx) return best_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closest to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] ghosts = [pos.argMax() for pos in livingGhostPositionDistributions] # djikstra's algorithm that i created, myself, and not djikstra toReturn = None for ghost in ghosts: distance = self.distancer.getDistance(pacmanPosition, ghost) for action in legal: new_dist = self.distancer.getDistance(Actions.getSuccessor(pacmanPosition, action), ghost) # if this is the minimum distance for the ghost's new position, choose the # action that will get pacman closer to the ghost if new_dist < distance: distance = new_dist toReturn = action return toReturn
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" likelyGhostPos = [] for dist in livingGhostPositionDistributions: mostLikelyPos = dist.argMax() likelyGhostPos += [mostLikelyPos] closestGhost = likelyGhostPos[0] for pos in likelyGhostPos[1:]: if self.distancer.getDistance(pacmanPosition, pos) < self.distancer.getDistance(pacmanPosition, closestGhost): closestGhost = pos minDistance = self.distancer.getDistance(Actions.getSuccessor(pacmanPosition, legal[0]), closestGhost) retAction = legal[0] for action in legal[1:]: if self.distancer.getDistance(Actions.getSuccessor(pacmanPosition, action), closestGhost) < minDistance: minDistance = self.distancer.getDistance(Actions.getSuccessor(pacmanPosition, action), closestGhost) retAction = action return retAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [ beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i + 1] ] "*** YOUR CODE HERE ***" closest_ghost = [] # find the closest ghost position that has not been captured yet for dist in livingGhostPositionDistributions: # find the most likely position, which is the position where the distribution is the highest ghost_pos = sorted(dist, key=dist.get, reverse=True) maze_dist = self.distancer.getDistance(ghost_pos[0], pacmanPosition) closest_ghost.append((ghost_pos[0], maze_dist)) # sort based on the maze distance in ascending order to have the closest ghost at index 0. closest_ghost = sorted(closest_ghost, key=lambda x: x[1]) # find the least maze distance action of the closest ghost found actions = [] for action in legal: maze_dist = self.distancer.getDistance( closest_ghost[0][0], Actions.getSuccessor(pacmanPosition, action)) actions.append((action, maze_dist)) actions = sorted(actions, key=lambda x: x[1]) # returns the action that has the least maze distance return actions[0][0]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ #Fetch Pacman Position pacmanPosition = gameState.getPacmanPosition() #Fetch Legal Postions legalPositions = [a for a in gameState.getLegalPacmanActions()] #Take all ghost postions, to find out the closest ghost ghosts = gameState.getLivingGhosts() #Get ghost distribution for all livin ghosts index = 0 ghostPositionDistributions = [] for beliefs in self.ghostBeliefs: if ghosts[index + 1]: ghostPositionDistributions.append(beliefs) index += 1 favBeliefs = [] #find coordinates where ghost has max probability for belief in ghostPositionDistributions: maxBelief = 0 maxCoordinate = 0 for coor in belief: if belief[coor] > maxBelief: maxBelief = belief[coor] maxCoordinate = coor favBeliefs.append(maxCoordinate) ghostPossiblePosition = None ghostPossibleProbability = 0 nextPossibbleSteps = [] #Find the coordiante with the highest pribability of having a ghost index = 0 for coordinate in favBeliefs: if (ghostPositionDistributions[index][coordinate] >= ghostPossibleProbability): ghostPossibleProbability = ghostPositionDistributions[index][ coordinate] ghostPossiblePosition = coordinate index += 1 #Find the next legal positions closest to ghost coordinate for action in legalPositions: nextStep = Actions.getSuccessor(pacmanPosition, action) distanceBtwGhostAndNextPosition = self.distancer.getDistance( nextStep, ghostPossiblePosition) nextPossibbleSteps.append( (distanceBtwGhostAndNextPosition, action)) #return the next step closestNextStep = min(nextPossibbleSteps) return closestNextStep[1] #(distance, NextMove)
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" localMaximum = [] for beliefs in livingGhostPositionDistributions: localMaximum.append(beliefs.argMax()) # print localMaximum goalCoordinate = None # Initialize Goal Co-ordinates and Probability goalProbability = 0 for i, position in enumerate(localMaximum): if livingGhostPositionDistributions[i][position] >= goalProbability: # If existing goalProbability is less than a new Ghost's probability, then overwrite the probability goalCoordinate = position # and assign the co-ordinates of the new ghost as the nearest one goalProbability = livingGhostPositionDistributions[i][position] Minimum = [] # Variable to store the list of Actions for action in legal: nextPosition = Actions.getSuccessor(pacmanPosition, action) # Possible successor with current action # print nextPosition Minimum.append((self.distancer.getDistance(nextPosition, goalCoordinate), action)) # Append the distance and action performed # print min(Minimum) return min(Minimum)[1] # Return only the list of actions for the shortest path
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" MAX_DIST = float("inf") MIN_PROB = - float("inf") closestPos = [] for gDistance in livingGhostPositionDistributions: bestP = MIN_PROB for pos in gDistance: if gDistance[pos] > bestP: bestP = gDistance[pos] bestPos = pos closestPos.append(bestPos) closestDis = MAX_DIST for pos in closestPos: state = gameState.getPacmanPosition() currDis = self.distancer.getDistance(pos, state) if currDis < closestDis: closestDis = currDis closestPos = pos closestDis = MAX_DIST for action in legal: state = gameState.getPacmanPosition() successor = Actions.getSuccessor(state, action) dis = self.distancer.getDistance(successor, closestPos) if dis < closestDis: closestDis = dis bestA = action return bestA
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [ beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i + 1] ] "*** YOUR CODE HERE ***" livingGhostBeliefPositions = [] for livingGhostPositionDistribution in livingGhostPositionDistributions: maxProb = 0.0 mostLikelyPosition = None for position in livingGhostPositionDistribution.keys(): if livingGhostPositionDistribution[position] > maxProb: mostLikelyPosition = position maxProb = livingGhostPositionDistribution[position] livingGhostBeliefPositions.append(mostLikelyPosition) bestAction = None minDist = float("inf") for action in legal: nextPacmanPosition = Actions.getSuccessor(pacmanPosition, action) minDistByAction = min([ self.distancer.getDistance(nextPacmanPosition, ghostPosition) for ghostPosition in livingGhostBeliefPositions ]) if minDistByAction < minDist: bestAction = action minDist = minDistByAction return bestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] # livingGhostPositionDistributions[i] = singleGhostbelief # singlebelief[pos] = p "*** YOUR CODE HERE ***" # find out the nearest ghost minGhostDist,minGhostPos = float('inf'), None for belief in livingGhostPositionDistributions: mostLikelyPos = belief.argMax() dist = self.distancer.getDistance(pacmanPosition, mostLikelyPos) if dist < minGhostDist: minGhostDist = dist minGhostPos = mostLikelyPos #choose the actions leading to the closest dist minDist,minActions = float('inf'), [] for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) dist = self.distancer.getDistance(minGhostPos, successorPosition) if dist< minDist: minDist = dist minActions = [action] elif dist == minDist: minAction.append(action) return random.choice(minAction)
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" # Take a new list to store predicted ghost positions predictedGhostPositions = list() # Iterate over each ghost for ghostPositionDist in livingGhostPositionDistributions: # Initialize the max_probabiity with the minimum probability of 0 maxProbability = 0 # Iterate over all possible ghost positions and get the position for which the # probabilty is the maximum for position in ghostPositionDist.keys(): if ghostPositionDist[position] > maxProbability: maxProbability = ghostPositionDist[position] calculatedPos = position predictedGhostPositions.append(calculatedPos) # Here we will calculate the minimum distance among all the predicted ghost positions # from pacman's current position. minDistance = float("inf") for ghostPosition in predictedGhostPositions: if minDistance > self.distancer.getDistance(pacmanPosition, ghostPosition): minDistance = self.distancer.getDistance(pacmanPosition, ghostPosition) closestGhost = ghostPosition # We will choose a move which will bring pacman closer to the ghost in order to eat it final_action = None costOfbestAction = float("inf") for action in legal: succ = Actions.getSuccessor(pacmanPosition, action) dist = self.distancer.getDistance(succ, closestGhost) if (dist < self.distancer.getDistance(pacmanPosition, closestGhost)) and dist < costOfbestAction: costOfbestAction = dist final_action = action return final_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" maxPos = tuple() maxBelief = -99999 #Iterate through all position, acquire position with highest belief for pos in livingGhostPositionDistributions[0].keys(): curBelief = livingGhostPositionDistributions[0][pos] if curBelief > maxBelief: maxBelief = curBelief maxPos = pos #Current Distance to goal curDist = self.distancer.getDistance(pacmanPosition, maxPos) rightAction = None #Iterate through all actions, pick action that minimizes distance for action in legal: successor = Actions.getSuccessor(pacmanPosition, action) newDist = self.distancer.getDistance(successor, maxPos) if newDist < curDist: rightAction = action return rightAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" # Find the position of the closest ghost minDistance = None closestGhostPosition = None for LGPD in livingGhostPositionDistributions: #LGPD = livingGhostPositionDistributions[i] MLPosition = LGPD.argMax() currentDistance = self.distancer.getDistance(pacmanPosition, MLPosition) if minDistance is None or currentDistance < minDistance: minDistance = currentDistance closestGhostPosition = MLPosition # Find the action that minimizes the distance to the closest ghost minDistance = None bestAction = None for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) distance = self.distancer.getDistance(successorPosition, closestGhostPosition) if minDistance is None or distance < minDistance: minDistance = distance bestAction = action return bestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] coord_goal = None prob_goal = 0 all_ghosts = [] distance_list = [] for pos in livingGhostPositionDistributions: all_ghosts.append(pos.argMax()) for p in enumerate(all_ghosts): positionDistribution = livingGhostPositionDistributions[p[0]][p[1]] if positionDistribution < prob_goal: continue else: prob_goal = positionDistribution coord_goal = p[1] for a in legal: successor = Actions.getSuccessor(pacmanPosition, a) distance = self.distancer.getDistance(successor, coord_goal) d = [distance, a] distance_list.append(d) minimum = min(distance_list) return minimum[1]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] # initialize a list minGhostPos = [] # append arg max to the list initiated from the ghost position distribution for ghost in livingGhostPositionDistributions: minGhostPos.append(ghost.argMax()) minGhostDist = float("inf") currentPos = pacmanPosition for position in minGhostPos: # use the mazeDistance as instructed in the comments tempDist = self.distancer.getDistance(pacmanPosition, position) # the min of the distance between pacman position and ghost distance we have from above minGhostPos = min(tempDist, minGhostDist) currentPos = position # initialize an Null action bestAction = None # initialize a min as positive infinity to compare the new dist using self.distancer minDist = float("inf") for actions in legal: newDist = self.distancer.getDistance( Actions.getSuccessor(pacmanPosition, actions), currentPos) # if the minDist we initiated before is less than the new distance calculated #then swap the values and set best action as the respective action from iteration if newDist < minDist: minDist = min(newDist, minDist) bestAction = actions #return the best action return bestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" mostLikeLyGhostPositions = [] for index in range(len(livingGhostPositionDistributions)): highestProb, mostProbPosition = 0, None for position, prob in livingGhostPositionDistributions[index].items(): if prob > highestProb: highestProb, mostProbPosition = prob, position mostLikeLyGhostPositions.append((mostProbPosition, self.distancer.getDistance(mostProbPosition, pacmanPosition))) leastDistance = float('inf') closestPosition = None for ghostPosition, distance in mostLikeLyGhostPositions: if distance < leastDistance: leastDistance = distance closestPosition = ghostPosition bestNewDistance = float('inf') bestAction = [] for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) newDistance = self.distancer.getDistance(closestPosition, successorPosition) if newDistance < bestNewDistance: bestNewDistance = newDistance bestAction = [action] elif newDistance == bestNewDistance: bestAction.append(action) return random.choice(bestAction)
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" import random curr_living_ghost = [] for d in livingGhostPositionDistributions: max_dis = -1000000 max_distribution = None for distance in d: if d[distance] > max_dis: max_dis = d[distance] max_distribution = distance if max_dis >= 0: curr_living_ghost.append(max_distribution) living_ghost_distance = [] for ghost in curr_living_ghost: living_ghost_distance.append( (ghost, self.distancer.getDistance(pacmanPosition, ghost))) min_distance = 1000000 min_position = None for item in living_ghost_distance: if item[1] < min_distance: min_position = item[0] movement = [] min_dis = 10000000 for action in legal: movement.append((action, self.distancer.getDistance( Actions.getSuccessor(pacmanPosition, action), min_position))) for item in movement: if item[1] < min_dis: min_distance = item[1] min_dis = min_distance actions = [] for action in movement: if action[1] == min_distance: actions.append(action[0]) return random.choice(actions)
class BasicAgentAA(BustersAgent): def registerInitialState(self, gameState): BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) self.countActions = 0 ''' Example of counting something''' def countFood(self, gameState): food = 0 for width in gameState.data.food: for height in width: if (height == True): food = food + 1 return food ''' Print the layout''' def printGrid(self, gameState): table = "" #print(gameState.data.layout) ## Print by terminal for x in range(gameState.data.layout.width): for y in range(gameState.data.layout.height): food, walls = gameState.data.food, gameState.data.layout.walls table = table + gameState.data._foodWallStr( food[x][y], walls[x][y]) + "," table = table[:-1] return table def printInfo(self, gameState): print "---------------- TICK ", self.countActions, " --------------------------" # Dimensiones del mapa width, height = gameState.data.layout.width, gameState.data.layout.height print "Width: ", width, " Height: ", height # Posicion del Pacman print "Pacman position: ", gameState.getPacmanPosition() # Acciones legales de pacman en la posicion actual print "Legal actions: ", gameState.getLegalPacmanActions() # Direccion de pacman print "Pacman direction: ", gameState.data.agentStates[0].getDirection( ) # Numero de fantasmas print "Number of ghosts: ", gameState.getNumAgents() - 1 # Fantasmas que estan vivos (el indice 0 del array que se devuelve corresponde a pacman y siempre es false) print "Living ghosts: ", gameState.getLivingGhosts() # Posicion de los fantasmas print "Ghosts positions: ", gameState.getGhostPositions() # Direciones de los fantasmas print "Ghosts directions: ", [ gameState.getGhostDirections().get(i) for i in range(0, gameState.getNumAgents() - 1) ] # Distancia de manhattan a los fantasmas print "Ghosts distances: ", gameState.data.ghostDistances # Puntos de comida restantes print "Pac dots: ", gameState.getNumFood() # Distancia de manhattan a la comida mas cercada print "Distance nearest pac dots: ", gameState.getDistanceNearestFood() # Paredes del mapa print "Map: \n", gameState.getWalls() # Puntuacion print "Score: ", gameState.getScore() def getDistance_with_wall(self, pos1, pos2): """ The getDistance function is the only one you'll need after you create the object. """ if self._distances == None: return manhattanDistance(pos1, pos2) if isInt(pos1) and isInt(pos2): return self.getDistanceOnGrid(pos1, pos2) pos1Grids = getGrids2D(pos1) pos2Grids = getGrids2D(pos2) bestDistance = self.default for pos1Snap, snap1Distance in pos1Grids: for pos2Snap, snap2Distance in pos2Grids: gridDistance = self.getDistanceOnGrid(pos1Snap, pos2Snap) distance = gridDistance + snap1Distance + snap2Distance if bestDistance > distance: bestDistance = distance return bestDistance def calculateDistribution(self, state): # Read variables from state numghosts = state.getNumAgents() - 1 legalActions = state.getLegalActions(0) # No tiene sentido que incluyamos Stop, buscamos que termine lo antes posible legalActions.remove("Stop") pos = state.getPacmanPosition() #posicion pacman ghosts_pos = state.getGhostPositions() #posicion fantasmas bestGhostAction = [ None ] * numghosts #mejor accion para cada uno de los ghosts distancesToGhosts = [ 999999999 ] * numghosts #distancia del pacman a cada uno de los ghosts #Encuentra la mejor accion del Pacman para cada fantasma for i in range(0, numghosts): mini = 9999999999 if (state.getLivingGhosts()[i + 1]): aux = 0 if 'North' in legalActions: aux = self.distancer.getDistance((pos[0], pos[1] + 1), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'North' distancesToGhosts[i] = aux mini = aux if 'East' in legalActions: aux = self.distancer.getDistance((pos[0] + 1, pos[1]), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'East' distancesToGhosts[i] = aux mini = aux if 'West' in legalActions: aux = self.distancer.getDistance((pos[0] - 1, pos[1]), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'West' distancesToGhosts[i] = aux mini = aux if 'South' in legalActions: aux = self.distancer.getDistance((pos[0], pos[1] - 1), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'South' distancesToGhosts[i] = aux mini = aux bestScore = min( distancesToGhosts) #distancia al fantasma o comida mas cercano bestAction = [] #mejor accion #Elige la mejor entre la mejor accion para cada fantasma/comida for action, distance in zip(bestGhostAction, distancesToGhosts): if distance == bestScore: if action != None: bestAction = [action] return bestAction[0] def chooseAction(self, gameState): action, bestGhostAction, distancesToGhosts = self.bestActions( gameState) #------------------------------FASE 4--------------------------------------------------# direc, score, output = self.printLineData(gameState) l = output.split(",") l.append(str(score)) x = [] #Seleccionar los atributos que usamos para cada instancia (no incluir la clase) for i in range(0, len(l)): if ((i >= 2 and i <= 9) or (i >= 18 and i <= 29)): x.append((l[i])) a = self.weka.predict("j48_tutorial1.model", x, "fase4.arff") if (a not in gameState.getLegalActions()): a = random.choice(gameState.getLegalActions()) #----------------------------------------------------------------------------------------# return a
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ print "Start" pacmanPosition = gameState.getPacmanPosition() print "PacmanPosition = ",pacmanPosition legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = self.ghostBeliefs likelyPositions = [] for i in range(1,len(livingGhosts)): if (livingGhosts[i] == True): # get max value key in livingGhostPositionDistributions[i-1] ghostPositionDistribution = livingGhostPositionDistributions[i-1] likelyPosition = ghostPositionDistribution.argMax() likelyPositions.append(likelyPosition) print "likely Positions List:",likelyPositions distances = util.Counter() for i in likelyPositions: distances[i] = self.distancer.getDistance(pacmanPosition,i) print "Target distances = ",distances sortedTargets = distances.sortedKeys() target = sortedTargets[len(sortedTargets)-1] print "target is,",target preferredAction = util.Counter() for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) preferredAction[action] = self.distancer.getDistance(successorPosition,target) sortedActions = preferredAction.sortedKeys(); print "returned Action = ",sortedActions[0],"\n" "*** YOUR CODE HERE ***" return sortedActions[len(sortedActions)-1]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] # Get our most likely positions most_likely_position = [] [ most_likely_position.append(max(distance, key=distance.get)) for distance in livingGhostPositionDistributions ] # Get our minimum distance / position our_distances = util.Counter() for position in most_likely_position: our_distances[position] = self.distancer.getDistance( pacmanPosition, position) shortest_position = min(our_distances, key=our_distances.get) # Use our minimum distance to find the best_action so far our_actions = util.Counter() for legal_action in legal: successor_position = Actions.getSuccessor(pacmanPosition, legal_action) our_actions[legal_action] = self.distancer.getDistance( successor_position, shortest_position) best_action_for = min(our_actions, key=our_actions.get) # Return our best action return best_action_for
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() act = {} livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" ghost_pos = [] for item in livingGhostPositionDistributions: tmp = max(item.keys(), key=(lambda k: item[k])) ghost_pos.append(tmp) for i in ghost_pos: act[i] = self.distancer.getDistance(i, pacmanPosition) act = min(act.keys(), key=(lambda k: act[k])) tmp_act = {} for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) succesorDistance = self.distancer.getDistance( successorPosition, act) tmp_act[action] = succesorDistance opt_action = min(tmp_act.keys(), key=(lambda k: tmp_act[k])) return opt_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" maxValue = 0.0 closestGhost = (0, 0) for key, value in livingGhostPositionDistributions[0].items( ): #Looping over livingGhostPositionDistribution and finding that position which if maxValue < value: # has highest probability. That ghost will be the nearest ghost maxValue = value closestGhost = key minDist = 10000 minLegal = legal[0] for legal_move in legal: #Looping over all legal moves for pacman successorPosition = Actions.getSuccessor( pacmanPosition, legal_move ) #Finding the successor position for the chosen pacman move mazeDistance = self.distancer.getDistance( successorPosition, closestGhost ) #Finding the distance between closestGhost and the successor position if minDist > mazeDistance: #The action which gives minimun distance to closestGhost is chosen to be next move minDist = mazeDistance minLegal = legal_move return minLegal
def getFeatures(self, gameState, action): distancer = Distancer(gameState.data.layout) distancer.getMazeDistances() #if have more food, make it more urgent to get back #move away from the ghosts #if on the defense side from getting set back, sort of act like a defender but don't make sacrifices features = util.Counter() successor = self.getSuccessor(gameState, action) foodList = self.getFood(successor).asList() features['foodLeft'] = len(foodList)#self.getScore(successor) #Run away from ghosts when on other side enemyIndices = self.getOpponents(successor) enemyPositions = [successor.getAgentPosition(index) for index in enemyIndices if not successor.getAgentState(index).isPacman] #only adds ghosts to the tally enemyDistances = [] for pos in enemyPositions: enemyDistances.append(distancer.getDistance(successor.getAgentPosition(self.index), pos)) ghostClose = 10 if len(enemyDistances) > 0 and min(enemyDistances) < 3 and successor.getAgentState(self.index).isPacman: #only cares about ghosts if its a pacman and the distance is less than three ghostClose = min(enemyDistances) features['ghostClose'] = ghostClose numEat = gameState.getAgentState(self.index).numCarrying #now, find out if the next move is moving closer to home nextMoveCloser = 0 currentX, currentY = gameState.getAgentPosition(self.index) succX, succY = successor.getAgentPosition(self.index) #if the next move is closer and numEat > 5, then homeUrgent is 1 and weight it ######SAM STUFF targetX = gameState.data.layout.width // 2 if gameState.isOnRedTeam(self.index): targetX = targetX - 1 targetPositions = [(targetX, y) for y in range(0, gameState.data.layout.height)] distancer = Distancer(gameState.data.layout) distancer.getMazeDistances() targetDistances = [] for position in targetPositions: try: targetDistances.append(distancer.getDistance(position, successor.getAgentPosition(self.index))) except: doNothing = 0 ############## minDist = min(targetDistances) features['homeUrgent'] = 30 if numEat > 0: features['homeUrgent'] = minDist enemies = [successor.getAgentState(i) for i in self.getOpponents(successor)] invaders = [a for a in enemies if a.isPacman and a.getPosition() != None] features['numInvaders'] = len(invaders) targetX = gameState.data.layout.width // 2 if not gameState.isOnRedTeam(self.index): targetX = targetX - 1 targetPositions = [(targetX, y) for y in range(0, gameState.data.layout.height)] distancer = Distancer(gameState.data.layout) distancer.getMazeDistances() targetsFarEnoughAway = [] for position in targetPositions: try: minDistance = min([distancer.getDistance(position, enemy.getPosition()) for enemy in enemies]) if minDistance > 7: #changed from 7 to 10 targetsFarEnoughAway.append(position) except: doNothing = 0 myPos = successor.getAgentState(self.index).getPosition() distanceToClosestGhost = min([distancer.getDistance(myPos, enemy.getPosition()) for enemy in enemies]) distanceToTPs = [distancer.getDistance(myPos, position) for position in targetsFarEnoughAway] if(gameState.getAgentState(self.index).isPacman): features['distanceToTargetCrossings'] = 0 features['ghostClose'] = 0 if distanceToClosestGhost > 4 else distanceToClosestGhost else: features['ghostClose'] = 0 features['distanceToTargetCrossings'] = min(distanceToTPs) if len(distanceToTPs) > 0 else 0 #numeats is bigger than 5 and the next move is closer to home, then set homeUrgent to positive #if numeats > 5 and next move is farther from home, set homeUrgent to negative #otherwise set homeUrgent to 0 # Compute distance to the nearest food if len(foodList) > 0: # This should always be True, but better safe than sorry myPos = successor.getAgentState(self.index).getPosition() minDistance = min([self.getMazeDistance(myPos, food) for food in foodList]) # if not successor.getAgentState(self.index).isPacman: #this basically means we only look for food if we're on the other side # minDistance = 100 features['distanceToFood'] = minDistance return features
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" if len(livingGhostPositionDistributions) == 0: return legal[0] # print livingGhostPositionDistributions import operator maxLikelyGhostPositions = [ max(ghost_dist.iteritems(), key=operator.itemgetter(1))[0] for ghost_dist in livingGhostPositionDistributions ] dist2allGhosts = [ self.distancer.getDistance(pos, pacmanPosition) for pos in maxLikelyGhostPositions ] # print maxLikelyGhostPositions , dist2allGhosts , min(dist2allGhosts) i, v = min(enumerate(dist2allGhosts), key=operator.itemgetter(1)) posClosestGhost = maxLikelyGhostPositions[i] # print posClosestGhost , legal dist_according_actions = [ self.distancer.getDistance( posClosestGhost, Actions.getSuccessor(pacmanPosition, action)) for action in legal ] i, v = min(enumerate(dist_according_actions), key=operator.itemgetter(1)) return legal[i]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" closestGhost = {} bestAction = {} for posDist in livingGhostPositionDistributions: # check for most probable location for ghost and set that as temp position and get # the temp manhattan distance between ghost and pacman relMaxPos = posDist.argMax() relDistance = self.distancer.getDistance(relMaxPos, pacmanPosition) if bool(closestGhost): # if out closest ghost is not empty if closestGhost["dist"] > relDistance: # if we found a closer ghost, set it as the closest ghost closestGhost["pos"] = relMaxPos closestGhost["dist"] = relDistance else: # if we are on our first ghost, default it as the closest closestGhost["pos"] = relMaxPos closestGhost["dist"] = relDistance for action in legal: successorPosition = Actions.getSuccessor( pacmanPosition, action) # find the distance between our potential successor position and our closest ghost newDistance = self.distancer.getDistance( successorPosition, closestGhost["pos"]) if bool(bestAction): # if best action isnt empty if (bestAction["dist"] > newDistance): # if we found a better action, set it as the best action bestAction["action"] = action bestAction["dist"] = newDistance else: # if we are on our first action, default it as the best bestAction["action"] = action bestAction["dist"] = newDistance return bestAction["action"]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition( ) # Posição atual do Pacman legal = [a for a in gameState.getLegalPacmanActions() ] # Ações possíveis do Pacman em sua posição atual livingGhosts = gameState.getLivingGhosts( ) # Cada posição da lista refere-se a um fantasma. Determina se o fantasma está vivo ou morto livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] i = 0 ghostsPositions = [] dists = [] # Armazena as posições mais prováveis de cada fantasma estar for ghost in livingGhosts: # Verifica se o fantasma está vivo if ghost == True: prob = 0 pos = (-1, -1) for pos_a, prob_a in livingGhostPositionDistributions[i].items( ): # Procura a posição mais provável de o fantasma estar if prob_a > prob: prob = prob_a pos = pos_a ghostsPositions.append( pos ) # Armazena a posição mais provável de o fantasma estar i += 1 # Recebe a posição mais próxima do Pacman (pos_clo) que provavelmente tem um fantasma dist_min = 10000000 # Menor distância entre o Pacman e a posição mais provável de um fantasma pos_clo = ( -1, -1 ) # Posição mais próxima do Pacman dentre as mais prováveis de ter um fantasma for p in ghostsPositions: d = self.distancer.getDistance(pacmanPosition, p) if d < dist_min: dist_min = d pos_clo = p # Verifica qual ação que mais aproxima o Pacman da posição mais próxima que provavelmente tem um fantasma a = "" for action in legal: successorPosition = Actions.getSuccessor( pacmanPosition, action) # Recebe uma ação do Pacman d = self.distancer.getDistance( pos_clo, successorPosition ) # Recebe a distância entre a posição onde o Pacman estará após essa ação e onde o fantasma mais próximo provavelmente está if d < dist_min: a = action return a
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" mostLikelyGP = util.Counter() closestpos = None closestdist = 999999 #loop to find the closest ghost for ghostDistrib in livingGhostPositionDistributions: maxprob = 0 maxpos = None #loop and find the most likely location for the ghost for pos, prob in ghostDistrib.items(): if prob > maxprob: maxprob = prob maxpos = pos tempdist = self.distancer.getDistance(pacmanPosition, maxpos) if tempdist < closestdist: closestpos = maxpos closestdist = tempdist #closest(ghost)pos has been found, now find best action to get closest to it closestaction = None closestchasedist = 99999 #loop through actions and see which takes us closest to the ghost for legalaction in legal: successorPosition = Actions.getSuccessor(pacmanPosition, legalaction) tempdist = self.distancer.getDistance(closestpos, successorPosition) if closestchasedist > tempdist: closestaction = legalaction closestchasedist = tempdist return closestaction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" #util.raiseNotDefined() localMaxGhost = [] for beliefs in livingGhostPositionDistributions: localMaxGhost.append(beliefs.argMax()) mostghostPos, mostghostProb = None, 0 # final one for i, belief in enumerate(localMaxGhost): if livingGhostPositionDistributions[i][belief] >= mostghostProb: mostghostProb = livingGhostPositionDistributions[i][belief] mostghostPos = belief mazeDistance = [] for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) mazeDistance.append( (self.distancer.getDistance(successorPosition, mostghostPos), action)) return min(mazeDistance)[1]
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() actions = gameState.getLegalPacmanActions() livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] # get the most likely ghost positions ghostPossitions = [] for distribution in livingGhostPositionDistributions: ghost = (max(distribution, key = distribution.get)) ghostPossitions.append(ghost) # choose to folow the ghost closest to packman ghostDistances = [] for ghost in ghostPossitions: distance = self.distancer.getDistance(pacmanPosition, ghost) ghostDistances.append(distance) ghost = ghostPossitions[ghostDistances.index(min(ghostDistances))] # pick the action that minimixes the distance to the chosen ghost nextGhostDistances = [] for action in actions: successor = Actions.getSuccessor(pacmanPosition, action) distance = self.distancer.getDistance(successor, ghost) nextGhostDistances.append(distance) action = actions[nextGhostDistances.index(min(nextGhostDistances))] return action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] closest_ghost_pos = None closest_ghost_dist = None for ghost_dist in livingGhostPositionDistributions: ghost_pos = None pos_prob = -1 for pos, prob in ghost_dist.items(): if prob > pos_prob: pos_prob = prob ghost_pos = pos distance = self.distancer.getDistance(ghost_pos, pacmanPosition) if closest_ghost_dist is None or closest_ghost_dist > distance: closest_ghost_dist = distance closest_ghost_pos = ghost_pos min_action = None min_action_distance = None for a in legal: new_pos = Actions.getSuccessor(pacmanPosition, a) dist = self.distancer.getDistance(new_pos, closest_ghost_pos) if min_action_distance is None or min_action_distance > dist: min_action_distance = dist min_action = a return min_action
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (in maze distance!). To find the maze distance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = [beliefs for i,beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" ############################## DONE ############################## distance = 10000000000 ghost = None returnAction = None for d in livingGhostPositionDistributions: tempGhost = d.argMax() tempDist = self.distancer.getDistance(pacmanPosition, tempGhost) if tempDist < distance: ghost = tempGhost distance = tempDist distance = 10000000000 for act in legal: tempDist = self.distancer.getDistance(ghost,Actions.getSuccessor(pacmanPosition, act)) if tempDist < distance: distance = tempDist returnAction = act return returnAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" bestGhostIndex = 0 bestGhostDistance = -1 bestGhostPosition = None for i in range(len(livingGhostPositionDistributions)): # distribution :: Position => Float (prob at positon) distribution = livingGhostPositionDistributions[i] bestPos = max(distribution, key=lambda x: distribution[x]) bestPosDist = self.distancer.getDistance(pacmanPosition, bestPos) if bestGhostDistance < 0 or bestPosDist < bestGhostDistance: bestGhostIndex = i bestGhostDistance = bestPosDist bestGhostPosition = bestPos def distanceToGhost(action): succPos = Actions.getSuccessor(pacmanPosition, action) return self.distancer.getDistance(succPos, bestGhostPosition) return min(legal, key=distanceToGhost)
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" maxProb = 0 distToBestGhost = float('inf') bestGhostPos = None minDistToGhost = float('inf') for belief in livingGhostPositionDistributions: for position, probability in belief.items(): if probability > maxProb: maxProb = probability maxProbPos = position maxProbDist = self.distancer.getDistance(maxProbPos, pacmanPosition) if maxProbDist <= minDistToGhost: minDistToGhost = maxProbDist bestGhostPos = maxProbPos bestAction = None bestDistance = float('inf') for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) distanceOfSuccessor = self.distancer.getDistance( successorPosition, bestGhostPos) if distanceOfSuccessor < bestDistance: bestDistance = distanceOfSuccessor bestAction = action return bestAction
class GreedyBustersAgent(BustersAgent): "An agent that charges the closest ghost." def registerInitialState(self, gameState): "Pre-computes the distance between every two points." BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) def chooseAction(self, gameState): """ First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closer to the closest ghost (according to mazeDistance!). To find the mazeDistance between any two positions, use: self.distancer.getDistance(pos1, pos2) To find the successor position of a position after an action: successorPosition = Actions.getSuccessor(position, action) livingGhostPositionDistributions, defined below, is a list of util.Counter objects equal to the position belief distributions for each of the ghosts that are still alive. It is defined based on (these are implementation details about which you need not be concerned): 1) gameState.getLivingGhosts(), a list of booleans, one for each agent, indicating whether or not the agent is alive. Note that pacman is always agent 0, so the ghosts are agents 1, onwards (just as before). 2) self.ghostBeliefs, the list of belief distributions for each of the ghosts (including ghosts that are not alive). The indices into this list should be 1 less than indices into the gameState.getLivingGhosts() list. """ pacmanPosition = gameState.getPacmanPosition() legal = [a for a in gameState.getLegalPacmanActions()] livingGhosts = gameState.getLivingGhosts() livingGhostPositionDistributions = \ [beliefs for i, beliefs in enumerate(self.ghostBeliefs) if livingGhosts[i+1]] "*** YOUR CODE HERE ***" ghostPos = [] for i in range(len(livingGhostPositionDistributions)): guess = None for p in livingGhostPositionDistributions[i].sortedKeys(): if livingGhostPositionDistributions[i][ p] > livingGhostPositionDistributions[i][guess]: guess = p ghostPos.append(guess) target = [(0, 0), 999999999] for p in ghostPos: if self.distancer.getDistance(p, pacmanPosition) < target[1]: target[0] = p target[1] = self.distancer.getDistance(p, pacmanPosition) decision = [] for action in legal: successorPosition = Actions.getSuccessor(pacmanPosition, action) if self.distancer.getDistance( target[0], successorPosition) < self.distancer.getDistance( target[0], pacmanPosition): decision.append(action) # choose random motion #import random #return random.choice(decision) return decision[0]