Module pacai.agents.keyboard

Expand source code
from pacai.agents.base import BaseAgent
from pacai.core.directions import Directions

class BaseKeyboardAgent(BaseAgent):
    """
    An general agent controlled by the keyboard.
    """

    def __init__(self, index = 0, keyboard = None, directionalKeys = {}, **kwargs):
        """
        directionalKeys is a dict of direction to keys for that direction.
        """

        super().__init__(index, **kwargs)

        self._keyboard = keyboard
        self._lastMove = Directions.STOP
        self._directionalKeys = directionalKeys

        # The keys that we are explictly looking for,
        self._queryKeys = set()
        for keys in self._directionalKeys.values():
            for key in keys:
                self._queryKeys.add(key)

    def getAction(self, state):
        # Note that we delay this check (instead of doing it in the constructor)
        # so that replays can create any agent and not worry about a GUI.
        if (self._keyboard is None):
            raise ValueError("Keyboard agents require a pacai.ui.keyboard.Keyboard.")

        intended_action = None
        legal = state.getLegalActions(self.index)

        keys = self._keyboard.query(self._queryKeys)
        if (keys != []):
            intended_action = self._translateKey(keys)
            if (intended_action not in legal):
                # The keyed action is illegal, ignore the key press.
                intended_action = None

        # If we have no intended action, try to do what we did last time.
        if (intended_action is None):
            intended_action = self._lastMove

        # If the final action is illegal, just stop.
        if (intended_action not in legal):
            intended_action = Directions.STOP

        self._lastMove = intended_action

        return intended_action

    def _translateKey(self, keysPressed):
        """
        Convert key presses into Directions (e.g. Directions.WEST).
        """

        for key in reversed(keysPressed):
            for (direction, possibleKeys) in self._directionalKeys.items():
                if (key in possibleKeys):
                    return direction

        return None

class WASDKeyboardAgent(BaseKeyboardAgent):
    """
    An agent controlled by WASD or the arrow keys.
    """

    KEYS = {
        Directions.NORTH: ['w', 'Up'],
        Directions.WEST: ['a', 'Left'],
        Directions.SOUTH: ['s', 'Down'],
        Directions.EAST: ['d', 'Right'],
    }

    def __init__(self, index = 0, keyboard = None, **kwargs):
        super().__init__(index, keyboard, WASDKeyboardAgent.KEYS, **kwargs)

class IJKLKeyboardAgent(BaseKeyboardAgent):
    """
    An agent controlled by IJKL.
    """

    KEYS = {
        Directions.NORTH: ['i'],
        Directions.WEST: ['j'],
        Directions.SOUTH: ['k'],
        Directions.EAST: ['l'],
    }

    def __init__(self, index = 0, keyboard = None, **kwargs):
        super().__init__(index, keyboard, IJKLKeyboardAgent.KEYS, **kwargs)

Classes

class BaseKeyboardAgent (index=0, keyboard=None, directionalKeys={}, **kwargs)

An general agent controlled by the keyboard.

directionalKeys is a dict of direction to keys for that direction.

Expand source code
class BaseKeyboardAgent(BaseAgent):
    """
    An general agent controlled by the keyboard.
    """

    def __init__(self, index = 0, keyboard = None, directionalKeys = {}, **kwargs):
        """
        directionalKeys is a dict of direction to keys for that direction.
        """

        super().__init__(index, **kwargs)

        self._keyboard = keyboard
        self._lastMove = Directions.STOP
        self._directionalKeys = directionalKeys

        # The keys that we are explictly looking for,
        self._queryKeys = set()
        for keys in self._directionalKeys.values():
            for key in keys:
                self._queryKeys.add(key)

    def getAction(self, state):
        # Note that we delay this check (instead of doing it in the constructor)
        # so that replays can create any agent and not worry about a GUI.
        if (self._keyboard is None):
            raise ValueError("Keyboard agents require a pacai.ui.keyboard.Keyboard.")

        intended_action = None
        legal = state.getLegalActions(self.index)

        keys = self._keyboard.query(self._queryKeys)
        if (keys != []):
            intended_action = self._translateKey(keys)
            if (intended_action not in legal):
                # The keyed action is illegal, ignore the key press.
                intended_action = None

        # If we have no intended action, try to do what we did last time.
        if (intended_action is None):
            intended_action = self._lastMove

        # If the final action is illegal, just stop.
        if (intended_action not in legal):
            intended_action = Directions.STOP

        self._lastMove = intended_action

        return intended_action

    def _translateKey(self, keysPressed):
        """
        Convert key presses into Directions (e.g. Directions.WEST).
        """

        for key in reversed(keysPressed):
            for (direction, possibleKeys) in self._directionalKeys.items():
                if (key in possibleKeys):
                    return direction

        return None

Ancestors

Subclasses

Static methods

def loadAgent(name, index, args={})

Inherited from: BaseAgent.loadAgent

Load an agent with the given class name. The name can be fully qualified or just the bare class name. If the bare name is given, the class should …

Methods

def final(self, state)

Inherited from: BaseAgent.final

Inform the agent about the result of a game.

def getAction(self, state)

Inherited from: BaseAgent.getAction

The BaseAgent will receive an AbstractGameState, and must return an action from Directions.

Expand source code
def getAction(self, state):
    # Note that we delay this check (instead of doing it in the constructor)
    # so that replays can create any agent and not worry about a GUI.
    if (self._keyboard is None):
        raise ValueError("Keyboard agents require a pacai.ui.keyboard.Keyboard.")

    intended_action = None
    legal = state.getLegalActions(self.index)

    keys = self._keyboard.query(self._queryKeys)
    if (keys != []):
        intended_action = self._translateKey(keys)
        if (intended_action not in legal):
            # The keyed action is illegal, ignore the key press.
            intended_action = None

    # If we have no intended action, try to do what we did last time.
    if (intended_action is None):
        intended_action = self._lastMove

    # If the final action is illegal, just stop.
    if (intended_action not in legal):
        intended_action = Directions.STOP

    self._lastMove = intended_action

    return intended_action
def observationFunction(self, state)

Inherited from: BaseAgent.observationFunction

Make an observation on the state of the game. Called once for each round of the game.

def registerInitialState(self, state)

Inherited from: BaseAgent.registerInitialState

Inspect the starting state.

class IJKLKeyboardAgent (index=0, keyboard=None, **kwargs)

An agent controlled by IJKL.

directionalKeys is a dict of direction to keys for that direction.

Expand source code
class IJKLKeyboardAgent(BaseKeyboardAgent):
    """
    An agent controlled by IJKL.
    """

    KEYS = {
        Directions.NORTH: ['i'],
        Directions.WEST: ['j'],
        Directions.SOUTH: ['k'],
        Directions.EAST: ['l'],
    }

    def __init__(self, index = 0, keyboard = None, **kwargs):
        super().__init__(index, keyboard, IJKLKeyboardAgent.KEYS, **kwargs)

Ancestors

Class variables

var KEYS

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Static methods

def loadAgent(name, index, args={})

Inherited from: BaseKeyboardAgent.loadAgent

Load an agent with the given class name. The name can be fully qualified or just the bare class name. If the bare name is given, the class should …

Methods

def final(self, state)

Inherited from: BaseKeyboardAgent.final

Inform the agent about the result of a game.

def getAction(self, state)

Inherited from: BaseKeyboardAgent.getAction

The BaseAgent will receive an AbstractGameState, and must return an action from Directions.

def observationFunction(self, state)

Inherited from: BaseKeyboardAgent.observationFunction

Make an observation on the state of the game. Called once for each round of the game.

def registerInitialState(self, state)

Inherited from: BaseKeyboardAgent.registerInitialState

Inspect the starting state.

class WASDKeyboardAgent (index=0, keyboard=None, **kwargs)

An agent controlled by WASD or the arrow keys.

directionalKeys is a dict of direction to keys for that direction.

Expand source code
class WASDKeyboardAgent(BaseKeyboardAgent):
    """
    An agent controlled by WASD or the arrow keys.
    """

    KEYS = {
        Directions.NORTH: ['w', 'Up'],
        Directions.WEST: ['a', 'Left'],
        Directions.SOUTH: ['s', 'Down'],
        Directions.EAST: ['d', 'Right'],
    }

    def __init__(self, index = 0, keyboard = None, **kwargs):
        super().__init__(index, keyboard, WASDKeyboardAgent.KEYS, **kwargs)

Ancestors

Class variables

var KEYS

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Static methods

def loadAgent(name, index, args={})

Inherited from: BaseKeyboardAgent.loadAgent

Load an agent with the given class name. The name can be fully qualified or just the bare class name. If the bare name is given, the class should …

Methods

def final(self, state)

Inherited from: BaseKeyboardAgent.final

Inform the agent about the result of a game.

def getAction(self, state)

Inherited from: BaseKeyboardAgent.getAction

The BaseAgent will receive an AbstractGameState, and must return an action from Directions.

def observationFunction(self, state)

Inherited from: BaseKeyboardAgent.observationFunction

Make an observation on the state of the game. Called once for each round of the game.

def registerInitialState(self, state)

Inherited from: BaseKeyboardAgent.registerInitialState

Inspect the starting state.