コード例 #1
0
    async def query_pathings(
        self, zipped_list: List[List[Union[Unit, Point2, Point3]]]
    ) -> List[Union[float, int]]:
        """ Usage: await self.query_pathings([[unit1, target2], [unit2, target2]])
        -> returns [distance1, distance2]
        Caution: returns 0 when path not found

        :param zipped_list:
        """
        assert zipped_list, "No zipped_list"
        assert isinstance(zipped_list, list), f"{type(zipped_list)}"
        assert isinstance(zipped_list[0], list), f"{type(zipped_list[0])}"
        assert len(zipped_list[0]) == 2, f"{len(zipped_list[0])}"
        assert isinstance(zipped_list[0][0],
                          (Point2, Unit)), f"{type(zipped_list[0][0])}"
        assert isinstance(zipped_list[0][1],
                          Point2), f"{type(zipped_list[0][1])}"
        if isinstance(zipped_list[0][0], Point2):
            results = await self._execute(query=query_pb.RequestQuery(
                pathing=(query_pb.RequestQueryPathing(
                    start_pos=common_pb.Point2D(x=p1.x, y=p1.y),
                    end_pos=common_pb.Point2D(x=p2.x, y=p2.y))
                         for p1, p2 in zipped_list)))
        else:
            results = await self._execute(query=query_pb.RequestQuery(
                pathing=(query_pb.RequestQueryPathing(
                    unit_tag=p1.tag, end_pos=common_pb.Point2D(x=p2.x, y=p2.y))
                         for p1, p2 in zipped_list)))
        return [float(d.distance) for d in results.query.pathing]
コード例 #2
0
 async def query_pathings(
     self, zipped_list: List[List[Union[Unit, Point2, Point3]]]
 ) -> List[Union[float, int]]:
     """ Usage: await self.query_pathings([[unit1, target2], [unit2, target2]])
     -> returns [distance1, distance2]
     Caution: returns 0 when path not found
     Might merge this function with the function above
     """
     assert isinstance(zipped_list, list)
     assert len(zipped_list) > 0
     assert isinstance(zipped_list[0], list)
     assert len(zipped_list[0]) == 2
     assert isinstance(zipped_list[0][0], (Point2, Unit))
     assert isinstance(zipped_list[0][1], Point2)
     if isinstance(zipped_list[0][0], Point2):
         results = await self._execute(query=query_pb.RequestQuery(pathing=[
             query_pb.RequestQueryPathing(
                 start_pos=common_pb.Point2D(x=p1.x, y=p1.y),
                 end_pos=common_pb.Point2D(x=p2.x, y=p2.y))
             for p1, p2 in zipped_list
         ]))
     else:
         results = await self._execute(query=query_pb.RequestQuery(pathing=[
             query_pb.RequestQueryPathing(
                 unit_tag=p1.tag, end_pos=common_pb.Point2D(x=p2.x, y=p2.y))
             for p1, p2 in zipped_list
         ]))
     results = [float(d.distance) for d in results.query.pathing]
     return results
コード例 #3
0
 async def query_pathing(
     self, start: Union[Unit, Point2, Point3], end: Union[Point2, Point3]
 ) -> Optional[Union[int, float]]:
     """ Caution: returns 0 when path not found """
     assert isinstance(start, (Point2, Unit))
     assert isinstance(end, Point2)
     if isinstance(start, Point2):
         result = await self._execute(
             query=query_pb.RequestQuery(
                 pathing=[
                     query_pb.RequestQueryPathing(
                         start_pos=common_pb.Point2D(x=start.x, y=start.y),
                         end_pos=common_pb.Point2D(x=end.x, y=end.y),
                     )
                 ]
             )
         )
     else:
         result = await self._execute(
             query=query_pb.RequestQuery(
                 pathing=[
                     query_pb.RequestQueryPathing(unit_tag=start.tag, end_pos=common_pb.Point2D(x=end.x, y=end.y))
                 ]
             )
         )
     distance = float(result.query.pathing[0].distance)
     if distance <= 0.0:
         return None
     return distance
コード例 #4
0
    async def query_pathing(
            self, start: Union[Unit, Point2, Point3],
            end: Union[Point2, Point3]) -> Optional[Union[int, float]]:
        """ Caution: returns "None" when path not found
        Try to combine queries with the function below because the pathing query is generally slow.

        :param start:
        :param end: """
        assert isinstance(start, (Point2, Unit))
        assert isinstance(end, Point2)
        if isinstance(start, Point2):
            result = await self._execute(query=query_pb.RequestQuery(pathing=[
                query_pb.RequestQueryPathing(
                    start_pos=common_pb.Point2D(x=start.x, y=start.y),
                    end_pos=common_pb.Point2D(x=end.x, y=end.y),
                )
            ]))
        else:
            result = await self._execute(query=query_pb.RequestQuery(pathing=[
                query_pb.RequestQueryPathing(unit_tag=start.tag,
                                             end_pos=common_pb.Point2D(
                                                 x=end.x, y=end.y))
            ]))
        distance = float(result.query.pathing[0].distance)
        if distance <= 0.0:
            return None
        return distance
コード例 #5
0
ファイル: utils.py プロジェクト: rainwangphy/pysc2
 def create_unit(self, unit_type, owner, pos, quantity=1):
     if isinstance(pos, tuple):
         pos = sc_common.Point2D(x=pos[0], y=pos[1])
     elif isinstance(pos, sc_common.Point):
         pos = sc_common.Point2D(x=pos.x, y=pos.y)
     return self.debug(create_unit=sc_debug.DebugCreateUnit(
         unit_type=unit_type, owner=owner, pos=pos, quantity=quantity))
コード例 #6
0
def combine_actions(action_iter):
    for key, items in groupby(action_iter, key=lambda a: a.combining_tuple):
        ability, target, queue = key

        if target is None:
            cmd = raw_pb.ActionRawUnitCommand(
                ability_id=ability.value,
                unit_tags=[u.unit.tag for u in items],
                queue_command=queue)
        elif isinstance(target, Point2):
            cmd = raw_pb.ActionRawUnitCommand(
                ability_id=ability.value,
                unit_tags=[u.unit.tag for u in items],
                queue_command=queue,
                target_world_space_pos=common_pb.Point2D(x=target.x,
                                                         y=target.y))
        elif isinstance(target, Unit):
            cmd = raw_pb.ActionRawUnitCommand(
                ability_id=ability.value,
                unit_tags=[u.unit.tag for u in items],
                queue_command=queue,
                target_unit_tag=target.tag)
        else:
            raise RuntimeError(
                f"Must target an unit or a point or None, found '{target !r}'")

        yield raw_pb.ActionRaw(unit_command=cmd)
コード例 #7
0
    async def debug_create_unit(
        self, unit_spawn_commands: List[List[Union[UnitTypeId, int, Point2,
                                                   Point3]]]):
        """ Usage example (will spawn 5 marines in the center of the map for player ID 1):
        await self._client.debug_create_unit([[UnitTypeId.MARINE, 5, self._game_info.map_center, 1]])

        :param unit_spawn_commands: """
        assert isinstance(unit_spawn_commands, list)
        assert unit_spawn_commands
        assert isinstance(unit_spawn_commands[0], list)
        assert len(unit_spawn_commands[0]) == 4
        assert isinstance(unit_spawn_commands[0][0], UnitTypeId)
        assert unit_spawn_commands[0][
            1] > 0  # careful, in realtime=True this function may create more units
        assert isinstance(unit_spawn_commands[0][2], (Point2, Point3))
        assert 1 <= unit_spawn_commands[0][3] <= 2

        await self._execute(debug=sc_pb.RequestDebug(
            debug=(debug_pb.DebugCommand(create_unit=debug_pb.DebugCreateUnit(
                unit_type=unit_type.value,
                owner=owner_id,
                pos=common_pb.Point2D(x=position.x, y=position.y),
                quantity=amount_of_units,
            )) for unit_type, amount_of_units, position, owner_id in
                   unit_spawn_commands)))
コード例 #8
0
ファイル: client.py プロジェクト: dbelliss/python-sc2
 async def query_pathing(self, start, end):
     assert isinstance(start, (Point2, Unit))
     assert isinstance(end, Point2)
     if isinstance(start, Point2):
         result = await self._execute(query=query_pb.RequestQuery(pathing=[
             query_pb.RequestQueryPathing(
                 start_pos=common_pb.Point2D(x=start.x, y=start.y),
                 end_pos=common_pb.Point2D(x=end.x, y=end.y))
         ]))
     else:
         result = await self._execute(query=query_pb.RequestQuery(pathing=[
             query_pb.RequestQueryPathing(unit_tag=start.tag,
                                          end_pos=common_pb.Point2D(
                                              x=end.x, y=end.y))
         ]))
     distance = float(result.query.pathing[0].distance)
     if distance <= 0.0:
         return None
     return distance
コード例 #9
0
 async def query_building_placement(self, ability: AbilityId, positions: List[Union[Unit, Point2, Point3]], ignore_resources: bool=True) -> List[ActionResult]:
     assert isinstance(ability, AbilityData)
     result = await self._execute(query=query_pb.RequestQuery(
         placements=[query_pb.RequestQueryBuildingPlacement(
             ability_id=ability.id.value,
             target_pos=common_pb.Point2D(x=position.x, y=position.y)
         ) for position in positions],
         ignore_resource_requirements=ignore_resources
     ))
     return [ActionResult(p.result) for p in result.query.placements]
コード例 #10
0
async def query_building_placement(ws, ability_id, point):
    if not isinstance(point, common.Point2D):
        point = common.Point2D(x=point[0], y=point[1])
    api_request = api.Request(query=api_query.RequestQuery(placements=[
        api_query.RequestQueryBuildingPlacement(ability_id=ability_id,
                                                target_pos=point)
    ]))
    await ws.send(api_request.SerializeToString())
    result = await ws.recv()
    response = api.Response.FromString(result)
    return response.query.placements[0].result == 1
コード例 #11
0
 async def obs_move_camera(self, position: Union[Unit, Units, Point2,
                                                 Point3]):
     """ Moves observer camera to the target position """
     assert isinstance(position, (Unit, Units, Point2, Point3))
     if isinstance(position, Units):
         position = position.center
     if isinstance(position, Unit):
         position = position.position
     await self._execute(obs_action=sc_pb.RequestObserverAction(actions=[
         sc_pb.ObserverAction(camera_move=sc_pb.ActionObserverCameraMove(
             world_pos=common_pb.Point2D(x=position.x, y=position.y)))
     ]))
コード例 #12
0
 def move(self, x, y):
     """
     create starcraft move action
     :param x: x location to move to
     :param y: y location to move to
     :return: move action
     """
     assert (0 <= x <= 64 and 0 <= y <= 64)
     point = common_pb.Point2D(x=x, y=y)
     return raw_pb.ActionRawUnitCommand(ability_id=16,
                                        unit_tags=[self.id],
                                        queue_command=False,
                                        target_world_space_pos=point)
コード例 #13
0
    async def query_building_placement(
            self,
            ability: AbilityData,
            positions: List[Union[Point2, Point3]],
            ignore_resources: bool = True) -> List[ActionResult]:
        """ This function might be deleted in favor of the function above (_query_building_placement_fast).

        :param ability:
        :param positions:
        :param ignore_resources: """
        assert isinstance(ability, AbilityData)
        result = await self._execute(query=query_pb.RequestQuery(
            placements=(query_pb.RequestQueryBuildingPlacement(
                ability_id=ability.id.value,
                target_pos=common_pb.Point2D(x=position[0], y=position[1]))
                        for position in positions),
            ignore_resource_requirements=ignore_resources,
        ))
        # Unnecessary converting to ActionResult?
        return [ActionResult(p.result) for p in result.query.placements]
コード例 #14
0
    async def _query_building_placement_fast(
            self,
            ability: AbilityData,
            positions: List[Union[Point2, Point3]],
            ignore_resources: bool = True) -> List[ActionResult]:
        """

        :param ability:
        :param positions:
        :param ignore_resources:
        """
        result = await self._execute(query=query_pb.RequestQuery(
            placements=(query_pb.RequestQueryBuildingPlacement(
                ability_id=ability.id.value,
                target_pos=common_pb.Point2D(x=position[0], y=position[1]))
                        for position in positions),
            ignore_resource_requirements=ignore_resources,
        ))
        # Success enum value is 1, see https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/error.proto#L7
        return [p.result == 1 for p in result.query.placements]
コード例 #15
0
    def get_agent_action(self, a_id, action):
        """Construct the action for agent a_id."""

        unit = self.get_unit_by_id(a_id)
        tag = unit.tag
        x = unit.pos.x
        y = unit.pos.y

        if action == 0:
            # no-op (valid only when dead)
            assert unit.health == 0, "No-op only available for dead agents."
            if self.debug:
                logging.debug("Agent {}: Dead".format(a_id))
            return None
        elif action == 1:
            # stop
            cmd = r_pb.ActionRawUnitCommand(ability_id=actions["stop"],
                                            unit_tags=[tag],
                                            queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Stop".format(a_id))

        elif action == 2:
            # move north
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x,
                                                         y=y +
                                                         self._move_amount),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move North".format(a_id))

        elif action == 3:
            # move south
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x,
                                                         y=y -
                                                         self._move_amount),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move South".format(a_id))

        elif action == 4:
            # move east
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x +
                                                         self._move_amount,
                                                         y=y),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move East".format(a_id))

        elif action == 5:
            # move west
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x -
                                                         self._move_amount,
                                                         y=y),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move West".format(a_id))

        elif action == 6:
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["forcefield"],
                target_world_space_pos=sc_common.Point2D(
                    x=x + self.field_offset[0], y=y + self.field_offset[1]),
                unit_tags=[tag],
                queue_command=False)

            if self.debug:
                logging.debug(
                    "Agent {}: Releasing Force Field at Location: {}".format(
                        a_id,
                        (x + self.field_offset[0], y + self.field_offset[1])))

        elif action == 7:
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["autoturrent"],
                target_world_space_pos=sc_common.Point2D(x=x, y=y),
                unit_tags=[tag],
                queue_command=False)

            if self.debug:
                logging.debug(
                    "Agent {}: Building A Auto-Turrent at Location: {}".format(
                        a_id, (x, y)))

        else:
            # attack/heal units that are in range
            target_id = action - self.n_actions_no_attack
            if self.map_content == "MMM" and self.unit_to_name(
                    unit) == 'medivac':
                target_unit = self.agents[target_id]
                action_name = "heal"
            else:
                target_unit = self.enemies[target_id]
                action_name = "attack"

            action_id = actions[action_name]
            target_tag = target_unit.tag

            cmd = r_pb.ActionRawUnitCommand(ability_id=action_id,
                                            target_unit_tag=target_tag,
                                            unit_tags=[tag],
                                            queue_command=False)

            if self.debug:
                logging.debug("Agent {} {}s unit # {}".format(
                    a_id, action_name, target_id))

        sc_action = sc_pb.Action(action_raw=r_pb.ActionRaw(unit_command=cmd))
        return sc_action
コード例 #16
0
    def get_agent_action(self, a_id, action):
        """Construct the action for agent a_id."""
        avail_actions = self.get_avail_agent_actions(a_id)

        # modify
        # assert avail_actions[action] == 1, \
        #         "Agent {} cannot perform action {}".format(a_id, action)
        if avail_actions[action] != 1:
            return None

        unit = self.get_unit_by_id(a_id)
        tag = unit.tag
        x = unit.pos.x
        y = unit.pos.y

        if action == 0:
            # no-op (valid only when dead)
            assert unit.health == 0, "No-op only available for dead agents."
            if self.debug:
                logging.debug("Agent {}: Dead".format(a_id))
            return None
        elif action == 1:
            # stop
            cmd = r_pb.ActionRawUnitCommand(ability_id=actions["stop"],
                                            unit_tags=[tag],
                                            queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Stop".format(a_id))

        elif action == 2:
            # move north
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x,
                                                         y=y +
                                                         self._move_amount),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move North".format(a_id))

        elif action == 3:
            # move south
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x,
                                                         y=y -
                                                         self._move_amount),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move South".format(a_id))

        elif action == 4:
            # move east
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x +
                                                         self._move_amount,
                                                         y=y),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move East".format(a_id))

        elif action == 5:
            # move west
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=actions["move"],
                target_world_space_pos=sc_common.Point2D(x=x -
                                                         self._move_amount,
                                                         y=y),
                unit_tags=[tag],
                queue_command=False)
            if self.debug:
                logging.debug("Agent {}: Move West".format(a_id))
        else:
            # attack/heal units that are in range
            target_id = action - self.n_actions_no_attack
            if self.map_type == "MMM" and unit.unit_type == self.medivac_id:
                target_unit = self.agents[target_id]
                action_name = "heal"
            else:
                target_unit = self.enemies[target_id]
                action_name = "attack"

            action_id = actions[action_name]
            target_tag = target_unit.tag

            cmd = r_pb.ActionRawUnitCommand(ability_id=action_id,
                                            target_unit_tag=target_tag,
                                            unit_tags=[tag],
                                            queue_command=False)

            if self.debug:
                logging.debug("Agent {} {}s unit # {}".format(
                    a_id, action_name, target_id))

        sc_action = sc_pb.Action(action_raw=r_pb.ActionRaw(unit_command=cmd))
        return sc_action
コード例 #17
0
ファイル: starcraft2.py プロジェクト: shariqiqbal2810/pymarl
    def get_agent_action(self, a_id, action):

        unit = self.get_unit_by_id(a_id)
        tag = unit.tag
        x = unit.pos.x
        y = unit.pos.y

        if action == 0:
            # no-op (valid only when dead)
            try:
                assert unit.health == 0, "No-op chosen but the agent's unit is not dead"
            except Exception as e:
                pass
            if self.debug_inputs:
                print("Agent %d: Dead" % a_id)
            return None
        elif action == 1:
            # stop
            cmd = r_pb.ActionRawUnitCommand(ability_id=action_stop_id,
                                            unit_tags=[tag],
                                            queue_command=False)
            if self.debug_inputs:
                print("Agent %d: Stop" % a_id)

        elif action == 2:
            # north
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=action_move_id,
                target_world_space_pos=sc_common.Point2D(x=x,
                                                         y=y +
                                                         self._move_amount),
                unit_tags=[tag],
                queue_command=False)
            if self.debug_inputs:
                print("Agent %d: North" % a_id)

        elif action == 3:
            # south
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=action_move_id,
                target_world_space_pos=sc_common.Point2D(x=x,
                                                         y=y -
                                                         self._move_amount),
                unit_tags=[tag],
                queue_command=False)
            if self.debug_inputs:
                print("Agent %d: South" % a_id)

        elif action == 4:
            # east
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=action_move_id,
                target_world_space_pos=sc_common.Point2D(x=x +
                                                         self._move_amount,
                                                         y=y),
                unit_tags=[tag],
                queue_command=False)
            if self.debug_inputs:
                print("Agent %d: East" % a_id)

        elif action == 5:
            # west
            cmd = r_pb.ActionRawUnitCommand(
                ability_id=action_move_id,
                target_world_space_pos=sc_common.Point2D(x=x -
                                                         self._move_amount,
                                                         y=y),
                unit_tags=[tag],
                queue_command=False)
            if self.debug_inputs:
                print("Agent %d: West" % a_id)
        else:
            # attack/heal units that are in range
            target_id = action - self.n_actions_no_attack
            if self.map_type == 'MMM' and unit.unit_type == self.medivac_id:
                target_unit = self.agents[target_id]
                action_id = action_heal_id
            else:
                target_unit = self.enemies[target_id]
                action_id = action_attack_id
            target_tag = target_unit.tag

            cmd = r_pb.ActionRawUnitCommand(ability_id=action_id,
                                            target_unit_tag=target_tag,
                                            unit_tags=[tag],
                                            queue_command=False)

            if self.debug_inputs:
                print("Agent %d attacks enemy # %d" % (a_id, target_id))

        sc_action = sc_pb.Action(action_raw=r_pb.ActionRaw(unit_command=cmd))
        return sc_action
コード例 #18
0
def combine_actions(action_iter):
    """
    Example input:
    [
        # Each entry in the list is a unit command, with an ability, unit, target, and queue=boolean
        UnitCommand(AbilityId.TRAINQUEEN_QUEEN, Unit(name='Hive', tag=4353687554), None, False),
        UnitCommand(AbilityId.TRAINQUEEN_QUEEN, Unit(name='Lair', tag=4359979012), None, False),
        UnitCommand(AbilityId.TRAINQUEEN_QUEEN, Unit(name='Hatchery', tag=4359454723), None, False),
    ]
    """
    for key, items in groupby(action_iter, key=lambda a: a.combining_tuple):
        ability: AbilityId
        target: Union[None, Point2, Unit]
        queue: bool
        # See constants.py for combineable abilities
        combineable: bool
        ability, target, queue, combineable = key

        if combineable:
            # Combine actions with no target, e.g. train and research commands
            if target is None:
                cmd = raw_pb.ActionRawUnitCommand(
                    ability_id=ability.value,
                    unit_tags={u.unit.tag
                               for u in items},
                    queue_command=queue)
            # Combine actions with target point
            elif isinstance(target, Point2):
                cmd = raw_pb.ActionRawUnitCommand(
                    ability_id=ability.value,
                    unit_tags={u.unit.tag
                               for u in items},
                    queue_command=queue,
                    target_world_space_pos=common_pb.Point2D(x=target.x,
                                                             y=target.y),
                )
            # Combine actions with target unit
            elif isinstance(target, Unit):
                cmd = raw_pb.ActionRawUnitCommand(
                    ability_id=ability.value,
                    unit_tags={u.unit.tag
                               for u in items},
                    queue_command=queue,
                    target_unit_tag=target.tag,
                )
            else:
                raise RuntimeError(
                    f"Must target a unit, point or None, found '{target !r}'")

            yield raw_pb.ActionRaw(unit_command=cmd)

        else:
            """
            Return one action for each unit; this is required for certain commands that would otherwise be grouped, and only executed once
            Examples:
            Select 3 hatcheries, build a queen with each hatch - the grouping function would group these unit tags and only issue one train command once to all 3 unit tags - resulting in one total train command
            I imagine the same thing would happen to certain other abilities: Battlecruiser yamato on same target, queen transfuse on same time, ghost snipe on same target, all build commands with the same unit type and also all morphs (zergling to banelings)
            However, other abilities can and should be grouped, see constants.py 'COMBINEABLE_ABILITIES'
            """
            u: UnitCommand
            if target is None:
                for u in items:
                    cmd = raw_pb.ActionRawUnitCommand(ability_id=ability.value,
                                                      unit_tags={u.unit.tag},
                                                      queue_command=queue)
                    yield raw_pb.ActionRaw(unit_command=cmd)
            elif isinstance(target, Point2):
                for u in items:
                    cmd = raw_pb.ActionRawUnitCommand(
                        ability_id=ability.value,
                        unit_tags={u.unit.tag},
                        queue_command=queue,
                        target_world_space_pos=common_pb.Point2D(x=target.x,
                                                                 y=target.y),
                    )
                    yield raw_pb.ActionRaw(unit_command=cmd)

            elif isinstance(target, Unit):
                for u in items:
                    cmd = raw_pb.ActionRawUnitCommand(
                        ability_id=ability.value,
                        unit_tags={u.unit.tag},
                        queue_command=queue,
                        target_unit_tag=target.tag,
                    )
                    yield raw_pb.ActionRaw(unit_command=cmd)
            else:
                raise RuntimeError(
                    f"Must target a unit, point or None, found '{target !r}'")
コード例 #19
0
ファイル: position.py プロジェクト: AlexanderKomi/python-sc2
 def as_Point2D(self) -> common_pb.Point2D:
     return common_pb.Point2D(x=self.x, y=self.y)
コード例 #20
0
ファイル: debug_test.py プロジェクト: zeuseyera/pysc2-kr
    def test_multi_player(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.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=sc_pb.InterfaceOptions(raw=True))

            controller.create_game(create)
            controller.join_game(join)

            info = controller.game_info()
            map_size = info.start_raw.map_size

            controller.step(2)

            obs = controller.observe()

            def get_marines(obs):
                return {
                    u.tag: u
                    for u in obs.observation.raw_data.units
                    if u.unit_type == units.Terran.Marine
                }

            self.assertEmpty(get_marines(obs))

            controller.debug(
                sc_debug.DebugCommand(create_unit=sc_debug.DebugCreateUnit(
                    unit_type=units.Terran.Marine,
                    owner=1,
                    pos=sc_common.Point2D(x=map_size.x // 2, y=map_size.y //
                                          2),
                    quantity=5)))

            controller.step(2)

            obs = controller.observe()

            marines = get_marines(obs)
            self.assertEqual(5, len(marines))

            tags = sorted(marines.keys())

            controller.debug([
                sc_debug.DebugCommand(kill_unit=sc_debug.DebugKillUnit(
                    tag=[tags[0]])),
                sc_debug.DebugCommand(unit_value=sc_debug.DebugSetUnitValue(
                    unit_value=sc_debug.DebugSetUnitValue.Life,
                    value=5,
                    unit_tag=tags[1])),
            ])

            controller.step(2)

            obs = controller.observe()

            marines = get_marines(obs)
            self.assertEqual(4, len(marines))
            self.assertNotIn(tags[0], marines)
            self.assertEqual(marines[tags[1]].health, 5)