Module pacai.bin.capture

Capture is a variant of pacman where two teams face off. The goal is to eat more food than your opponent. On your side of the map, you are a ghost and can eat pacmen. On your opponents side of the map, you are a pacman and can eat food and capsules.

Functions

def loadAgents(isRed, agentModule, textgraphics, args)

Calls agent factories and returns lists of agents.

def main(argv)

Entry point for a capture game. The args are a blind pass of sys.argv with the executable stripped.

def parseAgentArgs(str)
def readCommand(argv)

Processes the command used to run capture from the command line.

def replayGame(layout, agents, actions, display, length, redTeamName, blueTeamName)
def runGames(layout, agents, display, length, numGames, record, numTraining, redTeamName, blueTeamName, catchExceptions=False, **kwargs)

Classes

class AgentRules

These functions govern how each agent interacts with her environment.

Expand source code
class AgentRules:
    """
    These functions govern how each agent interacts with her environment.
    """

    AGENT_SPEED = 1.0

    @staticmethod
    def getLegalActions(state, agentIndex):
        """
        Returns a list of possible actions.
        """

        agentState = state.getAgentState(agentIndex)
        return Actions.getPossibleActions(agentState.getPosition(), agentState.getDirection(),
                state.getWalls())

    @staticmethod
    def applyAction(state, action, agentIndex):
        """
        Edits the state to reflect the results of the action.
        """

        legal = AgentRules.getLegalActions(state, agentIndex)
        if (action not in legal):
            raise ValueError('Illegal action: ' + str(action))

        agentState = state.getAgentState(agentIndex)

        # Update position.
        vector = Actions.directionToVector(action, AgentRules.AGENT_SPEED)
        agentState.updatePosition(vector)

        # Eat.
        nextPosition = agentState.getPosition()
        nearest = nearestPoint(nextPosition)
        if (agentState.isPacman() and manhattan(nearest, nextPosition) <= 0.9):
            AgentRules.consume(nearest, state, state.isOnRedTeam(agentIndex))

        # Potentially change agent type.
        if (nextPosition == nearest):
            # Agents are pacmen when they are not on their own side.
            position = agentState.getPosition()
            agentState.setIsPacman(state.isOnRedTeam(agentIndex) != state.isOnRedSide(position))

    @staticmethod
    def consume(position, state, isRed):
        """
        There is an agent of the specified team on the given position.
        If there is anything they can eat, do it.
        Note that the consuming agent is guarenteed to be in pacman form (not ghost form).
        """

        x, y = position

        # Eat food.
        if (state.hasFood(x, y)):
            state.eatFood(x, y)

            if (isRed):
                state.addScore(FOOD_POINTS)
            else:
                state.addScore(-FOOD_POINTS)

            if ((isRed and state.getBlueFood().count() <= MIN_FOOD)
                    or (not isRed and state.getRedFood().count() <= MIN_FOOD)):
                state.endGame(True)

            return

        # Eat a capsule.
        if (isRed):
            myCapsules = state.getBlueCapsules()
        else:
            myCapsules = state.getRedCapsules()

        if (position in myCapsules):
            state.eatCapsule(x, y)

            # Reset ghosts' scared timers.
            if (isRed):
                otherTeam = state.getBlueTeamIndices()
            else:
                otherTeam = state.getRedTeamIndices()

            for agentIndex in otherTeam:
                state.getAgentState(agentIndex).setScaredTimer(SCARED_TIME)

    @staticmethod
    def decrementTimer(agentState):
        if (not agentState.isScared()):
            return

        agentState.decrementScaredTimer()
        if (not agentState.isScared()):
            # If the ghost is done being scared, snap it to the closest point.
            agentState.snapToNearestPoint()

    @staticmethod
    def checkDeath(state, agentIndex):
        agentState = state.getAgentState(agentIndex)

        if (state.isOnRedTeam(agentIndex)):
            teamPointModifier = 1
            otherTeam = state.getBlueTeamIndices()
        else:
            teamPointModifier = -1
            otherTeam = state.getRedTeamIndices()

        for otherAgentIndex in otherTeam:
            otherAgentState = state.getAgentState(otherAgentIndex)

            # Ignore agents with a matching type (e.g. two ghosts).
            if (agentState.isPacman() == otherAgentState.isPacman()):
                continue

            otherPosition = otherAgentState.getPosition()

            # Ignore other agents that are too far away.
            if (otherPosition is None
                    or manhattan(otherPosition, agentState.getPosition()) > COLLISION_TOLERANCE):
                continue

            # If we are a brave ghost or they are a scared ghost, then we will eat them.
            # Otherwise, we are being eatten.
            if (agentState.isBraveGhost() or otherAgentState.isScaredGhost()):
                state.addScore(teamPointModifier * KILL_POINTS)
                otherAgentState.respawn()
            else:
                state.addScore(teamPointModifier * -KILL_POINTS)
                agentState.respawn()

Class variables

var AGENT_SPEED

Static methods

def applyAction(state, action, agentIndex)

Edits the state to reflect the results of the action.

def checkDeath(state, agentIndex)
def consume(position, state, isRed)

There is an agent of the specified team on the given position. If there is anything they can eat, do it. Note that the consuming agent is guarenteed to be in pacman form (not ghost form).

def decrementTimer(agentState)
def getLegalActions(state, agentIndex)

Returns a list of possible actions.

class CaptureGameState (layout, timeleft)

A game state specific to capture.

Expand source code
class CaptureGameState(AbstractGameState):
    """
    A game state specific to capture.
    """

    def __init__(self, layout, timeleft):
        super().__init__(layout)

        self._timeleft = timeleft

        # The index of agents on each team.
        self._blueTeam = []
        self._redTeam = []

        # Matches indexes with getAgentStates().
        # True if the agent is on the red team, false otherwise.
        self._teams = []

        for agentIndex in range(self.getNumAgents()):
            agentState = self.getAgentState(agentIndex)
            agentIsRed = self.isOnRedSide(agentState.getPosition())

            self._teams.append(agentIsRed)

            if (agentIsRed):
                self._redTeam.append(agentIndex)
            else:
                self._blueTeam.append(agentIndex)

        # Build some denormalized structures for fast access.

        self._redCapsules = []
        self._blueCapsules = []

        for capsule in self.getCapsules():
            if (self.isOnRedSide(capsule)):
                self._redCapsules.append(capsule)
            else:
                self._blueCapsules.append(capsule)

        self._redFood = Grid(self._food.getWidth(), self._food.getHeight(), initialValue = False)
        self._blueFood = Grid(self._food.getWidth(), self._food.getHeight(), initialValue = False)

        for x in range(self._food.getWidth()):
            for y in range(self._food.getHeight()):
                if (not self._food[x][y]):
                    continue

                if (self.isOnRedSide((x, y))):
                    self._redFood[x][y] = True
                else:
                    self._blueFood[x][y] = True

    # Override
    def generateSuccessor(self, agentIndex, action):
        # Check that successors exist.
        if (self.isOver()):
            raise RuntimeError("Can't generate successors of a terminal state.")

        successor = self._initSuccessor()
        successor._applySuccessorAction(agentIndex, action)

        return successor

    # Override
    def getLegalActions(self, agentIndex = 0):
        if (self.isOver()):
            return []

        return AgentRules.getLegalActions(self, agentIndex)

    # Override
    def eatCapsule(self, x, y):
        if (not self._capsulesCopied):
            self._redCapsules = self._redCapsules.copy()
            self._blueCapsules = self._blueCapsules.copy()

        super().eatCapsule(x, y)

        if (self.isOnRedSide((x, y))):
            self._redCapsules.remove((x, y))
        else:
            self._blueCapsules.remove((x, y))

    # Override
    def eatFood(self, x, y):
        if (not self._foodCopied):
            self._redFood = self._redFood.copy()
            self._blueFood = self._blueFood.copy()

        super().eatFood(x, y)

        if (self.isOnRedSide((x, y))):
            self._redFood[x][y] = False
        else:
            self._blueFood[x][y] = False

    def getBlueCapsules(self):
        """
        Get a list of remaining capsules on the blue side.
        The caller should not modify the list.
        """

        return self._blueCapsules

    def getBlueFood(self):
        """
        Returns a grid of food that corresponds to the food on the blue team's side.
        For the grid g, g[x][y] = True if there is food in (x, y) that belongs to
        blue (meaning blue is protecting it, red is trying to eat it).
        The caller should not modify the grid.
        """

        return self._blueFood

    def getBlueTeamIndices(self):
        """
        Returns a list of the agent index numbers for the agents on the blue team.
        The caller should not modify the list.
        """

        return self._blueTeam

    def getRedCapsules(self):
        """
        Get a list of remaining capsules on the red side.
        The caller should not modify the list.
        """

        return self._redCapsules

    def getRedFood(self):
        """
        Returns a grid of food that corresponds to the food on the red team's side.
        For the grid g, g[x][y] = True if there is food in (x, y) that belongs to
        red (meaning red is protecting it, blue is trying to eat it).
        The caller should not modify the grid.
        """

        return self._redFood

    def getRedTeamIndices(self):
        """
        Returns a list of agent index numbers for the agents on the red team.
        The caller should not modify the list.
        """

        return self._redTeam

    def getTimeleft(self):
        return self._timeleft

    def isOnBlueSide(self, position):
        """
        Check the position see if it is on the blue side.
        Note that this is not checking if a position/agent is on the blue TEAM,
        just the blue side of the board.
        Red is on the left side, blue on the right.
        """

        return not self.isOnRedSide(position)

    def isOnBlueTeam(self, agentIndex):
        """
        Returns true if the agent with the given agentIndex is on the red team.
        """

        return not self.isOnRedTeam(agentIndex)

    def isOnRedSide(self, position):
        """
        Check the position see if it is on the red side.
        Note that this is not checking if a position/agent is on the red TEAM,
        just the red side of the board.
        Red is on the left side, blue on the right.
        """

        return position[0] < int(self._layout.width / 2)

    def isOnRedTeam(self, agentIndex):
        """
        Returns true if the agent with the given agentIndex is on the red team.
        """

        return self._teams[agentIndex]

    def _applySuccessorAction(self, agentIndex, action):
        """
        Apply the action to the context state (self).
        """

        # Find appropriate rules for the agent.
        AgentRules.applyAction(self, action, agentIndex)
        AgentRules.checkDeath(self, agentIndex)
        AgentRules.decrementTimer(self.getAgentState(agentIndex))

        # Book keeping.
        self._lastAgentMoved = agentIndex
        self._timeleft -= 1

        self._hash = None

Ancestors

Methods

def eatCapsule(self, x, y)

Inherited from: AbstractGameState.eatCapsule

Mark the capsule at the given location as eaten.

def eatFood(self, x, y)

Inherited from: AbstractGameState.eatFood

Mark the food at the given location as eaten.

def generateSuccessor(self, agentIndex, action)

Inherited from: AbstractGameState.generateSuccessor

Returns the successor state after the specified agent takes the action. Treat the returned state as a SHALLOW copy that has been modified.

def getAgentPosition(self, index)

Inherited from: AbstractGameState.getAgentPosition

Returns a location tuple of the agent with the given index. It is possible for this method to return None if the agent's position is unknown (like if …

def getBlueCapsules(self)

Get a list of remaining capsules on the blue side. The caller should not modify the list.

def getBlueFood(self)

Returns a grid of food that corresponds to the food on the blue team's side. For the grid g, g[x][y] = True if there is food in (x, y) that belongs to blue (meaning blue is protecting it, red is trying to eat it). The caller should not modify the grid.

def getBlueTeamIndices(self)

Returns a list of the agent index numbers for the agents on the blue team. The caller should not modify the list.

def getCapsules(self)

Inherited from: AbstractGameState.getCapsules

Returns a list of positions (x, y) of the remaining capsules.

def getFood(self)

Inherited from: AbstractGameState.getFood

Returns a Grid of boolean food indicator variables …

def getInitialLayout(self)

Inherited from: AbstractGameState.getInitialLayout

Get the initial layout this state starte with. User's should typically call one of the more detailed methods directly, e.g. getWalls().

def getLegalActions(self, agentIndex=0)

Inherited from: AbstractGameState.getLegalActions

Gets the legal actions for the agent specified.

def getNumCapsules(self)

Inherited from: AbstractGameState.getNumCapsules

Get the amount of capsules left on the board.

def getNumFood(self)

Inherited from: AbstractGameState.getNumFood

Get the amount of food left on the board.

def getRedCapsules(self)

Get a list of remaining capsules on the red side. The caller should not modify the list.

def getRedFood(self)

Returns a grid of food that corresponds to the food on the red team's side. For the grid g, g[x][y] = True if there is food in (x, y) that belongs to red (meaning red is protecting it, blue is trying to eat it). The caller should not modify the grid.

def getRedTeamIndices(self)

Returns a list of agent index numbers for the agents on the red team. The caller should not modify the list.

def getTimeleft(self)
def getWalls(self)

Inherited from: AbstractGameState.getWalls

Returns a Grid of boolean wall indicator variables …

def hasCapsule(self, x, y)

Inherited from: AbstractGameState.hasCapsule

Returns true if the location (x, y) has a capsule.

def hasFood(self, x, y)

Inherited from: AbstractGameState.hasFood

Returns true if the location (x, y) has food.

def hasWall(self, x, y)

Inherited from: AbstractGameState.hasWall

Returns true if (x, y) has a wall, false otherwise.

def isOnBlueSide(self, position)

Check the position see if it is on the blue side. Note that this is not checking if a position/agent is on the blue TEAM, just the blue side of the board. Red is on the left side, blue on the right.

def isOnBlueTeam(self, agentIndex)

Returns true if the agent with the given agentIndex is on the red team.

def isOnRedSide(self, position)

Check the position see if it is on the red side. Note that this is not checking if a position/agent is on the red TEAM, just the red side of the board. Red is on the left side, blue on the right.

def isOnRedTeam(self, agentIndex)

Returns true if the agent with the given agentIndex is on the red team.

class CaptureRules

These game rules manage the control flow of a game, deciding when and how the game starts and ends.

Expand source code
class CaptureRules:
    """
    These game rules manage the control flow of a game, deciding when
    and how the game starts and ends.
    """

    def newGame(self, layout, agents, display, length, catchExceptions):
        initState = CaptureGameState(layout, length)
        starter = random.randint(0, 1)
        logging.info('%s team starts' % ['Red', 'Blue'][starter])
        game = Game(agents, display, self, startingIndex = starter,
                catchExceptions = catchExceptions)
        game.state = initState
        game.length = length

        self._totalBlueFood = initState.getBlueFood().count()
        self._totalRedFood = initState.getRedFood().count()

        return game

    def process(self, state, game):
        """
        Checks to see whether it is time to end the game.
        """

        # The two ways a game can end is by eatting food or a timeout.
        # The timeout endgame will be discovered here,
        # and the food endgame will be triggered elsewhere.
        # So, to continue in this method the game must be over (by food),
        # or the time must be out.

        if (not state.isOver() and state.getTimeleft() > 0):
            return

        game.gameOver = True

        redWin = False
        blueWin = False

        if (state.getRedFood().count() <= MIN_FOOD):
            logging.info("The Blue team ate all but %d of the opponents' dots." % MIN_FOOD)
            blueWin = True
        elif (state.getBlueFood().count() <= MIN_FOOD):
            logging.info("The Red team ate all but %d of the opponents' dots." % MIN_FOOD)
            redWin = True
        else:
            logging.info('Time is up.')

            if (state.getScore() < 0):
                blueWin = True
            elif (state.getScore() > 0):
                redWin = True

        if (not redWin and not blueWin):
            logging.info('Tie game!')
            state.endGame(False)
            return

        winner = 'Red'
        if (blueWin):
            winner = 'Blue'

        logging.info('The %s team wins by %d points.' % (winner, abs(state.getScore())))
        state.endGame(True)

    def agentCrash(self, game, agentIndex):
        if (game.state.isOnRedTeam(agentIndex)):
            logging.error("Red agent crashed.")
            game.state.setScore(-1)
        else:
            logging.error("Blue agent crashed.")
            game.state.setScore(1)

    def getMaxTotalTime(self, agentIndex):
        return 900  # Move limits should prevent this from ever happening

    def getMaxStartupTime(self, agentIndex):
        return 15  # 15 seconds for registerInitialState

    def getMoveWarningTime(self, agentIndex):
        return 1  # One second per move

    def getMoveTimeout(self, agentIndex):
        return 3  # Three seconds results in instant forfeit

    def getMaxTimeWarnings(self, agentIndex):
        return 2  # Third violation loses the game

Methods

def agentCrash(self, game, agentIndex)
def getMaxStartupTime(self, agentIndex)
def getMaxTimeWarnings(self, agentIndex)
def getMaxTotalTime(self, agentIndex)
def getMoveTimeout(self, agentIndex)
def getMoveWarningTime(self, agentIndex)
def newGame(self, layout, agents, display, length, catchExceptions)
def process(self, state, game)

Checks to see whether it is time to end the game.