def replayGame(layout, actions, display): import game rules = ClassicGameRules() agents = [game.Agent() ] + [game.Agent(i + 1) for i in range(layout.getNumGhosts())] game = rules.newGame(layout, agents[0], agents[1:], display) state = game.state display.initialize(state.data) for action in actions: # Execute the action state = state.generateSuccessor(*action) # Change the display display.update(state.data) # Allow for game specific conditions (winning, losing, etc.) rules.process(state, game) display.finish()
def runGames( layouts, agents, display, length, numGames, record, numTraining, redTeamName, blueTeamName, muteAgents=False, catchExceptions=False ): rules = CaptureRules() games = [] if numTraining > 0: print('Playing %d training games' % numTraining) # Inject global info at DummyAgent class DummyAgent.training_n = numTraining for i in range( numGames ): beQuiet = i < numTraining layout = layouts[i] if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: gameDisplay = display rules.quiet = False # Inject global info at DummyAgent class DummyAgent.nth = i g = rules.newGame( layout, agents, gameDisplay, length, muteAgents, catchExceptions ) g.run() if not beQuiet: games.append(g) g.record = None if record: import time, pickle, game #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.Agent() for a in agents], 'actions': g.moveHistory, 'length': length, 'redTeamName': redTeamName, 'blueTeamName':blueTeamName } #f.close() print("recorded") g.record = pickle.dumps(components) with open('replay-%d'%i,'wb') as f: f.write(g.record) if numGames > 1: scores = [game.state.data.score for game in games] redWinRate = [s > 0 for s in scores].count(True)/ float(len(scores)) blueWinRate = [s < 0 for s in scores].count(True)/ float(len(scores)) print('Average Score:', sum(scores) / float(len(scores))) print('Scores: ', ', '.join([str(score) for score in scores])) print('Red Win Rate: %d/%d (%.2f)' % ([s > 0 for s in scores].count(True), len(scores), redWinRate)) print('Blue Win Rate: %d/%d (%.2f)' % ([s < 0 for s in scores].count(True), len(scores), blueWinRate)) print('Record: ', ', '.join([('Blue', 'Tie', 'Red')[max(0, min(2, 1 + s))] for s in scores])) return games
def runGames(layout, agents, display, length, numGames, record, numTraining, redTeamName, blueTeamName, muteAgents=False, catchExceptions=False): rules = CaptureRules() games = [] if numTraining > 0: print('Playing %d training games' % numTraining) 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 g = rules.newGame(layout, agents, gameDisplay, length, muteAgents, catchExceptions) g.run() if not beQuiet: games.append(g) g.record = None if record: import pickle, game components = {'layout': layout, 'agents': [game.Agent() for a in agents], 'actions': g.moveHistory, 'length': length, 'redTeamName': redTeamName, 'blueTeamName':blueTeamName } print("recorded") g.record = pickle.dumps(components) #with open('replay','wb') as f: # f.write(g.record) try: f = open('replay', 'wb') f.write(g.record) except: print("File \"replay\" could not be written.") if numGames > 1: scores = [game.state.data.score for game in games] redWinRate = [s > 0 for s in scores].count(True) / float(len(scores)) blueWinRate = [s < 0 for s in scores].count(True) / float(len(scores)) print('Average Score:', sum(scores) / float(len(scores))) print('Scores: ', ', '.join([str(score) for score in scores])) print('Red Win Rate: %d/%d (%.2f)' % ([s > 0 for s in scores].count(True), len(scores), redWinRate)) print('Blue Win Rate: %d/%d (%.2f)' % ([s < 0 for s in scores].count(True), len(scores), blueWinRate)) print('Record: ', ', '.join([('Blue', 'Tie', 'Red')[max(0, min(2, 1 + s))] for s in scores])) return games
def runGames( layout, agents, display, length, numGames, record, numTraining, muteAgents=False, catchExceptions=False ): # Hack for agents writing to the display import __main__ __main__.__dict__['_display'] = display rules = CaptureRules() games = [] if numTraining > 0: print 'Playing %d training games' % numTraining 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 g = rules.newGame( layout, agents, gameDisplay, length, muteAgents, catchExceptions ) g.run() if not beQuiet: games.append(g) g.record = None if record: import time, cPickle, game 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.Agent() for a in agents], 'actions': g.moveHistory, 'length': length} g.record = cPickle.dumps(components) print >> f, g.record f.close() print "recorded" if numGames > 1: scores = [game.state.data.score for game in games] redWinRate = [s > 0 for s in scores].count(True)/ float(len(scores)) blueWinRate = [s < 0 for s in scores].count(True)/ float(len(scores)) print 'Average Score:', sum(scores) / float(len(scores)) print 'Scores: ', ', '.join([str(score) for score in scores]) print 'Red Win Rate: %d/%d (%.2f)' % ([s > 0 for s in scores].count(True), len(scores), redWinRate) print 'Blue Win Rate: %d/%d (%.2f)' % ([s < 0 for s in scores].count(True), len(scores), blueWinRate) print 'Record: ', ', '.join([('Blue', 'Tie', 'Red')[max(0, min(2, 1 + s))] for s in scores]) return games
def runGames( layout, agents, display, length, numGames, record, numTraining, pacmanTeamName, ghostTeamName, muteAgents=False, catchExceptions=True ): rules = CaptureRules() games = [] if numTraining > 0: print 'Playing %d training games' % numTraining 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 g = rules.newGame( layout, agents, gameDisplay, length, muteAgents, catchExceptions ) g.run() if not beQuiet: games.append(g) g.record = None if record: import time, cPickle, game #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.Agent() for a in agents], 'actions': g.moveHistory, 'length': length, 'pacmanTeamName': pacmanTeamName, 'ghostTeamName':ghostTeamName } #f.close() print "recorded" g.record = cPickle.dumps(components) with open('replay_{}_{}'.format(pacmanTeamName, round(time.time(), 0)),'wb') as f: f.write(g.record) if numGames > 1: scores = [game.state.data.score for game in games] times = [game.length - game.state.data.timeleft for game in games] pacmanWinRate = [s > 0 for s in scores].count(True)/ float(len(scores)) print 'Times:', times print 'Average Score:', sum(scores) / float(len(scores)) print 'Scores: ', ', '.join([str(score) for score in scores]) print 'Pacman Win Rate: %d/%d (%.2f)' % ([s > 0 for s in scores].count(True), len(scores), pacmanWinRate) return games
def runGames(layouts, agents, display, length, numMatches, record, numTraining, redTeamName, blueTeamName, muteAgents=False, catchExceptions=False): rules = CaptureRules() matches = [] if numTraining > 0: print 'Playing %d training games' % numTraining for i in range(numMatches): print 'Match ' + str(i + 1) + ":" rounds = [] for startingTeam in [0, 1]: beQuiet = i < numTraining layout = layouts[i] print 'Playing with layout ' + str(i) if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: gameDisplay = display rules.quiet = False g = rules.newGame(layout, agents, gameDisplay, length, muteAgents, catchExceptions, startingTeam) g.run() if not beQuiet: rounds.append(g) g.record = None if record: import time, cPickle, game #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.Agent() for a in agents], 'actions': g.moveHistory, 'length': length, 'redTeamName': redTeamName, 'blueTeamName': blueTeamName, 'startingTeam': startingTeam } #f.close() print "recorded" g.record = cPickle.dumps(components) if not os.path.exists(record): os.makedirs(record) if not os.path.exists(record + '/' + redTeamName): os.makedirs(record + '/' + redTeamName) if not os.path.exists(record + '/' + blueTeamName): os.makedirs(record + '/' + blueTeamName) if not os.path.exists(record + '/' + redTeamName + '/' + blueTeamName): os.makedirs(record + '/' + redTeamName + '/' + blueTeamName) if not os.path.exists(record + '/' + blueTeamName + '/' + redTeamName): os.makedirs(record + '/' + blueTeamName + '/' + redTeamName) with open( record + '/' + redTeamName + '/' + blueTeamName + '/' + redTeamName + '-' + blueTeamName + '-' + str(i) + '-' + str(startingTeam) + '.txt', 'wb') as f: f.write(g.record) with open( record + '/' + blueTeamName + '/' + redTeamName + '/' + redTeamName + '-' + blueTeamName + '-' + str(i) + '-' + str(startingTeam) + '.txt', 'wb') as f: f.write(g.record) matches.append(rounds) scores = [[round.state.data.score for round in match] for match in matches] matchResults = [] redRounds = 0 blueRounds = 0 redMatches = 0 blueMatches = 0 for match in matches: red = 0 blue = 0 for round in match: if round.state.data.score > 0: red += 1 if round.state.data.score < 0: blue += 1 redRounds += red blueRounds += blue if red > blue: redMatches += 1 matchResults.append('Red') elif blue > red: blueMatches += 1 matchResults.append('Blue') else: matchResults.append('Tie') if redMatches > blueMatches: winner = redTeamName elif blueMatches > redMatches: winner = blueTeamName else: winner = 'Tie' results = { 'winner': winner, 'redMatches': redMatches, 'blueMatches': blueMatches, 'redRounds': redRounds, 'blueRounds': blueRounds, 'matches': matchResults, 'roundScores': scores } print 'Winner: ' + winner print 'Red Matches: ' + str(redMatches) print 'Blue Matches: ' + str(blueMatches) print 'Red Rounds: ' + str(redRounds) print 'Blue Rounds: ' + str(blueRounds) print 'Matches: ' + str(matchResults) print 'Round Scores: ' + str(scores) return results
def run_games(layouts, agents, display, length, num_games, record, num_training, red_team_name, blue_team_name, mute_agents=False, catch_exceptions=False, record_to=None): """Run 1 or more games.""" rules = CaptureRules() games = [] if num_training > 0: print('Playing %d training games' % num_training) for i in range(num_games): be_quiet = i < num_training layout = layouts[i] if be_quiet: # Suppress output and graphics import text_display game_display = text_display.NullGraphics() rules.quiet = True else: game_display = display rules.quiet = False g = rules.new_game(layout, agents, game_display, length, mute_agents, catch_exceptions) g.run() if not be_quiet: games.append(g) g.record = None print(red_team_name, blue_team_name) if record: import pickle import game # 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.Agent() for a in agents], 'actions': g.move_history, 'length': length, 'red_team_name': red_team_name, 'blue_team_name': blue_team_name } # f.close() print("recorded") g.record = pickle.dumps(components) if record_to is None: record_to = 'replay' with open(record_to + "_" + str(i), 'wb') as f: f.write(g.record) if num_games > 1: scores = [game.state.data.score for game in games] red_win_rate = [s > 0 for s in scores].count(True) / float(len(scores)) blue_win_rate = ([s < 0 for s in scores].count(True) / float(len(scores))) print('Average Score:', sum(scores) / float(len(scores))) print('Scores: ', ', '.join([str(score) for score in scores])) print('Red Win Rate: %d/%d (%.2f)' % ([s > 0 for s in scores].count(True), len(scores), red_win_rate)) print('Blue Win Rate: %d/%d (%.2f)' % ([s < 0 for s in scores].count(True), len(scores), blue_win_rate)) print( 'Record: ', ', '.join([('Blue', 'Tie', 'Red')[max(0, min(2, 1 + s))] for s in scores])) return games