def main(): import text_display import random # Setup things so we can call the planner random.seed('comp3620_6320_2016') # set RNG layout = load_layout() # read stdin display = text_display.NullGraphics() # disable graphics catch_exceptions = False # abort program on exception timeout = 60 # time out # Agents setup red_bird = agents.SearchAgent(0, fn='depth_first_search', prob='PositionSearchProblem', heuristic='blind_heuristic') black_bird = None rules = ClassicGameRules(timeout) game = rules.new_game(layout, red_bird, black_bird, display, False, catch_exceptions) game.solve()
def run_games(layout, pacman, ghosts, display, num_games, record, num_training=0, catch_exceptions=False, timeout=30): """Run the games; main execution loop when called from command line.""" import __main__ __main__.__dict__['_display'] = display rules = ClassicGameRules(timeout) games = [] for i in range(num_games): be_quiet = i < num_training 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 game = rules.new_game(layout, pacman, ghosts, game_display, be_quiet, catch_exceptions) game.run() if not be_quiet: games.append(game) if record: import time import pickle fname = ('recorded-game-%d' % (i + 1)) + '-'.join( [str(t) for t in time.localtime()[1:6]]) f = open(fname, 'w') components = {'layout': layout, 'actions': game.move_history} pickle.dump(components, f) f.close() if (num_games - num_training) > 0: scores = [game.state.get_score() for game in games] wins = [game.state.is_win() for game in games] win_rate = 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), win_rate)) print('Record: ', ', '.join([['Loss', 'Win'][int(w)] for w in wins])) return games
def get_display(graphics_by_default, options=None): graphics = graphics_by_default if options is not None and options.no_graphics: graphics = False if graphics: try: import graphics_display return graphics_display.PacmanGraphics(1, frame_time=.05) except ImportError: pass import text_display return text_display.NullGraphics()
def run_games(layouts, agents, display, length, num_games, record, num_training, red_team_name, blue_team_name, mute_agents=False, catch_exceptions=False): 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 if record: import time 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) with open('replay-%d' % 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
def read_command(): """ Processes the command used to run the program from the command line. ([str]) -> { str : object } """ from argparse import ArgumentParser usage_str = """ USAGE: python red_bird.py <options> EXAMPLES: (1) python red_bird.py -p MinimaxAgent -l anuAdversarial -a depth=4 -b GreedyBlackBirdAgent --frame_time 0.05 will start an adversarial game with your MinimaxAgent vs the GreedyBlackBirdAgent on the anuAdversarial level (2) python red_bird.py -l anuAdversarial -p KeyboardAgent -b GreedyBlackBirdAgent will allow you to play with the keyboard on the same level """ parser = ArgumentParser(usage_str) parser.add_argument('-n', '--num_games', dest='num_games', type=int, action='store', help='the number of GAMES to play', metavar='GAMES', default=1) parser.add_argument( '-l', '--layout', dest='layout', help='the LAYOUT_FILE from which to load the map layout (Mandatory)', metavar='LAYOUT_FILE', default=None) parser.add_argument( '-b', '--black_bird', dest='black_bird', help='the black_bird agent TYPE in the agents module to use', metavar='TYPE', default='BlackBirdAgent') parser.add_argument( '-a', '--agent_args', dest='agent_args', help= 'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"' ) parser.add_argument( '-p', '--red_bird', dest='red_bird', help='the agent TYPE in the search_agents module to use', metavar='TYPE', default='KeyboardAgent') parser.add_argument('-t', '--text_graphics', action='store_true', dest='text_graphics', help='Display output as text only', default=False) parser.add_argument('-q', '--quiettext_graphics', action='store_true', dest='quiet_graphics', help='Generate minimal output and no graphics', default=False) parser.add_argument('-z', '--zoom', type=float, dest='zoom', help='Zoom the size of the graphics window', default=1.0) parser.add_argument( '-f', '--fix_random_seed', action='store_true', dest='fix_random_seed', help='Fixes the random seed to always play the same game', default=False) parser.add_argument('--frame_time', dest='frame_time', type=float, help='Time to delay between frames; <0 means keyboard', default=0.1) parser.add_argument( '-c', '--catch_exceptions', action='store_true', dest='catch_exceptions', help='Turns on exception handling and timeouts during games', default=False) parser.add_argument( '--timeout', dest='timeout', type=float, help= 'Maximum length of time an agent can spend computing in a single game', default=30) options = parser.parse_args() args = dict() # Fix the random seed if options.fix_random_seed: random.seed('comp3620_6320_2016') # Choose a layout if options.layout is None: raise SystemExit("[Fatal]: No map layout was specified!") args['layout'] = layout.get_layout(options.layout) if args['layout'] == None: raise SystemExit("[Fatal]: Map layout " + options.layout + " cannot be found") # Choose a red_bird agent no_keyboard = options.text_graphics or options.quiet_graphics red_bird_type = load_agent(options.red_bird, no_keyboard) agent_opts = parse_agent_args(options.agent_args) red_bird = red_bird_type( 0, **agent_opts) # Instantiate red_bird with agent_args args['red_bird'] = red_bird # Choose a black_bird agent black_bird_type = load_agent(options.black_bird, no_keyboard) if args['layout'].has_black_bird(): args['black_bird'] = black_bird_type(1) else: args['black_bird'] = None # Choose a display format if options.quiet_graphics: import text_display args['display'] = text_display.NullGraphics() elif options.text_graphics: import text_display text_display.SLEEP_TIME = options.frame_time args['display'] = text_display.RedBirdGraphics() else: import graphics_display args['display'] = graphics_display.RedBirdGraphics( options.zoom, frame_time=options.frame_time) args['num_games'] = options.num_games args['catch_exceptions'] = options.catch_exceptions args['timeout'] = options.timeout return args
def read_command(argv): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usage_str = """ USAGE: python pacman.py <options> EXAMPLES: (1) python pacman.py - starts an interactive game (2) python pacman.py --layout small_classic --zoom 2 OR python pacman.py -l small_classic -z 2 - starts an interactive game on a smaller board, zoomed in """ parser = OptionParser(usage_str) parser.add_option('-n', '--num_games', dest='num_games', 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='medium_classic') parser.add_option( '-p', '--pacman', dest='pacman', help=default('the agent TYPE in the pacman_agents module to use'), metavar='TYPE', default='KeyboardAgent') parser.add_option('-t', '--text_graphics', action='store_true', dest='text_graphics', help='Display output as text only', default=False) parser.add_option('-q', '--quiet_text_graphics', action='store_true', dest='quiet_graphics', help='Generate minimal output and no graphics', default=False) parser.add_option( '-g', '--ghosts', dest='ghost', help=default('the ghost agent TYPE in the ghost_agents module to use'), metavar='TYPE', default='RandomGhost') parser.add_option('-k', '--numghosts', type='int', dest='num_ghosts', 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', '--fix_random_seed', action='store_true', dest='fix_random_seed', help='Fixes the random seed to always play the same game', default=False) parser.add_option( '-r', '--record_actions', 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='game_to_replay', help='A recorded game file (pickle) to replay', default=None) parser.add_option( '-a', '--agent_args', dest='agent_args', help= 'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"' ) parser.add_option( '-x', '--num_training', dest='num_training', type='int', help=default('How many episodes are training (suppresses output)'), default=0) parser.add_option( '--frame_time', dest='frame_time', type='float', help=default('Time to delay between frames; <0 means keyboard'), default=0.1) parser.add_option( '-c', '--catch_exceptions', action='store_true', dest='catch_exceptions', 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.fix_random_seed: random.seed('cs188') # Choose a layout args['layout'] = layout.get_layout(options.layout) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") # Choose a Pacman agent no_keyboard = options.game_to_replay == None and (options.text_graphics or options.quiet_graphics) pacman_type = load_agent(options.pacman, no_keyboard) agent_opts = parse_agent_args(options.agent_args) if options.num_training > 0: args['num_training'] = options.num_training if 'num_training' not in agent_opts: agent_opts['num_training'] = options.num_training pacman = pacman_type(**agent_opts) # Instantiate Pacman with agent_args args['pacman'] = pacman # Don't display training games if 'num_train' in agent_opts: options.num_quiet = int(agent_opts['num_train']) options.num_ignore = int(agent_opts['num_train']) # Choose a ghost agent ghost_type = load_agent(options.ghost, no_keyboard) args['ghosts'] = [ghost_type(i + 1) for i in range(options.num_ghosts)] # Choose a display format if options.quiet_graphics: import text_display args['display'] = text_display.NullGraphics() elif options.text_graphics: import text_display text_display.SLEEP_TIME = options.frame_time args['display'] = text_display.PacmanGraphics() else: import graphics_display args['display'] = graphics_display.PacmanGraphics( options.zoom, frame_time=options.frame_time) args['num_games'] = options.num_games args['record'] = options.record args['catch_exceptions'] = options.catch_exceptions args['timeout'] = options.timeout # Special case: recorded games don't use the run_games method or args structure if options.game_to_replay != None: print('Replaying recorded game %s.' % options.game_to_replay) import pickle f = open(options.game_to_replay) try: recorded = pickle.load(f) finally: f.close() recorded['display'] = args['display'] replay_game(**recorded) sys.exit(0) return args
def read_command(argv): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usage_str = """ 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 baseline_team -b my_team - starts a fully automated game where the red team is a baseline team and blue team is my_team """ parser = OptionParser(usage_str) parser.add_option('-r', '--red', help=default('Red team'), default='baseline_team') parser.add_option('-b', '--blue', help=default('Blue team'), default='baseline_team') 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('--red_opts', help=default('Options for red team (e.g. first=keys)'), default='') parser.add_option('--blue_opts', 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='default_capture') 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', '--num_games', type='int', help=default('Number of games to play'), default=1) parser.add_option('-f', '--fix_random_seed', 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', '--num_training', dest='num_training', type='int', help=default('How many episodes are training (suppresses output)'), default=0) parser.add_option('-c', '--catch_exceptions', 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 pygame_display # args['display'] = pygame_display.PacmanGraphics() if options.textgraphics: import text_display args['display'] = text_display.PacmanGraphics() elif options.quiet: import text_display args['display'] = text_display.NullGraphics() elif options.super_quiet: import text_display args['display'] = text_display.NullGraphics() args['mute_agents'] = True else: import capture_graphics_display # Hack for agents writing to the display capture_graphics_display.FRAME_TIME = 0 args['display'] = capture_graphics_display.PacmanGraphics(options.red, options.blue, options.zoom, 0, capture=True) import __main__ __main__.__dict__['_display'] = args['display'] args['red_team_name'] = options.red_name args['blue_team_name'] = options.blue_name if options.fix_random_seed: random.seed('CSI480') # Special case: recorded games don't use the run_games 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'] replay_game(**recorded) sys.exit(0) # Choose a pacman agent red_args, blue_args = parse_agent_args(options.red_opts), parse_agent_args(options.blue_opts) if options.num_training > 0: red_args['num_training'] = options.num_training blue_args['num_training'] = options.num_training nokeyboard = options.textgraphics or options.quiet or options.num_training > 0 print('\nRed team %s with %s:' % (options.red, red_args)) red_agents = load_agents(True, options.red, nokeyboard, red_args) print('\nBlue team %s with %s:' % (options.blue, blue_args)) blue_agents = load_agents(False, options.blue, nokeyboard, blue_args) args['agents'] = sum([list(el) for el in zip(red_agents, blue_agents)], []) # list of agents num_keyboard_agents = 0 for index, val in enumerate([options.keys0, options.keys1, options.keys2, options.keys3]): if not val: continue if num_keyboard_agents == 0: agent = keyboard_agents.KeyboardAgent(index) elif num_keyboard_agents == 1: agent = keyboard_agents.KeyboardAgent2(index) else: raise Exception('Max of two keyboard agents supported') num_keyboard_agents += 1 args['agents'][index] = agent # Choose a layout import layout layouts = [] for i in range(options.num_games): if options.layout == 'RANDOM': l = layout.Layout(random_layout().split('\n')) elif options.layout.startswith('RANDOM'): l = layout.Layout(random_layout(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.get_layout(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['num_games'] = options.num_games args['num_training'] = options.num_training args['record'] = options.record args['catch_exceptions'] = options.catch_exceptions return args