Ejemplo n.º 1
0
def readCommand(argv):
    """
    Processes the command used to run capture from the command line.
    """

    description = """
    DESCRIPTION:
        This program will run a capture game. Two teams of pacman agents are pitted against
        one another in a capture the flag style game. Collect the most pellets to win!

    EXAMPLES:
        (1) python -m pacai.bin.capture
          - Starts a game with two baseline agents.
        (2) python -m pacai.bin.capture --keys0
          - Starts an interactive game where the arrow keys control agent 0 and all other
            agents are baseline agents.
        (3) python -m pacai.bin.capture.py -r pacai.core.baselineTeam -b pacai.student.myTeam
          - Starts an automated game where the red team is a baseline team and blue
            team is pacai.student.myTeam.
    """

    parser = getParser(description, os.path.basename(__file__))

    parser.add_argument('-b', '--blue', dest = 'blue',
            action = 'store', type = str, default = 'pacai.core.baselineTeam',
            help = 'set blue team (default: %(default)s)')

    parser.add_argument('-l', '--layout', dest = 'layout',
            action = 'store', type = str, default = 'defaultCapture',
            help = 'use the specified map layout or input RANDOM<seed> '
                + 'for a random seeded map (i.e. RANDOM23) (default: %(default)s)')

    parser.add_argument('-r', '--red', dest = 'red',
            action = 'store', type = str, default = 'pacai.core.baselineTeam',
            help = 'set red team (default: %(default)s)')

    parser.add_argument('--blue-args', dest = 'blueArgs',
            action = 'store', type = str, default = None,
            help = 'comma separated arguments to be passed to blue team (e.g. \'opt1=val1,opt2\') '
                + '(default: %(default)s)')

    parser.add_argument('--keys0', dest = 'keys0',
            action = 'store_true', default = False,
            help = 'make agent 0 (first red player) a keyboard agent (default: %(default)s)')

    parser.add_argument('--keys1', dest = 'keys1',
            action = 'store_true', default = False,
            help = 'make agent 1 (first blue player) a keyboard agent (default: %(default)s)')

    parser.add_argument('--keys2', dest = 'keys2',
            action = 'store_true', default = False,
            help = 'make agent 2 (second red player) a keyboard agent (default: %(default)s)')

    parser.add_argument('--keys3', dest = 'keys3',
            action = 'store_true', default = False,
            help = 'make agent 3 (second blue player) a keyboard agent (default: %(default)s)')

    parser.add_argument('--max-moves', dest = 'maxMoves',
            action = 'store', type = int, default = 1200,
            help = 'set maximum number of moves in a game (default: %(default)s)')

    parser.add_argument('--red-args', dest = 'redArgs',
            action = 'store', type = str, default = None,
            help = 'comma separated arguments to be passed to red team (e.g. \'opt1=val1,opt2\') '
                + '(default: %(default)s)')

    options, otherjunk = parser.parse_known_args(argv)
    args = dict()

    if len(otherjunk) != 0:
        raise ValueError('Unrecognized options: \'%s\'.' % (str(otherjunk)))

    # Set the logging level.
    if options.quiet and options.debug:
        raise ValueError('Logging cannont be set to both debug and quiet.')

    if options.quiet:
        updateLoggingLevel(logging.WARNING)
    elif options.debug:
        updateLoggingLevel(logging.DEBUG)

    viewOptions = {
        'gifFPS': options.gifFPS,
        'gifPath': options.gif,
        'skipFrames': options.gifSkipFrames,
        'spritesPath': options.spritesPath,
    }

    # Choose a display format.
    if options.textGraphics:
        args['display'] = CaptureTextView(**viewOptions)
    elif options.nullGraphics:
        args['display'] = CaptureNullView(**viewOptions)
    else:
        # Defer importing the GUI unless we actually need it.
        # This allows people to not have tkinter installed.
        from pacai.ui.capture.gui import CaptureGUIView

        args['display'] = CaptureGUIView(fps = options.fps, title = 'Capture', **viewOptions)

    args['redTeamName'] = options.red
    args['blueTeamName'] = options.blue

    # If no seed entry generate a random seed value.
    seed = options.seed
    if seed is None:
        seed = random.randint(0, 2**32)
    random.seed(seed)
    logging.debug('Seed value: ' + str(seed))

    # Choose a pacman agent.
    redArgs = parseAgentArgs(options.redArgs)
    blueArgs = parseAgentArgs(options.blueArgs)

    if options.numTraining > 0:
        redArgs['numTraining'] = options.numTraining
        blueArgs['numTraining'] = options.numTraining

    nokeyboard = options.textGraphics or options.nullGraphics or options.numTraining > 0
    logging.debug('\nRed team %s with %s:' % (options.red, redArgs))
    redAgents = loadAgents(True, options.red, nokeyboard, redArgs)
    logging.debug('\nBlue team %s with %s:' % (options.blue, blueArgs))
    blueAgents = loadAgents(False, options.blue, nokeyboard, blueArgs)
    args['agents'] = sum([list(el) for el in zip(redAgents, blueAgents)], [])  # List of agents.

    numKeyboardAgents = 0
    for index, val in enumerate([options.keys0, options.keys1, options.keys2, options.keys3]):
        if (not val):
            continue

        if (numKeyboardAgents == 0):
            agent = keyboard.WASDKeyboardAgent(index, keyboard = args['display'].getKeyboard())
        elif (numKeyboardAgents == 1):
            agent = keyboard.IJKLKeyboardAgent(index, keyboard = args['display'].getKeyboard())
        else:
            raise ValueError('Max of two keyboard agents supported.')

        numKeyboardAgents += 1
        args['agents'][index] = agent

    # Choose a layout.
    if options.layout.startswith('RANDOM'):
        layoutSeed = None
        if (options.layout != 'RANDOM'):
            layoutSeed = int(options.layout[6:])

        args['layout'] = Layout(generateMaze(layoutSeed).split('\n'))
    elif options.layout.lower().find('capture') == -1:
        raise ValueError('You must use a capture layout with capture.py.')
    else:
        args['layout'] = getLayout(options.layout)

    if (args['layout'] is None):
        raise ValueError('The layout ' + options.layout + ' cannot be found.')

    args['length'] = options.maxMoves
    args['numGames'] = options.numGames
    args['numTraining'] = options.numTraining
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['replay'] = options.replay

    return args
Ejemplo n.º 2
0
def parseOptions(argv):
    """
    Processes the command used to run gridworld from the command line.
    """

    description = """
    DESCRIPTION:
        This program will create a gridworld. Explore and find the best path to the reward!

    EXAMPLES:
        (1) python -m pacai.bin.gridworld
            - Creats a gridworld with default settings.
        (2) python -m pacai.bin.gridworld --discount 0.7
            - Creats a gridworld with a 0.7 discount factor.
    """

    parser = argparse.ArgumentParser(
        description=textwrap.dedent(description),
        prog=os.path.basename(__file__),
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        '-a',
        '--agent',
        dest='agent',
        action='store',
        type=str,
        default='random',
        help=
        'agent type (options are \'random\', \'value\' and \'q\', default %(default)s)'
    )

    parser.add_argument(
        '-d',
        '--debug',
        dest='debug',
        action='store_true',
        default=False,
        help='set logging level to debug (default: %(default)s)')

    parser.add_argument(
        '-e',
        '--epsilon',
        dest='epsilon',
        action='store',
        type=float,
        default=0.3,
        help=
        'chance of taking a random action in q-learning (default %(default)s)')

    parser.add_argument(
        '-g',
        '--grid',
        dest='grid',
        action='store',
        type=str,
        default='BookGrid',
        help=
        'grid type: BookGrid, BridgeGrid, CliffGrid, MazeGrid, %(default)s (default)'
    )

    parser.add_argument(
        '-i',
        '--iterations',
        dest='iters',
        action='store',
        type=int,
        default=10,
        help='number of rounds of value iteration (default %(default)s)')

    parser.add_argument(
        '-k',
        '--episodes',
        dest='episodes',
        action='store',
        type=int,
        default=1,
        help='number of epsiodes of the MDP to run (default %(default)s)')

    parser.add_argument('-l',
                        '--learning-rate',
                        dest='learningRate',
                        action='store',
                        type=float,
                        default=0.5,
                        help='set the learning rate (default %(default)s)')

    parser.add_argument(
        '-n',
        '--noise',
        dest='noise',
        action='store',
        type=float,
        default=0.2,
        help=
        'set how often actions result in unintended directions (default %(default)s)'
    )

    parser.add_argument(
        '-p',
        '--pause',
        dest='pause',
        action='store_true',
        default=False,
        help=
        'pause GUI after each time step when running the MDP (default %(default)s)'
    )

    parser.add_argument(
        '-q',
        '--quiet',
        dest='quiet',
        action='store_true',
        default=False,
        help='set logging level to warning (default: %(default)s)')

    parser.add_argument(
        '-r',
        '--living-reward',
        dest='livingReward',
        action='store',
        type=float,
        default=0.0,
        help='reward for living for a time step (default %(default)s)')

    parser.add_argument(
        '-s',
        '--speed',
        dest='speed',
        action='store',
        type=float,
        default=1.0,
        help=
        'speed of animation, S>1.0 is faster, 0<S<1 is slower (default %(default)s)'
    )

    parser.add_argument(
        '-v',
        '--value-steps',
        dest='valueSteps',
        action='store_true',
        default=False,
        help='display each step of value iteration (default %(default)s)')

    parser.add_argument('-y',
                        '--discount',
                        dest='discount',
                        action='store',
                        type=float,
                        default=0.9,
                        help='discount on future (default %(default)s)')

    parser.add_argument('--manual',
                        dest='manual',
                        action='store_true',
                        default=False,
                        help='manually control agent (default %(default)s)')

    parser.add_argument('--null-graphics',
                        dest='nullGraphics',
                        action='store_true',
                        default=False,
                        help='generate no graphics (default: %(default)s)')

    parser.add_argument(
        '--text-graphics',
        dest='textGraphics',
        action='store_true',
        default=False,
        help='display output as text only (default: %(default)s)')

    parser.add_argument(
        '--window-size',
        dest='gridSize',
        action='store',
        type=int,
        default=150,
        help=
        'request a window width of X pixels *per grid cell* (default %(default)s)'
    )

    options, otherjunk = parser.parse_known_args(argv)

    if len(otherjunk) != 0:
        raise ValueError('Unrecognized options: \'%s\'.' % (str(otherjunk)))

    # Set the logging level
    if options.quiet and options.debug:
        raise ValueError('Logging cannont be set to both debug and quiet.')

    if options.quiet:
        updateLoggingLevel(logging.WARNING)
    elif options.debug:
        updateLoggingLevel(logging.DEBUG)

    if options.manual and options.agent != 'q':
        logging.info('Disabling Agents in Manual Mode.')
        options.agent = None

    # MANAGE CONFLICTS
    if options.textGraphics or options.nullGraphics:
        options.pause = False

    if options.manual:
        options.pause = True

    return options
Ejemplo n.º 3
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """

    description = """
    DESCRIPTION:
        This program will run a classic pacman game. Collect all the pellets before
        the ghosts catch you!

    EXAMPLES:
        (1) python -m pacai.bin.pacman
            - Starts an interactive game.
        (2) python -m pacai.bin.pacman --layout smallClassic
            - Starts an interactive game on a smaller board.
    """

    parser = getParser(description, os.path.basename(__file__))

    parser.add_argument('-g', '--ghosts', dest = 'ghost',
            action = 'store', type = str, default = 'RandomGhost',
            help = 'use the specified ghostAgent module for the ghosts (default: %(default)s)')

    parser.add_argument('-k', '--num-ghosts', dest = 'numGhosts',
            action = 'store', type = int, default = 4,
            help = 'set the maximum number of ghosts (default: %(default)s)')

    parser.add_argument('-l', '--layout', dest = 'layout',
            action = 'store', type = str, default = 'mediumClassic',
            help = 'use the specified map layout (default: %(default)s)')

    parser.add_argument('-p', '--pacman', dest = 'pacman',
            action = 'store', type = str, default = 'WASDKeyboardAgent',
            help = 'use the specified pacmanAgent module for pacman (default: %(default)s)')

    parser.add_argument('--agent-args', dest = 'agentArgs',
            action = 'store', type = str, default = None,
            help = 'comma separated arguments to be passed to agents (e.g. \'opt1=val1,opt2\')'
                + '(default: %(default)s)')

    parser.add_argument('--timeout', dest = 'timeout',
            action = 'store', type = int, default = 30,
            help = 'maximum time limit (seconds) an agent can spend computing per game '
                + '(default: %(default)s)')

    options, otherjunk = parser.parse_known_args(argv)
    args = dict()

    if len(otherjunk) != 0:
        raise ValueError('Unrecognized options: \'%s\'.' % (str(otherjunk)))

    # Set the logging level.
    if options.quiet and options.debug:
        raise ValueError('Logging cannont be set to both debug and quiet.')

    if options.quiet:
        updateLoggingLevel(logging.WARNING)
    elif options.debug:
        updateLoggingLevel(logging.DEBUG)

    # If seed value is not entered generate a random seed value.
    seed = options.seed
    if seed is None:
        seed = random.randint(0, 2**32)
    random.seed(seed)
    logging.debug('Seed value: ' + str(seed))

    # Choose a layout.
    args['layout'] = getLayout(options.layout, maxGhosts = options.numGhosts)
    if (args['layout'] is None):
        raise ValueError('The layout ' + options.layout + ' cannot be found.')

    # Choose a Pacman agent.
    noKeyboard = (options.replay is None and (options.textGraphics or options.nullGraphics))
    if (noKeyboard and ('KeyboardAgent' in options.pacman)):
        raise ValueError('Keyboard agents require graphics.')

    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining

    # Don't display training games.
    if 'numTrain' in agentOpts:
        options.numQuiet = int(agentOpts['numTrain'])
        options.numIgnore = int(agentOpts['numTrain'])

    viewOptions = {
        'gifFPS': options.gifFPS,
        'gifPath': options.gif,
        'skipFrames': options.gifSkipFrames,
        'spritesPath': options.spritesPath,
    }

    # Choose a display format.
    if options.nullGraphics:
        args['display'] = PacmanNullView(**viewOptions)
    elif options.textGraphics:
        args['display'] = PacmanTextView(**viewOptions)
    else:
        # Defer importing the GUI unless we actually need it.
        # This allows people to not have tkinter installed.
        from pacai.ui.pacman.gui import PacmanGUIView

        args['display'] = PacmanGUIView(fps = options.fps, title = 'Pacman', **viewOptions)
        agentOpts['keyboard'] = args['display'].getKeyboard()

    args['catchExceptions'] = options.catchExceptions
    args['gameToReplay'] = options.replay
    args['ghosts'] = [BaseAgent.loadAgent(options.ghost, i + 1) for i in range(options.numGhosts)]
    args['numGames'] = options.numGames
    args['pacman'] = BaseAgent.loadAgent(options.pacman, PACMAN_AGENT_INDEX, agentOpts)
    args['record'] = options.record
    args['timeout'] = options.timeout

    return args