def _launch_mp(self, interface): # Reserve a whole bunch of ports for the weird multiplayer implementation. self._ports = [ portpicker.pick_unused_port() for _ in range(1 + self._num_players * 2) ] assert len(self._ports) == len(set( self._ports)) # Ports must be unique. # Actually launch the game processes. self._sc2_procs = [ self._run_config.start(extra_ports=self._ports) for _ in range(self._num_players) ] self._controllers = [p.controller for p in self._sc2_procs] # Save the maps so they can access it. self._parallel.run( (c.save_map, self._map.path, self._map.data(self._run_config)) for c in self._controllers) # Create the game. Set the first instance as the host. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=self._map.path)) if self._random_seed is not None: create.random_seed = self._random_seed for p in self._players: if isinstance(p, Agent): create.player_setup.add(type=sc_pb.Participant) else: create.player_setup.add(type=sc_pb.Computer, race=p.race, difficulty=p.difficulty) self._controllers[0].create_game(create) # Create the join request. join = sc_pb.RequestJoinGame(options=interface) join.shared_port = self._ports.pop() join.server_ports.game_port = self._ports.pop() join.server_ports.base_port = self._ports.pop() for _ in range(self._num_players - 1): join.client_ports.add(game_port=self._ports.pop(), base_port=self._ports.pop()) join_reqs = [] for p in self._players: if isinstance(p, Agent): j = sc_pb.RequestJoinGame() j.CopyFrom(join) j.race = p.race join_reqs.append(j) # Join the game. This must be run in parallel because Join is a blocking # call to the game that waits until all clients have joined. self._parallel.run((c.join_game, join) for c, join in zip(self._controllers, join_reqs)) # Save them for restart. self._create_req = create self._join_reqs = join_reqs
async def join_game(self, race=None, observed_player_id=None, portconfig=None): ifopts = sc_pb.InterfaceOptions(raw=True, score=True) if race is None: assert isinstance(observed_player_id, int) # join as observer req = sc_pb.RequestJoinGame(observed_player_id=observed_player_id, options=ifopts) else: assert isinstance(race, Race) req = sc_pb.RequestJoinGame(race=race.value, options=ifopts) if portconfig: req.shared_port = portconfig.shared req.server_ports.game_port = portconfig.server[0] req.server_ports.base_port = portconfig.server[1] for ppc in portconfig.players: p = req.client_ports.add() p.game_port = ppc[0] p.base_port = ppc[1] result = await self._execute(join_game=req) self._game_result = None self._player_id = result.join_game.player_id return result.join_game.player_id
async def join_game(self, name=None, race=None, observed_player_id=None, portconfig=None, rgb_render_config=None): ifopts = sc_pb.InterfaceOptions( raw=True, score=True, show_cloaked=True, show_burrowed_shadows=True, raw_affects_selection=self.raw_affects_selection, raw_crop_to_playable_area=False, show_placeholders=True, ) if rgb_render_config: assert isinstance(rgb_render_config, dict) assert "window_size" in rgb_render_config and "minimap_size" in rgb_render_config window_size = rgb_render_config["window_size"] minimap_size = rgb_render_config["minimap_size"] self._renderer = Renderer(self, window_size, minimap_size) map_width, map_height = window_size minimap_width, minimap_height = minimap_size ifopts.render.resolution.x = map_width ifopts.render.resolution.y = map_height ifopts.render.minimap_resolution.x = minimap_width ifopts.render.minimap_resolution.y = minimap_height if race is None: assert isinstance( observed_player_id, int ), f"observed_player_id is of type {type(observed_player_id)}" # join as observer req = sc_pb.RequestJoinGame(observed_player_id=observed_player_id, options=ifopts) else: assert isinstance(race, Race) req = sc_pb.RequestJoinGame(race=race.value, options=ifopts) if portconfig: req.shared_port = portconfig.shared req.server_ports.game_port = portconfig.server[0] req.server_ports.base_port = portconfig.server[1] for ppc in portconfig.players: p = req.client_ports.add() p.game_port = ppc[0] p.base_port = ppc[1] if name is not None: assert isinstance(name, str), f"name is of type {type(name)}" req.player_name = name result = await self._execute(join_game=req) self._game_result = None self._player_id = result.join_game.player_id return result.join_game.player_id
async def join_game(self, name=None, race=None, observed_player_id=None, portconfig=None, rgb_render_config=None): ifopts = sc_pb.InterfaceOptions(raw=True, score=True) if rgb_render_config: assert isinstance(rgb_render_config, dict) assert 'window_size' in rgb_render_config and 'minimap_size' in rgb_render_config window_size = rgb_render_config['window_size'] minimap_size = rgb_render_config['minimap_size'] self._renderer = Renderer(self, window_size, minimap_size) map_width, map_height = window_size minimap_width, minimap_height = minimap_size ifopts.render.resolution.x = map_width ifopts.render.resolution.y = map_height ifopts.render.minimap_resolution.x = minimap_width ifopts.render.minimap_resolution.y = minimap_height if race is None: assert isinstance(observed_player_id, int) # join as observer req = sc_pb.RequestJoinGame(observed_player_id=observed_player_id, options=ifopts) else: assert isinstance(race, Race) req = sc_pb.RequestJoinGame(race=race.value, options=ifopts) if portconfig: req.shared_port = portconfig.shared req.server_ports.game_port = portconfig.server[0] req.server_ports.base_port = portconfig.server[1] for ppc in portconfig.players: p = req.client_ports.add() p.game_port = ppc[0] p.base_port = ppc[1] if name is not None: assert isinstance(name, str) req.player_name = name result = await self._execute(join_game=req) self._game_result = None self._player_id = result.join_game.player_id return result.join_game.player_id
def main(unused_argv): """Run SC2 to play a game or a replay.""" run_config = run_configs.get() map_inst = maps.get(FLAGS.map) ports = [portpicker.pick_unused_port() for _ in range(5)] sc2_procs = [run_config.start(extra_ports=ports) for _ in range(2)] controllers = [p.controller for p in sc2_procs] for c in controllers: c.save_map(map_inst.path, map_inst.data(run_config)) create = sc_pb.RequestCreateGame( realtime=FLAGS.realtime, local_map=sc_pb.LocalMap(map_path=map_inst.path)) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Participant) controllers[0].create_game(create) join = sc_pb.RequestJoinGame() join.shared_port = ports.pop() join.server_ports.game_port = ports.pop() join.server_ports.base_port = ports.pop() join.client_ports.add(game_port=ports.pop(), base_port=ports.pop()) threads = [ threading.Thread(target=human_runner, args=(controllers[0], join)), threading.Thread(target=agent_runner, args=(controllers[1], join)), ] for t in threads: t.start() for t in threads: t.join()
def get_map_size(map_name: str) -> tuple: """Get the map size. If this info hasn't already been extracted by the agent before, a game will be started in order to get it. The information will then be pickled and further calls to this function will look for the info in the pickled file. :param map_name: the map name :type map_name: str :return: a tuple :math:`(x, y)` containing the dimensions of the map :rtype: tuple """ if map_name in __data: map_size = __data[map_name] else: run_config = run_configs.get() map_inst = maps.get(map_name) with run_config.start(want_rgb=False) as controller: create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=map_inst.path, map_data=map_inst.data(run_config))) create.player_setup.add(type=sc_pb.Participant) join = sc_pb.RequestJoinGame( race=sc_common.Terran, options=sc_pb.InterfaceOptions(raw=True)) controller.create_game(create) controller.join_game(join) info = controller.game_info() map_size = info.start_raw.map_size __data[map_name] = (map_size.x, map_size.y) with open(__pickle, 'wb') as fp: pickle.dump(__data, fp, protocol=pickle.HIGHEST_PROTOCOL) return map_size
def get_static_data(): """Retrieve static data from the game.""" try: with open(STATIC_DATA_PICKLE_PATH, 'rb') as f: static_data = pickle.load(f) return static_data except FileNotFoundError: pass run_config = run_configs.get() with run_config.start() as controller: m = maps.get("Sequencer") # Arbitrary ladder map. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=common_pb.Random, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=common_pb.Terran, options=sc_pb.InterfaceOptions(raw=True)) controller.create_game(create) controller.join_game(join) static_data = controller.data_raw() with open(STATIC_DATA_PICKLE_PATH, 'wb') as f: static_data = pickle.dump(static_data, f, protocol=pickle.HIGHEST_PROTOCOL) return static_data
def testVsAgent(self): parallel = run_parallel.RunParallel() for _ in range(NUM_MATCHES): with host_remote_agent.VsAgent() as game: game.create_game("Simple64") controllers = [ remote_controller.RemoteController(host=host, port=host_port) for host, host_port in zip(game.hosts, game.host_ports) ] join = sc_pb.RequestJoinGame(options=sc_pb.InterfaceOptions( raw=True)) join.race = sc_common.Random join.shared_port = 0 join.server_ports.game_port = game.lan_ports[0] join.server_ports.base_port = game.lan_ports[1] join.client_ports.add(game_port=game.lan_ports[2], base_port=game.lan_ports[3]) parallel.run((c.join_game, join) for c in controllers) for _ in range(STEPS): parallel.run(c.step for c in controllers) response_observations = [c.observe() for c in controllers] if response_observations[0].player_result: break parallel.run(c.leave for c in controllers) parallel.run(c.close for c in controllers)
def human_runner(controller, join): """Run the human agent in a thread.""" j = sc_pb.RequestJoinGame() j.CopyFrom(join) j.race = sc2_env.Race[FLAGS.user_race] if FLAGS.render: j.options.raw = True j.options.feature_layer.width = 24 j.options.feature_layer.resolution.x = 64 j.options.feature_layer.resolution.y = 64 j.options.feature_layer.minimap_resolution.x = 64 j.options.feature_layer.minimap_resolution.y = 64 # j.options.render.resolution.x = 256 # j.options.render.resolution.y = 192 # j.options.render.minimap_resolution.x = 128 # j.options.render.minimap_resolution.y = 128 controller.join_game(j) if FLAGS.render: renderer = renderer_human.RendererHuman(render_feature_grid=False) renderer.run(run_configs.get(), controller, max_episodes=1) else: # Still step forward so the Mac/Windows renderer works. try: while True: frame_start_time = time.time() if not FLAGS.realtime: controller.step(FLAGS.step_mul) obs = controller.observe() if obs.player_result: break time.sleep(max(0, frame_start_time - time.time() + 1 / 22.4)) except KeyboardInterrupt: pass controller.quit()
def _launch(self): """Launch the StarCraft II game.""" self._run_config = run_configs.get() _map = maps.get(self.map_name) # Setting up the interface interface_options = sc_pb.InterfaceOptions(raw=True, score=False) self._sc2_proc = self._run_config.start(game_version=self.game_version, window_size=self.window_size) self.controller = self._sc2_proc.controller # Request to create the game create = sc_pb.RequestCreateGame( local_map=sc_pb.LocalMap( map_path=_map.path, map_data=self._run_config.map_data(_map.path)), realtime=False, random_seed=self.seed) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=races[self._bot_race], difficulty=difficulties[self.difficulty]) self.controller.create_game(create) join = sc_pb.RequestJoinGame(race=races[self._agent_race], options=interface_options) self.controller.join_game(join)
def test_observe_bots(self): run_config = run_configs.get() map_inst = maps.get("Simple64") with run_config.start(want_rgb=False) as controller: create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=map_inst.path, map_data=map_inst.data(run_config))) create.player_setup.add( type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryEasy) create.player_setup.add( type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryHard) create.player_setup.add(type=sc_pb.Observer) controller.create_game(create) join = sc_pb.RequestJoinGame( options=sc_pb.InterfaceOptions(), # cheap observations observed_player_id=0) controller.join_game(join) outcome = False for _ in range(60 * 60): # 60 minutes should be plenty. controller.step(16) obs = controller.observe() if obs.player_result: print("Outcome after %s steps (%0.1f game minutes):" % ( obs.observation.game_loop, obs.observation.game_loop / (16 * 60))) for r in obs.player_result: print("Player %s: %s" % (r.player_id, sc_pb.Result.Name(r.result))) outcome = True break self.assertTrue(outcome)
def _launch_mp(self, map_inst, interfaces): # Reserve a whole bunch of ports for the weird multiplayer implementation. self._ports = portspicker.pick_unused_ports(self._num_agents * 2) logging.info("Ports used for multiplayer: %s", self._ports) # Actually launch the game processes. self._sc2_procs = [ self._run_config.start(extra_ports=self._ports, want_rgb=interface.HasField("render")) for interface in interfaces ] self._controllers = [p.controller for p in self._sc2_procs] # Save the maps so they can access it. Don't do it in parallel since SC2 # doesn't respect tmpdir on windows, which leads to a race condition: # https://github.com/Blizzard/s2client-proto/issues/102 for c in self._controllers: c.save_map(map_inst.path, map_inst.data(self._run_config)) # Create the game. Set the first instance as the host. create = sc_pb.RequestCreateGame( local_map=sc_pb.LocalMap(map_path=map_inst.path), disable_fog=self._disable_fog, realtime=self._realtime) if self._random_seed is not None: create.random_seed = self._random_seed for p in self._players: if isinstance(p, Agent): create.player_setup.add(type=sc_pb.Participant) else: create.player_setup.add(type=sc_pb.Computer, race=p.race, difficulty=p.difficulty) self._controllers[0].create_game(create) # Create the join requests. agent_players = (p for p in self._players if isinstance(p, Agent)) join_reqs = [] for agent_index, p in enumerate(agent_players): ports = self._ports[:] join = sc_pb.RequestJoinGame(options=interfaces[agent_index]) join.shared_port = 0 # unused join.server_ports.game_port = ports.pop(0) join.server_ports.base_port = ports.pop(0) for _ in range(self._num_agents - 1): join.client_ports.add(game_port=ports.pop(0), base_port=ports.pop(0)) join.race = p.race join.player_name = p.name join_reqs.append(join) # Join the game. This must be run in parallel because Join is a blocking # call to the game that waits until all clients have joined. self._parallel.run((c.join_game, join) for c, join in zip(self._controllers, join_reqs)) # Save them for restart. self._create_req = create self._join_reqs = join_reqs
def _connect_remote(self, host, host_port, lan_ports, race, name, map_inst, save_map, interface): """Make sure this stays synced with bin/agent_remote.py.""" # Connect! logging.info("Connecting...") self._controllers = [ remote_controller.RemoteController(host, host_port) ] logging.info("Connected") if map_inst and save_map: run_config = run_configs.get() self._controllers[0].save_map(map_inst.path, map_inst.data(run_config)) # Create the join request. join = sc_pb.RequestJoinGame(options=interface) join.race = race join.player_name = name join.shared_port = 0 # unused join.server_ports.game_port = lan_ports.pop(0) join.server_ports.base_port = lan_ports.pop(0) join.client_ports.add(game_port=lan_ports.pop(0), base_port=lan_ports.pop(0)) logging.info("Joining game.") self._controllers[0].join_game(join) self._in_game = True logging.info("Game joined.")
def test_error(self): with run_configs.get().start() as controller: with self.assertRaises(remote_controller.RequestError): controller.create_game(sc_pb.RequestCreateGame()) # Missing map, etc. with self.assertRaises(protocol.ProtocolError): controller.join_game(sc_pb.RequestJoinGame()) # No game to join.
def check_apm(self, name): """Set up a game, yield, then check the apm in the replay.""" interface = sc_pb.InterfaceOptions(raw=True, score=False) interface.feature_layer.width = 24 interface.feature_layer.resolution.x = 64 interface.feature_layer.resolution.y = 64 interface.feature_layer.minimap_resolution.x = 64 interface.feature_layer.minimap_resolution.y = 64 create = sc_pb.RequestCreateGame(random_seed=1, local_map=sc_pb.LocalMap( map_path=self._map_path, map_data=self._map_data)) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_common.Protoss, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_common.Protoss, options=interface) self._controller.create_game(create) self._controller.join_game(join) self._info = self._controller.game_info() self._features = features.features_from_game_info( self._info, use_feature_units=True, use_raw_units=True) self._map_size = point.Point.build(self._info.start_raw.map_size) for i in range(60): yield i, self.step() data = self._controller.save_replay() replay_info = self._controller.replay_info(data) self._summary.append((name, replay_info))
def _launch(self): self._run_config = run_configs.get() self._map = maps.get(self.map_name) # Setting up the interface self.interface = sc_pb.InterfaceOptions( raw=True, # raw, feature-level data score=True) self._sc2_proc = self._run_config.start(game_version=self.game_version, window_size=self.window_size) self.controller = self._sc2_proc.controller # Create the game. create = sc_pb.RequestCreateGame( realtime=False, random_seed=self.seed, local_map=sc_pb.LocalMap(map_path=self._map.path, map_data=self._run_config.map_data( self._map.path))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=races[self._bot_race], difficulty=difficulties[self.difficulty]) self.controller.create_game(create) join = sc_pb.RequestJoinGame(race=races[self._agent_race], options=self.interface) self.controller.join_game(join)
def _connect_remote(self, host, host_port, lan_port, race, map_inst, interface): """Make sure this stays synced with bin/agent_remote.py.""" # Connect! logging.info("Connecting...") self._controllers = [ remote_controller.RemoteController(host, host_port) ] logging.info("Connected") # Create the join request. ports = [lan_port + p for p in range(4)] # 2 * num players *in the game*. join = sc_pb.RequestJoinGame(options=interface) join.race = race join.shared_port = 0 # unused join.server_ports.game_port = ports.pop(0) join.server_ports.base_port = ports.pop(0) join.client_ports.add(game_port=ports.pop(0), base_port=ports.pop(0)) if map_inst: run_config = run_configs.get() self._controllers[0].save_map(map_inst.path, map_inst.data(run_config)) self._controllers[0].join_game(join)
def test_load_random_map(self, controller, map_name): """Test loading a few random maps.""" m = maps.get(map_name) run_config = run_configs.get() logging.info("Loading map: %s", m.name) create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_common.Random, options=sc_pb.InterfaceOptions(raw=True)) controller.create_game(create) controller.join_game(join) # Verify it has the right mods and isn't running into licensing issues. info = controller.game_info() logging.info("Mods for %s: %s", m.name, info.mod_names) self.assertIn("Mods/Void.SC2Mod", info.mod_names) self.assertIn("Mods/VoidMulti.SC2Mod", info.mod_names) # Verify it can be played without making actions. for _ in range(3): controller.step() controller.observe()
def test_versions_create_game(self, game_version): log_center("starting create game: %s", game_version) run_config = run_configs.get() with run_config.start(version=game_version) as controller: interface = sc_pb.InterfaceOptions() interface.raw = True interface.score = True interface.feature_layer.width = 24 interface.feature_layer.resolution.x = 84 interface.feature_layer.resolution.y = 84 interface.feature_layer.minimap_resolution.x = 64 interface.feature_layer.minimap_resolution.y = 64 map_inst = maps.get("Simple64") create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=map_inst.path, map_data=map_inst.data(run_config))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_common.Terran, options=interface) controller.create_game(create) controller.join_game(join) for _ in range(5): controller.step(16) controller.observe() log_center("success: %s", game_version)
def _launch_sp(self, map_inst, interface): self._sc2_procs = [ self._run_config.start(want_rgb=interface.HasField("render")) ] self._controllers = [p.controller for p in self._sc2_procs] # Create the game. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=map_inst.path, map_data=map_inst.data(self._run_config)), disable_fog=self._disable_fog, realtime=self._realtime) agent = Agent(Race.random) for p in self._players: if isinstance(p, Agent): create.player_setup.add(type=sc_pb.Participant) agent = p else: create.player_setup.add(type=sc_pb.Computer, race=p.race, difficulty=p.difficulty) if self._random_seed is not None: create.random_seed = self._random_seed self._controllers[0].create_game(create) join = sc_pb.RequestJoinGame(options=interface, race=agent.race, player_name=agent.name) self._controllers[0].join_game(join)
def test_load_random_map(self): """Test loading a few random maps.""" all_maps = maps.get_maps() run_config = run_configs.get() with run_config.start() as controller: # Test only a few random maps when run locally to minimize time. count = 5 map_sample = random.sample(all_maps.items(), min(count, len(all_maps))) for _, map_class in sorted(map_sample): m = map_class() logging.info("Loading map: %s", m.name) create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_pb.Random, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_pb.Random, options=sc_pb.InterfaceOptions(raw=True)) controller.create_game(create) controller.join_game(join) # Verify it has the right mods and isn't running into licensing issues. info = controller.game_info() logging.info("Mods for %s: %s", m.name, info.mod_names) self.assertIn("Mods/Void.SC2Mod", info.mod_names) self.assertIn("Mods/VoidMulti.SC2Mod", info.mod_names) # Verify it can be played without making actions. for _ in range(3): controller.step() controller.observe()
def agent_runner(controller, join): """Run the agent in a thread.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) agent = agent_cls() interface = sc_pb.InterfaceOptions() interface.raw = True interface.score = True interface.feature_layer.width = 24 interface.feature_layer.resolution.x = FLAGS.feature_screen_size interface.feature_layer.resolution.y = FLAGS.feature_screen_size interface.feature_layer.minimap_resolution.x = FLAGS.feature_minimap_size interface.feature_layer.minimap_resolution.y = FLAGS.feature_minimap_size # if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size: # if FLAGS.rgb_screen_size < FLAGS.rgb_minimap_size: # sys.exit("Screen size can't be smaller than minimap size.") # interface.render.resolution.x = FLAGS.rgb_screen_size # interface.render.resolution.y = FLAGS.rgb_screen_size # interface.render.minimap_resolution.x = FLAGS.rgb_minimap_size # interface.render.minimap_resolution.y = FLAGS.rgb_minimap_size j = sc_pb.RequestJoinGame() j.CopyFrom(join) j.options.CopyFrom(interface) j.race = sc2_env.Race[FLAGS.agent_race] controller.join_game(j) feats = features.Features(game_info=controller.game_info()) agent.setup(feats.observation_spec(), feats.action_spec()) state = environment.StepType.FIRST reward = 0 discount = 1 while True: frame_start_time = time.time() if not FLAGS.realtime: controller.step(FLAGS.step_mul) obs = controller.observe() if obs.player_result: # Episode over. state = environment.StepType.LAST discount = 0 agent_obs = feats.transform_obs(obs) timestep = environment.TimeStep(step_type=state, reward=reward, discount=discount, observation=agent_obs) action = agent.step(timestep) if state == environment.StepType.LAST: break controller.act(feats.transform_action(obs.observation, action)) if FLAGS.realtime: time.sleep( max(0, frame_start_time - time.time() + FLAGS.step_mul / 22.4)) controller.quit()
def _launch(self): """Launch the StarCraft II game.""" self._run_config = run_configs.get(version=self.game_version) _map = maps.get(self.map_name) # Setting up the interface interface_options = sc_pb.InterfaceOptions(raw=True, score=False) self._sc2_proc = self._run_config.start(window_size=self.window_size, want_rgb=False) self._controller = self._sc2_proc.controller # Request to create the game create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=_map.path, map_data=self._run_config.map_data(_map.path)), realtime=False, random_seed=self._seed) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=races[self._bot_race], difficulty=difficulties[self.difficulty]) self._controller.create_game(create) join = sc_pb.RequestJoinGame(race=races[self._agent_race], options=interface_options) self._controller.join_game(join) game_info = self._controller.game_info() map_info = game_info.start_raw map_play_area_min = map_info.playable_area.p0 map_play_area_max = map_info.playable_area.p1 self.max_distance_x = map_play_area_max.x - map_play_area_min.x self.max_distance_y = map_play_area_max.y - map_play_area_min.y self.map_x = map_info.map_size.x self.map_y = map_info.map_size.y self.playable_x_max = map_play_area_max.x self.playable_x_min = map_play_area_min.x self.playable_y_max = map_play_area_max.y self.playable_y_min = map_play_area_min.x if map_info.pathing_grid.bits_per_pixel == 1: vals = np.array(list(map_info.pathing_grid.data)).reshape( self.map_x, int(self.map_y / 8)) self.pathing_grid = np.transpose( np.array([[(b >> i) & 1 for b in row for i in range(7, -1, -1)] for row in vals], dtype=np.bool)) else: self.pathing_grid = np.invert( np.flip(np.transpose( np.array(list(map_info.pathing_grid.data), dtype=np.bool).reshape(self.map_x, self.map_y)), axis=1)) self.terrain_height = np.flip( np.transpose( np.array(list(map_info.terrain_height.data)).reshape( self.map_x, self.map_y)), 1) / 255
def _join_pb(self, agent_race, interface): ports = copy.deepcopy(self._ports) join = sc_pb.RequestJoinGame(race=agent_race, options=interface) join.shared_port = ports.pop() join.server_ports.game_port = ports.pop() join.server_ports.base_port = ports.pop() for _ in range(len(self._agents) - 1): join.client_ports.add(game_port=ports.pop(), base_port=ports.pop()) return join
def main(unused_argv): configs = [ ("raw", interface_options(raw=True)), ("raw-feat-48", interface_options(raw=True, features=48)), ("feat-32", interface_options(features=32)), ("feat-48", interface_options(features=48)), ("feat-72", interface_options(features=72)), ("feat-96", interface_options(features=96)), ("feat-128", interface_options(features=128)), ("rgb-64", interface_options(rgb=64)), ("rgb-128", interface_options(rgb=128)), ] results = [] try: for config, interface in configs: timeline = [] run_config = run_configs.get() with run_config.start( want_rgb=interface.HasField("render")) as controller: map_inst = maps.get("Catalyst") create = sc_pb.RequestCreateGame( realtime=False, disable_fog=False, random_seed=1, local_map=sc_pb.LocalMap( map_path=map_inst.path, map_data=map_inst.data(run_config))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_common.Protoss, options=interface) controller.create_game(create) controller.join_game(join) for _ in range(FLAGS.count): controller.step(FLAGS.step_mul) start = time.time() obs = controller.observe() timeline.append(time.time() - start) if obs.player_result: break results.append((config, timeline)) except KeyboardInterrupt: pass names, values = zip(*results) print("\n\nTimeline:\n") print(",".join(names)) for times in zip(*values): print(",".join("%0.2f" % (t * 1000) for t in times))
def _launch_remote(self, host, config_port, race, name, interface, agent_interface_format): """Make sure this stays synced with bin/play_vs_agent.py.""" self._tcp_conn, settings = tcp_client(Addr(host, config_port)) self._map_name = settings["map_name"] if settings["remote"]: self._udp_sock = udp_server( Addr(host, settings["ports"]["server"]["game"])) daemon_thread(tcp_to_udp, (self._tcp_conn, self._udp_sock, Addr(host, settings["ports"]["client"]["game"]))) daemon_thread(udp_to_tcp, (self._udp_sock, self._tcp_conn)) extra_ports = [ settings["ports"]["server"]["game"], settings["ports"]["server"]["base"], settings["ports"]["client"]["game"], settings["ports"]["client"]["base"], ] self._run_config = run_configs.get(version=settings["game_version"]) self._sc2_procs = [ self._run_config.start(extra_ports=extra_ports, host=host, window_loc=(700, 50), want_rgb=interface.HasField("render")) ] self._controllers = [p.controller for p in self._sc2_procs] # Create the join request. join = sc_pb.RequestJoinGame(options=interface) join.race = race join.player_name = name join.shared_port = 0 # unused join.server_ports.game_port = settings["ports"]["server"]["game"] join.server_ports.base_port = settings["ports"]["server"]["base"] join.client_ports.add(game_port=settings["ports"]["client"]["game"], base_port=settings["ports"]["client"]["base"]) self._controllers[0].save_map(settings["map_path"], settings["map_data"]) self._controllers[0].join_game(join) self._game_info = [self._controllers[0].game_info()] self._features = [ features.features_from_game_info( game_info=self._game_info[0], agent_interface_format=agent_interface_format) ]
async def join_game(self, race=None, observed_player_id=None, portconfig=None): # Note modified by Davey for pysc2 screen_size_px = (64, 64) minimap_size_px = (64, 64) screen_size_px = point.Point(*screen_size_px) minimap_size_px = point.Point(*minimap_size_px) ifopts = sc_pb.InterfaceOptions( raw=True, score=True, feature_layer=sc_pb.SpatialCameraSetup(width=24)) screen_size_px.assign_to(ifopts.feature_layer.resolution) minimap_size_px.assign_to(ifopts.feature_layer.minimap_resolution) if race is None: assert isinstance(observed_player_id, int) # join as observer req = sc_pb.RequestJoinGame(observed_player_id=observed_player_id, options=ifopts) else: assert isinstance(race, Race) req = sc_pb.RequestJoinGame(race=race.value, options=ifopts) if portconfig: req.shared_port = portconfig.shared req.server_ports.game_port = portconfig.server[0] req.server_ports.base_port = portconfig.server[1] for ppc in portconfig.players: p = req.client_ports.add() p.game_port = ppc[0] p.base_port = ppc[1] result = await self._execute(join_game=req) self._game_result = None self._player_id = result.join_game.player_id return result.join_game.player_id
def create_game(self): create = sc_pb.RequestCreateGame(random_seed=self._config.random_seed, local_map=sc_pb.LocalMap( map_path=self._map_inst.path, map_data=self._map_data)) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_common.Terran, options=self._config.interface) self._controller.create_game(create) self._controller.join_game(join)
async def join_game(self, race=None, observed_player_id=None, portconfig=None): ifopts = sc_pb.InterfaceOptions(raw=True, score=True, feature_layer=sc_pb.SpatialCameraSetup ( width=24, resolution=common_pb.Size2DI(x=50,y=50), minimap_resolution=common_pb.Size2DI(x=50,y=50) ) ) # 임시로 설정해둔 값 if race is None: assert isinstance(observed_player_id, int) # join as observer req = sc_pb.RequestJoinGame( observed_player_id=observed_player_id, options=ifopts ) else: assert isinstance(race, Race) req = sc_pb.RequestJoinGame( race=race.value, options=ifopts ) if portconfig: req.shared_port = portconfig.shared req.server_ports.game_port = portconfig.server[0] req.server_ports.base_port = portconfig.server[1] for ppc in portconfig.players: p = req.client_ports.add() p.game_port = ppc[0] p.base_port = ppc[1] result = await self._execute(join_game=req) self._game_result = None self._player_id = result.join_game.player_id return result.join_game.player_id
def get_data(): run_config = run_configs.get() with run_config.start() as controller: m = maps.get("Sequencer") # Arbitrary ladder map. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=sc_pb.Random, difficulty=sc_pb.VeryEasy) join = sc_pb.RequestJoinGame(race=sc_pb.Random, options=sc_pb.InterfaceOptions(raw=True)) controller.create_game(create) controller.join_game(join) return controller.data()