def enhancedPacmanFeatures(state, action):
    """
    For each state, this function is called with each legal action.
    It should return a counter with { <feature name> : <feature value>, ... }
    """
    features = util.Counter()
    # *** YOUR CODE HERE ***
    succGameState = state.generateSuccessor(0, action)

    dist = 0

    for n in range(len(GameState.getGhostPositions(succGameState))):

        pac_location = GameState.getPacmanPosition(succGameState)
        ghost_loc = GameState.getGhostPositions(succGameState)
        dist += util.manhattanDistance(pac_location, ghost_loc[n])
        feat = 'dist'+str(n)
        features[feat] = util.manhattanDistance(pac_location, ghost_loc[n])



    if action == 'Stop':
        features['stopped'] += 1

    features['dist'] = dist
    features['foodCount'] = GameState.getNumFood(succGameState)
    features['power_pellet'] = len(GameState.getCapsules(succGameState))

    return features
def calculate_food_score(game_state: GameState):
    food_layout = game_state.getFood()

    initial_food = food_layout.width * food_layout.height

    return initial_food - game_state.getNumFood()

    """
Exemple #3
0
    def getFeatures(self, gameState, action):
        features = util.Counter()
        successor = self.getSuccessor(gameState, action)
        foodGrid = self.getFood(successor)
        foodList = foodGrid.asList()
        Capsule = self.getCapsules(gameState)
        Foodeaten = 40 - GameState.getNumFood(gameState)
        HomeFood = gameState.getRedFood()
        HomeFoodList = HomeFood.asList()
        features['successorScore'] = -len(foodList)  #self.getScore(successor)

        # Try to implement enemy aware offensive agent 09.16
        myState = successor.getAgentState(self.index)
        myPos = myState.getPosition()
        x, y = myPos
        enemies = [
            successor.getAgentState(i) for i in self.getOpponents(successor)
        ]
        protectors = [
            a for a in enemies
            if (not a.isPacman) and a.getPosition() != None and (
                a.scaredTimer == 0 or a.scaredTimer <= 3)
        ]
        features['numProtectors'] = len(protectors)
        if len(protectors) > 0:
            dists = [
                self.getMazeDistance(myPos, a.getPosition())
                for a in protectors
            ]
            features['protectorsDistance'] = min(dists)
            if gameState.getAgentState(self.index).numCarrying >= 2:
                myPos = successor.getAgentState(self.index).getPosition()
                HomeDistance = min([
                    self.getMazeDistance(myPos, food) for food in HomeFoodList
                ])
                features['GoBackHome'] = HomeDistance
            else:
                features['GoBackHome'] = 0

        # Try to go back home if food collected >=5

        #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])
            features['distanceToFood'] = minDistance
        if len(Capsule) > 0:
            features['Capsule'] = min(
                [self.getMazeDistance(myPos, Cap) for Cap in Capsule])
        return features
def betterEvaluationFunction(currentGameState: GameState):
    """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
    evaluation function (question 5).

    DESCRIPTION: <write something here so we know what you did>
    """
    "*** YOUR CODE HERE ***"
    # 首先判断当前是否已经结束
    if currentGameState.isWin():
        return float('inf')
    if currentGameState.isLose():
        return -float('inf')
    score = currentGameState.getScore()
    # 考虑food
    foods = currentGameState.getFood().asList()
    foodDis = [
        util.manhattanDistance(currentGameState.getPacmanPosition(), food)
        for food in foods
    ]
    foodDis.sort(reverse=True)
    numFoods = 3
    if currentGameState.getNumFood() < 3:
        numFoods = currentGameState.getNumFood()
    score -= foodDis[0] * 1.5
    # for i in range(numFoods):
    #     score-=(numFoods-i)*foodDis[i]
    # 如果附近有food 最好可以吃到
    score -= (currentGameState.getNumFood() * 4)
    # 考虑ghost
    ghostDis = [
        util.manhattanDistance(currentGameState.getPacmanPosition(), ghost)
        for ghost in currentGameState.getGhostPositions()
    ]
    score += max(3, min(ghostDis)) * 2
    # 考虑capsule
    score -= len(currentGameState.getCapsules()) * 4
    return score
Exemple #5
0
def betterEvaluationFunction(currentGameState: GameState) -> float:
    """
      Your extreme, unstoppable evaluation function (problem 4). Note that you can't fix a seed in this function.
    """
    score = currentGameState.getScore()
    numFoods = currentGameState.getNumFood()
    score -= 4.5 * numFoods
    pacPos = currentGameState.getPacmanPosition()
    numCapsules = len(currentGameState.getCapsules())
    ghostStates = [
        manhattanDistance(ghost, pacPos)
        for ghost in currentGameState.getGhostPositions()
    ]
    minGhost = min(ghostStates)
    index = ghostStates.index(minGhost)
    minGhost = 1.0 / minGhost
    if currentGameState.getGhostState(index + 1).scaredTimer > 5:
        minGhost *= -200
    score -= minGhost
    score -= numCapsules * 30
    if numFoods >= 1:
        foods = currentGameState.getFood().data
        num = 0
        arr = []
        for i in range(len(foods)):
            for j in range(len(foods[0])):
                if foods[i][j]:
                    arr.append((i, j))
                    num += 1
                    if num == numFoods:
                        break
            if num == numFoods:
                break
        nearest = min([util.manhattanDistance(pacPos, food) for food in arr])
        if numFoods > 1:
            score += 3.0 * pow(nearest, -1.0)
        else:
            score += 5.0 * pow(nearest, -1.0)
    return score
    def calculate_best_score(self, game_state: GameState, action):
        #  pacman
        next_game_state = game_state.getPacmanNextState(action)
        next_pacman_position = next_game_state.getPacmanPosition()

        # ghost
        # next_ghost_position = tuple(map(lambda v: int(v), next_game_state.getGhostPosition(1)))
        # print('\nnext Ghost position = ', next_ghost_position)

        next_ghost_positions = next_game_state.getGhostPositions()

        next_food_layout = next_game_state.getFood()

        food_points = ReflexAgent.eaten_food_points if next_game_state.getNumFood() < game_state.getNumFood() else 0

        ghost_penalization = ReflexAgent.ghost_penalization if self.pacman_will_die(next_pacman_position,
                                                                                    next_ghost_positions) else 0

        scores = []

        for x in range(next_food_layout.width):
            for y in range(next_food_layout.height):
                if self.has_food(next_food_layout, x, y):
                    pacman_distance_to_food = self.calculate_food_distance(game_state,
                                                                           pacman_position=next_pacman_position,
                                                                           food_position=(x, y))

                    distance_points = ReflexAgent.distance_coefficient / pacman_distance_to_food

                    score = distance_points + food_points - ghost_penalization
                    scores.append({'distance': pacman_distance_to_food, 'score': score,
                                   'foodAt': [x, y], 'action': action})

        if len(scores) == 0:
            score = ReflexAgent.all_food_eaten_points - ghost_penalization

            scores.append({'distance': 0, 'score': score, 'foodAt': None})

        # best score first
        scores.sort(key=lambda s: s['score'], reverse=True)

        # get the best score
        return scores[0]