Exemple #1
0
    def __init__(self,
                 enable_render=False,
                 layout_name="mediumClassic",
                 view_distance=(2, 2)):
        self.layouts = dict()
        self.layout_name = layout_name
        self.pacman = KeyboardAgent()
        self.ghosts = [
            RandomGhost(i + 1) if i % 2 == 0 else DirectionalGhost(i + 1)
            for i in range(20)
        ]
        frameTime = 0.03

        textDisplay.SLEEP_TIME = frameTime
        self.display_text = textDisplay.PacmanGraphics()
        self.display_graphics = graphicsDisplay.PacmanGraphics(
            1.0, frameTime=frameTime)

        self.beQuiet = True
        self.game = None
        self.view_distance = view_distance
        self.textGraphics = False
        self.reset(enable_render=enable_render, layout_name=layout_name)
Exemple #2
0
def readCommand( argv ):
  """
  Processes the command used to run pacman from the command line.
  """
  from optparse import OptionParser
  usageStr = """
  USAGE:      python pacman.py <options>
  EXAMPLES:   (1) python pacman.py
                  - starts an interactive game
              (2) python pacman.py --layout smallClassic --zoom 2
              OR  python pacman.py -l smallClassic -z 2
                  - starts an interactive game on a smaller board, zoomed in
  """
  parser = OptionParser(usageStr)
  
  parser.add_option('-n', '--numGames', dest='numGames', 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='mediumClassic')
  parser.add_option('-p', '--pacman', dest='pacman', 
                    help=default('the agent TYPE in the pacmanAgents module to use'), 
                    metavar='TYPE', default='KeyboardAgent')
  parser.add_option('-d', '--depth', dest='depth', type='int',
                    help=default('the search DEPTH passed to the agent'), metavar='DEPTH', default=2)
  parser.add_option('-b', '--betterEvaluation', dest='betterEval', 
                    help=default('Use the betterEvaluationFunction instead of scoreEvaluationFunction'), 
                    action='store_true', default=False)
  parser.add_option('-t', '--textGraphics', action='store_true', dest='textGraphics', 
                    help='Display output as text only', default=False)
  parser.add_option('-q', '--quietTextGraphics', action='store_true', dest='quietGraphics', 
                    help='Generate minimal output and no graphics', default=False)
  parser.add_option('--textGraphicsDelay', type='float', dest='delay', 
                    help='Pause length between moves in the text display', default=0.1)
  parser.add_option('-g', '--ghosts', dest='ghost', 
                    help=default('the ghost agent TYPE in the ghostAgents module to use'), 
                    metavar = 'TYPE', default='RandomGhost')
  parser.add_option('-k', '--numghosts', type='int', dest='numGhosts', 
                    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', '--fixRandomSeed', action='store_true', dest='fixRandomSeed', 
                    help='Fixes the random seed to always play the same game', default=False)
  parser.add_option('-r', '--recordActions', 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='gameToReplay', 
                    help='A recorded game file (pickle) to replay', default=None)
  parser.add_option('-a','--agentArgs',dest='agentArgs',
                    help='Comma seperated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"')
  parser.add_option('-x', '--numQuiet', dest='numQuiet', type='int',
                    help=default('How many episodes to suppress GUI for'), default=0)
  parser.add_option('-i', '--numIgnore', dest='numIgnore', type='int',
                    help=default('How many games to ignore for reporting average'), default=0)

  options, otherjunk = parser.parse_args()
  if len(otherjunk) != 0: 
	raise Exception('Command line input not understood: ' + str(otherjunk))
  args = dict()
  # Fix the random seed
  if options.fixRandomSeed: random.seed('cs188')  
  # Choose a layout
  args['layout'] = layout.getLayout( options.layout )
  if args['layout'] == None: raise "The layout " + options.layout + " cannot be found"
  
  # Choose a pacman agent
  noKeyboard = options.gameToReplay == None and (options.textGraphics or options.quietGraphics)
  pacmanType = loadAgent(options.pacman, noKeyboard)
  agentOpts = parseAgentArgs(options.agentArgs)
  pacman = pacmanType(**agentOpts) # Instantiate pacman with agentArgs
  if 'setDepth' in dir(pacman): pacman.setDepth(options.depth)
  if 'useBetterEvaluation' in dir(pacman) and options.betterEval: pacman.useBetterEvaluation()
  if 'setOptions' in dir(pacman) and options.agentArgs: 
    pacman.setOptions()
    # HACK for reinforcement project
    if 'numTrain' in agentOpts:
      options.numQuiet = int(agentOpts['numTrain'])
      options.numIgnore = int(agentOpts['numTrain'])
  try:
    import evaluation
    if 'setEvaluation' in dir(pacman):
      evalFn = getattr(evaluation, options.evaluationFn) 
      pacman.setEvaluation(evalFn)
  except ImportError: 
    pass
  args['pacman'] = pacman
    
  # Choose a ghost agent
  import ghostAgents
  ghostType = loadAgent(options.ghost, noKeyboard)
  #getattr(ghostAgents, options.ghost)
  args['ghosts'] = [ghostType( i+1 ) for i in range( options.numGhosts )]
  # Choose a display format
  if options.quietGraphics:
      import textDisplay
      args['display'] = textDisplay.NullGraphics()
  elif options.textGraphics:
    import textDisplay
    textDisplay.SLEEP_TIME = options.delay
    args['display'] = textDisplay.PacmanGraphics()      
  else:
    import graphicsDisplay
    args['display'] = graphicsDisplay.PacmanGraphics(options.zoom)
  args['numGames'] = options.numGames
  args['record'] = options.record
  
  # Special case: recorded games don't use the runGames method or args structure
  if options.gameToReplay != None:
    print 'Replaying recorded game %s.' % options.gameToReplay
    import cPickle
    recorded = cPickle.load(open(options.gameToReplay))
    recorded['display'] = args['display']
    replayGame(**recorded)
    sys.exit(0)

  args['numQuiet'] = options.numQuiet
  return args
Exemple #3
0
def readCommand(argv):
    """
  Processes the command used to run pacman from the command line.
  """
    from optparse import OptionParser
    usageStr = """
  USAGE:      python pacman.py <options>
  EXAMPLES:   (1) python capture.py
                  - starts an interactive game against a random opponent
              (2) python capture.py --numPlayers 4 --player2 KeyboardAgent2
                  - starts a two-player interactive game with w,a,s,d & i,j,k,l keys
              (2) python capture.py --numPlayers 4 --player1 RandomAgent
                  - starts a chaotic random game
  """
    parser = OptionParser(usageStr)

    parser.add_option('-1',
                      '--player1',
                      dest='p1',
                      help=default('the agent TYPE to use for player 1'),
                      metavar='TYPE',
                      default='KeyboardAgent')
    parser.add_option(
        '-2',
        '--player2',
        dest='p2',
        help=default(
            'the agent TYPE to use for player 2 (KeyboardAgent2 for i,j,k,l keys)'
        ),
        metavar='TYPE',
        default='OffensiveReflexAgent')
    parser.add_option('-3',
                      '--player3',
                      dest='p3',
                      help=default('the agent TYPE to use for player 3'),
                      metavar='TYPE',
                      default='OffensiveReflexAgent')
    parser.add_option('-4',
                      '--player4',
                      dest='p4',
                      help=default('the agent TYPE to use for player 4'),
                      metavar='TYPE',
                      default='OffensiveReflexAgent')
    parser.add_option('-5',
                      '--player5',
                      dest='p5',
                      help=default('the agent TYPE to use for player 5'),
                      metavar='TYPE',
                      default='OffensiveReflexAgent')
    parser.add_option('-6',
                      '--player6',
                      dest='p6',
                      help=default('the agent TYPE to use for player 6'),
                      metavar='TYPE',
                      default='OffensiveReflexAgent')
    parser.add_option(
        '-l',
        '--layout',
        dest='layout',
        help=default('the LAYOUT_FILE from which to load the map layout'),
        metavar='LAYOUT_FILE',
        default='mediumCapture')
    parser.add_option('-n',
                      '--nographics',
                      action='store_true',
                      dest='nographics',
                      help='Display output as text only',
                      default=False)
    #parser.add_option('-G', '--pygame', action='store_true', dest='pygame',
    #                  help='Display output with Pygame', default=False)
    parser.add_option('-k',
                      '--numPlayers',
                      type='int',
                      dest='numPlayers',
                      help=default('The maximum number of players'),
                      default=4)
    parser.add_option('-z',
                      '--zoom',
                      type='float',
                      dest='zoom',
                      help=default('Zoom in the graphics'),
                      default=1)
    parser.add_option('-t',
                      '--time',
                      type='int',
                      dest='time',
                      help=default('TIME limit of a game in moves'),
                      default=3000,
                      metavar='TIME')
    parser.add_option('-f',
                      '--fast',
                      action='store_true',
                      dest='fast',
                      help=default('Remove animation to speed up the game'),
                      default=False)

    options, otherjunk = parser.parse_args()
    assert len(otherjunk) == 0
    args = dict()

    # Choose a pacman agent
    p1 = loadAgent(options.p1, options.nographics)(0)
    p2 = loadAgent(options.p2, options.nographics)(1)
    p3 = loadAgent(options.p3, options.nographics)(2)
    p4 = loadAgent(options.p4, options.nographics)(3)
    p5 = loadAgent(options.p5, options.nographics)(4)
    p6 = loadAgent(options.p6, options.nographics)(5)
    args['agents'] = [p1, p2, p3, p4, p5, p6]

    # Choose a display format
    #if options.pygame:
    #   import pygameDisplay
    #    args['display'] = pygameDisplay.PacmanGraphics()
    if not options.nographics:
        import graphicsDisplay
        graphicsDisplay.FRAME_TIME = 0
        if not options.fast:
            graphicsDisplay.PAUSE_TIME = .1
        args['display'] = graphicsDisplay.PacmanGraphics(options.zoom,
                                                         capture=True)
    else:
        import textDisplay
        args['display'] = textDisplay.PacmanGraphics()

    # Choose a layout
    if options.layout.lower().find('capture') == -1:
        raise Exception('You must use a capture layout with capture.py')
    import layout
    args['layout'] = layout.getLayout(options.layout)
    if args['layout'] == None:
        raise Exception("The layout " + options.layout + " cannot be found")

    args['agents'] = args['agents'][:min(args['layout'].getNumGhosts(
    ), options.numPlayers)]
    args['time'] = options.time
    return args
Exemple #4
0
def readCommand(argv):
    """
  Processes the command used to run pacman from the command line.
  """
    from optparse import OptionParser
    usageStr = """
  USAGE:      python pacman.py <options>
  EXAMPLES:   (1) python capture.py
                  - starts an interactive game against two offensive agents
                    (you control the red agent with the arrow keys)
              (2) python capture.py --player2 KeyboardAgent2
                  - starts a two-player interactive game with w,a,s,d & i,j,k,l keys
              (3) python capture.py --player2 DefensiveReflexAgent
                  - starts a fully automated game
  """
    parser = OptionParser(usageStr)

    parser.add_option('-r',
                      '--red',
                      help=default('Red team'),
                      default='BaselineAgents')
    parser.add_option('-b',
                      '--blue',
                      help=default('Blue team'),
                      default='BaselineAgents')
    parser.add_option('--redOpts',
                      help=default('Options for red team (e.g. first=keys)'),
                      default='')
    parser.add_option('--blueOpts',
                      help=default('Options for blue team (e.g. first=keys)'),
                      default='')
    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'
        ),
        metavar='LAYOUT_FILE',
        default='defaultCapture')
    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('-k',
                      '--numPlayers',
                      type='int',
                      dest='numPlayers',
                      help=default('The maximum number of players'),
                      default=4)
    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=3000,
                      metavar='TIME')
    parser.add_option('-n',
                      '--numGames',
                      type='int',
                      help=default('Number of games to play'),
                      default=1)
    parser.add_option(
        '-f',
        '--fixRandomSeed',
        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',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option('-c',
                      '--catchExceptions',
                      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 pygameDisplay
    #    args['display'] = pygameDisplay.PacmanGraphics()
    if options.textgraphics:
        import textDisplay
        args['display'] = textDisplay.PacmanGraphics()
    elif options.quiet:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.super_quiet:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
        args['muteAgents'] = True
    else:
        import graphicsDisplay
        graphicsDisplay.FRAME_TIME = 0
        args['display'] = graphicsDisplay.PacmanGraphics(options.zoom,
                                                         0,
                                                         capture=True)

    if options.fixRandomSeed: random.seed('cs188')

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

    # Choose a pacman agent
    redArgs, blueArgs = parseAgentArgs(options.redOpts), parseAgentArgs(
        options.blueOpts)
    if options.numTraining > 0:
        redArgs['numTraining'] = options.numTraining
        blueArgs['numTraining'] = options.numTraining
    nokeyboard = options.textgraphics or options.quiet or options.numTraining > 0
    print '\nRed team %s with %s:' % (options.red, redArgs)
    redAgents = loadAgents(True, options.red, nokeyboard, redArgs)
    print '\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

    # Choose a layout
    if options.layout == 'RANDOM': options.layout = randomLayout()
    if options.layout.lower().find('capture') == -1:
        raise Exception('You must use a capture layout with capture.py')
    import layout
    args['layout'] = layout.getLayout(options.layout)
    if args['layout'] == None:
        raise Exception("The layout " + options.layout + " cannot be found")

    args['agents'] = args['agents'][:min(args['layout'].getNumGhosts(
    ), options.numPlayers)]
    args['length'] = options.time
    args['numGames'] = options.numGames
    args['numTraining'] = options.numTraining
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    return args
Exemple #5
0
def readCommand(argv):
    """
  Processes the command used to run pacman from the command line.
  """
    from optparse import OptionParser
    usageStr = """
  USAGE:      python pacclient.py <options>
  EXAMPLES:   (1) python pacclient.py
                  - starts an interactive game with a random teammate.
  EXAMPLES:   (2) python pacclient.py -2 OffenseAgent
                  - starts an interactive game with a random teammate.
  """
    parser = OptionParser(usageStr)

    parser.add_option('-a',
                      '--agents',
                      help=default('Your team'),
                      default='BaselineAgents')
    parser.add_option('--agentOpts',
                      help=default('Arguments passed to the factory'),
                      default='')
    parser.add_option('-t',
                      '--textgraphics',
                      action='store_true',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quiet',
                      action='store_true',
                      help='Display minimal output',
                      default=False)
    # parser.add_option('-G', '--pygame', action='store_true', dest='pygame',
    #                   help='Display output with Pygame graphics (faster)', default=False)
    parser.add_option('-z',
                      '--zoom',
                      type='float',
                      help=default('Zoom in the graphics'),
                      default=1)
    parser.add_option('-s',
                      '--server',
                      help=default('The SERVER to connect to'),
                      default='discourse.millennium.berkeley.edu')
    parser.add_option('-p',
                      '--port',
                      type='int',
                      help=default('The PORT to connect to'),
                      default=7226)
    parser.add_option('-U',
                      '--user',
                      help=default('Your username'),
                      default='guest')
    parser.add_option('-P',
                      '--password',
                      help=default('Your password'),
                      default='guest')
    parser.add_option('-g',
                      '--gamename',
                      help=default('The name of the game you wish to contact'),
                      default='')
    parser.add_option(
        '-f',
        '--fixRandomSeed',
        action='store_true',
        help='Fixes the random seed to always play the same game',
        default=False)

    options, otherjunk = parser.parse_args()
    if len(otherjunk) != 0: raise Exception("Illegal args: " + otherjunk)
    args = dict()

    agentArgs = parseAgentArgs(options.agentOpts)
    args['agentFactoryBuilder'] = loadAgentAccessor(options.agents, agentArgs)

    # Choose a display format
    #if options.pygame:
    # import pygameDisplay
    #  args['display'] = pygameDisplay.PacmanGraphics()
    if options.quiet:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textgraphics:
        import textDisplay
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(options.zoom, 0, True)

    if options.fixRandomSeed: random.seed('cs188')

    args['server'] = options.server
    args['port'] = options.port
    args['user'] = options.user
    args['password'] = options.password
    args['gamename'] = options.gamename

    return args
Exemple #6
0
    if 'numTrain' in agentOpts:
        options.numQuiet = int(agentOpts['numTrain'])
        options.numIgnore = int(agentOpts['numTrain'])

    # Choose a ghost agent
    ghostType = loadAgent(options.ghost, noKeyboard)
    args['ghosts'] = [ghostType( i+1 ) for i in range( options.numGhosts )]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(options.zoom, frameTime = options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout

    # Special case: recorded games don't use the runGames method or args structure
    if options.gameToReplay != None:
        print 'Replaying recorded game %s.' % options.gameToReplay
        import cPickle
        f = open(options.gameToReplay)
        try: recorded = cPickle.load(f)
        finally: f.close()
Exemple #7
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option("-n",
                      "--numGames",
                      dest="numGames",
                      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="mediumClassic")
    parser.add_option(
        "-p",
        "--pacman",
        dest="pacman",
        help=default("the agent TYPE in the pacmanAgents module to use"),
        metavar="TYPE",
        default="KeyboardAgent")
    parser.add_option("-d",
                      "--depth",
                      dest="depth",
                      type="int",
                      help=default("the search DEPTH passed to the agent"),
                      metavar="DEPTH",
                      default=2)
    parser.add_option("-t",
                      "--textGraphics",
                      action="store_true",
                      dest="textGraphics",
                      help="Display output as text only",
                      default=False)
    parser.add_option("-q",
                      "--quietTextGraphics",
                      action="store_true",
                      dest="quietGraphics",
                      help="Generate minimal output and no graphics",
                      default=False)
    parser.add_option("--textGraphicsDelay",
                      type="float",
                      dest="delay",
                      help="Pause length between moves in the text display",
                      default=0.1)
    parser.add_option(
        "-g",
        "--ghosts",
        dest="ghost",
        help=default("the ghost agent TYPE in the ghostAgents module to use"),
        metavar="TYPE",
        default="RandomGhost")
    parser.add_option("-k",
                      "--numghosts",
                      type="int",
                      dest="numGhosts",
                      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",
        "--fixRandomSeed",
        action="store_true",
        dest="fixRandomSeed",
        help="Fixes the random seed to always play the same game",
        default=False)
    parser.add_option(
        "-r",
        "--recordActions",
        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="gameToReplay",
                      help="A recorded game file (pickle) to replay",
                      default=None)

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

    # Fix the random seed
    if options.fixRandomSeed: random.seed("rseed")

    # Choose a layout
    import layout
    args["layout"] = layout.getLayout(options.layout)
    if args["layout"] == None:
        raise BaseException("The layout " + options.layout +
                            " cannot be found")

    # Choose a pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)

    pacman = pacmanType()  # Figure out how to instantiate pacman
    if "setDepth" in dir(pacman): pacman.setDepth(options.depth)
    try:
        import evaluation
        if "setEvaluation" in dir(pacman):
            evalFn = getattr(evaluation, options.evaluationFn)
            pacman.setEvaluation(evalFn)
    except ImportError:
        pass
    args["pacman"] = pacman

    # Choose a ghost agent
    import ghostAgents
    ghostType = getattr(ghostAgents, options.ghost)
    args["ghosts"] = [ghostType(i + 1) for i in range(options.numGhosts)]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args["display"] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.delay
        args["display"] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args["display"] = graphicsDisplay.PacmanGraphics(options.zoom)
    args["numGames"] = options.numGames
    args["record"] = options.record

    # Special case: recorded games don"t use the runGames method or args structure
    if options.gameToReplay != None:
        import cPickle
        recorded = cPickle.load(open(options.gameToReplay))
        recorded["display"] = args["display"]
        replayGame(**recorded)
        sys.exit(0)

    return args
Exemple #8
0
def readCommand(argv):
    """
  Processes the command used to run pacman from the command line.
  """
    from optparse import OptionParser
    usageStr = """
  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 baselineTeam -b myTeam
                  - starts a fully automated game where the red team is a baseline team and blue team is myTeam
  """
    parser = OptionParser(usageStr)

    parser.add_option('-r',
                      '--red',
                      help=default('Red team'),
                      default='baselineTeam')
    parser.add_option('-b',
                      '--blue',
                      help=default('Blue team'),
                      default='baselineTeam')
    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('--redOpts',
                      help=default('Options for red team (e.g. first=keys)'),
                      default='')
    parser.add_option('--blueOpts',
                      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='defaultCapture')
    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',
                      '--numGames',
                      type='int',
                      help=default('Number of games to play'),
                      default=1)
    parser.add_option(
        '-f',
        '--fixRandomSeed',
        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(
        '--recordLog',
        action='store_true',
        help='Writes game log  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(
        '--replayq',
        default=None,
        help=
        'Replays a recorded game file without display to generate result log.')
    parser.add_option('--delay-step',
                      type='float',
                      dest='delay_step',
                      help=default('Delay step in a play or replay.'),
                      default=0.03)
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option('-c',
                      '--catchExceptions',
                      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 pygameDisplay
    #    args['display'] = pygameDisplay.PacmanGraphics()
    if options.textgraphics:
        import textDisplay
        args['display'] = textDisplay.PacmanGraphics()
    elif options.quiet or options.replayq:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.super_quiet:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
        args['muteAgents'] = True
    else:
        import captureGraphicsDisplay
        # Hack for agents writing to the display
        captureGraphicsDisplay.FRAME_TIME = 0
        args['display'] = captureGraphicsDisplay.PacmanGraphics(options.red,
                                                                options.blue,
                                                                options.zoom,
                                                                0,
                                                                capture=True)
        import __main__
        __main__.__dict__['_display'] = args['display']

    args['redTeamName'] = options.red_name
    args['blueTeamName'] = options.blue_name

    if options.fixRandomSeed: random.seed('cs188')

    if options.recordLog:
        sys.stdout = open('log-0', 'w')
        sys.stderr = sys.stdout

    # Special case: recorded games don't use the runGames method or args structure
    if options.replay != None:
        print('Replaying recorded game %s.' % options.replay)
        import pickle
        recorded = pickle.load(open(options.replay, 'rb'), encoding="bytes")
        recorded['display'] = args['display']
        recorded['delay'] = options.delay_step
        recorded['redTeamName'] = options.red
        recorded['blueTeamName'] = options.blue
        recorded['waitEnd'] = False

        replayGame(**recorded)
        sys.exit(0)

    # Special case: recorded games don't use the runGames method or args structure
    if options.replayq != None:
        print('Replaying recorded game %s.' % options.replay)
        import pickle
        recorded = pickle.load(open(options.replayq, 'rb'), encoding="bytes")
        recorded['display'] = args['display']
        recorded['delay'] = 0.0
        recorded['redTeamName'] = options.red
        recorded['blueTeamName'] = options.blue
        recorded['waitEnd'] = False

        replayGame(**recorded)
        sys.exit(0)

    # Choose a pacman agent
    redArgs, blueArgs = parseAgentArgs(options.redOpts), parseAgentArgs(
        options.blueOpts)
    if options.numTraining > 0:
        redArgs['numTraining'] = options.numTraining
        blueArgs['numTraining'] = options.numTraining
    nokeyboard = options.textgraphics or options.quiet or options.numTraining > 0
    print('\nRed team %s with %s:' % (options.red, redArgs))
    redAgents = loadAgents(True, options.red, nokeyboard, redArgs)
    print('\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

    if None in blueAgents or None in redAgents:
        if None in blueAgents:
            print('\nBlue team failed to load!\n')
        if None in redAgents:
            print('\nRed team failed to load!\n')
        raise Exception('No teams found!')

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

    # Choose a layout
    import layout
    layouts = []
    for i in range(options.numGames):
        if options.layout == 'RANDOM':
            l = layout.Layout(randomLayout().split('\n'))
        elif options.layout.startswith('RANDOM'):
            l = layout.Layout(
                randomLayout(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.getLayout(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['numGames'] = options.numGames
    args['numTraining'] = options.numTraining
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['delay_step'] = options.delay_step
    return args
Exemple #9
0
def readCommand(argv):
    """
  Processes the command used to run pacman from the command line.
  """
    from optparse import OptionParser
    usageStr = """
  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 -p baselineTeam -b myTeam
                  - starts a fully automated game where the pacman team is a baseline team and ghost team is myTeam 
  """
    parser = OptionParser(usageStr)

    parser.add_option('-p',
                      '--pacman',
                      help=default('Pacman team'),
                      default='team')
    parser.add_option('--pac0',
                      help=default('Pacman at Index 0'),
                      default='None')
    parser.add_option('--pac1',
                      help=default('Pacman at Index 1'),
                      default='None')

    parser.add_option('-g',
                      '--ghost',
                      help=default('Ghost team'),
                      default='oneGhostTeam')
    parser.add_option('--pacman-name',
                      help=default('Pacman team name'),
                      default='Pacman')
    parser.add_option('--ghost-name',
                      help=default('Ghost team name'),
                      default='Ghost')
    parser.add_option(
        '--pacmanOpts',
        help=default('Options for pacman team (e.g. first=keys)'),
        default='')
    parser.add_option('--ghostOpts',
                      help=default('Options for ghost team (e.g. first=keys)'),
                      default='')
    parser.add_option(
        '--keys0',
        help='Make agent 0 (first pacman player) a keyboard agent',
        action='store_true',
        default=False)
    parser.add_option(
        '--keys1',
        help='Make agent 1 (second pacman player) a keyboard agent',
        action='store_true',
        default=False)
    parser.add_option(
        '--keys2',
        help='Make agent 2 (first ghost player) a keyboard agent',
        action='store_true',
        default=False)
    parser.add_option(
        '--keys3',
        help='Make agent 3 (second ghost 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='defaultCapture')
    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',
                      '--numGames',
                      type='int',
                      help=default('Number of games to play'),
                      default=1)
    parser.add_option(
        '-f',
        '--fixRandomSeed',
        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.')
    # TODO: This currently doesn't work, consider removing or fixing
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option('-c',
                      '--catchExceptions',
                      action='store_true',
                      default=True,
                      help='Catch exceptions and enforce time limits')

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

    # Variable to keep track of custom team
    customTeam = False
    if options.pac0 != 'None':
        customTeam = True
        options.pacman_name = 'Team ' + options.pac0 + " + " + options.pac1

    # Choose a display format
    if options.textgraphics:
        import textDisplay
        args['display'] = textDisplay.PacmanGraphics()
    elif options.quiet:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.super_quiet:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
        args['muteAgents'] = True
    else:
        import captureGraphicsDisplay
        # Hack for agents writing to the display
        captureGraphicsDisplay.FRAME_TIME = 0
        args['display'] = captureGraphicsDisplay.PacmanGraphics(options.pacman,
                                                                options.ghost,
                                                                options.zoom,
                                                                0,
                                                                capture=True)
        import __main__
        __main__.__dict__['_display'] = args['display']

    args['pacmanTeamName'] = options.pacman_name
    args['ghostTeamName'] = options.ghost_name

    if options.fixRandomSeed: random.seed('cs188')

    # Special case: recorded games don't use the runGames 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']
        replayGame(**recorded)
        sys.exit(0)

    # Choose a pacman agent
    pacmanTeamArgs, ghostTeamArgs = parseAgentArgs(
        options.pacmanOpts), parseAgentArgs(options.ghostOpts)
    if options.numTraining > 0:
        pacmanTeamArgs['numTraining'] = options.numTraining
        ghostTeamArgs['numTraining'] = options.numTraining
    nokeyboard = options.textgraphics or options.quiet or options.numTraining > 0

    # Default, loading from the phasexTeam.py
    if not customTeam:
        pacmanAgents = loadAgents(True, options.pacman, nokeyboard,
                                  pacmanTeamArgs)
        print('Pacman team %s with args %s:' %
              (options.pacman, pacmanTeamArgs))
    # Custom loading
    else:
        pacZero = loadOneAgent(True, options.pac0, 0)
        pacOne = loadOneAgent(True, options.pac1, 1)
        pacmanAgents = [pacZero, pacOne]

    ghostAgents = loadAgents(False, options.ghost, nokeyboard, ghostTeamArgs)
    if ghostAgents:
        print('Ghost team %s with args %s:' % (options.ghost, ghostTeamArgs))

    # Assume 2 agents on the pacman side, and
    # variable amount (0-2) on the ghost side
    args['agents'] = pacmanAgents + ghostAgents

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

    # Choose a layout
    import layout
    if options.layout == 'RANDOM':
        args['layout'] = layout.Layout(randomLayout().split('\n'),
                                       maxGhosts=len(ghostAgents))
    elif options.layout.startswith('RANDOM'):
        args['layout'] = layout.Layout(randomLayout(int(
            options.layout[6:])).split('\n'),
                                       maxGhosts=len(ghostAgents))
    elif options.layout.lower().find('capture') == -1:
        raise Exception('You must use a capture layout with capture.py')
    else:
        args['layout'] = layout.getLayout(options.layout,
                                          maxGhosts=len(ghostAgents))

    if args['layout'] == None:
        raise Exception("The layout " + options.layout + " cannot be found")
    args['length'] = options.time
    args['numGames'] = options.numGames
    args['numTraining'] = options.numTraining
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    return args
Exemple #10
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    parser = get_default_parser()

    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.fixRandomSeed: random.seed('cs188')

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

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining
    pacman = pacmanType(**agentOpts)  # Instantiate Pacman with agentArgs
    args['pacman'] = pacman

    # Choose a ghost agent
    ghostType = loadAgent(options.ghost, noKeyboard)
    ghostOpts = parseAgentArgs(options.ghostArgs)
    if options.numTraining > 0:
        if 'numTraining' not in ghostOpts:
            ghostOpts['numTraining'] = options.numTraining
    args['ghosts'] = [
        ghostType(index=i + 1, **ghostOpts) for i in range(options.numGhosts)
    ]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout

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

    return args
def readCommand( argv ):
  """
  Processes the command used to run pacman from the command line.
  """
  from optparse import OptionParser
  usageStr = """
  USAGE:      python pacclient.py <options>
  EXAMPLES:   (1) python pacclient.py 
                  - starts an interactive game with a random teammate.
  EXAMPLES:   (2) python pacclient.py -2 OffenseAgent 
                  - starts an interactive game with a random teammate.
  """
  parser = OptionParser(usageStr)
  
  parser.add_option('-1', '--player1', dest='p1', 
                    help=default('the agent TYPE to use for player 1 (KeyboardAgent for a,s,d,v keys)'), 
                    metavar='TYPE', default='OffensiveReflexAgent')
  parser.add_option('-2', '--player2', dest='p2', 
                    help=default('the agent TYPE to use for player 2 (KeyboardAgent2 for i,j,k,l keys)'), 
                    metavar='TYPE', default='DefensiveReflexAgent')
  parser.add_option('-3', '--player3', dest='p3', 
                    help=default('the agent TYPE to use for player 3 (unused)'), 
                    metavar='TYPE', default='OffensiveReflexAgent')
  #  parser.add_option('-4', '--player4', dest='p4', 
  #                    help=default('the agent TYPE to use for player 4 (unused)'), 
  #                    metavar='TYPE', default=None)
  parser.add_option('-n', '--nographics', action='store_true', dest='nographics', 
                    help='Display output as text only', default=False)
  parser.add_option('-q', '--quiet', action='store_true', dest='quiet', 
                    help='Display minimal output', default=False)
  # parser.add_option('-G', '--pygame', action='store_true', dest='pygame', 
  #                   help='Display output with Pygame graphics (faster)', default=False)
  parser.add_option('-z', '--zoom', type='float', dest='zoom', 
                    help=default('Zoom in the graphics'), default=1)
  parser.add_option('-s', '--server', dest='address',
                    help=default('The SERVER to connect to'), default='discourse.millennium.berkeley.edu')
  parser.add_option('-p', '--port', dest='port',
                    help=default('The PORT to connect to'), default='7226')
  parser.add_option('-U', '--user', dest='user',
                    help=default('Your username'), default='guest')
  parser.add_option('-P', '--pass', dest='password',
                    help=default('Your password'), default='guest')
  parser.add_option('-g', '--gamename', dest='gamename',
                    help=default('The name of the game you wish to contact'), default='')
  
  options, otherjunk = parser.parse_args()
  if len(otherjunk) != 0: raise Exception("Illegal args: " + otherjunk)
  args = dict()
  
  # Choose a pacman agent
  args['agents'] = []
  if options.p1:
    args['agents'].append(options.p1)
  if options.p2:
    args['agents'].append(options.p2)
  if options.p3:
    args['agents'].append(options.p3)
  #  if options.p4:
  #    args['agents'].append(options.p4)

  # Choose a display format
  #if options.pygame:
  # import pygameDisplay
  #  args['display'] = pygameDisplay.PacmanGraphics()
  if options.quiet:
    if True in [a.find('Keyboard') >= 0 for a in args['agents']]:
  	  raise Exception('Using the keyboard requires graphics (not text display)')  	  
    import textDisplay
    args['display'] = textDisplay.NullGraphics()
  elif options.nographics:
    import textDisplay
    args['display'] = textDisplay.PacmanGraphics()
  else:
    import graphicsDisplay
    graphicsDisplay.FRAME_TIME = 0
    args['display'] = graphicsDisplay.PacmanGraphics(options.zoom, True)
  
  args['server'] = options.address
  args['port'] = int(options.port)
  args['user'] = options.user
  args['password'] = options.password
  args['gamename'] = options.gamename
    
  return args
Exemple #12
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option('-n',
                      '--numGames',
                      dest='numGames',
                      type='int',
                      help=default('the number of GAMES to play'),
                      metavar='GAMES',
                      default=100)
    parser.add_option(
        '-l',
        '--layout',
        dest='layout',
        help=default('the LAYOUT_FILE from which to load the map layout'),
        metavar='LAYOUT_FILE',
        default='mediumClassic4')
    parser.add_option(
        '-p',
        '--pacman',
        dest='pacman',
        help=default('the agent TYPE in the pacmanAgents module to use'),
        metavar='TYPE',
        default='PacmanDQN')
    parser.add_option('-t',
                      '--textGraphics',
                      action='store_true',
                      dest='textGraphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quietTextGraphics',
                      action='store_true',
                      dest='quietGraphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghostAgents module to use'),
        metavar='TYPE',
        default='RandomGhost')
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='numGhosts',
                      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',
        '--fixRandomSeed',
        action='store_true',
        dest='fixRandomSeed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--recordActions',
        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='gameToReplay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agentArgs',
        dest='agentArgs',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frameTime',
        dest='frameTime',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option(
        '-c',
        '--catchExceptions',
        action='store_true',
        dest='catchExceptions',
        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)
    parser.add_option('--load_file',
                      dest='load_file',
                      type='str',
                      help=default('A CNN file to reload the agent'),
                      default=None)
    parser.add_option(
        '--save_file',
        dest='save_file',
        type='str',
        help=default('The file name which the CNN will be saved'),
        default=None)
    parser.add_option(
        '--explore_action',
        dest='explore_action',
        type='str',
        help=default('Wich agent/s will be used to get the explore action'),
        default='random')
    parser.add_option('--level',
                      dest='level',
                      type='int',
                      help=default('Level'),
                      default=2)

    parser.add_option('--train_start',
                      dest='train_start',
                      type='int',
                      help=default('Episodes before training starts'),
                      default=10000)
    parser.add_option('--batch_size',
                      dest='batch_size',
                      type='int',
                      help=default('Replay memory batch size'),
                      default=32)
    parser.add_option('--mem_size',
                      dest='mem_size',
                      type='int',
                      help=default('Replay memory size'),
                      default=100000)

    parser.add_option('--discount',
                      dest='discount',
                      type='float',
                      help=default('Discount rate (gamma value)'),
                      default=0.95)
    parser.add_option('--lr',
                      dest='lr',
                      type='float',
                      help=default('Learning rate'),
                      default=0.0002)
    parser.add_option('--lr_cyclic',
                      dest='lr_cyclic',
                      type='float',
                      help=default('Learning rate cyclic modifier'),
                      default=0)
    parser.add_option('--rms_decay',
                      dest='rms_decay',
                      type='float',
                      help=default('RMS Prop decay (switched to adam)'),
                      default=0.99)
    parser.add_option('--rms_eps',
                      dest='rms_eps',
                      type='float',
                      help=default('RMS Prop epsilon (switched to adam)'),
                      default=1e-6)

    parser.add_option('--eps',
                      dest='eps',
                      type='float',
                      help=default('Epsilon start value'),
                      default=1.0)
    parser.add_option('--eps_final',
                      dest='eps_final',
                      type='float',
                      help=default('Epsilon end value'),
                      default=0.1)
    parser.add_option(
        '--eps_step',
        dest='eps_step',
        type='int',
        help=default('Epsilon steps between start and end (linear)'),
        default=100000)
    parser.add_option('--minimax_depth',
                      dest='minimax_depth',
                      type='str',
                      help=default('minimax_depth'),
                      default='1')

    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.fixRandomSeed:
        random.seed('cs188')

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

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)

    agentOpts['width'] = layout.getLayout(options.layout).width
    agentOpts['height'] = layout.getLayout(options.layout).height

    meta_load = os.environ["GGA_EPI_IN"] if "GGA_EPI_IN" in os.environ else ""
    if meta_load != "" and os.path.isfile(meta_load):
        print('meta load: %s' % meta_load)
        agentOpts['load_file'] = meta_load
    elif options.gameToReplay is not None:
        agentOpts['load_file'] = 'saves/' + options.gameToReplay
    elif 'load_file' not in agentOpts.keys() and options.load_file is not None:
        agentOpts['load_file'] = 'saves/' + options.load_file
    else:
        agentOpts['load_file'] = None

    individualID = os.environ[
        'GGA_INDIVIDUAL_ID'] if "GGA_INDIVIDUAL_ID" in os.environ else 'None'
    parent1 = os.environ[
        'GGA_PARENT_1'] if "GGA_PARENT_1" in os.environ else 'None'
    parent2 = os.environ[
        'GGA_PARENT_2'] if "GGA_PARENT_2" in os.environ else 'None'
    print('individualID {}, parent1 {}, parent2 {}'.format(
        individualID, parent1, parent2))
    agentOpts['save_file'] = options.save_file if options.save_file else str(
        individualID)
    args['name'] = agentOpts['save_file']
    agentOpts['explore_action'] = options.explore_action

    agentOpts['train_start'] = options.train_start
    agentOpts['batch_size'] = options.batch_size
    agentOpts['mem_size'] = options.mem_size
    agentOpts['discount'] = options.discount
    agentOpts['lr'] = options.lr
    agentOpts['lr_cyclic'] = options.lr_cyclic
    agentOpts['rms_decay'] = options.rms_decay
    agentOpts['rms_eps'] = options.rms_eps
    agentOpts['eps'] = options.eps
    agentOpts['eps_final'] = options.eps_final
    agentOpts['eps_step'] = options.eps_step

    from datetime import datetime
    agentOpts['record_time'] = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining
    pacman = pacmanType(agentOpts)  # Instantiate Pacman with agentArgs
    args['pacman'] = pacman
    pacman.width = agentOpts['width']
    pacman.height = agentOpts['height']

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

    # Choose a ghost agent
    ghostType = loadAgent(options.ghost, noKeyboard)
    args['ghosts'] = [ghostType(i + 1) for i in range(options.numGhosts)]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout
    args['level'] = options.level

    if options.gameToReplay is not None:
        print(('Running game %s.' % options.gameToReplay))
        runGame(**args)
        sys.exit(0)

    return args
Exemple #13
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option('-n',
                      '--numGames',
                      dest='numGames',
                      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='mediumClassic')
    parser.add_option(
        '-p',
        '--pacmen',
        dest='pacmen',
        help=default(
            'the agent TYPE in the pacmanAgents module to use; separate by comma for multi Pacmen purpose'
        ),
        metavar='TYPE',
        default='KeyboardAgent')
    parser.add_option(
        '--pacmanAmounts',
        dest='pacmen_amounts',
        help=default('set the amount of Pacmen for each type specified'))
    parser.add_option('-t',
                      '--textGraphics',
                      action='store_true',
                      dest='textGraphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quietTextGraphics',
                      action='store_true',
                      dest='quietGraphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghostAgents module to use'),
        metavar='TYPE',
        default='RandomGhost')
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='numGhosts',
                      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',
        '--fixRandomSeed',
        action='store_true',
        dest='fixRandomSeed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--recordActions',
        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='gameToReplay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agentArgs',
        dest='agentArgs',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frameTime',
        dest='frameTime',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option(
        '-c',
        '--catchExceptions',
        action='store_true',
        dest='catchExceptions',
        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)
    parser.add_option(
        '--trainingGraphics',
        dest='trainingGraphics',
        action='store_true',
        help=default('Display graphics during training for pacman games.'),
        default=False)
    parser.add_option(
        '--trainingGraphicsUpdateFrequency',
        dest='trainingGraphicsUpdateFrequency',
        type='int',
        help=default(
            'Set graphics update frequency for the game board if trainingGraphics is set to True.'
        ),
        default=None)
    parser.add_option(
        '--evalGraphics',
        dest='evalGraphics',
        action='store_true',
        help=default('Display graphics during evaluation for pacman games.'),
        default=False)

    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.fixRandomSeed:
        random.seed('cs188')

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining >= 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining

    pacmen_types = [
        pacman_type.strip() for pacman_type in options.pacmen.split(",")
    ]
    pacmen_amounts = [
        int(pacman_amount.strip())
        for pacman_amount in options.pacmen_amounts.split(",")
    ]

    # to assign different colors for different Pacman type
    pacmen_types_corresponding_indexes = []
    new_type_beginning_index = 0
    for pacman_amount in pacmen_amounts:
        pacmen_types_corresponding_indexes.append([
            x
            for x in range(new_type_beginning_index, new_type_beginning_index +
                           pacman_amount)
        ])
        new_type_beginning_index += pacman_amount
    args[
        'pacmen_types_corresponding_indexes'] = pacmen_types_corresponding_indexes

    total_pacmen = 0
    # create pacmen
    args['pacmen'] = []
    pacmen_iter = 0
    pacman_type_start_index = 0

    for pacman_type in pacmen_types:
        try:
            pacmen_type_amount = int(pacmen_amounts[pacmen_iter])
        except:
            pacmen_type_amount = 1
        total_pacmen += pacmen_type_amount
        pacmanType = loadAgent(pacman_type, noKeyboard)
        pacmen = pacmanType(pacmen_type_amount, pacman_type,
                            pacman_type_start_index,
                            **agentOpts)  # Instantiate Pacman with agentArgs
        args['pacmen'] += pacmen
        pacman_type_start_index += pacmen_type_amount
        pacmen_iter += 1

    args['total_pacmen'] = total_pacmen

    # Choose and process a layout for enough pacmen
    args['layout'] = layout.getLayout(options.layout, total_pacmen)
    if args['layout'] == None:
        raise Exception("The layout " + options.layout + " cannot be found")

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

    # Choose a ghost agent
    ghostType = loadAgent(options.ghost, noKeyboard)
    args['ghosts'] = [
        ghostType(i)
        for i in range(total_pacmen, total_pacmen + options.numGhosts)
    ]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout

    args['graphics'] = options.trainingGraphics
    args['graphicsUpdateFrequency'] = options.trainingGraphicsUpdateFrequency

    args['evalGraphics'] = options.evalGraphics

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

    return args
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option('-n',
                      '--numGames',
                      dest='numGames',
                      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='mediumClassic')
    parser.add_option(
        '-p',
        '--pacman',
        dest='pacman',
        help=default('The name of the module in which pac man agent class is. \
                      Note : Pac man agent class name has to match module name with first letter capitalized \
                      e.g. if module name is pacman.py then the class name has to be Pacman '
                     ),
        metavar='TYPE',
        default='human')
    parser.add_option('-t',
                      '--textGraphics',
                      action='store_true',
                      dest='textGraphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quietTextGraphics',
                      action='store_true',
                      dest='quietGraphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghostAgents module to use'),
        metavar='TYPE',
        default='randyghost')
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='numGhosts',
                      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',
        '--fixRandomSeed',
        action='store_true',
        dest='fixRandomSeed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--recordActions',
        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='gameToReplay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agentArgs',
        dest='agentArgs',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frameTime',
        dest='frameTime',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option(
        '-c',
        '--catchExceptions',
        action='store_true',
        dest='catchExceptions',
        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)
    parser.add_option('--rshuffle',
                      action='store_true',
                      dest='rshuffle',
                      help=default('Turns on random shuffling for food dots'),
                      default=False)
    parser.add_option('--rgshuffle',
                      action='store_true',
                      dest='rshuffle',
                      help=default('Turns on random shuffling for ghosts'),
                      default=False)
    parser.add_option(
        '--maxfoods',
        dest='maxfoods',
        help=default(
            'Comma separated values to fixes max number of small and big foods. Applies only when rshuffle is activated.'
        ),
        default="1,0")

    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.fixRandomSeed:
        random.seed('cs188')

    # Choose a layout
    layout_name = options.layout
    tempLayout = ""
    if options.rshuffle:
        tempLayout = open("layouts/templay.lay", "w+")
        layoutStr = tryToLoadFile("layouts/" + layout_name + ".lay")
        layoutStr = layoutStr.replace("o", " ")
        layoutStr = layoutStr.replace(".", " ")
        layoutStr = list(layoutStr)
        foodlst = options.maxfoods.split(",")
        nb_foods = int(foodlst[0])
        try:
            nb_bigfoods = int(foodlst[1])
        except BaseException:
            nb_bigfoods = random.randint(0, 5)
            nb_foods -= nb_bigfoods
        indices = [i for i, x in enumerate(layoutStr) if x == " "]
        indices_foods = random.sample(set(indices),
                                      min(nb_foods, len(indices)))
        indices_bigfoods = random.sample(
            set(indices) - set(indices_foods),
            min(nb_bigfoods, len(set(indices) - set(indices_foods))))
        for i in indices_foods:
            layoutStr[i] = '.'
        for i in indices_bigfoods:
            layoutStr[i] = 'o'
        layoutStr = "".join(layoutStr)
        tempLayout.write(layoutStr)
        tempLayout.close()
        layout_name = "templay"
    args['layout'] = layout.getLayout(layout_name)
    if args['layout'] is None:
        raise Exception("The layout " + layout_name + " cannot be found")
    try:
        os.remove(tempLayout)
    except BaseException:
        pass
    # Choose a Pacman agent
    noKeyboard = options.gameToReplay is None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgentCustom(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining
    gpatterndict = dict()
    gpatterndict["leftyghost"] = 0
    gpatterndict["greedyghost"] = 1
    gpatterndict["randyghost"] = 2
    gpatterndict["rpickyghost"] = 3
    pacman = pacmanType(index=0,
                        time_eater=SCARED_TIME,
                        g_pattern=gpatterndict[options.ghost])
    args['pacman'] = pacman

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

    # Choose a ghost agent
    ghostType = loadAgentCustom(options.ghost, noKeyboard)
    args['ghosts'] = [ghostType(i + 1) for i in range(options.numGhosts)]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout

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

    return args
Exemple #15
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser

    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option(
        "-n",
        "--numGames",
        dest="numGames",
        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="mediumClassic",
    )
    parser.add_option(
        "-p",
        "--pacman",
        dest="pacman",
        help=default("the agent TYPE in the pacmanAgents module to use"),
        metavar="TYPE",
        default="KeyboardAgent",
    )
    parser.add_option(
        "-t",
        "--textGraphics",
        action="store_true",
        dest="textGraphics",
        help="Display output as text only",
        default=False,
    )
    parser.add_option(
        "-q",
        "--quietTextGraphics",
        action="store_true",
        dest="quietGraphics",
        help="Generate minimal output and no graphics",
        default=False,
    )
    parser.add_option(
        "-g",
        "--ghosts",
        dest="ghost",
        help=default("the ghost agent TYPE in the ghostAgents module to use"),
        metavar="TYPE",
        default="RandomGhost",
    )
    parser.add_option(
        "-k",
        "--numghosts",
        type="int",
        dest="numGhosts",
        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",
        "--fixRandomSeed",
        action="store_true",
        dest="fixRandomSeed",
        help="Fixes the random seed to always play the same game",
        default=False,
    )
    parser.add_option(
        "-r",
        "--recordActions",
        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="gameToReplay",
        help="A recorded game file (pickle) to replay",
        default=None,
    )
    parser.add_option(
        "-a",
        "--agentArgs",
        dest="agentArgs",
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"',
    )
    parser.add_option(
        "-x",
        "--numTraining",
        dest="numTraining",
        type="int",
        help=default("How many episodes are training (suppresses output)"),
        default=0,
    )
    parser.add_option(
        "--frameTime",
        dest="frameTime",
        type="float",
        help=default("Time to delay between frames; <0 means keyboard"),
        default=0.1,
    )
    parser.add_option(
        "-c",
        "--catchExceptions",
        action="store_true",
        dest="catchExceptions",
        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.fixRandomSeed:
        random.seed("cs188")

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

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args["numTraining"] = options.numTraining
        if "numTraining" not in agentOpts:
            agentOpts["numTraining"] = options.numTraining
    pacman = pacmanType(**agentOpts)  # Instantiate Pacman with agentArgs
    args["pacman"] = pacman

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

    # Choose a ghost agent
    ghostType = loadAgent(options.ghost, noKeyboard)
    args["ghosts"] = [ghostType(i + 1) for i in range(options.numGhosts)]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay

        args["display"] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay

        textDisplay.SLEEP_TIME = options.frameTime
        args["display"] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay

        args["display"] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args["numGames"] = options.numGames
    args["record"] = options.record
    args["catchExceptions"] = options.catchExceptions
    args["timeout"] = options.timeout

    # Special case: recorded games don't use the runGames method or args structure
    if options.gameToReplay != None:
        print("Replaying recorded game %s." % options.gameToReplay)
        import pickle

        f = open(options.gameToReplay, "rb")
        try:
            recorded = pickle.load(f)
        finally:
            f.close()
        recorded["display"] = args["display"]
        replayGame(**recorded)
        sys.exit(0)

    return args
Exemple #16
0
def readCommand( argv ):
  """
  Processes the command used to run pacman from the command line.
  """
  from optparse import OptionParser
  usageStr = """
  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 -p baselineTeam -b myTeam
                  - starts a fully automated game where the pacman team is a baseline team and ghost team is myTeam 
  """
  # TODO: Update above according to final defaults
  parser = OptionParser(usageStr)
  parser.add_option('-p', '--pacman', help=default('Pacman team'),
                    default='phase3Team') # TODO: Think about if we should leave this default
  parser.add_option('-g', '--ghost', help=default('Ghost team'),
                    default='P3oneGhostTeam')
  parser.add_option('--pacman-name', help=default('Pacman team name'),
                    default='Pacman')
  parser.add_option('--ghost-name', help=default('Ghost team name'),
                    default='Ghost')
  parser.add_option('--keys0', help='Make agent 0 (first pacman player) a keyboard agent', action='store_true',default=False)
  parser.add_option('--keys1', help='Make agent 1 (second pacman player) a keyboard agent', action='store_true',default=False)
  parser.add_option('--keys2', help='Make agent 2 (first ghost player) a keyboard agent', action='store_true',default=False)
  parser.add_option('--keys3', help='Make agent 3 (second ghost 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='defaultCapture')
  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', '--numGames', type='int',
                    help=default('Number of games to play'), default=10)
  parser.add_option('-f', '--fixRandomSeed', 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.')
  # TODO: This currently doesn't work, consider removing or fixing
  parser.add_option('-x', '--numTraining', dest='numTraining', type='int',
                    help=default('How many episodes are training (suppresses output)'), default=0) 
  parser.add_option('-c', '--catchExceptions', action='store_true', default=True,
                    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.textgraphics:
    import textDisplay
    args['display'] = textDisplay.PacmanGraphics()
  elif options.quiet:
    import textDisplay
    args['display'] = textDisplay.NullGraphics()
  elif options.super_quiet:
    import textDisplay
    args['display'] = textDisplay.NullGraphics()
    args['muteAgents'] = True
  else:
    import captureGraphicsDisplay
    # Hack for agents writing to the display
    captureGraphicsDisplay.FRAME_TIME = 0
    args['display'] = captureGraphicsDisplay.PacmanGraphics(options.pacman, options.ghost, options.zoom, 0, capture=True)
    import __main__
    __main__.__dict__['_display'] = args['display']


  args['pacmanTeamName'] = options.pacman_name
  args['ghostTeamName'] = options.ghost_name

  if options.fixRandomSeed: random.seed('cs188')

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

  # Choose a pacman agent
  nokeyboard = options.textgraphics or options.quiet
  pacmanAgents = loadAgents(True, 'phase3Team', nokeyboard, {})
  ghostAgents = loadAgents(False, 'P3oneGhostTeam', nokeyboard, {})

  # Assume 2 agents on the pacman side, and
  # variable amount (0-2) on the ghost side
  args['agents'] = pacmanAgents + ghostAgents

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

  # Generate the layouts
  args['layouts'] = generateLayouts(LAYOUT_SEED, ghostAgents)




  args['length'] = options.time
  args['numGames'] = options.numGames
  args['numTraining'] = options.numTraining
  args['record'] = options.record
  args['catchExceptions'] = options.catchExceptions
  return args
Exemple #17
0
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option('-n',
                      '--numGames',
                      dest='numGames',
                      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='mediumClassic')
    parser.add_option(
        '-p',
        '--pacman',
        dest='pacman',
        help=default('the agent TYPE in the pacmanAgents module to use'),
        metavar='TYPE',
        default='KeyboardAgent')
    parser.add_option('-t',
                      '--textGraphics',
                      action='store_true',
                      dest='textGraphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quietTextGraphics',
                      action='store_true',
                      dest='quietGraphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghostAgents module to use'),
        metavar='TYPE',
        default='RandomGhost')
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='numGhosts',
                      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',
        '--fixRandomSeed',
        action='store_true',
        dest='fixRandomSeed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--recordActions',
        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='gameToReplay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agentArgs',
        dest='agentArgs',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frameTime',
        dest='frameTime',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option(
        '-c',
        '--catchExceptions',
        action='store_true',
        dest='catchExceptions',
        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)
    ####################################################################################################################
    # CPSC 481 - Add option to trigger our Ghost Agents...
    ####################################################################################################################
    parser.add_option(
        '-o',
        '--originalGhosts',
        action='store_true',
        dest='originalGhosts',
        help='Load CPSC481 original ghosts Blinky, Pinky, Inky, Clyde',
        default=False)
    parser.add_option('--blinky',
                      action='store_true',
                      dest='blinky',
                      help='Load CPSC481 Blinky',
                      default=False)
    parser.add_option('--pinky',
                      action='store_true',
                      dest='pinky',
                      help='Load CPSC481 Pinky',
                      default=False)
    parser.add_option('--inky',
                      action='store_true',
                      dest='inky',
                      help='Load CPSC481 Inky',
                      default=False)
    parser.add_option('--clyde',
                      action='store_true',
                      dest='clyde',
                      help='Load CPSC481 Clyde',
                      default=False)
    parser.add_option('-d',
                      '--drawPath',
                      action='store_true',
                      dest='drawPath',
                      help='Draw path to target',
                      default=False)
    parser.add_option(
        '--reinforcementLearning',
        dest='weights',
        help=
        'Comma separated values of initial weights for qLearning features. e.g. "1,2,3,4"'
    )
    ####################################################################################################################

    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.fixRandomSeed: random.seed('cs188')

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

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining
    pacman = pacmanType(**agentOpts)  # Instantiate Pacman with agentArgs
    args['pacman'] = pacman

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

    ####################################################################################################################
    # CPSC 481 - We now have individual ghost classes now.... run them all with "-o" or individually i.e. "--blinky"
    ####################################################################################################################
    if options.originalGhosts is True:
        blinky = loadAgent('Blinky', noKeyboard)
        pinky = loadAgent('Pinky', noKeyboard)
        inky = loadAgent('Inky', noKeyboard)
        clyde = loadAgent('Clyde', noKeyboard)
        args['ghosts'] = [blinky(1), pinky(2), inky(3), clyde(4)]
    else:
        if options.blinky or options.pinky or options.inky or options.clyde:
            args['ghosts'] = []
            if options.blinky:
                args['ghosts'].append(
                    loadAgent('Blinky', noKeyboard)(len(args['ghosts']) + 1))
            if options.pinky:
                args['ghosts'].append(
                    loadAgent('Pinky', noKeyboard)(len(args['ghosts']) + 1))
            if options.inky:
                args['ghosts'].append(
                    loadAgent('Inky', noKeyboard)(len(args['ghosts']) + 1))
            if options.clyde:
                args['ghosts'].append(
                    loadAgent('Clyde', noKeyboard)(len(args['ghosts']) + 1))
        else:  # Default Ghosts...
            ghostType = loadAgent(options.ghost, noKeyboard)
            args['ghosts'] = [
                ghostType(i + 1) for i in range(options.numGhosts)
            ]

    import __main__
    if options.drawPath:
        __main__.__dict__['_drawPath'] = True
    else:
        __main__.__dict__['_drawPath'] = False

    # Attempt to bring in command line starting weights...
    if options.weights:
        __main__.__dict__['_weights'] = parseWeights(options.weights)
        __main__.__dict__['_reinforcementLearning'] = True
    else:
        __main__.__dict__['_reinforcementLearning'] = False

    ####################################################################################################################

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout

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

    return args
def readCommand(argv):
    """
    Processes the command used to run pacman from the command line.
    """
    from optparse import OptionParser
    usageStr = """
    USAGE:      python pacman.py <options>
    EXAMPLES:   (1) python pacman.py
                    - starts an interactive game
                (2) python pacman.py --layout smallClassic --zoom 2
                OR  python pacman.py -l smallClassic -z 2
                    - starts an interactive game on a smaller board, zoomed in
    """
    parser = OptionParser(usageStr)

    parser.add_option('-n',
                      '--numGames',
                      dest='numGames',
                      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='mediumClassic')
    parser.add_option(
        '-p',
        '--pacman',
        dest='pacman',
        help=default('the agent TYPE in the pacmanAgents module to use'),
        metavar='TYPE',
        default='KeyboardAgent')
    parser.add_option('-t',
                      '--textGraphics',
                      action='store_true',
                      dest='textGraphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quietTextGraphics',
                      action='store_true',
                      dest='quietGraphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghostAgents module to use'),
        metavar='TYPE',
        default='RandomGhost')
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='numGhosts',
                      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',
        '--fixRandomSeed',
        action='store_true',
        dest='fixRandomSeed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--recordActions',
        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='gameToReplay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agentArgs',
        dest='agentArgs',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frameTime',
        dest='frameTime',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option(
        '-c',
        '--catchExceptions',
        action='store_true',
        dest='catchExceptions',
        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.fixRandomSeed: random.seed('cs188')

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

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining
    pacman = pacmanType(**agentOpts)  # Instantiate Pacman with agentArgs
    args['pacman'] = pacman

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

    # Choose a ghost agent
    ghostType = loadAgent(options.ghost, noKeyboard)
    args['ghosts'] = [ghostType(i + 1) for i in range(options.numGhosts)]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout

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

    return args
Exemple #19
0
def readCommand(argv):
    """
  Processes the command used to run pacman from the command line.
  """
    from optparse import OptionParser
    usageStr = """
  USAGE:      python pacman.py <options>
  EXAMPLES:   (1) python pacman.py
                  - starts an interactive game
              (2) python pacman.py --layout smallClassic --zoom 2
              OR  python pacman.py -l smallClassic -z 2
                  - starts an interactive game on a smaller board, zoomed in
  """
    parser = OptionParser(usageStr)

    parser.add_option('-n',
                      '--numGames',
                      dest='numGames',
                      type='int',
                      help=default('the number of GAMES to play'),
                      metavar='GAMES',
                      default=1)
    parser.add_option(
        '-l',
        '--layout',
        dest='layouts',
        help=default('the LAYOUT_FILE from which to load the map layout'),
        metavar='LAYOUT_FILE',
        default=None)
    parser.add_option(
        '-p',
        '--pacman',
        dest='pacman',
        help=default('the agent TYPE in the competitionAgents module to use'),
        metavar='TYPE',
        default='KeyboardAgent')
    parser.add_option('--name',
                      metavar='NAME',
                      dest='name',
                      help=default('Name for this agent'),
                      default=None)
    parser.add_option('-t',
                      '--textGraphics',
                      action='store_true',
                      dest='textGraphics',
                      help='Display output as text only',
                      default=False)
    parser.add_option('-q',
                      '--quietTextGraphics',
                      action='store_true',
                      dest='quietGraphics',
                      help='Generate minimal output and no graphics',
                      default=False)
    parser.add_option(
        '-g',
        '--ghosts',
        dest='ghost',
        help=default('the ghost agent TYPE in the ghostAgents module to use'),
        metavar='TYPE',
        default=None)
    parser.add_option('-k',
                      '--numghosts',
                      type='int',
                      dest='numGhosts',
                      help=default('The maximum number of ghosts to use'),
                      default=6)
    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',
        '--fixRandomSeed',
        action='store_true',
        dest='fixRandomSeed',
        help='Fixes the random seed to always play the same game',
        default=False)
    parser.add_option(
        '-r',
        '--recordActions',
        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='gameToReplay',
                      help='A recorded game file (pickle) to replay',
                      default=None)
    parser.add_option(
        '-a',
        '--agentArgs',
        dest='agentArgs',
        help=
        'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"'
    )
    parser.add_option(
        '-x',
        '--numTraining',
        dest='numTraining',
        type='int',
        help=default('How many episodes are training (suppresses output)'),
        default=0)
    parser.add_option(
        '--frameTime',
        dest='frameTime',
        type='float',
        help=default('Time to delay between frames; <0 means keyboard'),
        default=0.1)
    parser.add_option('-i',
                      '--time',
                      type='int',
                      dest='time',
                      help=default('TIME limit of a game in moves'),
                      default=3000,
                      metavar='TIME')
    parser.add_option(
        '-c',
        '--catchExceptions',
        action='store_true',
        dest='catchExceptions',
        help='Turns on exception handling and timeouts during games',
        default=True)
    parser.add_option(
        '--timeout',
        dest='timeout',
        type='int',
        help=default(
            'Maximum length of time an agent can spend computing in a single game'
        ),
        default=3000)

    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.fixRandomSeed:
        print("Random seed reset")
        random.seed('cs188')
        random.getstate()

    # Choose a layout
    if options.layouts == None:
        lays = [
            f for f in os.listdir('./layouts')
            if os.path.isfile(os.path.join("./layouts", f))
        ]
        lays = [f for f in lays if re.match(r'level.*lay$', f)]
        lays.sort()
    else:
        lays = options.layouts.split(
            ',')  # split if multiple layouts specified
    print("Layouts : ", lays)
    # now load these layouts
    #if options.numGames==None: options.numGames=len(lays) # if not given play every layout
    layobj = []
    for i in range(len(lays)):
        layobj.append(layout.getLayout(lays[i]))
        if layobj[i] == None:
            raise Exception("The layout " + lays[i] + " cannot be found")
    args['layouts'] = layobj

    # Choose a Pacman agent
    noKeyboard = options.gameToReplay == None and (options.textGraphics
                                                   or options.quietGraphics)
    pacmanType = loadAgent(options.pacman, noKeyboard)
    agentOpts = parseAgentArgs(options.agentArgs)
    if options.numTraining > 0:
        args['numTraining'] = options.numTraining
        if 'numTraining' not in agentOpts:
            agentOpts['numTraining'] = options.numTraining
    pacman = pacmanType(**agentOpts)  # Instantiate Pacman with agentArgs
    args['pacman'] = pacman

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

    # Choose a ghost agent
    if options.ghost == None:
        import ghostAgents
        ghostnames = [f for f in dir(ghostAgents) if re.match(r'.*Ghost$', f)]
        ghostnames.reverse()
    else:
        ghostnames = options.ghost.split(
            ',')  # split if multiple layouts specified
    print("Ghosts : ", ghostnames)
    ghostobj = []
    for i in range(len(ghostnames)):
        ghostclass = loadAgent(ghostnames[i],
                               noKeyboard)  # load abstract class
        ghostobj.append(ghostclass(i + 1))  # generate instantiation
    args['ghosts'] = ghostobj
    args['numGhosts'] = options.numGhosts

    #ghostType = loadAgent(options.ghost, noKeyboard)
    #args['ghosts'] = [ghostType( i+1 ) for i in range( options.numGhosts )]

    # Choose a display format
    if options.quietGraphics:
        import textDisplay
        args['display'] = textDisplay.NullGraphics()
    elif options.textGraphics:
        import textDisplay
        textDisplay.SLEEP_TIME = options.frameTime
        args['display'] = textDisplay.PacmanGraphics()
    else:
        import graphicsDisplay
        args['display'] = graphicsDisplay.PacmanGraphics(
            options.zoom, frameTime=options.frameTime)
    args['numGames'] = options.numGames
    args['length'] = options.time
    args['record'] = options.record
    args['catchExceptions'] = options.catchExceptions
    args['timeout'] = options.timeout
    args['name'] = options.name

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

    return args