def execute(self, grades, moduleDict, solutionDict): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state.initialize(lay, 0) problem = searchAgents.CornersProblem(game_state) start_state = problem.getStartState() h0 = searchAgents.cornersHeuristic(start_state, problem) succs = problem.getSuccessors(start_state) # cornerConsistencyA for succ in succs: h1 = searchAgents.cornersHeuristic(succ[0], problem) if h0 - h1 > 1: grades.addMessage('FAIL: inconsistent heuristic') return False heuristic_cost = searchAgents.cornersHeuristic(start_state, problem) true_cost = float(solutionDict['cost']) # cornerNontrivial if heuristic_cost == 0: grades.addMessage('FAIL: must use non-trivial heuristic') return False # cornerAdmissible if heuristic_cost > true_cost: grades.addMessage('FAIL: Inadmissible heuristic') return False path = solutionDict['path'].split() states = followPath(path, problem) heuristics = [] for state in states: heuristics.append(searchAgents.cornersHeuristic(state, problem)) for i in range(0, len(heuristics) - 1): h0 = heuristics[i] h1 = heuristics[i + 1] # cornerConsistencyB if h0 - h1 > 1: grades.addMessage('FAIL: inconsistent heuristic') return False # cornerPosH if h0 < 0 or h1 < 0: grades.addMessage('FAIL: non-positive heuristic') return False # cornerGoalH if heuristics[len(heuristics) - 1] != 0: grades.addMessage('FAIL: heuristic non-zero at goal') return False grades.addMessage( 'PASS: heuristic value less than true cost at start state') return True
def execute(self, grades, moduleDict, solutionDict): # load student code and staff code solutions multiAgents = moduleDict['multiAgents'] studentAgent = getattr(multiAgents, self.alg)(depth=self.depth) allActions = map(lambda x: json.loads(x), solutionDict['optimalActions'].split('\n')) altDepthActions = map(lambda x: json.loads(x), solutionDict['altDepthActions'].split('\n')) partialPlyBugActions = map( lambda x: json.loads(x), solutionDict['partialPlyBugActions'].split('\n')) # set up game state and play a game random.seed(self.seed) lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) pac = GradingAgent(self.seed, studentAgent, allActions, altDepthActions, partialPlyBugActions) # check return codes and assign grades stats = run(lay, self.layout_name, pac, [DirectionalGhost(i + 1) for i in range(2)], name=self.alg) if stats['timeouts'] > 0: self.addMessage('Agent timed out on smallClassic. No credit') return self.testFail(grades) if stats['crashes'] > 0: self.addMessage('Agent crashed on smallClassic. No credit') return self.testFail(grades) code = pac.checkFailure() if code == 0: return self.testPass(grades) elif code == -3: if pac.getWrongStatesExplored() >= 0: self.addMessage('Bug: Wrong number of states expanded.') return self.testFail(grades) else: return self.testPass(grades) elif code == -2: self.addMessage('Bug: Partial Ply Bug') return self.testFail(grades) elif code == -1: self.addMessage('Bug: Search depth off by 1') return self.testFail(grades) elif code > 0: moves = pac.getSuboptimalMoves() state, studentMove, optMove = random.choice(moves) self.addMessage('Bug: Suboptimal moves') self.addMessage('State:%s\nStudent Move:%s\nOptimal Move:%s' % (state, studentMove, optMove)) return self.testFail(grades)
def solution(self, logicPlan): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) pac = logicAgents.LogicAgent('flp', 'FoodPlanningProblem', logicPlan) ghosts = [] disp = textDisplay.NullGraphics() games = pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=180) gameState = games[0].state return (gameState.isWin(), gameState.getScore(), pac.actions)
def solution(self, search, searchAgents): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) gameState = pacman.GameState() gameState.initialize(lay, 0) problem = searchAgents.CornersProblem(gameState) path = search.bfs(problem) gameState = pacman.GameState() gameState.initialize(lay, 0) visited = getStatesFromPath(gameState.getPacmanPosition(), path) top, right = gameState.getWalls().height-2, gameState.getWalls().width-2 missedCorners = [p for p in ( (1, 1), (1, top), (right, 1), (right, top)) if p not in visited] return path, missedCorners
def solution(self, search): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) pac = searchAgents.SearchAgent('plp', 'PositionSearchProblem', search) ghosts = [] disp = textDisplay.NullGraphics() games = pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=1000) gameState = games[0].state return (gameState.isWin(), gameState.getScore(), pac.actions)
def solution(self, logicPlan): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) pac = logicAgents.CheckSatisfiabilityAgent( 'check_location_satisfiability', 'LocMapProblem', logicPlan) ghosts = [] disp = textDisplay.NullGraphics() games = pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=180) loc_sat_models = logicPlan.check_location_satisfiability( self.x1_y1, self.x0_y0, self.action0, self.action1, pac.problem) return loc_sat_models
def execute(self, grades, module_dict, solution_dict): """Run student code. Overrides test_classes.TestCase.execute If an error message is returned, print error and return false. If a good solution is returned, print the solution and return true. Otherwise, print both the correct and student's solution and return false. """ search = module_dict['search'] search_agents = module_dict['search_agents'] # total = 0 true_cost = float(solution_dict['cost']) thresholds = list(map(int, solution_dict['thresholds'].split())) points_per_threshold = 1 if 'points_per_threshold' in solution_dict: points_per_threshold = int(solution_dict['points_per_threshold']) game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state.initialize(lay, 0) problem = search_agents.CornersProblem(game_state) start_state = problem.get_start_state() if search_agents.corners_heuristic(start_state, problem) > true_cost: grades.add_message('FAIL: Inadmissible heuristic') return False path = search.a_star(problem, search_agents.corners_heuristic) print("path:", path) print("path length:", len(path)) cost = problem.get_cost_of_actions(path) if cost > true_cost: grades.add_message('FAIL: Inconsistent heuristic') return False expanded = problem._expanded points = 0 for threshold in thresholds: if expanded <= threshold: points += points_per_threshold grades.add_points(points) if points >= len(thresholds): grades.add_message('PASS: Heuristic resulted in expansion of ' + '%d nodes' % expanded) else: grades.add_message('FAIL: Heuristic resulted in expansion of ' + '%d nodes' % expanded) return True
def execute(self, grades, moduleDict, solutionDict, result=[]): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] searchAgents_ta = moduleDict['searchAgents-TA'] total = 0 true_cost = float(solutionDict['cost']) thresholds = [int(x) for x in solutionDict['thresholds'].split()] game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state.initialize(lay, 0) problem = searchAgents.CornersProblem(game_state) problem_ta = searchAgents_ta.CornersProblem(game_state) start_state = problem.getStartState() if searchAgents.cornersHeuristic(start_state, problem) > true_cost: grades.addMessage('FAIL: Inadmissible heuristic') result.extend( ["FAIL: Inadmissible heuristic", False, None, tok - tik]) return False tik = time.time() path = search.astar(problem, searchAgents.cornersHeuristic) tok = time.time() print("path:", path) print("path length:", len(path)) cost = problem_ta.getCostOfActions(path) if cost > true_cost: grades.addMessage('FAIL: Inconsistent heuristic') result.extend( ["FAIL: Inconsistent heuristic", False, None, tok - tik]) return False expanded = problem.get_expanded() # points = 0 # for threshold in thresholds: # if expanded <= threshold: # points += 1 # grades.addPoints(points) # if points >= len(thresholds): # grades.addMessage('PASS: Heuristic resulted in expansion of %d nodes' % expanded) # else: # grades.addMessage('FAIL: Heuristic resulted in expansion of %d nodes' % expanded) grades.addMessage('PASS: Heuristic resulted in expansion of %d nodes' % expanded) result.extend(["PASS", True, expanded, tok - tik]) return True
def solution(self, search, search_agents): """Return solution info: (solution, missed_corners).""" lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state = pacman.GameState() game_state.initialize(lay, 0) problem = search_agents.CornersProblem(game_state) path = search.bfs(problem) game_state = pacman.GameState() game_state.initialize(lay, 0) visited = get_states_from_path(game_state.get_pacman_position(), path) top = game_state.get_walls().height - 2 right = game_state.get_walls().width - 2 missed_corners = [p for p in ((1, 1), (1, top), (right, 1), (right, top)) if p not in visited] return path, missed_corners
def run(layout_str, pac, ghosts, disp, nGames = 1, name = 'games', maxMoves=-1, quiet = True): "Runs a few games and outputs their statistics." starttime = time.time() lay = layout.Layout(layout_str) #print '*** Running %s on' % name, layname,'%d time(s).' % nGames games = busters.runGames(lay, pac, ghosts, disp, nGames, maxMoves) #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]} statTuple = (stats['wins'], len(games), sum(stats['scores']) * 1.0 / len(games)) if not quiet: print '*** Won %d out of %d games. Average score: %f ***' % statTuple return stats
def execute(self, grades, moduleDict, solutionDict): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] total = 0 true_cost = float(solutionDict['cost']) thresholds = [int(x) for x in solutionDict['thresholds'].split()] #EXTRA, USED TO CONFIGURE DYNAMIC THRESHOLD VALUES thresholdPoints = [ int(x) for x in solutionDict['thresholdPoints'].split() ] game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state.initialize(lay, 0) problem = searchAgents.CornersProblem(game_state) start_state = problem.getStartState() if searchAgents.cornersHeuristic(start_state, problem) > true_cost: grades.addMessage('FAIL: Inadmissible heuristic') return False path = search.astar(problem, searchAgents.cornersHeuristic) print("path:", path) print("path length:", len(path)) cost = problem.getCostOfActions(path) if cost > true_cost: grades.addMessage('FAIL: Inconsistent heuristic') return False expanded = problem._expanded points = 0 #Original # for threshold in thresholds: # if expanded <= threshold: # points += 1 #Extra for z in range(len(thresholds)): if expanded <= thresholds[z]: points += thresholdPoints[z] #Extra Ends grades.addPoints(points) if points >= len(thresholds): grades.addMessage( 'PASS: Heuristic resulted in expansion of %d nodes' % expanded) else: grades.addMessage( 'FAIL: Heuristic resulted in expansion of %d nodes' % expanded) return True
def writeSolution(self, moduleDict, filePath): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] handle = open(filePath, 'w') handle.write( '# This solution file specifies the length of the optimal path\n') handle.write( '# as well as the thresholds on number of nodes expanded to be\n') handle.write('# used in scoring.\n') lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) start_state = pacman.GameState() start_state.initialize(lay, 0) problem = searchAgents.CornersProblem(start_state) solution = search.astar(problem, searchAgents.cornersHeuristic) handle.write('cost: "%d"\n' % len(solution)) handle.write('path: """\n%s\n"""\n' % wrap_solution(solution)) handle.write('thresholds: "2000 1600 1200"\n') handle.close() return True
def writeSolution(self, moduleDict, filePath): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] # write comment handle = open(filePath, 'w') handle.write('# In order for a heuristic to be admissible, the value\n') handle.write('# of the heuristic must be less at each state than the\n') handle.write('# true cost of the optimal path from that state to a goal.\n') # solve problem and write solution lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) start_state = pacman.GameState() start_state.initialize(lay, 0) problem = searchAgents.CornersProblem(start_state) solution = search.astar(problem, searchAgents.cornersHeuristic) handle.write('cost: "%d"\n' % len(solution)) handle.write('path: """\n%s\n"""\n' % wrap_solution(solution)) handle.close() return True
def getSolInfo(self, search, searchAgents): alg = getattr(search, self.alg) lay = layout.Layout([l.strip() for l in self.layout_text.split("\n")]) start_state = pacman.GameState() start_state.initialize(lay, 0) problemClass = getattr(searchAgents, self.searchProblemClassName) problemOptions = {} if self.costFn != None: problemOptions["costFn"] = self.costFn problem = problemClass(start_state, **problemOptions) heuristic = ( getattr(searchAgents, self.heuristicName) if self.heuristicName != None else None ) if heuristic != None: solution = alg(problem, heuristic) else: solution = alg(problem) if type(solution) != type([]): return ( None, None, "The result of %s must be a list. (Instead, it is %s)" % (self.alg, type(solution)), ) from game import Directions dirs = Directions.LEFT.keys() if [el in dirs for el in solution].count(False) != 0: return ( None, None, "Output of %s must be a list of actions from game.Directions" % self.alg, ) expanded = problem._expanded return solution, expanded, None
def execute(self, grades, moduleDict, solutionDict): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] total = 0 true_cost = float(solutionDict['cost']) thresholds = map(int, solutionDict['thresholds'].split()) basePoints = int(solutionDict['basePoints']) game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state.initialize(lay, 0) problem = searchAgents.CornersProblem(game_state) # BEGIN SOLUTION NO PROMPT patchExpansionExploit(problem) # END SOLUTION NO PROMPT start_state = problem.getStartState() if searchAgents.cornersHeuristic(start_state, problem) > true_cost: grades.addMessage('FAIL: Inadmissible heuristic') return False path = search.astar(problem, searchAgents.cornersHeuristic) print "path:", path print "path length:", len(path) cost = problem.getCostOfActions(path) if cost > true_cost: grades.addMessage('FAIL: Inconsistent heuristic') return False expanded = problem._expanded # BEGIN SOLUTION NO PROMPT expanded = problem._secretKeyLol # END SOLUTION NO PROMPT grades.addPoints(basePoints) points = 0 for threshold in thresholds: if expanded <= threshold: points += 3 grades.addPoints(points) if points >= len(thresholds): grades.addMessage( 'PASS: Heuristic resulted in expansion of %d nodes' % expanded) else: grades.addMessage( 'FAIL: Heuristic resulted in expansion of %d nodes' % expanded) return True
def execute(self, grades, moduleDict, solutionDict): search = moduleDict['search'] searchAgents = moduleDict['searchAgents'] total = 0 true_cost = float(solutionDict['cost']) thresholds = [int(x) for x in solutionDict['thresholds'].split()] game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) game_state.initialize(lay, 0) problem = searchAgents.CornersProblem(game_state) start_state = problem.getStartState() if searchAgents.cornersHeuristic(start_state, problem) > true_cost: grades.addMessage('FAIL: Inadmissible heuristic') return False path = search.astar(problem, searchAgents.cornersHeuristic) print("path:", path) print("path length:", len(path)) cost = problem.getCostOfActions(path) if cost > true_cost: grades.addMessage( 'FAIL: non-optimal solution returned (inadmissible heuristic, cycle checking error, or other search error' ) return False expanded = problem._expanded points = 0 for threshold in thresholds: if expanded <= threshold: points += 1 grades.addPoints(points) if points >= len(thresholds): grades.addMessage( 'PASS: Heuristic resulted in expansion of %d nodes' % expanded) else: if (points > 0): grades.addMessage( 'REDUCED MARK: Heuristic resulted in expansion of %d nodes' % expanded) if (points == 0): grades.addMessage( 'FAIL: Heuristic resulted in expansion of %d nodes more than maximum allowed' % expanded) return True
def solution(self, logicPlan): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) ghosts = [] disp = graphicsDisplay.PacmanGraphics(frameTime=0.5) # TODO: Figure out if we can use no-graphics pac = logicAgents.LocalizationLogicAgent( 'loc', 'LocalizationProblem', logicPlan, display=disp, scripted_actions=self.scriptedActions) pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=300) return pac.planning_fn_output
def solution(self, logicPlan): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) ghosts = [] disp = graphicsDisplay.PacmanGraphics(frameTime=0.5, render_walls_beforehand=False) # TODO: Figure out if we can use no-graphics pac = logicAgents.SLAMLogicAgent('slam', 'SLAMProblem', logicPlan, display=disp, scripted_actions=self.scriptedActions) pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=1800) return pac.planning_fn_output
def writeSolution(self, moduleDict, filePath): # load module, set seed, create ghosts and macman, run game multiAgents = moduleDict['multiAgents'] random.seed(self.seed) lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) if self.alg == 'ExpectimaxAgent': ourPacOptions = {'expectimax': 'True'} elif self.alg == 'AlphaBetaAgent': ourPacOptions = {'alphabeta': 'True'} else: ourPacOptions = {} pac = PolyAgent(self.seed, multiAgents, ourPacOptions, self.depth) run(lay, self.layout_name, pac, [DirectionalGhost(i + 1) for i in range(2)], name=self.alg) (optimalActions, altDepthActions, partialPlyBugActions) = pac.getTraces() # recover traces and record to file handle = open(filePath, 'w') self.writeList(handle, 'optimalActions', optimalActions) self.writeList(handle, 'altDepthActions', altDepthActions) self.writeList(handle, 'partialPlyBugActions', partialPlyBugActions) handle.close()
def solution(self, search): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) pac = searchAgents.SearchAgent('fglp', 'FoodGhostsSearchProblem', search) ghosts = [ patrollingGhostAgents.PatrollingGhost(i) for i in xrange(1, lay.getNumGhosts() + 1) ] disp = textDisplay.NullGraphics() games = pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=1000) gameState = games[0].state return (gameState.isWin(), gameState.getScore(), pac.actions)
def load(self, fileName): global data connectError = False try: dt.fileName = fileName dt.data = layout.Layout() self.data = dt.data # small hack so that other modules can reach data without hassle. if os.path.isfile(fileName): # could be that it's a new file (first startup) -> default layout gets a default filename dt.data.load(fileName) if dt.data.userName and dt.data.password and dt.data.server and dt.data.broker: try: IOT.connect(dt.data.userName, dt.data.password, dt.data.server, dt.data.broker) except Exception as e: connectError = True showError(e, None, "Failed to connect, please check your account settings or network. ") raise # raise the exception again, we don't want the menu to load, cause it will fail self.loadMenu() #must be done after connecting, cause it might have to load assets else: self.loadMenu() #must be done before editLayout (for new layouts) self.editLayout(None) # there is no connection yet, automatically go to edit mode. Also helps with the button. except Exception as e: if not connectError: showError(e)
def layout_parts_sheets(self, width, height, step=None, units="in", speed="fast"): l = layout.Layout(self.basename + '-sheet', width, height, step=step, units=units) # sort by size (ascending), then place in reverse order (largest first) sorted_list = [] for rib in self.right_ribs: sorted_list.append((rib.hull_area(), rib)) for rib in self.left_ribs: sorted_list.append((rib.hull_area(), rib)) print "placement_list:", sorted_list sorted_list = sorted(sorted_list, key=lambda fields: fields[0]) # place the ribs for (area, rib) in reversed(sorted_list): rib.placed = l.draw_part_cut_line(rib.contour, speed=speed) l.save()
def getSolInfo(self, search, searchAgents): alg = getattr(search, self.alg) lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) start_state = pacman.GameState() start_state.initialize(lay, 0) problemClass = getattr(searchAgents, self.searchProblemClassName) problemOptions = {} if self.costFn != None: problemOptions['costFn'] = self.costFn problem = problemClass(start_state, **problemOptions) # BEGIN SOLUTION NO PROMPT patchExpansionExploit(problem) # END SOLUTION NO PROMPT heuristic = getattr( searchAgents, self.heuristicName) if self.heuristicName != None else None if heuristic != None: solution = alg(problem, heuristic) else: solution = alg(problem) if type(solution) != type([]): return None, None, 'The result of %s must be a list. (Instead, it is %s)' % ( self.alg, type(solution)) from game import Directions dirs = Directions.LEFT.keys() if [el in dirs for el in solution].count(False) != 0: return None, None, 'Output of %s must be a list of actions from game.Directions' % self.alg expanded = problem._expanded # BEGIN SOLUTION NO PROMPT expanded = problem._secretKeyLol # END SOLUTION NO PROMPT return solution, expanded, None
def execute(self, grades, moduleDict, solutionDict): search = moduleDict["search"] searchAgents = moduleDict["searchAgents"] total = 0 true_cost = float(solutionDict["cost"]) thresholds = [int(x) for x in solutionDict["thresholds"].split()] game_state = pacman.GameState() lay = layout.Layout([l.strip() for l in self.layout_text.split("\n")]) game_state.initialize(lay, 0) problem = searchAgents.CornersProblem(game_state) start_state = problem.getStartState() if searchAgents.cornersHeuristic(start_state, problem) > true_cost: grades.addMessage("FAIL: Inadmissible heuristic") return False path = search.astar(problem, searchAgents.cornersHeuristic) print("path:", path) print("path length:", len(path)) cost = problem.getCostOfActions(path) if cost > true_cost: grades.addMessage("FAIL: Inconsistent heuristic") return False expanded = problem._expanded points = 0 for threshold in thresholds: if expanded <= threshold: points += 1 grades.addPoints(points) if points >= len(thresholds): grades.addMessage( "PASS: Heuristic resulted in expansion of %d nodes" % expanded ) else: grades.addMessage( "FAIL: Heuristic resulted in expansion of %d nodes" % expanded ) return True
def get_solution_info(self, search, search_agents): """Return solution info: (solution, expanded states, error message).""" alg = getattr(search, self.alg) lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')]) start_state = pacman.GameState() start_state.initialize(lay, 0) problem_class = getattr(search_agents, self.search_problem_class_name) problem_options = {} if self.cost_fn is not None: problem_options['cost_fn'] = self.cost_fn problem = problem_class(start_state, **problem_options) if self.heuristic_name is not None: heuristic = getattr(search_agents, self.heuristic_name) else: heuristic = None if heuristic is not None: solution = alg(problem, heuristic) else: solution = alg(problem) if not isinstance(solution, list): return (None, None, 'The result of %s must be a list. (Instead, it is %s)' % (self.alg, type(solution))) from game import Directions dirs = list(Directions.LEFT.keys()) if [el in dirs for el in solution].count(False) != 0: return (None, None, ('Output of %s must be a list of actions ' % self.alg) + 'from game.Directions') expanded = problem._expanded return solution, expanded, None
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='treasureHunt') 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 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='StationaryGhostAgent') 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=1) parser.add_option('-z', '--zoom', type='float', dest='zoom', help=default('Zoom the size of the graphics window'), default=1.0) parser.add_option('-d', '--displayGhosts', action='store_true', dest='displayGhosts', 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) parser.add_option('-r', '--randomBoard', action='store_true', dest='randomBoard', help='Generates some random board', default=False) parser.add_option('-v', '--vpiBoard', action='store_true', dest='vpiBoard', help='Generates a special board for the VPI sub-problem', default=False) parser.add_option('-s', '--seed', type='str', dest='seed', help=default('Generates a random board using the specified seed'), default=None) options, otherjunk = parser.parse_args() if len(otherjunk) != 0: raise Exception('Command line input not understood: ' + otherjunk) args = dict() if options.randomBoard or options.seed: # options.seed defaults to None which uses system time args['layout'] = layout.Layout(options.seed) elif options.vpiBoard: args['layout'] = layout.Layout(options.seed, vpi=True) else: # 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.displayGhosts, frameTime = options.frameTime, hunters=True) args['numGames'] = options.numGames return args
def solution(self, searchAgents): lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')]) gameState = pacman.GameState() gameState.initialize(lay, 0) path = searchAgents.ClosestDotSearchAgent().findPathToClosestDot(gameState) return path
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 generateLayouts(seedLst, ghostAgents): import layout return [layout.Layout(randomLayout(seed).split('\n'), maxGhosts=len(ghostAgents)) for seed in seedLst]
def run(self): g.init() if not self.journal: utils.load() g.xo = False load_save.retrieve() self.toc = layout.toc() self.layout = layout.Layout(g.w - 2 * g.offset, int(g.h * 19 / 24)) self.render() self.jig = jig.Jig() self.buttons_setup() if self.canvas <> None: self.canvas.grab_focus() ctrl = False pygame.key.set_repeat(600, 120) key_ms = pygame.time.get_ticks() going = True while going: if self.journal: # Pump GTK messages. while gtk.events_pending(): gtk.main_iteration() # Pump PyGame messages. for event in pygame.event.get(): if event.type == pygame.QUIT: if not self.journal: utils.save() going = False elif event.type == pygame.MOUSEMOTION: g.pos = event.pos g.redraw = True if self.canvas <> None: self.canvas.grab_focus() elif event.type == pygame.MOUSEBUTTONDOWN: g.redraw = True if event.button == 1: bu = '' if self.bu == None: bu = buttons.check() if bu != '': self.do_button(bu) self.flush_queue() else: self.do_click() elif event.type == pygame.KEYDOWN: # throttle keyboard repeat if pygame.time.get_ticks() - key_ms > 110: key_ms = pygame.time.get_ticks() if ctrl: if event.key == pygame.K_q: if not self.journal: utils.save() going = False break else: ctrl = False if event.key in (pygame.K_LCTRL, pygame.K_RCTRL): ctrl = True break self.do_key(event.key) g.redraw = True self.flush_queue() elif event.type == pygame.KEYUP: ctrl = False if not going: break if self.layout.movie != None: self.layout.movie.update() self.update() if g.redraw: self.display() if g.version_display: utils.version_display() g.screen.blit(g.pointer, g.pos) pygame.display.flip() g.redraw = False g.clock.tick(40)