Beispiel #1
0
    async def create_game(self,
                          game_map,
                          players,
                          realtime: bool,
                          random_seed=None,
                          disable_fog=None):
        req = sc_pb.RequestCreateGame(
            local_map=sc_pb.LocalMap(map_path=str(game_map.relative_path)),
            realtime=realtime,
            disable_fog=disable_fog)
        if random_seed is not None:
            req.random_seed = random_seed

        for player in players:
            p = req.player_setup.add()
            p.type = player.type.value
            if isinstance(player, Computer):
                p.race = player.race.value
                p.difficulty = player.difficulty.value
                p.ai_build = player.ai_build.value

        logger.info("Creating new game")
        logger.info(f"Map:     {game_map.name}")
        logger.info(f"Players: {', '.join(str(p) for p in players)}")
        result = await self._execute(create_game=req)
        return result
Beispiel #2
0
    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)
Beispiel #3
0
    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 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()
Beispiel #5
0
    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
Beispiel #6
0
    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)
Beispiel #7
0
  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)
Beispiel #8
0
    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
Beispiel #9
0
    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)
Beispiel #10
0
    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)
Beispiel #11
0
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()
Beispiel #12
0
    def _setup_game(self):
        # Save the maps so they can access it.
        map_path = os.path.basename(self._map.path)
        self._parallel.run(
            (c.save_map, map_path, self._run_config.map_data(self._map.path))
            for c in self._controllers)

        # construct interface
        interface = sc_pb.InterfaceOptions(raw=True, score=True)
        self._screen.assign_to(interface.feature_layer.resolution)
        self._minimap.assign_to(interface.feature_layer.minimap_resolution)

        # Create the create request.
        create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
            map_path=map_path))
        for _ in range(len(self._agents)):
            create.player_setup.add(type=sc_pb.Participant)

        # Create the join request.
        joins = [self._join_pb(race, interface) for race in self._races]

        # This is where actually game plays
        # Create and Join
        print("create")
        self._controllers[0].create_game(create)
        print("join")
        self._parallel.run(
            (c.join_game, join) for join, c in zip(joins, self._controllers))
        print("play_game")
        self._game_infos = self._parallel.run(
            (c.game_info) for c in self._controllers)
        self._features = [features.Features(info) for info in self._game_infos]
        print("setup game ok")
Beispiel #13
0
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
Beispiel #14
0
    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()
Beispiel #15
0
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
Beispiel #16
0
    def create_game(self, map_name):
        """Create a game for the agents to join.

        Args:
          map_name: The map to use.
        """
        self._reconnect()

        map_inst = maps.get(map_name)
        map_data = map_inst.data(self._run_config)
        if map_name not in self._saved_maps:
            for controller in self._controllers:
                controller.save_map(map_inst.path, map_data)
            self._saved_maps.add(map_name)

        # Form the create game message.
        create = sc_pb.RequestCreateGame(
            local_map=sc_pb.LocalMap(map_path=map_inst.path),
            disable_fog=False)

        # Set up for two agents.
        for _ in range(self._num_agents):
            create.player_setup.add(type=sc_pb.Participant)

        # Create the game.
        self._controllers[0].create_game(create)
        self._disconnect()
Beispiel #17
0
    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
Beispiel #18
0
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 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)
Beispiel #20
0
    async def create_game(self, game_map, players, realtime):
        assert isinstance(realtime, bool)
        req = sc_pb.RequestCreateGame(
            local_map=sc_pb.LocalMap(map_path=str(game_map.path)),
            realtime=realtime)

        for player in players:
            p = req.player_setup.add()
            p.type = player.type.value
            if isinstance(player, Computer):
                p.race = player.race.value
                p.difficulty = player.difficulty.value

        result = await self._execute(create_game=req)
        return result
Beispiel #21
0
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()
def main(unused_argv):
    interface = sc_pb.InterfaceOptions()
    interface.score = True
    interface.raw = FLAGS.raw
    if FLAGS.feature_size:
        interface.feature_layer.width = 24
        FLAGS.feature_size.assign_to(interface.feature_layer.resolution)
        FLAGS.feature_size.assign_to(
            interface.feature_layer.minimap_resolution)
    if FLAGS.rgb_size:
        FLAGS.rgb_size.assign_to(interface.render.resolution)
        FLAGS.rgb_size.assign_to(interface.render.minimap_resolution)

    timeline = []

    try:
        run_config = run_configs.get()
        with run_config.start() as controller:
            map_inst = maps.get("Simple64")
            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.Random,
                                         options=interface)
            controller.create_game(create)
            controller.join_game(join)

            for _ in range(500):
                controller.step()
                start = time.time()
                obs = controller.observe()
                timeline.append(time.time() - start)
                if obs.player_result:
                    break
    except KeyboardInterrupt:
        pass

    print("Timeline:")
    for t in timeline:
        print(t * 1000)
Beispiel #23
0
  def _launch(self, interface, player_setup):
    agent_race, bot_race, difficulty = player_setup

    self._sc2_procs = [self._run_config.start()]
    self._controllers = [p.controller for p in self._sc2_procs]

    # Create the game.
    create = sc_pb.RequestCreateGame(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[bot_race],
                            difficulty=difficulties[difficulty])
    self._controllers[0].create_game(create)

    join = sc_pb.RequestJoinGame(race=races[agent_race], options=interface)
    self._controllers[0].join_game(join)
Beispiel #24
0
def get_data():
    """Retrieve static data from the game."""
    run_config = run_configs.get()

    with run_config.start(want_rgb=False) as controller:
        m = maps.get(FLAGS.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_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)
        return controller.data()
Beispiel #25
0
    async def create_game(self, game_map, players, realtime):
        assert isinstance(realtime, bool)
        req = sc_pb.RequestCreateGame(
            local_map=sc_pb.LocalMap(map_path=str(game_map.relative_path)),
            realtime=realtime)

        for player in players:
            p = req.player_setup.add()
            p.type = player.type.value
            if isinstance(player, Computer):
                p.race = player.race.value
                p.difficulty = player.difficulty.value

        logger.info("Creating new game")
        logger.info(f"Map:     {game_map.name}")
        logger.info(f"Players: {', '.join(str(p) for p in players)}")
        result = await self._execute(create_game=req)
        return result
Beispiel #26
0
    def test_general_actions(self):
        run_config = run_configs.get()
        with run_config.start(want_rgb=False) as controller:
            map_inst = maps.get("Simple64")
            create = sc_pb.RequestCreateGame(
                realtime=False,
                disable_fog=False,
                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.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)

            abilities = controller.data().abilities

            errors = []

            for f in actions.FUNCTIONS:
                if abilities[
                        f.ability_id].remaps_to_ability_id != f.general_id:
                    errors.append(
                        "FUNCTIONS %s/%s has abilitiy %s, general %s, expected "
                        "general %s" %
                        (f.id, f.name, f.ability_id, f.general_id,
                         abilities[f.ability_id].remaps_to_ability_id))

            for f in actions.RAW_FUNCTIONS:
                if abilities[
                        f.ability_id].remaps_to_ability_id != f.general_id:
                    errors.append(
                        "RAW_FUNCTIONS %s/%s has abilitiy %s, general %s, expected "
                        "general %s" %
                        (f.id, f.name, f.ability_id, f.general_id,
                         abilities[f.ability_id].remaps_to_ability_id))

            print("\n".join(errors))
            self.assertFalse(errors)
Beispiel #27
0
 def requestCreateDetails(self):
     """add configuration to the SC2 protocol create request"""
     createReq = sc_pb.RequestCreateGame(  # used to advance to Status.initGame state, when hosting
         realtime=self.realtime,
         disable_fog=self.fogDisabled,
         random_seed=int(
             time.time()
         ),  # a game is created using the current second timestamp as the seed
         local_map=sc_pb.LocalMap(map_path=self.mapLocalPath,
                                  map_data=self.mapData))
     for player in self.players:
         reqPlayer = createReq.player_setup.add(
         )  # add new player; get link to settings
         playerObj = PlayerPreGame(player)
         if playerObj.isComputer:
             reqPlayer.difficulty = playerObj.difficulty.gameValue()
         reqPlayer.type = c.types.PlayerControls(
             playerObj.control).gameValue()
         reqPlayer.race = playerObj.selectedRace.gameValue()
     return createReq  # SC2APIProtocol.RequestCreateGame
Beispiel #28
0
    def test_versions_create_game(self):
        run_config = run_configs.get()
        failures = []
        for game_version in sorted(run_config.get_versions().keys()):
            try:
                log_center("starting create game: %s", game_version)
                with run_config.start(version=game_version,
                                      want_rgb=False) 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)
            except:  # pylint: disable=bare-except
                logging.exception("Failed")
                log_center("failure: %s", game_version)
                failures.append(game_version)
        self.assertEmpty(failures)
Beispiel #29
0
    def create_game(
            self,
            map_name,
            bot_difficulty=sc_pb.VeryEasy,
            bot_race=sc_common.Random,
            bot_first=False):
        """Create a game, one remote agent vs the specified bot.

        Args:
          map_name: The map to use.
          bot_difficulty: The difficulty of the bot to play against.
          bot_race: The race for the bot.
          bot_first: Whether the bot should be player 1 (else is player 2).
        """
        self._reconnect()
        self._controller.ping()

        # Form the create game message.
        map_inst = maps.get(map_name)
        map_data = map_inst.data(self._run_config)
        if map_name not in self._saved_maps:
            self._controller.save_map(map_inst.path, map_data)
            self._saved_maps.add(map_name)

        create = sc_pb.RequestCreateGame(
            local_map=sc_pb.LocalMap(map_path=map_inst.path, map_data=map_data),
            disable_fog=False)

        # Set up for one bot, one agent.
        if not bot_first:
            create.player_setup.add(type=sc_pb.Participant)

        create.player_setup.add(
            type=sc_pb.Computer, race=bot_race, difficulty=bot_difficulty)

        if bot_first:
            create.player_setup.add(type=sc_pb.Participant)

        # Create the game.
        self._controller.create_game(create)
        self._disconnect()
Beispiel #30
0
    def _launch(self, interface, player_setup):
        agent_race, bot_race, difficulty = player_setup
        # changed by mindgameSC2
        if self.game_version is not None:
            self._sc2_procs = [self._run_config.start(game_version=self.game_version)]
        else:
            self._sc2_procs = [self._run_config.start()]
        self._controllers = [p.controller for p in self._sc2_procs]

        # Create the game.
        create = sc_pb.RequestCreateGame(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[bot_race],
                                difficulty=difficulties[difficulty])
        create.random_seed = 5
        # create.disable_fog = True
        self._controllers[0].create_game(create)

        join = sc_pb.RequestJoinGame(race=races[agent_race], options=interface)
        self._controllers[0].join_game(join)