Example #1
0
    def __init__(self, gameState, playerIndex, **kwargs):
        # define the time allowed for simulation
        # seconds can be 0.8? Cuz the whole waiting time is 1.
        seconds = kwargs.get('time', 0.6)
        # seconds = kwargs.get('time', 0.8)
        self.calculateTime = datetime.timedelta(seconds=seconds)

        self.maxMoves = kwargs.get('maxMoves', 20)
        # self.maxMoves = kwargs.get('maxMoves', 30)
        self.states = [gameState]
        self.index = playerIndex
        self.wins = util.Counter()
        self.plays = util.Counter()
        self.C = kwargs.get('C', 1)
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)
        self.distancer.getMazeDistances()
        self.gameState = gameState

        if gameState.isOnRedTeam(self.index):
            self.enemies = gameState.getBlueTeamIndices()
            self.foodList = gameState.getBlueFood()
            self.capsule = gameState.getBlueCapsules()
        else:
            self.enemies = gameState.getRedTeamIndices()
            self.foodList = gameState.getRedFood()
            self.capsule = gameState.getRedCapsules()
Example #2
0
 def registerInitialState(self, gameState):
   self.red = gameState.isOnRedTeam(self.index)
   # Even though there are up to 6 agents creating a distancer, the distances
   # will only actually be computed once, before the start of the game 
   self.distancer = distanceCalculator.Distancer(gameState.data.layout)
   
   # comment this out to forgo maze distance computation and use manhattan distances
   self.distancer.getMazeDistances()
   
   self.legalPositions = []
   walls = gameState.getWalls()    
   width = self.getLayoutWidth(gameState)    
   height = self.getLayoutHeight(gameState)
   
   for x in range(width):
     for y in range(height):
       if not walls[x][y]:
         self.legalPositions.append((x,y))
   
   self.beliefs = util.Counter()    
   #check enemy pacman only?
   for agent in self.getOpponents(gameState):
     self.beliefs[agent] = util.Counter()
     
     for p in self.legalPositions:        
       if (p[0] <= width/2 and gameState.isOnRedTeam(agent)) or (p[0] >= width/2 and not gameState.isOnRedTeam(agent)):
         self.beliefs[agent][p] = 1.0
     
     self.beliefs[agent].normalize()
       
   import __main__
   if '_display' in dir(__main__):
     self.display = __main__._display
    def registerInitialState(self, gameState):
        """
        This method handles the initial setup of the
        agent to populate useful fields (such as what team
        we're on).

        A distanceCalculator instance caches the maze distances
        between each pair of positions, so your agents can use:
        self.distancer.getDistance(p1, p2)
        """
        self.red = gameState.isOnRedTeam(self.index[0])  #0 or 1 doesn't mater
        wallChar = 'r' if self.red else 'b'

        layout = gameState.data.layout.deepCopy()
        walls = layout.walls
        for x in range(layout.width):
            for y in range(layout.height):
                #if walls[x][y] is wallChar:#calculate distance for positions which are reachable for only self team
                if walls[x][y] is 'r' or walls[x][
                        y] is 'b':  #calculate distance for positions which are reachable for at least one team
                    walls[x][y] = False

        self.distancer = distanceCalculator.Distancer(layout)

        # comment this out to forgo maze distance computation and use manhattan distances
        self.distancer.getMazeDistances()

        import __main__
        if '_display' in dir(__main__):
            self.display = __main__._display
Example #4
0
    def registerInitialState(self, gameState):
        """
    This method handles the initial setup of the
    agent to populate useful fields (such as what team
    we're on).
    
    If you want initialization any items a single time for a team
    (i.e. the first agent that gets created does the work) you'll
    need to create your own team class and only let it initialize
    once.
    
    A distanceCalculator instance caches the maze distances 
    between each pair of positions, so your agents can use:
    self.distancer.getDistance(p1, p2)
    """
        self.red = gameState.isOnRedTeam(self.index)
        # Even though there are up to 6 agents creating a distancer, the distances
        # will only actually be computed once, before the start of the game
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)

        # comment this out to forgo maze distance computation and use manhattan distances
        self.distancer.getMazeDistances()

        # or uncomment this to forget maze distances and just use manhattan distances for this agent
        #self.distancer.useManhattanDistances()

        import __main__
        if '_display' in dir(__main__):
            self.display = __main__._display
Example #5
0
    def registerInitialState(self, gameState):
        print "HybridAgent"
        CaptureAgent.registerInitialState(self, gameState)
        self.numagents = gameState.getNumAgents()
        self.start = gameState.getAgentPosition(self.index)
        #self.myindex =
        #self.mycolor =
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)
        self.distancer.getMazeDistances()

        self.walls = gameState.getWalls()
        self.legalpositions = self.getlegal(self.walls)

        self.oldfood = self.getFoodYouAreDefending(gameState)
        self.scared = False  # gameState.data.agentStates[self.index].scaredTimer
        self.opponents = self.getOpponents(gameState)

        self.initializebeliefs(gameState)
        self.message = self.beliefs

        self.observeEnabled = False
        self.elapseEnabled = False

        self.myred = gameState.isOnRedTeam(self.index)
        self.walls = gameState.getWalls()
        self.legalpositions = self.getlegal(self.walls)
        self.width = self.walls.width
        self.height = self.walls.height

        # Feature-based
        self.isOffensive = True
        self.touchHome = False
        self.foodTotal = len(self.getFood(gameState).asList())
        self.foodToReturn = 0
Example #6
0
 def registerInitialState(self, gameState):
     self.start = gameState.getAgentPosition(self.index)
     CaptureAgent.registerInitialState(self, gameState)
     self.capsule_time = 0
     self.distancer = distanceCalculator.Distancer(gameState.data.layout)
     self.distancer.getMazeDistances()
     self.weights = None
Example #7
0
 def chooseCapsules(self, gameState, capsuleLimit, opponentEvidences):
     P = PowersInference()
     e_1 = [
         opponentEvidences[0]['sum0'], opponentEvidences[0]['sum1'],
         opponentEvidences[0]['sum2'], opponentEvidences[0]['sum3']
     ]
     e_2 = [
         opponentEvidences[1]['sum0'], opponentEvidences[1]['sum1'],
         opponentEvidences[1]['sum2'], opponentEvidences[1]['sum3']
     ]
     P.infer(e_1, 0)
     P.infer(e_2, 1)
     #Tells us maze distances
     distancer = distanceCalculator.Distancer(gameState.data.layout)
     distancer.getMazeDistances()
     kmeans = KMeans(gameState, self.isRed)
     food = gameState.getRedFood().asList(
     ) if not self.isRed else gameState.getBlueFood().asList()
     scare_locations = kmeans.pick_capsules(food, distancer)
     capsules = []
     for location in scare_locations:
         x, y = location
         capsules.append(ScareCapsule(x, y))
     """
  grenade_locations = self.pick_grenades( gameState, distancer )
  for (x, y) in grenade_locations:
      capsules.append( GrenadeCapsule(x, y) )
  """
     return capsules
Example #8
0
    def registerInitialState(self, gameState):
        """
    This method handles the initial setup of the
    agent to populate useful fields (such as what team
    we're on).

    A distanceCalculator instance caches the maze distances
    between each pair of positions, so your agents can use:
    self.distancer.getDistance(p1, p2)
    """
        self.red = gameState.isOnRedTeam(self.index)
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)

        # comment this out to forgo maze distance computation and use manhattan distances
        self.distancer.getMazeDistances()

        import __main__
        if '_display' in dir(__main__):
            self.display = __main__._display

        # record the pushback status and reinvasion location
        self.offense = False
        self.targetPos = None

        # save some reused variables
        self.w = gameState.getWalls().width
        self.h = gameState.getWalls().height
Example #9
0
		def registerInitialState(self, gameState):
				self.start = gameState.getAgentPosition(self.index)
				opponentAgents = self.getOpponents(gameState)
				self.inferenceModules = [ExactInference(idx, self) for idx in opponentAgents]
				for inference in self.inferenceModules:
						inference.initialize(gameState)
				self.opponentBeliefs = [inf.getBeliefDistribution() for inf in self.inferenceModules]
				self.red = gameState.isOnRedTeam(self.index)
				self.distancer = distanceCalculator.Distancer(gameState.data.layout)
				self.distancer.getMazeDistances()
				self.observe_enabled = False
 def registerInitialState(self, gameState):
     """
 This method handles the initial setup of the
 agent to populate useful fields (such as what team
 we're on).  
 """
     self.red = gameState.isOnRedTeam(self.index)
     self.distancer = distanceCalculator.Distancer(gameState.data.layout)
     import __main__
     if '_display' in dir(__main__):
         self.display = __main__._display
Example #11
0
    def registerInitialState(self, gameState):
        """
        This method handles the initial setup of the
        agent to populate useful fields (such as what team
        we're on).

        A distanceCalculator instance caches the maze distances
        between each pair of positions, so your agents can use:
        self.distancer.getDistance(p1, p2)

        IMPORTANT: This method may run for at most 15 seconds.
        """
        """
    	you can have your own distanceCalculator. (you can even have multiple distanceCalculators, if you need.)
    	reference the registerInitialState function in captureAgents.py and baselineTeam.py to understand more about the distanceCalculator. 
    	"""
        """
        Each agent has two indexes, one for pacman and the other for ghost.
        self.index[0]: pacman
        self.index[1]: ghost
        """
        '''
        Make sure you do not delete the following line. If you would like to
        use Manhattan distances instead of maze distances in order to save
        on initialization time, please take a look at
        CaptureAgent.registerInitialState in captureAgents.py.
        '''
        CaptureAgent.registerInitialState(self, gameState)
        '''
        Your initialization code goes here, if you need any.
        '''
        """
        overwrite distancer
        only calculate distance positions which are reachable for self team
        """
        self.red = gameState.isOnRedTeam(self.index[0])  #0 or 1 doesn't mater
        wallChar = 'r' if self.red else 'b'

        layout = gameState.data.layout.deepCopy()
        walls = layout.walls
        for x in range(layout.width):
            for y in range(layout.height):
                if walls[x][y] is wallChar:
                    walls[x][y] = False

        self.distancer = distanceCalculator.Distancer(layout)

        # comment this out to forgo maze distance computation and use manhattan distances
        self.distancer.getMazeDistances()

        self.start = [
            gameState.getAgentPosition(index) for index in self.index
        ]
Example #12
0
    def registerInitialState(self, gameState):
        self.escape = False
        self.start = gameState.getAgentPosition(self.index)
        CaptureAgent.registerInitialState(self, gameState)
        self.food = None
        self.totalFood = len(self.getFood(gameState).asList())

        foodList = self.getFood(gameState).asList()
        self.chooseFood(foodList)

        self.distancer = distanceCalculator.Distancer(gameState.data.layout)
        self.distancer.getMazeDistances()
Example #13
0
 def registerInitialState(self, gameState):
   self.red = gameState.isOnRedTeam(self.index)
   self.distancer = distanceCalculator.Distancer(gameState.data.layout)
   self.enemyTeam = self.getEnemyTeam(gameState, self.red)
   self.legalPositions = [p for p in gameState.getWalls().asList(False) if p[1] > 1]
   jointInference.initialize(gameState, self.legalPositions, self.red, 300)
   import __main__
   if '_display' in dir(__main__):
     self.display = __main__._display
   self.enemyBeliefs = util.Counter()
   
   self.firstMove = True
Example #14
0
    def analyzeMap(self, isRed, legalpositions, layout):
        self.width = max([p[0] for p in legalpositions])
        otherwidth = layout.width

        self.halfway = self.width / 2
        self.ourside = [
            p for p in legalpositions
            if operator.xor(p[0] > self.halfway, isRed)
        ]
        self.theirside = [
            p for p in legalpositions
            if not operator.xor(p[0] > self.halfway, isRed)
        ]

        ourSideLayout = layout.deepCopy()
        x = -1
        if (isRed):
            x = 1
        sideToWallOff = self.halfway + x
        for i in range(layout.height):
            ourSideLayout.walls[sideToWallOff][i] = True

        self.distancer = distanceCalculator.Distancer(layout)
        self.distancer.getMazeDistances()
        self.ourSideDistancer = distanceCalculator.Distancer(ourSideLayout)
        self.ourSideDistancer.getMazeDistances()

        ourborder = []
        for pos in self.ourside:
            if len([
                    p for p in self.theirside
                    if util.manhattanDistance(p, pos) == 1
            ]):
                ourborder.append(pos)

        return ourborder
Example #15
0
    def registerInitialState(self, gameState):
        """
    This method handles the initial setup of the
    agent to populate useful fields.

    A distanceCalculator instance caches the maze distances 
    between each pair of positions, so your agents can use:
    self.distancer.getDistance(p1, p2)
    """
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)

        # uncomment this line to use maze-distances (instead of manhatten distances as default.)
        self.distancer.getMazeDistances()

        self.classifier
Example #16
0
    def run(self):
        """
    Main control loop for game play.
    """
        self.display.initialize(self.state.data)
        distancer = distanceCalculator.Distancer(self.state.data.layout)
        # precompute the maze distances so one of the agents doesn't have to do so
        distancer.getMazeDistances()
        self.numMoves = 0

        ###self.display.initialize(self.state.makeObservation(1).data)
        # inform learning agents of the game start
        for i in range(len(self.agents)):
            agent = self.agents[i]
            if not agent:
                self.mute(i)
                # this is a null agent, meaning it failed to load
                # the other team wins
                print "Agent %d failed to load" % i
                self.unmute()
                self._agentCrash(i, quiet=True)
                return
            if ("registerInitialState" in dir(agent)):
                self.mute(i)
                if self.catchExceptions:
                    try:
                        timed_func = TimeoutFunction(
                            agent.registerInitialState,
                            int(self.rules.getMaxStartupTime(i)))
                        try:
                            start_time = time.time()
                            timed_func(self.state.deepCopy())
                            time_taken = time.time() - start_time
                            self.totalAgentTimes[i] += time_taken
                        except TimeoutFunctionException:
                            print "Agent %d ran out of time on startup!" % i
                            self.unmute()
                            self.agentTimeout = True
                            self._agentCrash(i, quiet=True)
                            return
                    except Exception, data:
                        self._agentCrash(i, quiet=False)
                        self.unmute()
                        return
                else:
                    agent.registerInitialState(self.state.deepCopy())
                ## TODO: could this exceed the total time
                self.unmute()
 def registerInitialState(self, gameState):
     """
 This method handles the initial setup of the
 agent to populate useful fields (such as what team
 we're on).
 A distanceCalculator instance caches the maze distances
 between each pair of positions, so your agents can use:
 self.distancer.getDistance(p1, p2)
 """
     self.red = gameState.isOnRedTeam(self.index)
     self.distancer = distanceCalculator.Distancer(gameState.data.layout)
     # comment this out to forgo maze distance computation and use manhattan distances
     self.distancer.getMazeDistances()
     import __main__
     if '_display' in dir(__main__):
         self.display = __main__._display
Example #18
0
    def registerInitialState(self, gameState):
        "Initial setups"
        self.red = gameState.isOnRedTeam(self.index)
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)
        self.distancer.getMazeDistances()

        import __main__
        if '_display' in dir(__main__):
            self.display = __main__._display

        self.inferenceModules = None
        self.firstMove = True

        # save some reused variables
        self.w = gameState.getWalls().width
        self.h = gameState.getWalls().height
Example #19
0
    def registerInitialState(self, gameState):
        """
    Initialize the beliefs of the enemies uniformly
    and many related operations
    """
        CaptureAgent.registerInitialState(self, gameState)

        global beliefs

        # legalPositions is a useful variable. it's not provided! let's construct it
        width = gameState.data.layout.width
        height = gameState.data.layout.height
        self.legalPositions = [(x, y) for x in range(width)
                               for y in range(height)
                               if not gameState.hasWall(x, y)]

        # set legalPositions for defending and offending respectively
        self.defensiveLegalPositions = [
            p for p in self.legalPositions if self.isOurTerrain(gameState, p)
        ]
        self.offensiveLegalPositions = [
            p for p in self.legalPositions
            if not (p in self.defensiveLegalPositions)
        ]

        # we need a new distancer for calculating distance within defensive area
        tmpGameState = gameState.deepCopy()
        defensiveLayout = tmpGameState.data.layout
        for pos in self.offensiveLegalPositions:
            defensiveLayout.walls[pos[0]][pos[1]] = True
        self.defensiveDistancer = distanceCalculator.Distancer(defensiveLayout)
        self.defensiveDistancer.getMazeDistances()

        # initialize beliefs according to legalPositions
        for enemyId in self.getOpponents(gameState):
            self.initializeBeliefs(gameState, enemyId, initial=True)

        # set availableActions for each grid
        self.setNeighbors(gameState)

        # set boundaries - entries of the enemy!
        self.setBoundary(gameState)

        # set trainsition model
        self.transition = util.Counter()
        self.transition['favor'] = 0.8
        self.transition['indifferent'] = 0.05
    def registerInitialState(self, gameState):
        # super(CaptureAgent1, self).registerInitialState(gameState)
        self.red = gameState.isOnRedTeam(self.index)
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)

        # comment this out to forgo maze distance computation and use manhattan distances
        self.distancer.getMazeDistances()

        import __main__
        if '_display' in dir(__main__):
            self.display = __main__._display

        self.walls = gameState.getWalls()
        self.legalPositions = [p for p in self.walls.asList(False) if p[1] > 0]
        self.babies = self.getFoodYouAreDefending(gameState).asList()
        self.beliefs = [
            util.Counter(),
            util.Counter(),
            util.Counter(),
            util.Counter()
        ]
        self.isPacman = [
            gameState.getAgentState(i).isPacman
            for i in range(gameState.getNumAgents())
        ]

        # Initialize zero position of the opponents, beliefs of the opponents and pacman_land - ghost_land of the opponents
        if self.red:
            self.opponentZeroPos = [(30, 14), (30, 13), (30, 12)]
            c = 0
            for idx in self.getOpponents(gameState):
                self.beliefs[idx][(30, 13 + c)] = 1
                c += 1
            self.pacman_land = 15
            self.ghost_land = 16
            self.going_left = -1
        else:
            self.opponentZeroPos = [(1, 1), (1, 2), (1, 3)]
            c = 1
            for idx in self.getOpponents(gameState):
                self.beliefs[idx][(1, 1 + c)] = 1
                c -= 1
            self.pacman_land = 16
            self.ghost_land = 15
            self.going_left = 1

        self.examineMaze(gameState)
Example #21
0
    def registerInitialState(self, gameState):
        self.start = gameState.getAgentPosition(self.index)
        CaptureAgent.registerInitialState(self, gameState)
        self.enemies = self.getOpponents(gameState)
        self.infer = InferenceModule(self)
        self.infer.initialize(gameState)

        grid = gameState.data.layout
        width = grid.width
        height = grid.height
        v_state = gameState.deepCopy()
        v_layout = v_state.data.layout
        ve_x = width / 2 if self.red else width / 2 - 1
        for y in range(0, height):
            v_layout.walls[ve_x][y] = True
        self.v_dist_obj = distanceCalculator.Distancer(v_layout)
        self.v_dist_obj.dc.run()
    def registerInitialState(self, gameState):
        CaptureAgent.registerInitialState(self, gameState)
        self.numagents = gameState.getNumAgents()
        #self.myindex =
        #self.mycolor =
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)
        self.distancer.getMazeDistances()

        self.walls = gameState.getWalls()
        self.legalpositions = self.getlegal(self.walls)

        self.oldfood = self.getFoodYouAreDefending(gameState)
        self.scared = False
        self.opponents = self.getOpponents(gameState)

        self.initializebeliefs(gameState)
        self.message = self.beliefs
  def registerInitialState(self, gameState):
    # super(CaptureAgent1, self).registerInitialState(gameState)
    self.red = gameState.isOnRedTeam(self.index)
    self.distancer = distanceCalculator.Distancer(gameState.data.layout)

    # comment this out to forgo maze distance computation and use manhattan distances
    self.distancer.getMazeDistances()

    import __main__
    if '_display' in dir(__main__):
      self.display = __main__._display

    # print self.distancer.isReadyForMazeDistance()
    # print self.display

    # print self.debugDraw(cells=, color=, clear=False)
    # print self.debugClear()

    # To show belief, for debugging
    # print self.displayDistributionsOverPositions()

    # Forget observations
    # print self.final()
    # print self.getCurrentObservation()
    # print self.getPreviousObservation()

    self.walls = gameState.getWalls()
    self.legalPositions = [p for p in self.walls.asList(False) if p[1] > 0]
    self.babies = self.getFoodYouAreDefending(gameState).asList()
    self.eaten = []
    self.beliefs = [util.Counter(), util.Counter(), util.Counter(), util.Counter()]
    self.isPacman = [gameState.getAgentState(i).isPacman for i in range(gameState.getNumAgents())]
    
    if self.red:
      self.opponentZeroPos = [(30, 14), (30, 13), (30, 12)]
      c = 0
      for idx in self.getOpponents(gameState):
        self.beliefs[idx][(30, 13 + c)] = 1
        c += 1
    else:
      self.opponentZeroPos = [(1, 1), (1, 2), (1, 3)]
      c = 1
      for idx in self.getOpponents(gameState):
        self.beliefs[idx][(1, 1 + c)] = 1
        c -= 1
Example #24
0
    def registerInitialState(self, gameState):
        self.start = gameState.getAgentPosition(self.index)
        CaptureAgent.registerInitialState(self, gameState)
        self.food = None
        self.totalFood = len(self.getFood(gameState).asList())
        self.startState = gameState

        foodList = self.getFood(gameState).asList()
        self.chooseFood(foodList)
        self.distancer = distanceCalculator.Distancer(gameState.data.layout)
        self.distancer.getMazeDistances()
        self.escape = 1
        self.defense = 2
        self.offense = 3
        self.status = self.offense
        self.goodFood = self.chooseGoodFood(foodList)
        self.save = False
        self.bound = gameState.data.layout.width / 2
        if gameState.isOnRedTeam(self.index):
            self.bound -= 1
Example #25
0
  def registerInitialState(self, gameState):
    """
    This method handles the initial setup of the
    agent to populate useful fields (such as what team
    we're on). 
    
    A distanceCalculator instance caches the maze distances
    between each pair of positions, so your agents can use:
    self.distancer.getDistance(p1, p2)

    IMPORTANT: This method may run for at most 15 seconds.
    """

    ''' 
    Make sure you do not delete the following line. If you would like to
    use Manhattan distances instead of maze distances in order to save
    on initialization time, please take a look at
    CaptureAgent.registerInitialState in captureAgents.py. 
    '''
    CaptureAgent.registerInitialState(self, gameState)
    self.distancer = distanceCalculator.Distancer(gameState.data.layout)
Example #26
0
 def registerInitialState(self, gameState):
   """
   This method handles the initial setup of the
   agent to populate useful fields (such as what team
   we're on).
   
   A distanceCalculator instance caches the maze distances 
   between each pair of positions, so your agents can use:
   self.distancer.getDistance(p1, p2)
   """
   self.red = gameState.isOnRedTeam(self.index)
   self.distancer = distanceCalculator.Distancer(gameState.data.layout)
   self.enemyIndices = self.getOpponents(gameState)
   
   # comment this out to forgo maze distance computation and use manhattan distances
   self.distancer.getMazeDistances()
   self.legalPositions = [p for p in gameState.getWalls().asList(False) if p[1] > 1]
   import __main__
   if '_display' in dir(__main__):
     self.display = __main__._display
   jointInference.initialize(gameState, self.legalPositions, self.enemyIndices, 300)
   self.beliefs = util.Counter()  
Example #27
0
    def registerInitialState(self, gameState):
        #print "PRINT 1"
        CaptureAgent.registerInitialState(self, gameState)
        self.isRed = gameState.isOnRedTeam(self.index)

        self.distances = distanceCalculator.Distancer(gameState.data.layout)
        self.distances.getMazeDistances()

        self.foodHolding = 0
        self.enemy1FoodHolding = 0

        ApproximateQAgent.__init__(self)
        self.startEpisode()
        #print "PRINT 2"

        self.fileName = "testFile" + str(self.index)
        if not os.path.isfile(self.fileName):
            for i in range(0, 20):
                print "404 FILE NOT FOUND ------------ ERROR ERROR ERROR ERROR ERROR ERROR ERROR "
            self.weights = util.Counter()
        else:
            myFile = open(self.fileName, "rb")
            unpickled = pickle.load(myFile)
            self.weights = unpickled
Example #28
0
  def getFeatures(self, gameState, action):

    self.gameState = gameState

    features = util.Counter()
    successor = self.getSuccessor(self.gameState, action)

    myState = successor.getAgentState(self.index)
    myPos = myState.getPosition()

    # self.isRed = False
    # if self.index%2 == 0:
    #   self.isRed = True
    # else:
    #   self.isRed = False

    # Computes whether we're on defense (1) or offense (0)
    features['onDefense'] = 1
    if myState.isPacman: features['onDefense'] = 0

    # state = self.gameState.deepCopy()
    # Adds the sonar signal
    pos = successor.getAgentPosition(self.index)
    n = successor.getNumAgents()
    # print 'getNumAgents()', n # 4
    distances = []

    # for i in range(n):
    #   if successor.getAgentPosition(i) != None:
    #     distances.append(noisyDistance(pos, successor.getAgentPosition(i)))

    # print 'distances', distances

    # distances = [noisyDistance(pos, state.getAgentPosition(i)) for i in range(n)]
    
    # state.agentDistances = distances

    # gState = self.gameState.makeObservation(self.index)
    
    dists = []

    # Computes distance to invaders we can see
    enemies = [successor.getAgentState(i) for i in self.getOpponents(successor)]
    # Invader: Enemy in the vision
    invaders = [a for a in enemies if a.isPacman and a.getPosition() != None]
    features['numInvaders'] = len(invaders)
    if len(invaders) > 0:
      # dists = [self.gameState.getMazeDistance(myPos, a.getPosition()) for a in invaders]
      # print 'invaders', invaders
      poss = [a.getPosition() for a in invaders]
      # print 'poss', poss
      # if self.distancer != None:
        # dists = [self.getMazeDistance(myPos, a.getPosition()) for a in invaders]
      dists = [self.getMazeDistance(myPos, a.getPosition()) for a in invaders]
      # dists = [super(DefenseAgent, self).getMazeDistance(myPos, a.getPosition()) for a in invaders]
      # dists = [distanceCalculator.Distancer(self.gameState.data.layout).getDistance(myPos, a.getPosition()) for a in invaders]
      
      if dists != []:
        features['invaderDistance'] = min(dists)
        # print 'min(dists)', min(dists)
      else:
        features['invaderDistance'] = 0

      # for i in self.getOpponents(successor):
      #   nd = noisyDistance(pos, successor.getAgentPosition(i))
      #   if nd > 0:
      #     print 'noisyDist', nd
      #     dists.append(nd)

      # print 'dists', dists
      # features['invaderDistance'] = min(dists)

    # else:
      # features['invaderDistance'] = min(distances)

    # #  Enemy index: 1, 3
    # for i in invaders:
    #   print '******Enemy Pos:', i.getPosition(), 'found by index', self.index
    # print 'Index', self.index, 'Defender Pos:', myPos     #  index 0

    if action == Directions.STOP: features['stop'] = 1
    rev = Directions.REVERSE[gameState.getAgentState(self.index).configuration.direction]
    if action == rev: features['reverse'] = 1


    # In the begining, leave home as far as possible
    ## print 'myPos', myPos
    startPos = gameState.getInitialAgentPosition(self.index)
    # startPos = (1.0, 1.0)
    ## print 'startPos', startPos
    if len(invaders) > 0:
      features['distToHome'] = 0
    else:
      features['distToHome'] = distanceCalculator.Distancer(gameState.data.layout).getDistance(startPos, myPos)
      # features['distToHome'] = self.getMazeDistance(self.startPosition,myPos)
      # features['distToHome'] = self.getMazeDistance(startPos, myPos)
      # features['distToHome'] = self.getMazeDistance(self.start, myPos)


    if self.getIsRed():
      centralX = (gameState.data.layout.width - 2)/2
    else:
      centralX = ((gameState.data.layout.width - 2)/2) + 1

    centralY = (gameState.data.layout.height)/2
    centralPos = (centralX, centralY)

    if len(invaders) > 0:
      features['distToCentral'] = 0
    else:
      features['distToCentral'] = distanceCalculator.Distancer(gameState.data.layout).getDistance(centralPos, myPos)
    

    features['distToHome'] = 0
    features['distToCentral'] = 0

    return features
Example #29
0
 def registerInitialState(self, gameState):
     self.red = gameState.isOnRedTeam(self.index)
     self.distancer = distanceCalculator.Distancer(gameState.data.layout)
     self.distancer.getMazeDistances()
     self.getLegalPositions(gameState)
     self.initializeBeliefDistributions(gameState)
Example #30
0
  def __init__(self, gameState, agent, forRed):
    """
    Constructor.
    """
    if forRed and PositionEstimator.red is None:
      self.width = gameState.data.layout.width
      self.height = gameState.data.layout.height

      self.walls = gameState.getWalls()
      self.walkablePositions = self.getWalkablePositions()
      self.distancer = distanceCalculator.Distancer(gameState.data.layout)

      self.numPlayers = gameState.getNumAgents()
      self.team = agent.getTeam(gameState) # assume only 1 teammate, also assume smaller index will be created first
      self.opponents = agent.getOpponents(gameState) # do we need to store this? since we are passing agent into update

      ######################
      # book keeping facts #
      ######################  
      self.isPacman = [False for i in range(self.numPlayers)]
      self.isScared = [0 for i in range(self.numPlayers)]
      self.lastSeenPos = [gameState.getInitialAgentPosition(i) for i in range(self.numPlayers)]
      self.lastCarrying = [0 for i in range(self.numPlayers)]
      self.lastScore = [0, 0]
      self.updateBookKeepingFacts(gameState)
      # self.updateBookKeepingFacts(gameState)
      # self.noisyProb = gameState.getDistanceProb(0, gameState.getAgentDistances()[agent.index])

      self.estimations = self.getInitialEstimations(gameState)
      self.prevDefending = PositionEstimator.getAllDefendingItems(gameState, agent)
      self.lastUpdatePlayer = agent.index
      PositionEstimator.red = self

    elif not forRed and PositionEstimator.blue is None:
      self.width = gameState.data.layout.width
      self.height = gameState.data.layout.height

      self.walls = gameState.getWalls()
      self.walkablePositions = self.getWalkablePositions()
      self.distancer = distanceCalculator.Distancer(gameState.data.layout)

      self.numPlayers = gameState.getNumAgents()
      self.team = agent.getTeam(gameState) # assume only 1 teammate, also assume smaller index will be created first
      self.opponents = agent.getOpponents(gameState) # do we need to store this? since we are passing agent into update

      ######################
      # book keeping facts #
      ######################
      self.isPacman = [False for i in range(self.numPlayers)]
      self.isScared = [0 for i in range(self.numPlayers)]
      self.lastSeenPos = [gameState.getInitialAgentPosition(i) for i in range(self.numPlayers)]
      self.lastCarrying = [0 for i in range(self.numPlayers)]
      self.lastScore = [0, 0]
      self.updateBookKeepingFacts(gameState)
      # self.updateBookKeepingFacts(gameState)
      # self.noisyProb = gameState.getDistanceProb(0, gameState.getAgentDistances()[agent.index])

      self.estimations = self.getInitialEstimations(gameState)
      self.prevDefending = PositionEstimator.getAllDefendingItems(gameState, agent)
      self.lastUpdatePlayer = agent.index
      PositionEstimator.blue = self