def execute(self, grades, moduleDict, solutionDict): #print moduleDict agentType = getattr(moduleDict['powerChoosingAgents'], self.agentName) agentOpts = pacman.parseAgentArgs(self.agentArgs) if self.agentArgs != '' else {} agent = agentType(**agentOpts) lay = layout.getLayout(self.layoutName, 3) #disp = self.question.getDisplay() import textDisplay disp = textDisplay.NullGraphics() #disp = graphicsDisplay.PacmanGraphics(1, frameTime = self.frameTime) #print disp random.seed(self.seed) stats = run(lay, self.layoutName, agent, self.ghosts, self.ghostPowers, disp, self.numGames) #games = pacman.runGames(lay, agent, self.ghosts, disp, self.numGames, False, catchExceptions=True, timeout=self.maxTime) #totalTime = time.time() - startTime #stats = {'time': totalTime, 'wins': [g.state.isWin() for g in games].count(True), # 'games': games, 'scores': [g.state.getScore() for g in games], # 'timeouts': [g.agentTimeout for g in games].count(True), 'crashes': [g.agentCrashed for g in games].count(True)} averageScore = sum(stats['scores']) / float(len(stats['scores'])) nonTimeouts = self.numGames - stats['timeouts'] wins = stats['wins'] print "Number of wins : " + str(wins) print "Minimum number of required wins : " +str(self.winsMinimum) if(wins >= self.winsMinimum): return self.testPass(grades) else: return self.testFail(grades)
def readCommand(argv): from optparse import OptionParser usageStr = """ USAGE: python carParking.py <options> """ parser = OptionParser(usageStr) parser.add_option('-d', '--driver', dest='driver', help=default('the agent TYPE in the driverAgent module to use'), metavar='TYPE', default='KeyboardAgent') parser.add_option('-l', '--layout', dest='layout', help=default('the LAYOUT_FILE from which to load the map layout'), metavar='LAYOUT_FILE', default='small') options, otherjunk = parser.parse_args(argv) if len(otherjunk) != 0: raise Exception('Command line input not understood: ' + str(otherjunk)) args = dict() args['display'] = graphicsDisplay.carParkingGraphics() # Choose a layout args['layout'] = layout.getLayout( options.layout ) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") # Choose a driver agent driverType = loadAgent(options.driver) args['driver'] = driverType() return args
def spawnGame(self, client, clientUrl): try: args = clientUrl.split("?")[1].split("&") clientKeys = dict([a.split("=") for a in args]) self.assignmentIds[client] = clientKeys['assignmentId'] self.hitIds[client] = clientKeys['hitId'] except Exception as e: print e return TIMEOUT = 30 layoutName, nGhosts = self.LAYOUTS[random.randint(0, len(self.LAYOUTS) - 1)] lyt = layout.getLayout(layoutName) self.pacmen[client] = pacmanAgents.GreedyAgent() pacman = self.pacmen[client] # pacmanAgents.GreedyAgent() #ghosts = [ghostAgents.RandomGhost(1), ghostAgents.DirectionalGhost(2)] ghosts = self.GHOSTS[:nGhosts] rules = ClassicGameRules(TIMEOUT) display = NetworkDisplay(client, layoutName) game = rules.newGame(lyt, pacman, ghosts, display, quiet=True) self.games[client] = game self.traces[client] = [] self.displays[client] = display game.net_start() self.tick(client)
def getLayoutInfo(req): thisLayout = layout.getLayout(options.layout); mapLayout = MapLayout(); mapLayout.height = thisLayout.height mapLayout.width = thisLayout.width mapLayout.map = [mapLayout.EMPTY] * (mapLayout.width * mapLayout.height) for i, j in thisLayout.walls.asList(): x = i; y = j; mapLayout.map[y * mapLayout.width + x] = mapLayout.WALL for i, j in thisLayout.food.asList(): x = i; y = j; mapLayout.map[y * mapLayout.width + x] = mapLayout.FOOD for i, j in thisLayout.agentPositions: x = j[0]; y = j[1]; if (i == False): mapLayout.map[y * mapLayout.width + x] = mapLayout.GHOST else: print "Pacman: ", x, ", ", y mapLayout.map[y * mapLayout.width + x] = mapLayout.PACMAN for i, j in thisLayout.capsules: x = i; y = j; mapLayout.map[y * mapLayout.width + x] = mapLayout.BIG_FOOD print mapLayout.map info = [mapLayout, options.numGhosts] return info
def getAssembly(absPath,count=2000000): fastq=fastq2reads.getReads(absPath) if count<=1 :count=1000 reads = [ read+'0' for read in fastq[1::4][:count]] SA = dc.getSA(''.join(reads)) links = overlap.getOverlap(SA,reads) links = layout.getLayout(links) return getPartAssembly(fastq,links,0)
def run_game(): lay = layout.getLayout('q1/1-ExactObserve') gameDisplay = graphicsDisplay.PacmanGraphics(frameTime = 0.1) # initialize the display of the playing field, needed here for the Pacman agent ghosts = [trackingTestClasses.SeededRandomGhostAgent(1)] # controls the behavior of a random ghost mr_pacman = BustersAgent(ghostAgents=ghosts, inference=inference.ExactInference, elapseTimeEnable=False) # controls the pacman behavior game = rules.newGame(lay, mr_pacman, ghostAgents=ghosts, display=gameDisplay, maxMoves=50) # instantiate a Game instance, see below game.run() # run the game, until Pacman catches a ghost.
def runGames( layout, randomLayout, pacman, ghosts, display, numGames, record, numTraining = 0, catchExceptions=False ): import __main__ import layout as layoutPy __main__.__dict__['_display'] = display rules = ClassicGameRules() games = [] layouts = [] # Load all layouts if randomLayout: mypath = "layouts/generatedLayouts/" layout_files = [f for f in listdir(mypath) if isfile(join(mypath, f))] for lay in layout_files: layout = layoutPy.getLayout("generatedLayouts/"+lay) if layout == None: raise Exception("The layout ", lay, "cannot be found") layouts.append(layout) for i in range( numGames ): beQuiet = i < numTraining if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: gameDisplay = display rules.quiet = False if randomLayout: #Pick a random layout layout = layouts[(int)(random.random()*len(layouts))] game = rules.newGame( layout, pacman, ghosts, gameDisplay, beQuiet, catchExceptions=catchExceptions) game.run() if not beQuiet: games.append(game) if record: import time, cPickle fname = ('recorded-game-%d' % (i + 1)) + '-'.join([str(t) for t in time.localtime()[1:6]]) f = file(fname, 'w') components = {'layout': layout, 'agents': game.agents, 'actions': game.moveHistory} cPickle.dump(components, f) f.close() if numGames > 1: scores = [game.state.getScore() for game in games] wins = [game.state.isWin() for game in games] winRate = wins.count(True)/ float(len(wins)) print 'Average Score:', sum(scores) / float(len(scores)) print 'Scores: ', ', '.join([str(score) for score in scores]) print 'Win Rate: %d/%d (%.2f)' % (wins.count(True), len(wins), winRate) print 'Record: ', ', '.join([ ['Loss', 'Win'][int(w)] for w in wins]) return games
def __init__(self, mapLayout, geneInfo): if type(mapLayout) == str: mapLayout = getLayout(mapLayout) self.mapInfo = mapLayout.mapInfo self.intersections = mapLayout.intersections self.crossroads = mapLayout.crossroads self.roads = mapLayout.roads self.cars = [] self.trafficlights = [] self.geneInfo = geneInfo self.initialTrafficLights() self.data = [[None for _ in range(r.getDistance())] for r in self.roads]
def initializeGameState(self): rospy.wait_for_service('pacman_inialize_game_state') try: getInitializationInfo = rospy.ServiceProxy('pacman_inialize_game_state', PacmanInitializationInfo) initInfo = getInitializationInfo() thisLayout = layout.getLayout(initInfo.layout) numGhosts = initInfo.numGhosts self.gameState.initialize(thisLayout, numGhosts) print "Game initialized" except rospy.ServiceException, e: print "Service call failed: %s"%e
def run(self): agentIndex = self.startAgentIndex agent0setup = self.agents[0].makeSetup() agent1setup = self.agents[1].makeSetup() self.state = GameState(getLayout("smallGrid.lay"),agent0setup, agent1setup) turns = 0 if SETUP: self.state.prnt(0) while True: if self.state.isWon(0): self.agent0wins += 1 break if self.state.isWon(1): self.agent1wins += 1 break if turns > 2000: self.num2000turns += 1 break turns += 1 agent = self.agents[agentIndex] action = agent.getAction(self.state) nextState = self.state.getSuccessor(agentIndex, action) self.numGames += 1 if self.learn: agent.learningRate = 1.0/self.numGames agent.update(self.state, action, nextState) self.state = nextState if BOARD: self.state.prnt(0) agentIndex = 1-agentIndex if BOARD: time.sleep(0.02) if self.learn: self.agents[0].final(self.state) self.agents[1].final(self.state) return turns
def spawnGame(self): TIMEOUT = 30 #LAYOUT = layout.getLayout('mediumClassic') layoutName = self.LAYOUTS[random.randint(0, len(self.LAYOUTS) - 1)] LAYOUT = layout.getLayout(layoutName) #LAYOUT = layout.getLayout(self.LAYOUTS[3]) PACMAN = self.pacman # pacmanAgents.GreedyAgent() #GHOSTS = [ghostAgents.RandomGhost(i+1) for i in range(2)] GHOSTS = [ghostAgents.RandomGhost(1), ghostAgents.DirectionalGhost(2)] RULES = ClassicGameRules(TIMEOUT) DISPLAY = self self.game = RULES.newGame(LAYOUT, PACMAN, GHOSTS, DISPLAY) self.game.net_start() self.tick() print >>self.log, ">>>", self.gameStep, layoutName
def run(layname, pac, ghosts, nGames = 1, name = 'games'): """ Runs a few games and outputs their statistics. """ starttime = time.time() lay = layout.getLayout(layname,3) disp = textDisplay.NullGraphics() print '*** Running %s on' % name, layname,'%d time(s).' % nGames games = pacman.runGames(lay, pac, ghosts, disp, nGames, False, catchExceptions=True ) print '*** Finished running %s on' % name, layname,'after %d seconds.' % (time.time() - starttime) stats = {'time': time.time() - starttime, 'wins': [g.state.isWin() for g in games].count(True), 'games': games, 'scores': [g.state.getScore() for g in games], 'timeouts': [g.agentTimeout for g in games].count(True)} print '*** Won %d out of %d games. Average score: %f ***' % (stats['wins'], len(games), sum(stats['scores']) * 1.0 / len(games)) return stats
def __init__(self, player1, player2): self.p1 = player1 self.p2 = player2 self.p1.protocol.sendLine("500:0:War was beginning...") self.p2.protocol.sendLine("500:1:War was beginning...") self.waiting = False self.turn = None self.numAgents = 0 self.agentIndex = 0 self.rules = None # Managing incoming moves self.nextStateNumber = 0 self.nextStateSem = threading.Semaphore() # Start up the game self.rules = capture.CaptureRules() self.game = self.rules.newGame(layout.getLayout(gameConfig['map']), range(0,gameConfig['nump']), gameConfig['graphics'], gameConfig['length'])
def __init__(self, layoutName): board = layout.getLayout(layoutName) self.walls = board.walls self.boardText = board.layoutText for i in xrange(len(self.boardText)): self.boardText[i] = list(self.boardText[i]) self.goal = None for x in xrange(board.food.width): for y in xrange(board.food.height): if board.food[x][y]: self.goal = (x, y) self.currentState = board.agentPositions[0][1] self._agentAlive = True self.ghosts = [] for agents in board.agentPositions[1:]: self.ghosts.append(agents[1])
def parseArgs(argv): """ Parse the arguments. """ parser = OptionParser() parser.add_option('-l', '--layout', dest='layout', type='str', default='single_cross') parser.add_option('-n', '--number', dest='number', type='int', default=10) parser.add_option('-z', '--zoom', dest='size', type='int', default=16) parser.add_option('-d', '--delay', dest='delay', type='float', default=0.2) parser.add_option('-g', '--generation', dest='generation', type='int', default=20) parser.add_option('-a', '--amount', dest='amount', type='int', default=20) parser.add_option('-s', '--save', dest='save', type='str', default='save.p') parser.add_option('-r', '--load', dest='load', type='str', default='') parser.add_option('--no_display', action='store_false', dest='display', default=True) parser.add_option('--no_simulate', action='store_false', dest='simulate', default=True) (options, otherjunk) = parser.parse_args(argv) if len(otherjunk) != 0: raise Exception('Command line input not understood: ' + str(otherjunk)) arguments = {} arguments['layoutName'] = options.layout arguments['layout'] = getLayout(options.layout) if arguments['layout'] is None: raise Exception('The layout ' + options.layout + " can't be found.") arguments['display'] = options.display arguments['simulate'] = options.simulate arguments['number'] = options.number arguments['size'] = options.size arguments['delay'] = options.delay arguments['generation'] = options.generation arguments['amount'] = options.amount arguments['save'] = options.save arguments['load'] = options.load return arguments
pg.display.init() if DEBUG: info = pg.display.Info() print(info) screen = pg.display.set_mode(DISPLAY, dflags) #sets display object pg.display.set_caption("Mokman! Use arrows or Controller Stick to move!") screenp = pg.display.get_surface() timer = pg.time.Clock() seconds = 0 up = down = left = right = running = False #get maze object whish creates Mokman mazes sprites as well as #initial enemy ghost spawns, teleports, food and powerups maplay = 'randomfMap' mapchunksf = 'mapchunks' mapchunks = layout.getLayout(mapchunksf) level = layout.getLayout(maplay) global levelt #global mapglobal mapglobal = mapchunks levelt = level.layoutText #t for template to load level mapchunkst = mapglobal.layoutText X_DIM = level.width Y_DIM = level.height #get sound resources snd_pellet = { 0: pg.mixer.Sound(os.path.join(SCRIPT_PATH, "res", "sounds", "pellet1.wav")), 1: pg.mixer.Sound(os.path.join(SCRIPT_PATH, "res", "sounds", "pellet2.wav"))
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 <<<<<<< HEAD if options.fixRandomSeed: random.seed('cs188') ======= if options.fixRandomSeed: random.seed('cs123') >>>>>>> 8623eb170f7b44d0cb71352681ed646d62cf21f6 # 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'])
def read_command(argv): from optparse import OptionParser usage_str = """ USAGE: python experiment.py <options> EXAMPLES: (1) python experiment.py --layout testRL --pacman=AlphaBetaAgent --ghosts=QLearningGhost --numTraining=10 """ parser = OptionParser(usage_str) 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( '-a', '--agentArgs', dest='agentArgs', help= 'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"' ) parser.add_option( '-g', '--ghosts', dest='ghost', help=default('the ghost agent TYPE in the ghostAgents module to use'), metavar='TYPE', default='QLearningGhost') parser.add_option( '-x', '--numTraining', dest='numTraining', type='int', help=default('How many episodes are training (suppresses output)'), default=10) parser.add_option('-k', '--numghosts', type='int', dest='numGhosts', help=default('The maximum number of ghosts to use'), default=4) 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( '--ghostArgs', dest='ghostArgs', help= 'Comma separated values sent to ghost. e.g. "opt1=val1,opt2,opt3=val3"' ) 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'] is None: raise Exception("The layout " + options.layout + " cannot be found") # Initialize a Pacman agent pacmanType = loadAgent(options.pacman, nographics=False) pacmanOpts = parseAgentArgs(options.agentArgs) pacman = pacmanType( **pacmanOpts ) # Instantiate Pacman with depth=2 # To Do: allow depth as an argument args['pacman'] = pacman # Initialize Ghost agents ghostType = loadAgent(options.ghost, nographics=False) ghostOpts = parseAgentArgs(options.ghostArgs) args['ghosts'] = [ ghostType(index=i + 1, numTraining=options.numTraining, **ghostOpts) for i in range(options.numGhosts) ] # Set number of training episodes for experiment args['numTraining'] = options.numTraining return args, options
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
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 supress 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 import 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) pacman = pacmanType() # Figure out how to instantiate pacman 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: agentOpts = parseAgentArgs(options.agentArgs) pacman.setOptions(agentOpts) # HACK HACK 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
def execute(self, grades, moduleDict, solutionDict): startTime = time.time() agentType = getattr(moduleDict['multiAgents'], self.agentName) agentOpts = pacman.parseAgentArgs( self.agentArgs) if self.agentArgs != '' else {} agent = agentType(**agentOpts) lay = layout.getLayout(self.layoutName, 3) disp = self.question.getDisplay() random.seed(self.seed) games = pacman.runGames(lay, agent, self.ghosts, disp, self.numGames, False, catchExceptions=True, timeout=self.maxTime) totalTime = time.time() - startTime stats = { 'time': totalTime, 'wins': [g.state.isWin() for g in games].count(True), 'games': games, 'scores': [g.state.getScore() for g in games], 'timeouts': [g.agentTimeout for g in games].count(True), 'crashes': [g.agentCrashed for g in games].count(True) } averageScore = sum(stats['scores']) / float(len(stats['scores'])) nonTimeouts = self.numGames - stats['timeouts'] wins = stats['wins'] def gradeThreshold(value, minimum, thresholds, name): points = 0 passed = (minimum == None) or (value >= minimum) if passed: for t in thresholds: if value >= t: points += 1 return (passed, points, value, minimum, thresholds, name) results = [ gradeThreshold(averageScore, self.scoreMinimum, self.scoreThresholds, "average score"), gradeThreshold(nonTimeouts, self.nonTimeoutMinimum, self.nonTimeoutThresholds, "games not timed out"), gradeThreshold(wins, self.winsMinimum, self.winsThresholds, "wins") ] totalPoints = 0 for passed, points, value, minimum, thresholds, name in results: if minimum == None and len(thresholds) == 0: continue # print passed, points, value, minimum, thresholds, name totalPoints += points if not passed: assert points == 0 self.addMessage("%s %s (fail: below minimum value %s)" % (value, name, minimum)) else: self.addMessage("%s %s (%s of %s points)" % (value, name, points, len(thresholds))) if minimum != None: self.addMessage(" Grading scheme:") self.addMessage(" < %s: fail" % (minimum, )) if len(thresholds) == 0 or minimum != thresholds[0]: self.addMessage(" >= %s: 0 points" % (minimum, )) for idx, threshold in enumerate(thresholds): self.addMessage(" >= %s: %s points" % (threshold, idx + 1)) elif len(thresholds) > 0: self.addMessage(" Grading scheme:") self.addMessage(" < %s: 0 points" % (thresholds[0], )) for idx, threshold in enumerate(thresholds): self.addMessage(" >= %s: %s points" % (threshold, idx + 1)) if any([not passed for passed, _, _, _, _, _ in results]): totalPoints = 0 return self.testPartial(grades, totalPoints, self.maxPoints)
def readCommand(argv): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usageStr = """ USAGE: python busters.py <options> EXAMPLE: python busters.py --layout bigHunt - starts an interactive game on a big board """ 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='oneHunt') parser.add_option( '-p', '--pacman', dest='pacman', help=default('the agent TYPE in the pacmanAgents module to use'), metavar='TYPE', default='BustersKeyboardAgent') parser.add_option( '-a', '--agentArgs', dest='agentArgs', help= 'Comma seperated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"' ) parser.add_option( '-g', '--ghosts', dest='ghost', help=default('the ghost agent TYPE in the ghostAgents module to use'), metavar='TYPE', default='StaticGhost') parser.add_option('-q', '--quietTextGraphics', action='store_true', dest='quietGraphics', help='Generate minimal output and no graphics', default=False) 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('-s', '--showGhosts', action='store_true', dest='showGhosts', help='Renders the ghosts in the display (cheating)', default=True) parser.add_option( '-t', '--frameTime', dest='frameTime', type='float', help=default('Time to delay between frames; <0 means keyboard'), default=0.1) 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('bustersPacman') # Choose a layout args['layout'] = layout.getLayout(options.layout) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") # Choose a ghost agent ghostType = loadAgent(options.ghost, options.quietGraphics) args['ghosts'] = [ghostType(i + 1) for i in range(options.numGhosts)] # Choose a Pacman agent noKeyboard = options.quietGraphics pacmanType = loadAgent(options.pacman, noKeyboard) agentOpts = parseAgentArgs(options.agentArgs) agentOpts['ghostAgents'] = args['ghosts'] pacman = pacmanType(**agentOpts) # Instantiate Pacman with agentArgs args['pacman'] = pacman import graphicsDisplay args['display'] = graphicsDisplay.FirstPersonPacmanGraphics(options.zoom, \ options.showGhosts, \ frameTime = options.frameTime) args['numGames'] = options.numGames return args
def runGames(layout_name, pacman, ghosts, display, numGames, record, numTraining=0, catchExceptions=False, timeout=30): import __main__ __main__.__dict__['_display'] = display rules = ClassicGameRules(timeout) layout2 = layout.getLayout(layout_name) pacman.selfTesting = False pacman.currentTrainingEpisode = 0 games = [] testScores = [] testWins = [] for i in range(numGames): beQuiet = i < numTraining testing = i >= numTraining # beQuiet = i < 100 beQuiet = False # beQuiet = True if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() # rules.quiet = True else: # import textDisplay # gameDisplay = textDisplay.NullGraphics() gameDisplay = display rules.quiet = False game = rules.newGame(layout2, pacman, ghosts, gameDisplay, beQuiet, testing, catchExceptions) game.run() if not beQuiet: games.append(game) if record: import time, cPickle fname = ('recorded-game-%d' % (i + 1)) + '-'.join( [str(t) for t in time.localtime()[1:6]]) f = file(fname, 'w') components = {'layout': layout, 'actions': game.moveHistory} cPickle.dump(components, f) f.close() if (i % testInterval == 0) and i > 0: pacman.selfTesting = True pacman.currentTrainingEpisode = i try: epsilonCopy = pacman.arbitrator.epsilon alphaCopy = pacman.arbitrator.alpha pacman.arbitrator.epsilon = 0.00 pacman.arbitrator.alpha = 0.0 except Exception, data: sys.exc_clear() epsilonCopy = pacman.epsilon alphaCopy = pacman.alpha pacman.epsilon = 0.00 pacman.alpha = 0.0 try: arbitratorEpsilonCopy = pacman.arbitratorEpsilon pacman.arbitratorEpsilon = 0.01 except Exception, data: sys.exc_clear() pass scores = [] sumScore = 0.0 winCount = 0 for j in range(testRepitition): game = rules.newGame(layout2, pacman, ghosts, gameDisplay, True, True, catchExceptions) game.run() sumScore += game.state.getScore() scores.append(round(game.state.getScore(), 2)) if game.state.isWin(): winCount += 1 print "Testing at", i, scores, "Won", winCount testScores.append(round(sumScore / testRepitition, 2)) testWins.append(winCount) print testScores print testWins pacman.selfTesting = False try: pacman.arbitrator.epsilon = epsilonCopy pacman.arbitrator.alpha = alphaCopy except Exception, data: sys.exc_clear() pacman.epsilon = epsilonCopy pacman.alpha = alphaCopy
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
this won't be true if seed=None, for example. """ self.np_random, seed1 = seeding.np_random(seed) # Derive a random seed. This gets passed as a uint, but gets # checked as an int elsewhere, so we need to keep it below # 2**31. seed2 = seeding.hash_seed(seed1 + 1) % 2**31 random.seed(seed2) return [seed1, seed2] if __name__ == '__main__': import layout learn_layout = layout.getLayout('learnGrid') ghosts = [] #display = VizGraphics(includeInfoPane=False, zoom=1) display = PacPosGraphics() env = PacmanEnv(learn_layout, ghosts, display) env.reset() state = env.game.state pacman = RandomAgent(onlyLegal=False) #pacman = LeftTurnAgent() #pacman = GreedyAgent() totals = [] total = 0 games = 0 while games < 100: obs, reward, done, info = env.step(pacman.getAction(state))
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('cs188') # Choose a layout import 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) pacman = pacmanType() # Figure out how to instantiate pacman if 'setDepth' in dir(pacman): pacman.setDepth(options.depth) if 'useBetterEvaluation' in dir(pacman) and options.betterEval: pacman.useBetterEvaluation() try: import evaluation if 'setEvaluation' in dir(pacman):
def execute(self, grades, moduleDict, solutionDict): startTime = time.time() agentType = getattr(moduleDict['multiAgents'], self.agentName) agentOpts = pacman.parseAgentArgs( self.agentArgs) if self.agentArgs != '' else {} agent = agentType(**agentOpts) lay = layout.getLayout(self.layoutName, 3) disp = self.question.getDisplay() random.seed(self.seed) games = pacman.runGames(lay, agent, self.ghosts, disp, self.numGames, False, catchExceptions=True, timeout=self.maxTime) totalTime = time.time() - startTime stats = { 'time': totalTime, 'wins': [g.state.isWin() for g in games].count(True), 'games': games, 'scores': [g.state.getScore() for g in games], 'timeouts': [g.agentTimeout for g in games].count(True), 'crashes': [g.agentCrashed for g in games].count(True) } averageScore = sum(stats['scores']) / float(len(stats['scores'])) nonTimeouts = self.numGames - stats['timeouts'] wins = stats['wins'] def gradeThreshold(value, minimum, thresholds, name): points = 0 passed = (minimum == None) or (value >= minimum) if passed: for t in thresholds: if value >= t: points += 1 return (passed, points, value, minimum, thresholds, name) results = [ gradeThreshold(averageScore, self.scoreMinimum, self.scoreThresholds, "average score"), gradeThreshold(nonTimeouts, self.nonTimeoutMinimum, self.nonTimeoutThresholds, "games not timed out"), gradeThreshold(wins, self.winsMinimum, self.winsThresholds, "wins") ] totalPoints = 0 for passed, points, value, minimum, thresholds, name in results: if minimum == None and len(thresholds) == 0: continue # print passed, points, value, minimum, thresholds, name subtest_maxPoints = 0 if passed: if name == "average score": if self.agentName == "ReflexAgent": points_mapping = {0: 0, 1: 3, 2: 5} subtest_maxPoints = 5 elif self.agentName == "ExpectimaxAgent": points_mapping = {0: 0, 1: 1, 2: 2} subtest_maxPoints = 2 else: raise ValueError( "Must have either ReflexAgent or Expectimax Agent") points = points_mapping[points] elif name == "games not timed out": pass elif name == "wins": if self.agentName == "ReflexAgent": points_mapping = {0: 0, 1: 5} subtest_maxPoints = 5 elif self.agentName == "ExpectimaxAgent": points_mapping = {0: 0, 1: 5, 2: 8} subtest_maxPoints = 8 else: raise ValueError( "Must have either ReflexAgent or Expectimax Agent") points = points_mapping[points] else: raise ValueError( "name must be 'average score', 'games not timed out', or 'wins'" ) totalPoints += points if not passed: assert points == 0 self.addMessage("%s %s (fail: below minimum value %s)" % (value, name, minimum)) else: self.addMessage("%s %s (%s of %s points)" % (value, name, points, subtest_maxPoints)) # Not printing grading schema because ours has a very different structure # if minimum != None: # self.addMessage(" Grading scheme:") # self.addMessage(" < %s: fail" % (minimum,)) # if len(thresholds)==0 or minimum != thresholds[0]: # self.addMessage(" >= %s: 0 points" % (minimum,)) # for idx, threshold in enumerate(thresholds): # self.addMessage(" >= %s: %s points" % (threshold, idx+1)) # elif len(thresholds) > 0: # self.addMessage(" Grading scheme:") # self.addMessage(" < %s: 0 points" % (thresholds[0],)) # for idx, threshold in enumerate(thresholds): # self.addMessage(" >= %s: %s points" % (threshold, idx+1)) if any([not passed for passed, _, _, _, _, _ in results]): totalPoints = 0 return self.testPartial(grades, totalPoints, self.maxPoints)
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. """ 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 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.FirstPersonPacmanGraphics( 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
save(Result(args['layoutName'], cars), args['save']) else: mapLayout = args['layout'] gene = Gene(mapLayout.getTrafficLights()) geneInfo = GeneInfo(gene) carmap = CarMap(mapLayout, geneInfo) cars = randomStartEndPoint(args['number']) carmap = CarMap(mapLayout, geneInfo) simulation = Simulation(cars, carmap) app = Graphic(mapLayout.mapInfo, carmap.cars, carmap.trafficlights, args['size']) start_new_thread(run, ()) app.run() else: r = load(args['load']) mapLayout = getLayout(r.layout) geneStr = raw_input('Input Gene String: ') gene = Gene(mapLayout.getTrafficLights(), False, geneStr) geneInfo = GeneInfo(gene) carmap = CarMap(mapLayout, geneInfo) cars = r.cars simulation = Simulation(cars, carmap) if args['display'] is True: app = Graphic(mapLayout.mapInfo, carmap.cars, carmap.trafficlights, args['size']) start_new_thread(run, ()) app.run() else: run()
def runGames(layoutName, pacman, ghosts, numGames, numGamesToDisplay=1, numTraining=0, catchExceptions=False, timeout=30, **args): """ A copy of same function in pacman.py """ #__main__.__dict__['_display'] = display layout = getLayout(layoutName) rules = ClassicGameRules(timeout) games = [] avgScore = 0 winCnt = 0 name = getTitleName(pacman, layoutName, numGames) numGames = max(numGames, numGamesToDisplay) numTraining = numGames - numGamesToDisplay frameDir = f"gif/{name}" import shutil # delete older dir if os.path.exists(frameDir): input("FrameDir exist, confirm to delete it") shutil.rmtree(frameDir) os.mkdir(frameDir) for i in range(numGames): print( f"({i}/{numGames}) game start, avgScore {avgScore:.2f} winCnt {winCnt}" ) #beQuiet = i < numTraining beQuiet = (i < numTraining) if beQuiet: # Suppress output and graphics gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: import graphicsDisplay gameDisplay = graphicsDisplay.PacmanGraphicsGif( zoom=1.0, capture=False, frameTime=0.001, storeFrameDir=frameDir, gameIdx=i - numTraining + 1, totalGame=numGamesToDisplay) rules.quiet = False game = rules.newGame(layout, pacman, ghosts, gameDisplay, beQuiet, catchExceptions) game.run() avgScore = (avgScore * i + game.state.getScore()) / (i + 1) winCnt += game.state.isWin() games.append(game) # end of simulation of games # report and save the results scores = [game.state.getScore() for game in games] wins = [game.state.isWin() for game in games] winRate = wins.count(True) / float(len(wins)) print('Average Score:', sum(scores) / float(len(scores))) #print('Scores: ', ', '.join([str(score) for score in scores])) print('Win Rate: %d/%d (%.2f)' % (wins.count(True), len(wins), winRate)) #print('Record: ', ', '.join( # [['Loss', 'Win'][int(w)] for w in wins])) ## save the result np.save(f"data/{name}.npy", { 'wins': wins, 'scores': scores }, allow_pickle=True) return games
def execute(self, grades, moduleDict, solutionDict): startTime = time.time() agentType = getattr(moduleDict['multiAgents'], self.agentName) agentOpts = pacman.parseAgentArgs(self.agentArgs) if self.agentArgs != '' else {} agent = agentType(**agentOpts) lay = layout.getLayout(self.layoutName, 3) disp = textDisplay.NullGraphics() random.seed(self.seed) games = pacman.runGames(lay, agent, self.ghosts, disp, self.numGames, False, catchExceptions=True, timeout=self.maxTime) totalTime = time.time() - startTime stats = {'time': totalTime, 'wins': [g.state.isWin() for g in games].count(True), 'games': games, 'scores': [g.state.getScore() for g in games], 'timeouts': [g.agentTimeout for g in games].count(True), 'crashes': [g.agentCrashed for g in games].count(True)} averageScore = sum(stats['scores']) / float(len(stats['scores'])) nonTimeouts = self.numGames - stats['timeouts'] wins = stats['wins'] def gradeThreshold(value, minimum, thresholds, name): points = 0 passed = (minimum == None) or (value >= minimum) if passed: for t in thresholds: if value >= t: points += 1 return (passed, points, value, minimum, thresholds, name) results = [gradeThreshold(averageScore, self.scoreMinimum, self.scoreThresholds, "average score"), gradeThreshold(nonTimeouts, self.nonTimeoutMinimum, self.nonTimeoutThresholds, "games not timed out"), gradeThreshold(wins, self.winsMinimum, self.winsThresholds, "wins")] totalPoints = 0 for passed, points, value, minimum, thresholds, name in results: if minimum == None and len(thresholds)==0: continue # print passed, points, value, minimum, thresholds, name totalPoints += points if not passed: assert points == 0 self.addMessage("%s %s (fail: below minimum value %s)" % (value, name, minimum)) else: self.addMessage("%s %s (%s of %s points)" % (value, name, points, len(thresholds))) if minimum != None: self.addMessage(" Grading scheme:") self.addMessage(" < %s: fail" % (minimum,)) if len(thresholds)==0 or minimum != thresholds[0]: self.addMessage(" >= %s: 0 points" % (minimum,)) for idx, threshold in enumerate(thresholds): self.addMessage(" >= %s: %s points" % (threshold, idx+1)) elif len(thresholds) > 0: self.addMessage(" Grading scheme:") self.addMessage(" < %s: 0 points" % (thresholds[0],)) for idx, threshold in enumerate(thresholds): self.addMessage(" >= %s: %s points" % (threshold, idx+1)) if any([not passed for passed, _, _, _, _, _ in results]): totalPoints = 0 return self.testPartial(grades, totalPoints, self.maxPoints)
server = app.server df = getData('PASSES') sheets = getSheets() df_list = list() x_text_list = list() y_text_list = list() hover_list = list() x_min_list = list() x_max_list = list() y_min_list = list() y_max_list = list() app = getLayout(app, len(df)) number_sheets = 6 for index in range(number_sheets): df = getData(sheets[index]) x_text = getXAxisText(sheets[index]) y_text = getYAxisText(sheets[index]) hover = ( "%%{text} [%%{customdata[0]}] <br><br>%s = %%{x}<br>%s = %%{y}<extra></extra>" % (x_text, y_text)) x_min = 0 x_max = df[x_text].max() + 5
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
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
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, ) parser.add_option( "--frameTime", dest="frameTime", type="float", help=default("Time to delay between frames, <0 means keyboard"), default=0.1, ) 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, options.frameTime) 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
def readCommand( argv ): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usageStr = """ USAGE: python pacman.py <options> EXAMPLE: python sonar.py --layout bigHunt - starts an interactive game on a big board """ 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='smallHunt') parser.add_option('-p', '--pacman', dest='pacman', help=default('the agent TYPE in the pacmanAgents module to use'), metavar='TYPE', default='SonarKeyboardAgent') parser.add_option('-k', '--numghosts', type='int', dest='numGhosts', help=default('The maximum number of ghosts to use'), default=4) parser.add_option('-d', '--distributeGhosts', action='store_true', help=default('Place the ghosts randomly'), default=False) 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('-s', '--showGhosts', action='store_true', dest='showGhosts', help='Renders the ghosts in the display (cheating)', 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('sonarPacman') # Choose a layout import layout args['layout'] = layout.getLayout( options.layout ) if args['layout'] == None: raise "The layout " + options.layout + " cannot be found" # Choose a pacman agent pacmanType = loadAgent(options.pacman) pacman = pacmanType() # Figure out how to instantiate pacman args['pacman'] = pacman # Choose a ghost agent args['numGhosts'] = options.numGhosts # Choose a display format import graphicsDisplay args['display'] = graphicsDisplay.FirstPersonPacmanGraphics(options.zoom, options.showGhosts) args['numGames'] = options.numGames args['record'] = options.record 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
def getStartState(layoutName): s = pacman.GameState() lay1 = layout.getLayout(layoutName,3) s.initialize(lay1, 0) return s
def buildExperience(self, layoutName, displayActive=False, limit=None): import pacmanAgents, ghostAgents from pacman import ClassicGameRules from game import Directions import layout theLayout = layout.getLayout(layoutName) if theLayout == None: raise Exception("The layout " + layoutName + " cannot be found") display = None # Choose a display format if not displayActive: import textDisplay display = textDisplay.NullGraphics() else: import graphicsDisplay display = graphicsDisplay.PacmanGraphics(frameTime=0.01) rules = ClassicGameRules() agents = [pacmanAgents.GreedyAgent()] + [ ghostAgents.DirectionalGhost(i + 1) for i in range(theLayout.getNumGhosts()) ] game = rules.newGame(theLayout, agents[0], agents[1:], display) initialState = game.state display.initialize(initialState.data) exploredStateHashes = {initialState.__hash__()} pendingStates = {initialState} counter = 0 while pendingStates: pendingState = pendingStates.pop() for action in pendingState.getLegalActions(): if action == Directions.STOP: continue try: # Execute the action newState = util.getSuccessor(agents, display, pendingState, action) reward = newState.data.score - pendingState.data.score self.remember(pendingState, action, reward, newState) counter += 1 if not (newState.isWin() or newState.isLose( )) and newState.__hash__() not in exploredStateHashes: exploredStateHashes.add(newState.__hash__()) pendingStates.add(newState) except Exception, e: #print(e) pass if counter % 100 == 0: self.persist() if counter % 2000 == 0: print("Explored " + str(counter) + " states") if limit is not None and counter > limit: break
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 Bayesians - starts a fully automated game where the red team is a baseline team and blue team is Bayesians """ 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("--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("--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" ) parser.add_option( "--frameTime", dest="frameTime", type="float", help=default("Time to delay between frames; <0 means keyboard"), default=0.1, ) 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 captureGraphicsDisplay args["display"] = captureGraphicsDisplay.PacmanGraphics( options.red, options.blue, options.zoom, options.frameTime, capture=True ) import __main__ __main__.__dict__["_display"] = args["display"] args["redTeamName"] = options.red args["blueTeamName"] = options.blue 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 = cPickle.load(urlopen(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 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.startswith("RANDOM"): args["layout"] = 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: args["layout"] = layout.getLayout(options.layout) 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
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
from searchAgents import SearchAgent, AStarCornersAgent, AStarFoodSearchAgent, ClosestDotSearchAgent from searchAgents import PositionSearchProblem import util import search import layout import pacman from game import Actions, Directions from util import Stack, Queue, PriorityQueue from graphicsDisplay import PacmanGraphics tiny_corner_layout = layout.getLayout('tinyCorners') medium_corner_layout = layout.getLayout('mediumCorners') big_corner_layout = layout.getLayout('bigCorners') tiny_maze = layout.getLayout('tinymaze') medium_classic = layout.getLayout('mediumClassic') test_search = layout.getLayout('testSearch') tricky_search = layout.getLayout('trickySearch') rules = pacman.ClassicGameRules(0) sa = AStarFoodSearchAgent() gameDisplay = PacmanGraphics(zoom=0.9, frameTime=0.1) # visualization game = rules.newGame(tricky_search, sa, [], gameDisplay, False, False) game.run() ''' '''
mapLayout = args['layout'] gene = Gene(mapLayout.getTrafficLights()) geneInfo = GeneInfo(gene) carmap = CarMap(mapLayout, geneInfo) cars = randomStartEndPoint(args['number']) carmap = CarMap(mapLayout, geneInfo) simulation = Simulation(cars, carmap) app = Graphic(mapLayout.mapInfo, carmap.cars, carmap.trafficlights, args['size']) start_new_thread(run, ()) app.run() else: r = load(args['load']) mapLayout = getLayout(r.layout) geneStr = raw_input('Input Gene String: ') gene = Gene(mapLayout.getTrafficLights(), False, geneStr) geneInfo = GeneInfo(gene) carmap = CarMap(mapLayout, geneInfo) cars = r.cars simulation = Simulation(cars, carmap) if args['display'] is True: app = Graphic(mapLayout.mapInfo, carmap.cars, carmap.trafficlights, args['size']) start_new_thread(run, ()) app.run() else: run()
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
from display import * import layout from graphicsDisplay import * from BotTracker import * from makePacbot import * import random from flask import Flask, jsonify from serial import Serial from json import dumps import copy from threading import Thread, Lock, Timer import time lock = Lock() restart = False lay = layout.getLayout("pacbotLayout.lay") pacbot = PacBot((23, 13), "right") game = GameState(copy.deepcopy(grid), lay, pacbot) botTracker = BotTracker() graphics = None session = True app = Flask("Pacman") @app.route('/pac-bot') def pacBot(): return jsonify(getFormattedGameData()) def getFormattedGameData():
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('--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('--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 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 args['blueTeamName'] = options.blue 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 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.startswith('RANDOM'): args['layout'] = 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: args['layout'] = layout.getLayout(options.layout) 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
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
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
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) 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 busters.py <options> EXAMPLE: python busters.py --layout bigHunt - starts an interactive game on a big board """ 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='oneHunt') parser.add_option('-p', '--pacman', dest='pacman', help=default('the agent TYPE in the pacmanAgents module to use'), metavar='TYPE', default='BustersKeyboardAgent') parser.add_option('-a','--agentArgs',dest='agentArgs', help='Comma seperated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"') 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('-q', '--quietTextGraphics', action='store_true', dest='quietGraphics', help='Generate minimal output and no graphics', default=False) 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('-s', '--showGhosts', action='store_true', dest='showGhosts', help='Renders the ghosts in the display (cheating)', default=False) parser.add_option('-t', '--frameTime', dest='frameTime', type='float', help=default('Time to delay between frames; <0 means keyboard'), default=0.1) 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('bustersPacman') # Choose a layout args['layout'] = layout.getLayout( options.layout ) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") # Choose a ghost agent ghostType = loadAgent(options.ghost, options.quietGraphics) args['ghosts'] = [ghostType( i+1 ) for i in range( options.numGhosts )] # Choose a Pacman agent noKeyboard = options.quietGraphics pacmanType = loadAgent(options.pacman, noKeyboard) agentOpts = parseAgentArgs(options.agentArgs) agentOpts['ghostAgents'] = args['ghosts'] pacman = pacmanType(**agentOpts) # Instantiate Pacman with agentArgs args['pacman'] = pacman import graphicsDisplay args['display'] = graphicsDisplay.FirstPersonPacmanGraphics(options.zoom, \ options.showGhosts, \ frameTime = options.frameTime) args['numGames'] = options.numGames return args
from game import GameStateData from game import Game from game import Directions from game import Actions from util import nearestPoint from util import manhattanDistance import searchAgents import util, layout import sys, types, time, random, os lo = layout.getLayout("tinyCorners") cp = searchAgents.CornersProblem()
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
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.FirstPersonPacmanGraphics(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
from searchAgents import SearchAgent, AStarCornersAgent, AStarFoodSearchAgent, ClosestDotSearchAgent from searchAgents import PositionSearchProblem import util import search import layout import pacman from game import Actions, Directions from util import Stack, Queue, PriorityQueue from graphicsDisplay import PacmanGraphics tiny_corner_layout = layout.getLayout('tinyCorners') medium_corner_layout = layout.getLayout('mediumCorners') big_corner_layout = layout.getLayout('bigCorners') tiny_maze = layout.getLayout('tinymaze') medium_classic = layout.getLayout('mediumClassic') test_search = layout.getLayout('testSearch') tricky_search = layout.getLayout('trickySearch') rules = pacman.ClassicGameRules(0) sa = AStarFoodSearchAgent() gameDisplay = PacmanGraphics(zoom = 0.9, frameTime=0.1) # visualization game = rules.newGame(tricky_search, sa, [], gameDisplay, False, False) game.run() ''' '''
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('-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) 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('cs188') # Choose a layout import 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) pacman = pacmanType() # Figure out how to instantiate pacman if 'setDepth' in dir(pacman): pacman.setDepth(options.depth) if 'useBetterEvaluation' in dir(pacman) and options.betterEval: pacman.useBetterEvaluation() 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: print 'Replaying recorded game %s.' % options.gameToReplay import cPickle recorded = cPickle.load(open(options.gameToReplay)) 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> EXAMPLE: python sonar.py --layout bigHunt - starts an interactive game on a big board """ 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='smallHunt') parser.add_option('-p', '--pacman', dest='pacman', help=default('the agent TYPE in the pacmanAgents module to use'), metavar='TYPE', default='SonarKeyboardAgent') 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('-s', '--showGhosts', action='store_true', dest='showGhosts', help='Renders the ghosts in the display (cheating)', 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('sonarPacman') # Choose a layout import layout args['layout'] = layout.getLayout( options.layout ) if args['layout'] == None: raise "The layout " + options.layout + " cannot be found" # Choose a pacman agent pacmanType = loadAgent(options.pacman) pacman = pacmanType() # Figure out how to instantiate pacman args['pacman'] = pacman # Choose a ghost agent args['numGhosts'] = options.numGhosts # Choose a display format import graphicsDisplay args['display'] = graphicsDisplay.FirstPersonPacmanGraphics(options.zoom, options.showGhosts) args['numGames'] = options.numGames args['record'] = options.record return args