def debug(): for idx, argvStr in enumerate(argvStrList): start = 0 if idx in range(0, 8): print "********", idx, "*********" argvList = argvStr.split(" ") args = pacman.readCommand(argvList) pacman.runGames(**args)
def execute(self, grades, moduleDict, solutionDict): self.addMessage('Grading agent using command: python pacman.py %s'% (self.pacmanParams,)) pacman.TEST_MODULE = moduleDict startTime = time.time() games = pacman.runGames(** pacman.readCommand(self.pacmanParams.split(' '))) totalTime = time.time() - startTime numGames = len(games) 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 = 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 run(lay, layName, pac, ghosts, disp, nGames=1, name='games'): """ Runs a few games and outputs their statistics. """ starttime = time.time() print('*** Running %s on' % name, layName, '%d time(s).' % nGames) games = pacman.runGames(lay, pac, ghosts, disp, nGames, False, catchExceptions=True, timeout=120) 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), 'crashes': [g.agentCrashed 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 run(lay, layName, pac, ghosts, disp, nGames=1, name="games"): """ Runs a few games and outputs their statistics. """ starttime = time.time() print("*** Running %s on" % name, layName, "%d time(s)." % nGames) games = pacman.runGames( lay, pac, ghosts, disp, nGames, False, catchExceptions=True, timeout=120 ) 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), "crashes": [g.agentCrashed 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 test(self): args = pacman.readCommand([ '-p', 'RectangularRoomCleaner', '-l', layout, '-q', '--frameTime', '0', '--timeout', '1' ]) games = pacman.runGames(**args) self.assertTrue(games[0].state.isWin())
def main(pacman_agent): total_scores = 0. total_weight = 0. for n_case, case in enumerate(evaluation_cases): print('running game {} / {}, {}'.format(n_case + 1, len(evaluation_cases), case[0])) layout, score_weight = case # Run the pacman game and get its score pacman_cmd = 'python pacman.py --pacman {} -l {} -q' pacman_cmd_args = pacman_cmd.format(pacman_agent, layout) # skip 'python pacman.py' in the command line arguments above args = pacman.readCommand(pacman_cmd_args.split()[2:]) games = pacman.runGames(**args) # Take the average of the game scores. Note that there should be only # one game in games, unless `-n` is used in pacman.py scores = [game.state.getScore() for game in games] game_score = sum(scores) / len(scores) total_scores += game_score * score_weight total_weight += score_weight final_score = total_scores / total_weight print("Final score: ", final_score)
def run(layname, pac, ghosts, nGames=1, name='games', catchExceptions=True): """ Runs a few games and outputs their statistics. """ import pacman, time, layout, textDisplay 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=catchExceptions) 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 main(pacman_agent): total_scores = 0. total_weight = 0. for n_case, case in enumerate(evaluation_cases): print('running game {} / {}, {}'.format(n_case + 1, len(evaluation_cases), case[0])) layout, score_weight = case # Run the pacman game and get its score pacman_cmd = 'python pacman.py --pacman {} -l {} -q' pacman_cmd_args = pacman_cmd.format(pacman_agent, layout) # skip 'python pacman.py' in the command line arguments above args = pacman.readCommand(pacman_cmd_args.split()[2:]) games = pacman.runGames(**args) # Take the average of the game scores. Note that there should be only # one game in games, unless `-n` is used in pacman.py scores = [game.state.getScore() for game in games] game_score = sum(scores) / len(scores) total_scores += game_score * score_weight total_weight += score_weight final_score = total_scores / total_weight print("Final score: ", final_score) # Generate results.json score_fields = {} score_fields['score'] = final_score score_fields['visibility'] = 'visible' score_fields['leaderboard'] = [{"name": "Score", "value": final_score}] score_fields['output'] = 'successfully run {} games!'.format( len(evaluation_cases))
def solution(self, logicPlan): lay = layout.Layout([l.strip() for l in self.layoutText.split("\n")]) pac = logicAgents.LogicAgent("fglp", "FoodGhostsPlanningProblem", logicPlan) 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 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, 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 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=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.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, 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 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) games = 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) games = pacman.runGames(lay, pac, ghosts, disp, 1, False, catchExceptions=True, timeout=1200) return pac.planning_fn_output
def eval_genomes_single(genomes, config): for id, genome in genomes: genome.fitness = 0 nn_model = neat.nn.FeedForwardNetwork.create(genome, config) pacmanType = pacman.loadAgent("NEATAgent", True) cmd_line_args['pacman'] = pacmanType(nn_model=nn_model) cmd_line_args['display'] = textDisplay.NullGraphics() #cmd_line_args['display'] = graphicsDisplay.PacmanGraphics() games = pacman.runGames(**cmd_line_args) for game in games: genome.fitness += game.state.getScore()
def runSingleGame(self): # run game and get if win or lose self.args['pacman'].startEpisode() games = pacman.runGames(**self.args) single_game = games.pop() is_win = single_game.state.isWin() match_score = single_game.state.getScore() # end game self.end_game(is_win, match_score)
def run(lay, layName, pac, ghosts, disp, nGames=1, name='games'): """ Runs a few games and outputs their statistics. """ starttime = time.time() print '*** Running %s on' % name, layName, '%d time(s).' % nGames games = pacman.runGames(lay, pac, ghosts, disp, nGames, False, catchExceptions=True, timeout=120) 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), 'crashes': [g.agentCrashed 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 eval_genomes(genome, config): genome.fitness = 0 nn_model = neat.nn.FeedForwardNetwork.create(genome, config) pacmanType = pacman.loadAgent("NEATAgent", True) cmd_line_args['pacman'] = pacmanType(nn_model=nn_model) cmd_line_args['display'] = textDisplay.NullGraphics() # cmd_line_args['display'] = graphicsDisplay.PacmanGraphics() games = pacman.runGames(**cmd_line_args) result = 0 for game in games: result += game.state.getScore() return float(result) / float(len(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 = 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 totalPoints += points if any([not passed for passed, _, _, _, _, _ in results]): totalPoints = 0 return self.testPartial(grades, totalPoints, self.maxPoints)
def execute(self, grades, moduleDict, solutionDict): grades.addMessage('Testing Deep Q Network...') # Load Pacman Agent nographics = False pacmanType = loadAgent("PacmanDeepQAgent", nographics) pacman = pacmanType(self.layout) # Load Ghost Agent ghostType = loadAgent("RandomGhost", nographics) numghosts = 1 ghosts = [ghostType(i + 1) for i in range(numghosts)] numTraining = pacman.model.numTrainingGames # Set by student numGames = numTraining + self.numEvalGames record = False games = runGames(self.layout, self.horizon, pacman, ghosts, self.display, numGames, record, numTraining=numTraining, catchExceptions=False, timeout=30) scores = [game.state.getScore() for game in games] wins = [game.state.isWin() for game in games] winRate = wins.count(True) / float(len(wins)) if winRate < self.winThresh: grades.addMessage( 'FAIL:\nWinRate = {} < {} threshold for full credit'.format( winRate, self.winThresh)) return False elif winRate < self.winThreshEC: grades.addMessage( 'PASS:\nWinRate = {} >= {} threshold for full credit'.format( winRate, self.winThresh)) grades.assignFullCredit() return True else: grades.addMessage( 'PASS:\nWinRate = {} >= {} threshold for extra credit'.format( winRate, self.winThreshEC)) grades.assignFullCredit() grades.addPoints(1) return True
def runq4(): """ Runs their expectimax agent a few times and checks for victory! """ random.seed(SEED) nGames = 20 print 'Running your agent %d times to compute the average score...' % nGames params = '-l smallClassic -p ExpectimaxAgent -a evalFn=better -q -n %d -c' % nGames games = pacman.runGames(**pacman.readCommand(params.split(' '))) timeouts = [game.agentTimeout for game in games].count(True) wins = [game.state.isWin() for game in games].count(True) averageWinScore = 0 if wins >= nGames / 2: averageWinScore = average([game.state.getScore() if game.state.isWin() else None for game in games]) return timeouts, wins, averageWinScore
def evaluate_candidates(candidates, args): nn_model = args["nn_model"] cmd_line_args = args["cmd_line_args"] candidates_fitness = [] for candidate in candidates: nn_model.set_weights(candidate) pacmanType = pacman.loadAgent("BioAgent", True) cmd_line_args['pacman'] = pacmanType(nn_model=nn_model) cmd_line_args['display'] = textDisplay.NullGraphics() #cmd_line_args['display'] = graphicsDisplay.PacmanGraphics() games = pacman.runGames(**cmd_line_args) candidate_fitness = 0 for game in games: candidate_fitness += game.state.getScore() candidates_fitness.append(candidate_fitness) print(candidates_fitness) return candidates_fitness
def main(pacman_agent): n_trials = 2 if os.path.exists('../autograder'): print("POSTOJIIII ") else: print("NE POSTOJI") final_scores = [] for _ in range(n_trials): total_scores = 0. total_weight = 0. for n_case, case in enumerate(evaluation_cases): print('running game {} / {}, {}'.format(n_case + 1, len(evaluation_cases), case[0])) layout, score_weight = case # Run the pacman game and get its score pacman_cmd = 'python pacman.py --pacman {} -l {} -q' pacman_cmd_args = pacman_cmd.format(pacman_agent, layout) # skip 'python pacman.py' in the command line arguments above args = pacman.readCommand(pacman_cmd_args.split()[2:]) games = pacman.runGames(**args) # Take the average of the game scores. Note that there should be only # one game in games, unless `-n` is used in pacman.py scores = [game.state.getScore() for game in games] game_score = sum(scores) / len(scores) total_scores += game_score * score_weight total_weight += score_weight final_score_i = total_scores / total_weight final_scores.append(final_score_i) final_score = sum(final_scores) / n_trials # Write scores for gradescope to read if os.path.exists('../autograder'): # print("USAOUSAO USAO USAO USAO USAO ") # Generate results.json score_fields = {} score_fields['score'] = final_score score_fields['visibility'] = 'visible' score_fields['leaderboard'] = [{"name": "Score", "value": final_score}] score_fields['output'] = 'successfully run {} games!'.format( len(evaluation_cases)) write_output(score_fields)
def runq4(): """ Runs their expectimax agent a few times and checks for victory! """ random.seed(SEED) nGames = 20 print 'Running your agent %d times to compute the average score...' % nGames print 'The timeout message (if any) is obtained by running the game once, rather than %d times' % nGames params = '-l smallClassic -p ExpectimaxAgent -a evalFn=better -q -n %d -c --timeout=30000' % nGames games = pacman.runGames(**pacman.readCommand(params.split(' '))) timeouts = [game.agentTimeout for game in games].count(True) wins = [game.state.isWin() for game in games].count(True) averageWinScore = 0 if wins >= nGames / 2: averageWinScore = average([game.state.getScore() if game.state.isWin() else None for game in games]) print 'Average score of winning games: %d \n' % averageWinScore return timeouts, wins, averageWinScore
def run(layname, pac, ghosts, nGames = 1, name = 'games'): """ Runs a few games and outputs their statistics. """ if grader.fatalError: return {'time': 65536, 'wins': 0, 'games': None, 'scores': [0]*nGames, 'timeouts': nGames} 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 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 evaluate(self): # # TO DO: # call pac.runGames and run the game with this particle's parameters # base = ["-p", "PacmanQAgent", "-x", "2000", "-n", "2100", "-l", "smallGrid", "-q", "-a"] config = "epsilon=" + str(self.position_i[0]) + ",alpha=" + str(self.position_i[1]) + ",gamma=" + str(self.position_i[2]) base.append(config) print(config) args = pac.readCommand( base ) # Get game components based on input averageScore = pac.runGames( **args ) #averageScore=random.uniform(1,500) self.score_i=averageScore # save the averageScore this iteration had # check to see if the current position is an individual best if self.score_i>self.score_best_i or self.score_best_i==-1: self.pos_best_i=list(self.position_i) self.score_best_i=self.score_i
pacman program. """ import sys, os, re, importlib dir_local = os.getcwd() dir_central = os.path.join(dir_local, '..', 'scripts') sys.path.append(dir_central) # append the scripts dir to the path os.chdir(dir_central) # import pacman files from central scripts directory import pacman os.chdir( dir_local ) # import asssignment files from local directory, overriding central files for file in os.listdir('.'): if file.endswith('.py') and file != os.path.basename(__file__): importlib.import_module(file[:-3]) os.chdir( dir_central) # change back to central directory for script execution if len(sys.argv) == 1: args = re.split(r' *', input("Enter any command line arguments?")) sys.argv.extend([a for a in args if a != '']) args = pacman.readCommand( sys.argv[1:]) # Get game components based on input pacman.runGames(**args)
def runPacman(): rospy.init_node('pacman_interface', anonymous=True) a=["-p", "RosWaitAgent", "-l", "originalClassic", "-k", "4"] args = pacman.readCommand(a) pacman.runGames(**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 = 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)
return Directions.STOP return self.buffer.pop() def socketReceive(actionStr): print "RECEIVE" parts = actionStr.split() if parts[0] == self.agentKey: self.buffer.push(actionStr) class PlayerNetworkMasterAgent(NetworkMasterAgent): def __init__(self): NetworkMasterAgent.__init__(self, KeyboardAgent(), "PLAYER") class PlayerNetworkSlaveAgent(NetworkSlaveAgent): def __init__(self): NetworkSlaveAgent.__init__(self, "PLAYER") if __name__ == '__main__': factory = WebSocketClientFactory('ws://localhost:9000') factory.protocol = ClientProtocol connectWS(factory) #reactor.run() thread = Thread(target = reactor.run, args = (False,)) thread.start() args = readCommand(sys.argv[1:]) runner = lambda: runGames(**args) runner() #thread = Thread(target = runner) #thread.start()
def interactive(): args = readCommand( "--layout testMaze --pacman KeyboardAgent --createPolicy".split()) return runGames(**args)
# Add a stdout reporter to show progress in the terminal. p.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() p.add_reporter(stats) p.add_reporter(neat.Checkpointer(5)) # Run for up to 300 generations (parallel) pe = neat.ParallelEvaluator(4, eval_genomes) winner = p.run(pe.evaluate, 1000) #winner = p.run(eval_genomes_single, 100) # Display the winning genome. print('\nBest genome:\n{!s}'.format(winner)) # Save the winner to disk with open('winner-feedforward.out', 'wb') as f: pickle.dump(winner, f) # Show output of the most fit genome against training data. print('\nOutput:') winner_net = neat.nn.FeedForwardNetwork.create(winner, config) # Load the final agent and run a few games with it pacmanType = pacman.loadAgent("NEATAgent", True) cmd_line_args['pacman'] = pacmanType(nn_model=winner_net) cmd_line_args['display'] = textDisplay.NullGraphics() #cmd_line_args['display'] = graphicsDisplay.PacmanGraphics() cmd_line_args['numGames'] = 10 games = pacman.runGames(**cmd_line_args) pass
'-l', 'mediumClassic', '-g', 'DirectionalGhost', '--frameTime', '0', '-n', '100' ] str_args = [ '-l', 'TinyMaze', '-g', 'DirectionalGhost', '--frameTime', '0', '-n', '100' ] str_args = [ '-l', 'TestMaze', '-g', 'DirectionalGhost', '--frameTime', '0', '-n', '100' ] args = readCommand(str_args) # args['display'] = textDisplay.NullGraphics() # Disable rendering args['pacman'] = MCTSagent() out = runGames(**args) scores = [o.state.getScore() for o in out] print(scores) else: # TicTacToe winner = [] n = 200 for i in range(n): winner.append( play_game(MCTSagent(), human=TICTACTOE_VS_HUMAN, deterministic=TICTACTOE_DETERMINIST)) print("Game", i) print('MCTS win: ', np.sum([i == -1 for i in winner]) / float(n)) print('Draw: ', np.sum([i == 0 for i in winner]) / float(n))
import pacman as pac import sys if __name__ == '__main__': """ Used to start a game, with pacman module """ base = [ "-p", "PacmanQAgent", "-x", "2000", "-n", "2010", "-l", "smallGrid", "-a" ] base.append("epsilon=0.1,alpha=0.3,gamma=0.7") args = pac.readCommand(base) # Get game components based on input averageScore = pac.runGames(**args) print(averageScore) pass #--- EXAMPLE ------------------------------------------------------------------+ # python pso.py -p PacmanQAgent -x 2000 -n 2010 -l smallGrid -a epsilon=0.1,alpha=0.3,gamma=0.7
""" This script is used for combining the local assignment files with the central script files, and starting the pacman program. """ import sys, os, re, importlib dir_local = os.getcwd() dir_central = os.path.join(dir_local, '..', 'scripts') sys.path.append(dir_central) # append the scripts dir to the path os.chdir(dir_central) # import pacman files from central scripts directory import pacman os.chdir(dir_local) # import asssignment files from local directory, overriding central files for file in os.listdir(): if file.endswith('.py') and file != os.path.basename(__file__): importlib.import_module(file[:-3]) os.chdir(dir_central) # change back to central directory for script execution if len(sys.argv) == 1: args = re.split(r' *', input("Enter any command line arguments?")) sys.argv.extend([a for a in args if a != '']) args = pacman.readCommand(sys.argv[1:]) # Get game components based on input pacman.runGames(**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 += 6 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, 6 * 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, 6 * (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, 6 * (idx + 1))) if any([not passed for passed, _, _, _, _, _ in results]): totalPoints = 0 return self.testPartial(grades, totalPoints, self.maxPoints)
from pacman import runGames, readCommand from time import time layout_list = [ "originalClassic", "testClassic", "trappedClassic", "trickyClassic", "smallClassic", "minimaxClassic", "openClassic", "mediumClassic", "contestClassic", "capsuleClassic" ] ghost_agents = ["DirectionalGhost", "RandomGhost"] for curr_layout in layout_list: print("Current layout: ", curr_layout) games_counter = 10 args = readCommand([ "-n", str(games_counter), "-k", "2", "-l", curr_layout, "-p", "CompetitionAgent", "-q", "-g", ghost_agents[1] ]) # Get game components based on input start = time() avg = runGames(**args) end = time() print("Current layout AVG completion time: ", float(end - start) / float(games_counter)) print("\n")