Пример #1
0
def betterEvaluationFunction(currentGameState):
  """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
    evaluation function (question 5).
  """

  pacPos = currentGameState.getPacmanPosition()
  numCapsules = len(currentGameState.getCapsules())

  # Determine distance to nearest Ghost, don't care if farther than 7
  gDistance = 7
  for pos in currentGameState.getGhostPositions():
    problem = searchAgents.PositionSearchProblem(currentGameState, goal=pos, start=pacPos)
    gDistance = min(gDistance, len(search.breadthFirstSearch(problem)))

  # Determine distance to nearest food
  fDistance = 0
  
  foodGrid = currentGameState.getFood()
  foodList = foodGrid.asList()
  numFood = len(foodList)
  if len(foodList) > 0:
    fProblem = searchAgents.PositionSearchProblem(currentGameState, goal=foodList[0], start=pacPos)
    fDistance = len(search.breadthFirstSearch(problem))

  # Make shorter ghost distance attractive when ghosts are scared
  newGhostStates = currentGameState.getGhostStates()
  newScaredTime = 0
  newScaredTime = reduce(lambda x, y: x.scaredTimer + y.scaredTimer, newGhostStates)
  if newScaredTime > 6:
    gDistance = -gDistance

  px, py = pacPos
  fDensity = 0

  def minus1(l):
    l[:] = [x - 1 for x in l]
    return l

  width = len(foodGrid[:][0])
  height = len(foodGrid[0])

  # Compute density of food surrounding Pacman
  for i in minus1(range(5)):
    intx = px + i
    if intx < 0 or intx > width-1:
      continue

    for j in minus1(range(5)):
      inty = py + j
      if inty < 0 or inty > height-1:
        continue
      if foodGrid[intx][inty]:
        fDensity += 1

  # Return linear combination of factors
  return 3 * gDistance - 13*numCapsules + 1.0/(fDistance+1) + 1*fDensity - 2*numFood
Пример #2
0
 def getPathToApproachPoint(self, gameState, myState):
   """
   A path takes the form [(whereYouAre, whatYouDo), ...]
   """
   problem = OtherSideProblem(gameState, myState.getPosition(), self.west)
   states, actions, cost = search.breadthFirstSearch(problem)
   return zip(states, actions)  
 def findPathToClosestDot(self, gameState):
     "Returns a path (a list of actions) to the closest dot, starting from gameState"
     # Here are some useful elements of the startState
     startPosition = gameState.getPacmanPosition()
     food = gameState.getFood()
     walls = gameState.getWalls()
     problem = AnyFoodSearchProblem(gameState)
     totDist = 99999
     closestPellet = 1
     foodList = food.asList()
     for foodPellet in foodList:
         
         dist = self.distance(startPosition, foodPellet)
         
         if dist < totDist:
             print dist
             print totDist
             closestPellet = foodPellet
             totDist = dist
     
     
     problem.goal = closestPellet
     
     actions  = search.breadthFirstSearch(problem)
     
     return actions
     
     "*** YOUR CODE HERE ***"
     util.raiseNotDefined()
Пример #4
0
 def getAction(self, state):
     """
     From game.py:
     The Agent will receive a GameState and must return an action from
     Directions.{North, South, East, West, Stop}
     """
     if not self.food or len(self.food) < 3:
         self.getNewFood(state)
     if not self.actions:
         problem = AnyFoodSearchProblem(state, self.food.pop(0))
         result = search.breadthFirstSearch(problem)
         if not result:
             self.getNewFood(state)
             problem = AnyFoodSearchProblem(state, self.food.pop(0))
         self.actions = search.breadthFirstSearch(problem)
     return self.actions.pop(0)
Пример #5
0
 def getPathToNearestDot(self, gameState, myState):
   """
   A path takes the form [(whereYouAre, whatYouDo), ...]
   """
   food = self.getFood(gameState)
   problem = AnyDotWithGameStates( gameState, food, self.index)
   states, actions, cost = search.breadthFirstSearch(problem)
   return zip(states, actions)
Пример #6
0
 def getPathToNearestDot(self, gameState, myState):
   """
   A path takes the form [(whereYouAre, whatYouDo), ...]
   """
   food = self.getFood(gameState)
   problem = AnyDotOnSideWillDo(nearestPoint(myState.getPosition()), food, gameState.getWalls())
   states, actions, cost = search.breadthFirstSearch(problem)
   return zip(states, actions)
Пример #7
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        return search.breadthFirstSearch(problem)
Пример #8
0
def closestFoodDistance(gameState):
    """
    Returns the the distance to the closest food
    """
    from search import breadthFirstSearch
    startPosition = gameState.getPacmanPosition()
    food = gameState.getFood()
    walls = gameState.getWalls()
    problem = AnyFoodSearchProblem(gameState)
    path = breadthFirstSearch(problem)
    return len(path)
Пример #9
0
 def findPathToClosestDot(self, gameState):
     "Returns a path (a list of actions) to the closest dot, starting from gameState"
     # Here are some useful elements of the startState
     from search import breadthFirstSearch
     startPosition = gameState.getPacmanPosition()
     food = gameState.getFood()
     walls = gameState.getWalls()
     problem = AnyFoodSearchProblem(gameState)
     path = breadthFirstSearch(problem)       
     return path
     "*** YOUR CODE HERE ***"
     util.raiseNotDefined()
Пример #10
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        # use bfs. bfs will give you the shortest path, it spits out the solution, which is the path.
        # It is done. We return the path [a list of action]
        return search.breadthFirstSearch(problem)
Пример #11
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        return search.breadthFirstSearch(problem)
Пример #12
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        action_list = breadthFirstSearch(problem)

        return action_list
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        #find the closest food to me and move towards it
        actions = search.breadthFirstSearch(problem)
        return actions
        util.raiseNotDefined()
Пример #14
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        #We already coded breadth first search, which will find our closest pellet.
        return search.breadthFirstSearch(problem)
Пример #15
0
  def findPathToClosestDot(self, gameState):
    "Returns a path (a list of actions) to the closest dot, starting from gameState"
    # Here are some useful elements of the startState
    startPosition = gameState.getPacmanPosition()
    #print 'startPosition: ' + str(startPosition) #DEBUG
    food = gameState.getFood()
    walls = gameState.getWalls()
    problem = AnyFoodSearchProblem(gameState)

    "*** YOUR CODE HERE ***"
    actions = search.breadthFirstSearch(problem)
    #print 'actions: ' + str(actions) #DEBUG
    return actions
Пример #16
0
    def findPathToClosestDot(self, gameState):
        """
           En yakın noktaya giden bir yolu döndürür.
        """

        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        action_list = breadthFirstSearch(problem)

        return action_list
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition(self.index)
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState, self.index)

        return search.breadthFirstSearch(problem)
        util.raiseNotDefined()
Пример #18
0
 def findPathToClosestDot(self, gameState):
     """
     Returns a path (a list of actions) to the closest dot, starting from
     gameState.
     """
     # Here are some useful elements of the startState
     startPosition = gameState.getPacmanPosition()
     food = gameState.getFood()
     walls = gameState.getWalls()
     problem = AnyFoodSearchProblem(gameState)
     #prob = PositionSearchProblem(gameState, start=startPosition, goal=food, warn=False, visualize=False)
     prob2 = AnyFoodSearchProblem(gameState)
     return search.breadthFirstSearch(prob2)
Пример #19
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        # BFS gurantees the shortest path but isn't optimal
        return search.breadthFirstSearch(problem)
Пример #20
0
def foodHeuristic(state, problem):
    """
    Your heuristic for the FoodSearchProblem goes here.

    This heuristic must be consistent to ensure correctness.  First, try to come
    up with an admissible heuristic; almost all admissible heuristics will be
    consistent as well.

    If using A* ever finds a solution that is worse uniform cost search finds,
    your heuristic is *not* consistent, and probably not admissible!  On the
    other hand, inadmissible or inconsistent heuristics may find optimal
    solutions, so be careful.

    The state is a tuple ( pacmanPosition, foodGrid ) where foodGrid is a Grid
    (see game.py) of either True or False. You can call foodGrid.asList() to get
    a list of food coordinates instead.

    If you want access to info like walls, capsules, etc., you can query the
    problem.  For example, problem.walls gives you a Grid of where the walls
    are.

    If you want to *store* information to be reused in other calls to the
    heuristic, there is a dictionary called problem.heuristicInfo that you can
    use. For example, if you only want to count the walls once and store that
    value, try: problem.heuristicInfo['wallCount'] = problem.walls.count()
    Subsequent calls to this heuristic can access
    problem.heuristicInfo['wallCount']
    """
    position, foodGrid = state
    "*** YOUR CODE HERE ***"
    food_positions = foodGrid.asList()  # Store food co-ordinates as a list
    manhattan = []  # Initialize empty list for manhattan distances
    if problem.isGoalState(state):  # Heuristic for goal state is zero
        return 0
    for food in food_positions:
        result = PositionSearchProblem(problem.startingGameState,
                                       start=position,
                                       goal=food,
                                       warn=False,
                                       visualize=True)
        # Calculate search path from position to every food using BFS
        dist = len(
            search.breadthFirstSearch(result)
        )  #BFS returns a path so value returned will be distance that path
        # dist = len(search.aStarSearch(result))
        # dist = len(search.depthFirstSearch(result))
        # dist = len(search.uniformCostSearch(result))
        # In above step  we can perform search by astar ,DFS or uniform cost as commented above
        manhattan.append(dist)
    return max(
        manhattan)  # Heuristic will be the maximum of all distances calculated
Пример #21
0
    def registerInitialState(self, state):
        "This method is called before any moves are made."

        "Start with the CornersProblem, this should at least cover the walls quickly"

        foodList = state.getFood().asList()

        distance, food = min([(mazeDistance(state.getPacmanPosition(), food, state), food) for food in foodList])

        problem = PositionSearchProblem(state, lambda x: 1, food, state.getPacmanPosition(), warn=False, visualize=False)
        solution = search.breadthFirstSearch(problem)

        self.totalCost = len(solution)
        self.solution = solution
Пример #22
0
 def findPathToClosestDot(self, gameState):
     """
     Returns a path (a list of actions) to the closest dot, starting from
     gameState.f
     """
     # Here are some useful elements of the startState
     startPosition = gameState.getPacmanPosition()
     food = gameState.getFood()
     walls = gameState.getWalls()
     problem = AnyFoodSearchProblem(gameState)
     "*** YOUR CODE HERE ***"
     #Camino que sera aprovechado para alcanzar todos los goals
     #dijkstra y brfs funcionan
     return search.breadthFirstSearch(problem)
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        return search.breadthFirstSearch(problem) #return the suboptimal search solution obtained through bfs for the problem.
        util.raiseNotDefined()
Пример #24
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.

        python pacman.py -l bigSearch -p ClosestDotSearchAgent -z .5
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        return search.breadthFirstSearch(problem)
Пример #25
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        path = search.breadthFirstSearch(
            problem)  # Bfs finds closest food first.
        return path  # return actions to reach food
def foodHeuristic(state, problem):
    """
    Your heuristic for the FoodSearchProblem goes here.

    This heuristic must be consistent to ensure correctness.  First, try to come
    up with an admissible heuristic; almost all admissible heuristics will be
    consistent as well.

    If using A* ever finds a solution that is worse uniform cost search finds,
    your heuristic is *not* consistent, and probably not admissible!  On the
    other hand, inadmissible or inconsistent heuristics may find optimal
    solutions, so be careful.

    The state is a tuple ( pacmanPosition, foodGrid ) where foodGrid is a Grid
    (see game.py) of either True or False. You can call foodGrid.asList() to get
    a list of food coordinates instead.

    If you want access to info like walls, capsules, etc., you can query the
    problem.  For example, problem.walls gives you a Grid of where the walls
    are.

    If you want to *store* information to be reused in other calls to the
    heuristic, there is a dictionary called problem.heuristicInfo that you can
    use. For example, if you only want to count the walls once and store that
    value, try: problem.heuristicInfo['wallCount'] = problem.walls.count()
    Subsequent calls to this heuristic can access
    problem.heuristicInfo['wallCount']
    """
    position, foodGrid = state
    "*** YOUR CODE HERE ***"
    #print(problem.startingGameState)
    #print("goodgrid:",foodGrid.asList())
    #print('position:',position)
    foodloc = foodGrid.asList()
    Gamestate = problem.startingGameState
    if not foodloc:
        return 0
    maxdistance = 0
    for loc in foodloc:
        #distance = ((loc[0] - position[0])**2 + (loc[1] - position[1])**2) ** 0.5
        #distance = abs(loc[0] - position[0]) + abs(loc[1] - position[1])
        singleprob = PositionSearchProblem(Gamestate,
                                           start=position,
                                           goal=loc,
                                           warn=False,
                                           visualize=False)
        distance = len(search.breadthFirstSearch(singleprob))
        maxdistance = max(distance, maxdistance)
    return maxdistance
Пример #27
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** MY CODE BEGINS HERE ***"
        return search.breadthFirstSearch(problem)
        #return search.uniformCostSearch(problem)  #just the same thing
        util.raiseNotDefined()
Пример #28
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        from search import breadthFirstSearch

        #bfs avalin miveye nazdik ra peida mikonad
        return breadthFirstSearch(problem)
Пример #29
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        # using bfs to find the actions to be taken to solve the problem
        return search.breadthFirstSearch(problem)
        util.raiseNotDefined()
Пример #30
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        from search import breadthFirstSearch
        result = breadthFirstSearch(problem)

        return result

        util.raiseNotDefined()
Пример #31
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        "initialize some variables"
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "use breadthFirstSearch one AnyFoodSearchProblem to make it find the closest food dot"
        actionlist = search.breadthFirstSearch(problem)
        return actionlist
Пример #32
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        closest = None
        for pellet in food.asList():
            if closest == None:
                closest = pellet
                continue
            distance1 = abs(closest[0]-startPosition[0]) + abs(closest[1]-startPosition[1])
            distance2 = abs(pellet[0]-startPosition[0]) + abs(pellet[0]-startPosition[0])
            if distance1 < distance2:
                closest = pellet

        self.searchType = AnyFoodSearchProblem
        self.searchFunction = lambda prob: search.breadthFirstSearch(problem)
        return search.breadthFirstSearch(problem)
Пример #33
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)
        temp = food.asList()

        from search import breadthFirstSearch

        # Bfs finds closest food first. #
        return breadthFirstSearch(problem)  # Return actions
Пример #34
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        #util.raiseNotDefined()
        # We need the nearest food crumb, which is given by BFS as it searches the shallowesd goal first.
        return search.breadthFirstSearch(problem)
Пример #35
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        foodGrid = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        #We don't have to do much here once AnyFoodSearch is implemented.  We just basically pass the problem on to
        #a search function.  I chose BFS because it's more efficient than DFS and does not require a heuristic.
        return search.breadthFirstSearch(problem)
Пример #36
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        foodGrid = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        #We don't have to do much here once AnyFoodSearch is implemented.  We just basically pass the problem on to
        #a search function.  I chose BFS because it's more efficient than DFS and does not require a heuristic.
        return search.breadthFirstSearch(problem)
Пример #37
0
    def findPathToClosestDot(self, gameState):
        import search as s  # our bfs finally paying off !!
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        return s.breadthFirstSearch(
            problem
        )  # breadth first search actually finds everything we need it to do it will find the next closest food, e arent certain that this works in every case but it works in this one. Kinda cheese but it works.
Пример #38
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        #startPosition = gameState.getPacmanPosition()
        #food = gameState.getFood()
        #walls = gameState.getWalls()
        #problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        # 함수의 인자인 gameState를 AnyFoodSearchProblem에 넘겨 새로운 problem을 생성한다.
        problem = AnyFoodSearchProblem(gameState)
        # 새로운 problem을 Breadth First Search로 탐색해서 길을 찾은 후 반환한다.
        return search.breadthFirstSearch(problem)
Пример #39
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        actionspath = [] #this is a position search problem so use the bfs from q2
        actionspath = search.breadthFirstSearch(problem)
        return actionspath
        util.raiseNotDefined()
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        # Simply run a BFS, where the goal is any food pellet.
        return (search.breadthFirstSearch(problem))

        util.raiseNotDefined()
Пример #41
0
 def findPathToClosestDot(self, gameState):
     """
     Returns a path (a list of actions) to the closest dot, starting from
     gameState.
     """
     # Here are some useful elements of the startState
     startPosition = gameState.getPacmanPosition()
     food = gameState.getFood()
     walls = gameState.getWalls()
     problem = AnyFoodSearchProblem(gameState)
     "*** YOUR CODE HERE ***"
     '''The problem obtained is given to Uniform Cost search and the actions returned by the Uniform Cost search is returned by this function. 
     In Uniform Cost search , all the dots nearest are first visited. We can also use Breadth First search here but I used uniform cost search since    
     breadth first search is just a special case of Uniform cost.'''
     actions = search.breadthFirstSearch(problem)
     return actions
Пример #42
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        directions = search.breadthFirstSearch(
            problem
        )  # Finding path to the closes dot can be performed by BFS algorithm so as to get the optimal solution.
        return directions
Пример #43
0
    def findPathToClosestDot(self, gameState = registerInitialState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        #To get a list of action we can use and search from search.py
        from search import breadthFirstSearch
        return breadthFirstSearch(problem)
        util.raiseNotDefined()
Пример #44
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        # do BFS with AnyFoodSearchProlem (which has as goal state 'any food')
        # since BFS searches breadth first, you will always get the closest food
        from search import breadthFirstSearch
        return breadthFirstSearch(problem)
Пример #45
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"

        """ Using BFS defined in search.py to find the goal""" 
        from search import breadthFirstSearch
        return breadthFirstSearch(problem)
Пример #46
0
 def evalFn(self, successor, action):
   if self.getFood(successor).count() == 0: return 1000
   myState = successor.getAgentState(self.index)
   pos = myState.getPosition() 
   if pos != nearestPoint(pos): return self.evalFn(successor.generateSuccessor(self.index, action), action)
   
   food = self.getFood(successor)
   problem = AnyDotOnSideWillDo(nearestPoint(pos), food, successor.getWalls())
   distanceToFood = search.breadthFirstSearch(problem)[2]
   
   distanceToOpponent = 100
   for enemyIndex in self.getOpponents(successor):
     opp = successor.getAgentState(enemyIndex)
     if not opp.isPacman:
       distanceToOpponent = min(distanceToOpponent, manhattanDistance(myState.getPosition(), opp.getPosition()))
     
   return -0.3 * distanceToFood + self.getScore(successor) + 2 * math.log(distanceToOpponent)
Пример #47
0
def primsMinSpanningTreeHeuristic(state, gameState, edges):
    vNew = []
    totalDist = 0
    
    currentFoodGrid = state[1]
    vertices = foodGridToFoodList(currentFoodGrid)
           
    if (len(vertices) == 0):
        return 0
    
    start = state[0] #Pacman's position
    
    delStart = False
    if (start not in edges.keys()): #This is only to keep the edge hash from becoming really big.
        delStart = True
        edges[start] = {}
        for pellet in vertices:
          problem = CustomPositionSearchProblem(gameState, lambda x: 1, pellet, start)
          actions = search.breadthFirstSearch(problem)
          distance = len(actions) #we can do this because the cost function is 1
          edges[start][pellet] = distance 
          #DO WE NEED TO ADD THE START AS A DESTINATION TO ALL THE OTHER PELLETS TOO? I DONT THINK SO...
    
    vNew.append(start)
    
    nearestV = None
    nearestD = 999999
    while len(vertices) > 0:
        nearestV = None
        nearestD = 999999 
        for sVertex in vNew:
            for eVertex in vertices:
                if (edges[sVertex][eVertex] < nearestD):
                    nearestD = edges[sVertex][eVertex]
                    nearestV = eVertex
        assert nearestV != None
        vNew.append(eVertex)
        vertices.remove(eVertex)
        totalDist += nearestD
        
    if (delStart):
        del edges[start]
    
    #print "h = ",totalDist,", ",foodCount," food, ", len(edges.keys()), "nodes in edge hash: ", edges.keys()
    #print "Prim distance=", totalDist, ", pellet count=", len(vertices), " and pacman position=", start    
    return totalDist
Пример #48
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"

        #since we are trying to find closest 'goal', BFS will allows us to do that
        return search.breadthFirstSearch(problem)

        util.raiseNotDefined()
Пример #49
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        """"""
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)
        """BFS is called to append the path to next food. THe Goal of AnyFoodSearchProblem is edited so that 
        when the Pacman will reach the nearest food, it returns True"""
        return search.breadthFirstSearch(problem)

        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"

        # We can just call BFS as defined in search on the AnyFoodSearchProblem defined above
        return breadthFirstSearch(problem)

        util.raiseNotDefined()
Пример #51
0
 def findPathToClosestDot(self, gameState):
   "Returns a path (a list of actions) to the closest dot, starting from gameState"
   # Here are some useful elements of the startState
   startPosition = gameState.getPacmanPosition()
   food = gameState.getFood().asList()
   walls = gameState.getWalls()
   problem = AnyFoodSearchProblem(gameState)
   
   from game import Directions
   s = Directions.SOUTH
   w = Directions.WEST
   e = Directions.EAST
   n = Directions.NORTH
   
   "*** YOUR CODE HERE ***"
   path =  search.breadthFirstSearch(problem)
   
   return path
Пример #52
0
def getFoodHeuristic(gameState):
  """
  Instead of filling in the foodHeuristic function directly, you can fill in
  this function which takes a full gameState for Pacman (see pacman.py) and
  returns a heuristic function.  The heuristic function must
    - take a single parameter, a search state
    - return a non-negative number that is the value of the heuristic at that state

  This function is *only* here for students who want to create more complex
  heuristics that use aspects of the gameState other than the food Grid and
  Pacman's location (such as where the walls are, etc.)

  Note: The state that will be passed to your heuristic function is a tuple
  ( pacmanPosition, foodGrid ) where foodGrid is a Grid (see game.py) of either
  True or False.
  """
  # If you don't want to implement this method, you can leave this default implementation
  #return foodHeuristic

  print "Preprocessing started."
  #get positions of all the food pellets on the board
  #edgeInfo = util.FasterPriorityQueue()
  distanceInfo = {}
  foodGrid = gameState.getFood()
  foodList = foodGridToFoodList(foodGrid)
  for startPellet in foodList:
      distanceInfo[startPellet] = {}
      for endPellet in foodList:
          if (startPellet == endPellet):
              continue
          #if (distanceInfo.has_key((endPellet,startPellet))):
          #    continue
          problem = CustomPositionSearchProblem(gameState, lambda x: 1, endPellet, startPellet)
          actions = search.breadthFirstSearch(problem)
          distance = len(actions) #because costFunction = 1
          distanceInfo[startPellet][endPellet] = distance
          #edgeInfo.push((startPellet,endPellet),distance)

  print "Preprocessing done."
  #This is an example of Closures, which does not exist in C.
  #heuristicFn = lambda state: minSpanningTreeHeuristic(state,gameState, distanceInfo)
  heuristicFn = lambda state: primsMinSpanningTreeHeuristic(state, gameState, distanceInfo)  
  return heuristicFn
Пример #53
0
def mazeDistance(point1, point2, gameState):
    """
    Returns the maze distance between any two points, using the search functions
    you have already built.  The gameState can be any game state -- Pacman's position
    in that state is ignored.

    Example usage: mazeDistance( (2,4), (5,6), gameState)

    This might be a useful helper function for your ApproximateSearchAgent.
    """
    x1, y1 = point1
    x2, y2 = point2
    walls = gameState.getWalls()
    assert not walls[x1][y1], 'point1 is a wall: ' + point1
    assert not walls[x2][y2], 'point2 is a wall: ' + str(point2)
    prob = PositionSearchProblem(gameState, start=point1, goal=point2, warn=False)
    l = len(search.breadthFirstSearch(prob))
    print l
    return l
Пример #54
0
  def findPathToClosestDot(self, gameState):
    "Returns a path (a list of actions) to the closest dot, starting from gameState"
    # Here are some useful elements of the startState
    startPosition = gameState.getPacmanPosition()
    food = gameState.getFood()
    walls = gameState.getWalls()
    problem = AnyFoodSearchProblem(gameState)

    "*** YOUR CODE HERE ***"

    DEBUG = False;

    if DEBUG:
      print "gameState:\n"
      print type(gameState),"\n"
      print gameState,"\n"
      print "startPosition:\n"
      print type(startPosition),"\n"
      print startPosition,"\n"
      print "food:\n"
      print type(food),"\n"
      print food,"\n"
      print "walls:\n"
      print type(walls),"\n"
      print walls,"\n"
      print "problem:\n"
      print type(problem),"\n"
      print problem,"\n"
    
    """I think this is the right way to call a search, and it should return
    the path to the goal.  Now we need to try and figure out what the goal
    is and it should work.  I really want to use aStarSearch because I feel
    like that might be the most efficient thing to do but have to figure
    out how to make it work before I can worry about which type of search
    is the most efficient algorythm.  Also not sure if we have everything
    to call aStarSearch so I guess the uniformCostSearch will be a good
    place to start."""
    #return search.depthFirstSearch(problem)
    return search.breadthFirstSearch(problem) #this does really good
    #return search.uniformCostSearch(problem)
    #return search.aStarSearch(problem)

    util.raiseNotDefined()
Пример #55
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        import sys
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

#bestDist = sys.maxint
#        bestPos = startPosition
#        foods = food.asList()
#        for pos in foods:
#            dist = mazeDistance(startPosition, pos, gameState)
#            if bestDist > dist:
#                bestDist = dist
#                bestPos = pos
#        problem = AnyFoodSearchProblem(gameState)
        return search.breadthFirstSearch(problem)
Пример #56
0
 def findPathToClosestDot(self, gameState):
     startPosition = gameState.getPacmanPosition()
     food = gameState.getFood()
     walls = gameState.getWalls()
     walls_list = walls.asList()
     problem = AnyFoodSearchProblem(gameState)
     problem.startState=startPosition
     food_cord=food.asList()
     food_count=len(food_cord)
     distance=[0]*food_count
     dictionary={}
     for i in range(food_count):
             for j in range(2):
                 distance[i]=(distance[i]+abs((food_cord[i][j] - startPosition[j])) )   
             dictionary[food_cord[i]]=distance[i]
     goal_state=min(dictionary, key=dictionary.get)
     problem.goal=goal_state
     from search import breadthFirstSearch
     bfs=breadthFirstSearch(problem)
     return bfs
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        # startPosition = gameState.getPacmanPosition()
        # food = gameState.getFood()
        # walls = gameState.getWalls()

        #just use the framework that was already made
        problem = AnyFoodSearchProblem(gameState)
        actions = search.breadthFirstSearch(problem)

        return actions
        "*** YOUR CODE HERE ***"

        util.raiseNotDefined()
Пример #58
0
 """
   moves: number of random moves to apply

   Creates a random eight puzzle by applying
   a series of 'moves' random moves to a solved
   puzzle.
 """
 puzzle = EightPuzzleState([0,1,2,3,4,5,6,7,8])
 for i in range(moves):
   # Execute a random legal move
   puzzle = puzzle.result(random.sample(puzzle.legalMoves(), 1)[0])
 return puzzle

if __name__ == '__main__':
  puzzle = createRandomEightPuzzle(25)
  print('A random puzzle:')
  print(puzzle)
  
  problem = EightPuzzleSearchProblem(puzzle)
  path = search.breadthFirstSearch(problem)
  print('BFS found a path of %d moves: %s' % (len(path), str(path)))
  curr = puzzle
  i = 1
  for a in path:
    curr = curr.result(a)
    print('After %d move%s: %s' % (i, ("", "s")[i>1], a))
    print(curr)
    
    raw_input("Press return for the next state...")   # wait for key stroke
    i += 1
state_transitions = {
    "A": ["L", "B"],
    "B": ["A", "C"],
    "C": ["B", "D"],
    "D": ["C", "E"],
    "E": ["D", "F"],
    "F": ["E", "G"],
    "G": ["F", "H"],
    "H": ["G", "I"],
    "I": ["H", "J"],
    "J": ["I", "K"],
    "K": ["J", "L"],
    "L": ["K", "A"],
}


if __name__ == "__main__":

    #
    # A few examples of finding paths through the puzzle using BFS and DFS.
    #

    print ("From NotInGraph to 'L'")
    printStates(depthFirstSearch("NotInGraph", "G", successorsf))

    print ("\nFrom A to G (DFS): ")
    printStates(depthFirstSearch("A", "G", successorsf))

    print ("\nFrom A to E (BFS): ")
    printStates(breadthFirstSearch("A", "E", successorsf))