Пример #1
0
def read_command(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usage_str = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout small_classic --zoom 2
                OR  python pacman.py -l small_classic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usage_str)

    parser.add_option('-n',
                      '--num_games',
                      dest='num_games',
                      type='int',
                      help=default('the number of GAMES to play'),
                      metavar='GAMES',
                      default=1)
    parser.add_option(
        '-l',
        '--layout',
        dest='layout',
        help=default('the LAYOUT_FILE from which to load the map layout'),
        metavar='LAYOUT_FILE',
        default='medium_classic')
    parser.add_option(
        '-p',
        '--pacman',
        dest='pacman',
        help=default('the agent TYPE in the pacman_agents module to use'),
        metavar='TYPE',
        default='KeyboardAgent')
    parser.add_option('-t',
                      '--text_graphics',
                      action='store_true',
                      dest='text_graphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quiet_text_graphics',
                      action='store_true',
                      dest='quiet_graphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghost_agents module to use'),
        metavar='TYPE',
        default='RandomGhost')
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='num_ghosts',
                      help=default('The maximum number of ghosts to use'),
                      default=4)
    parser.add_option('-z',
                      '--zoom',
                      type='float',
                      dest='zoom',
                      help=default('Zoom the size of the graphics window'),
                      default=1.0)
    parser.add_option(
        '-f',
        '--fix_random_seed',
        action='store_true',
        dest='fix_random_seed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--record_actions',
        action='store_true',
        dest='record',
        help=
        'Writes game histories to a file (named by the time they were played)',
        default=False)
    parser.add_option('--replay',
                      dest='game_to_replay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agent_args',
        dest='agent_args',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--num_training',
        dest='num_training',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frame_time',
        dest='frame_time',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option(
        '-c',
        '--catch_exceptions',
        action='store_true',
        dest='catch_exceptions',
        help='Turns on exception handling and timeouts during games',
        default=False)
    parser.add_option(
        '--timeout',
        dest='timeout',
        type='int',
        help=default(
            'Maximum length of time an agent can spend computing in a single game'
        ),
        default=30)

    options, otherjunk = parser.parse_args(argv)
    if len(otherjunk) != 0:
        raise Exception('Command line input not understood: ' + str(otherjunk))
    args = dict()

    # Fix the random seed
    if options.fix_random_seed:
        random.seed('cs188')

    # Choose a layout
    args['layout'] = layout.get_layout(options.layout)
    if args['layout'] == None:
        raise Exception("The layout " + options.layout + " cannot be found")

    # Choose a Pacman agent
    no_keyboard = options.game_to_replay == None and (options.text_graphics or
                                                      options.quiet_graphics)
    pacman_type = load_agent(options.pacman, no_keyboard)
    agent_opts = parse_agent_args(options.agent_args)
    if options.num_training > 0:
        args['num_training'] = options.num_training
        if 'num_training' not in agent_opts:
            agent_opts['num_training'] = options.num_training
    pacman = pacman_type(**agent_opts)  # Instantiate Pacman with agent_args
    args['pacman'] = pacman

    # Don't display training games
    if 'num_train' in agent_opts:
        options.num_quiet = int(agent_opts['num_train'])
        options.num_ignore = int(agent_opts['num_train'])

    # Choose a ghost agent
    ghost_type = load_agent(options.ghost, no_keyboard)
    args['ghosts'] = [ghost_type(i + 1) for i in range(options.num_ghosts)]

    # Choose a display format
    if options.quiet_graphics:
        import text_display
        args['display'] = text_display.NullGraphics()
    elif options.text_graphics:
        import text_display
        text_display.SLEEP_TIME = options.frame_time
        args['display'] = text_display.PacmanGraphics()
    else:
        import graphics_display
        args['display'] = graphics_display.PacmanGraphics(
            options.zoom, frame_time=options.frame_time)
    args['num_games'] = options.num_games
    args['record'] = options.record
    args['catch_exceptions'] = options.catch_exceptions
    args['timeout'] = options.timeout

    # Special case: recorded games don't use the run_games method or args structure
    if options.game_to_replay != None:
        print('Replaying recorded game %s.' % options.game_to_replay)
        import pickle
        f = open(options.game_to_replay)
        try:
            recorded = pickle.load(f)
        finally:
            f.close()
        recorded['display'] = args['display']
        replay_game(**recorded)
        sys.exit(0)

    return args
Пример #2
0
def read_command(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usage_str = """
                USAGE:      python pacman.py <options>
                EXAMPLES:   (1) python capture.py
                - starts a game with two baseline agents
                (2) python capture.py --keys0
                - starts a two-player interactive game where the arrow keys control agent 0, and all other agents are baseline agents
                (3) python capture.py -r baseline_team -b my_team
                - starts a fully automated game where the red team is a baseline team and blue team is my_team
                """
    parser = OptionParser(usage_str)

    parser.add_option('-r', '--red', help=default('Red team'),
                    default='baseline_team')
    parser.add_option('-b', '--blue', help=default('Blue team'),
                    default='baseline_team')
    parser.add_option('--red-name', help=default('Red team name'),
                    default='Red')
    parser.add_option('--blue-name', help=default('Blue team name'),
                    default='Blue')
    parser.add_option('--red_opts', help=default('Options for red team (e.g. first=keys)'),
                    default='')
    parser.add_option('--blue_opts', help=default('Options for blue team (e.g. first=keys)'),
                    default='')
    parser.add_option('--keys0', help='Make agent 0 (first red player) a keyboard agent', action='store_true', default=False)
    parser.add_option('--keys1', help='Make agent 1 (second red player) a keyboard agent', action='store_true', default=False)
    parser.add_option('--keys2', help='Make agent 2 (first blue player) a keyboard agent', action='store_true', default=False)
    parser.add_option('--keys3', help='Make agent 3 (second blue player) a keyboard agent', action='store_true', default=False)
    parser.add_option('-l', '--layout', dest='layout',
                    help=default('the LAYOUT_FILE from which to load the map layout; use RANDOM for a random maze; use RANDOM<seed> to use a specified random seed, e.g., RANDOM23'),
                    metavar='LAYOUT_FILE', default='default_capture')
    parser.add_option('-t', '--textgraphics', action='store_true', dest='textgraphics',
                    help='Display output as text only', default=False)

    parser.add_option('-q', '--quiet', action='store_true',
                    help='Display minimal output and no graphics', default=False)

    parser.add_option('-Q', '--super-quiet', action='store_true', dest="super_quiet",
                    help='Same as -q but agent output is also suppressed', default=False)

    parser.add_option('-z', '--zoom', type='float', dest='zoom',
                    help=default('Zoom in the graphics'), default=1)
    parser.add_option('-i', '--time', type='int', dest='time',
                    help=default('TIME limit of a game in moves'), default=1200, metavar='TIME')
    parser.add_option('-n', '--num_games', type='int',
                    help=default('Number of games to play'), default=1)
    parser.add_option('-f', '--fix_random_seed', action='store_true',
                    help='Fixes the random seed to always play the same game', default=False)
    parser.add_option('--record', action='store_true',
                    help='Writes game histories to a file (named by the time they were played)', default=False)
    parser.add_option('--replay', default=None,
                    help='Replays a recorded game file.')
    parser.add_option('-x', '--num_training', dest='num_training', type='int',
                    help=default('How many episodes are training (suppresses output)'), default=0)
    parser.add_option('-c', '--catch_exceptions', action='store_true', default=False,
                    help='Catch exceptions and enforce time limits')

    options, otherjunk = parser.parse_args(argv)
    assert len(otherjunk) == 0, "Unrecognized options: " + str(otherjunk)
    args = dict()

    # Choose a display format
    #if options.pygame:
    #   import pygame_display
    #    args['display'] = pygame_display.PacmanGraphics()
    if options.textgraphics:
        import text_display
        args['display'] = text_display.PacmanGraphics()
    elif options.quiet:
        import text_display
        args['display'] = text_display.NullGraphics()
    elif options.super_quiet:
        import text_display
        args['display'] = text_display.NullGraphics()
        args['mute_agents'] = True
    else:
        import capture_graphics_display
        # Hack for agents writing to the display
        capture_graphics_display.FRAME_TIME = 0
        args['display'] = capture_graphics_display.PacmanGraphics(options.red, options.blue, options.zoom, 0, capture=True)
        import __main__
        __main__.__dict__['_display'] = args['display']

    args['red_team_name'] = options.red_name
    args['blue_team_name'] = options.blue_name

    if options.fix_random_seed:
        random.seed('CSI480')

    # Special case: recorded games don't use the run_games method or args structure
    if options.replay != None:
        print('Replaying recorded game %s.' % options.replay)
        import pickle
        recorded = pickle.load(open(options.replay))
        recorded['display'] = args['display']
        replay_game(**recorded)
        sys.exit(0)

    # Choose a pacman agent
    red_args, blue_args = parse_agent_args(options.red_opts), parse_agent_args(options.blue_opts)
    if options.num_training > 0:
        red_args['num_training'] = options.num_training
        blue_args['num_training'] = options.num_training
    nokeyboard = options.textgraphics or options.quiet or options.num_training > 0
    print('\nRed team %s with %s:' % (options.red, red_args))
    red_agents = load_agents(True, options.red, nokeyboard, red_args)
    print('\nBlue team %s with %s:' % (options.blue, blue_args))
    blue_agents = load_agents(False, options.blue, nokeyboard, blue_args)
    args['agents'] = sum([list(el) for el in zip(red_agents, blue_agents)], [])  # list of agents

    num_keyboard_agents = 0
    for index, val in enumerate([options.keys0, options.keys1, options.keys2, options.keys3]):
        if not val:
            continue
        if num_keyboard_agents == 0:
            agent = keyboard_agents.KeyboardAgent(index)
        elif num_keyboard_agents == 1:
            agent = keyboard_agents.KeyboardAgent2(index)
        else:
            raise Exception('Max of two keyboard agents supported')
        num_keyboard_agents += 1
        args['agents'][index] = agent

    # Choose a layout
    import layout
    layouts = []
    for i in range(options.num_games):
        if options.layout == 'RANDOM':
            l = layout.Layout(random_layout().split('\n'))
        elif options.layout.startswith('RANDOM'):
            l = layout.Layout(random_layout(int(options.layout[6:])).split('\n'))
        elif options.layout.lower().find('capture') == -1:
            raise Exception('You must use a capture layout with capture.py')
        else:
            l = layout.get_layout(options.layout)
        if l == None:
            raise Exception("The layout " + options.layout + " cannot be found")

        layouts.append(l)

    args['layouts'] = layouts
    args['length'] = options.time
    args['num_games'] = options.num_games
    args['num_training'] = options.num_training
    args['record'] = options.record
    args['catch_exceptions'] = options.catch_exceptions
    return args