Пример #1
0
 def cure_target(u, target):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = \
       ABILITY_ID.EFFECT_TRANSFUSION.value
     action.action_raw.unit_command.target_unit_tag = target.tag
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action
Пример #2
0
def parse_replay(replay_player_path, sampled_frame_path, reward):
    if os.path.isfile(os.path.join(FLAGS.parsed_replay_path, 'GlobalFeatures', replay_player_path)):
        return

    # Global Info
    with open(os.path.join(FLAGS.parsed_replay_path, 'GlobalInfos', replay_player_path)) as f:
        global_info = json.load(f)
    units_info = static_data.StaticData(Parse(global_info['data_raw'], sc_pb.ResponseData())).units
    feat = features.features_from_game_info(Parse(global_info['game_info'], sc_pb.ResponseGameInfo()))

    # Sampled Frames
    with open(sampled_frame_path) as f:
        sampled_frames = json.load(f)
    sampled_actions_idx = [frame // FLAGS.step_mul - 1 for frame in sampled_frames] # Create index to retrieve actions corresponding to sampled frames

    # Actions
    with open(os.path.join(FLAGS.parsed_replay_path, 'Actions', replay_player_path)) as f:
        actions = json.load(f)
    sampled_actions = [None if len(actions[idx]) == 0 else Parse(actions[idx][0], sc_pb.Action()) 
                for idx in sampled_actions_idx] # Get first action executed after each sampled frame

    # Observations
    observations =  [obs for obs in stream.parse(os.path.join(FLAGS.parsed_replay_path,
                            'SampledObservations', replay_player_path), sc_pb.ResponseObservation)]

    assert len(sampled_frames) == len(sampled_actions_idx) == len(sampled_actions) == len(observations)

    states = process_replay(sampled_frames, sampled_actions, observations, feat, units_info, reward)

    with open(os.path.join(FLAGS.parsed_replay_path, 'GlobalFeatures', replay_player_path), 'w') as f:
        json.dump(states, f)
Пример #3
0
    async def execute(self) -> bool:
        templars = self.cache.own(self.allowed_types).ready
        for ht in templars:  # type: Unit
            if ht.is_idle and ht.tag in self.already_merging_tags:
                self.knowledge.roles.clear_task(ht)
                self.already_merging_tags.remove(ht.tag)

        templars = templars.tags_not_in(self.already_merging_tags)

        if templars.amount > 1:
            unit: Unit = templars[0]
            self.already_merging_tags.append(unit.tag)

            target: Unit = templars.tags_not_in(self.already_merging_tags).closest_to(unit)

            # Reserve upcoming archon so that they aren't stolen by other states.
            self.knowledge.roles.set_task(UnitTask.Reserved, unit)
            self.knowledge.roles.set_task(UnitTask.Reserved, target)
            self.knowledge.print(f"[ARCHON] merging {str(unit.type_id)} and {str(unit.type_id)}")

            from s2clientprotocol import raw_pb2 as raw_pb
            from s2clientprotocol import sc2api_pb2 as sc_pb
            command = raw_pb.ActionRawUnitCommand(
                ability_id=AbilityId.MORPH_ARCHON.value,
                unit_tags=[unit.tag, target.tag],
                queue_command=False
            )
            action = raw_pb.ActionRaw(unit_command=command)
            await self.ai._client._execute(action=sc_pb.RequestAction(
                actions=[sc_pb.Action(action_raw=action)]
            ))

        return True
Пример #4
0
 def act(dc):
     tech = self._tech_tree.getUnitData(type_id)
     pos = self._placer.get_building_position(type_id, dc)
     if pos == None: return []
     extractor_tags = set(
         u.tag
         for u in dc.units_of_type(UNIT_TYPE.ZERG_EXTRACTOR.value))
     builders = dc.units_of_types(tech.whatBuilds)
     prefered_builders = [
         u for u in builders
         if (u.unit_type != UNIT_TYPE.ZERG_DRONE.value
             or len(u.orders) == 0 or
             (u.orders[0].ability_id == ABILITY.HARVEST_GATHER_DRONE.
              value and u.orders[0].target_tag not in extractor_tags))
     ]
     if len(prefered_builders) > 0:
         builder = utils.closest_unit(pos, prefered_builders)
     else:
         if len(builders) == 0: return []
         builder = utils.closest_unit(pos, builders)
     action = sc_pb.Action()
     action.action_raw.unit_command.unit_tags.append(builder.tag)
     action.action_raw.unit_command.ability_id = tech.buildAbility
     if isinstance(pos, Unit):
         action.action_raw.unit_command.target_unit_tag = pos.tag
     else:
         action.action_raw.unit_command.target_world_space_pos.x = pos[
             0]
         action.action_raw.unit_command.target_world_space_pos.y = pos[
             1]
     return [action]
Пример #5
0
def act_rally_worker(target_tag, base_tag):
    action = sc_pb.Action()
    action.action_raw.unit_command.ability_id = \
      ABILITY_ID.RALLY_HATCHERY_WORKERS.value
    action.action_raw.unit_command.target_unit_tag = target_tag
    action.action_raw.unit_command.unit_tags.append(base_tag)
    return action
Пример #6
0
def move(u, pos):
    action = sc_pb.Action()
    action.action_raw.unit_command.ability_id = 16
    action.action_raw.unit_command.target_world_space_pos.x = pos[0]
    action.action_raw.unit_command.target_world_space_pos.y = pos[1]
    action.action_raw.unit_command.unit_tags.append(u)
    return action
Пример #7
0
 def chat(self, message, channel=sc_pb.ActionChat.Broadcast):
   """Send chat message as a broadcast."""
   if message:
     action_chat = sc_pb.ActionChat(
         channel=channel, message=message)
     action = sc_pb.Action(action_chat=action_chat)
     return self.act(action)
Пример #8
0
 def _normal_unit_attack(self, unit, target_pos):
     action = sc_pb.Action()
     action.action_raw.unit_command.unit_tags.append(unit.tag)
     action.action_raw.unit_command.ability_id = ABILITY.ATTACK_ATTACK.value
     action.action_raw.unit_command.target_world_space_pos.x = target_pos[0]
     action.action_raw.unit_command.target_world_space_pos.y = target_pos[1]
     return [action]
Пример #9
0
 def _attack_target(self, u, pos):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = ABILITY_ID.ATTACK_ATTACK.value
     action.action_raw.unit_command.target_world_space_pos.x = pos[0]
     action.action_raw.unit_command.target_world_space_pos.y = pos[1]
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action
Пример #10
0
def sample_action_from_player(action_path):
    feat = features.Features(screen_size_px=(1, 1), minimap_size_px=(1, 1))
    with open(action_path) as f:
        actions = json.load(f)

    frame_id = 0
    result_frames = []
    for action_strs in actions:
        action_name = None
        for action_str in action_strs:
            action = Parse(action_str, sc_pb.Action())
            try:
                func_id = feat.reverse_action(action).function
                func_name = FUNCTIONS[func_id].name
                if func_name.split('_')[0] in {
                        'Build', 'Train', 'Research', 'Morph', 'Cancel',
                        'Halt', 'Stop'
                }:
                    action_name = func_name
                    break
            except:
                pass
        if frame_id > 0 and (action_name is not None
                             or frame_id % FLAGS.skip == 0):
            result_frames.append(frame_id - FLAGS.step_mul)

        frame_id += FLAGS.step_mul

    return result_frames
Пример #11
0
 def _move_to_home(self):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = tp.ABILITY_ID.SMART.value
     action.action_raw.unit_command.target_world_space_pos.x = self._home[0]
     action.action_raw.unit_command.target_world_space_pos.y = self._home[1]
     action.action_raw.unit_command.unit_tags.append(self._scout.unit().tag)
     return action
Пример #12
0
 def _assign_workers_gather_gas(self, dc):
     idle_extractors = [
         u for u in dc.units_of_type(UNIT_TYPE.ZERG_EXTRACTOR.value)
         if u.int_attr.ideal_harvesters - u.int_attr.assigned_harvesters > 0
     ]
     if len(idle_extractors) == 0: return []
     extractor = random.choice(idle_extractors)
     num_workers_need = extractor.int_attr.ideal_harvesters - \
         extractor.int_attr.assigned_harvesters
     extractor_tags = set(
         u.tag for u in dc.units_of_type(UNIT_TYPE.ZERG_EXTRACTOR.value))
     workers = [
         u for u in dc.units_of_type(UNIT_TYPE.ZERG_DRONE.value)
         if (len(u.orders) == 0 or (
             u.orders[0].ability_id == ABILITY.HARVEST_GATHER_DRONE.value
             and u.orders[0].target_tag not in extractor_tags))
     ]
     if len(workers) == 0: return []
     assigned_workers = utils.closest_units(extractor, workers,
                                            num_workers_need)
     action = sc_pb.Action()
     action.action_raw.unit_command.unit_tags.extend(
         [u.tag for u in assigned_workers])
     action.action_raw.unit_command.ability_id = \
         ABILITY.HARVEST_GATHER_DRONE.value
     action.action_raw.unit_command.target_unit_tag = extractor.tag
     return [action]
    def transform_raw(self, func_call):
        """
    Added by @danielfirebanks

    Uses func_call to setup Action(), calls function in actions_modified to setup ActionRaw()
    Taken from features.py

    :param func_call:
    :return: sc_pb.Action()
    """

        func_id = func_call.function
        try:
            func = actions.FUNCTIONS[func_id]
        except KeyError:
            raise ValueError("Invalid function id: %s." % func_id)

        # Create an action
        sc2_action = sc_pb.Action()

        # Convert them to python types.
        kwargs = {
            type_.name: type_.fn(a)
            for type_, a in zip(func.args, func_call.arguments)
        }

        kwargs["action"] = sc2_action

        if func.ability_id:
            kwargs["ability_id"] = func.ability_id

        actions.FUNCTIONS[func_id].function_type(**kwargs)

        return sc2_action
Пример #14
0
def parse_replay(replay_player_path, sampled_action_path, reward):
    if os.path.isfile(os.path.join(FLAGS.parsed_replay_path, 'GlobalFeatures', replay_player_path)):
        return

    # Global Info
    with open(os.path.join(FLAGS.parsed_replay_path, 'GlobalInfos', replay_player_path)) as f:
        global_info = json.load(f)
    units_info = static_data.StaticData(Parse(global_info['data_raw'], sc_pb.ResponseData())).units
    feat = features.Features(Parse(global_info['game_info'], sc_pb.ResponseGameInfo()))

    # Sampled Actions
    with open(sampled_action_path) as f:
        sampled_action = json.load(f)
    sampled_action_id = [id // FLAGS.step_mul + 1 for id in sampled_action]

    # Actions
    with open(os.path.join(FLAGS.parsed_replay_path, 'Actions', replay_player_path)) as f:
        actions = json.load(f)
    actions = [None if len(actions[idx]) == 0 else Parse(actions[idx][0], sc_pb.Action())
                for idx in sampled_action_id]

    # Observations
    observations =  [obs for obs in stream.parse(os.path.join(FLAGS.parsed_replay_path,
                            'SampledObservations', replay_player_path), sc_pb.ResponseObservation)]

    assert len(sampled_action) == len(sampled_action_id) == len(actions) == len(observations)

    states = process_replay(sampled_action, actions, observations, feat, units_info, reward)

    with open(os.path.join(FLAGS.parsed_replay_path, 'GlobalFeatures', replay_player_path), 'w') as f:
        json.dump(states, f)
Пример #15
0
 async def chat_send(self, message: str, team_only: bool):
     """ Writes a message to the chat """
     ch = ChatChannel.Team if team_only else ChatChannel.Broadcast
     await self._execute(action=sc_pb.RequestAction(actions=[
         sc_pb.Action(action_chat=sc_pb.ActionChat(channel=ch.value,
                                                   message=message))
     ]))
Пример #16
0
def act_move_to_pos(unit_tag, target_pos):
    action = sc_pb.Action()
    action.action_raw.unit_command.ability_id = ABILITY_ID.MOVE.value
    action.action_raw.unit_command.target_world_space_pos.x = target_pos[0]
    action.action_raw.unit_command.target_world_space_pos.y = target_pos[1]
    action.action_raw.unit_command.unit_tags.append(unit_tag)
    return action
Пример #17
0
def act_build_by_pos(builder_tag, target_pos, ability_id):
    action = sc_pb.Action()
    action.action_raw.unit_command.ability_id = ability_id
    action.action_raw.unit_command.target_world_space_pos.x = target_pos[0]
    action.action_raw.unit_command.target_world_space_pos.y = target_pos[1]
    action.action_raw.unit_command.unit_tags.append(builder_tag)
    return action
Пример #18
0
    def select_action(self, select_rect):
        """Return a `sc_pb.Action` with the selection filled."""
        action = sc_pb.Action()

        if select_rect.tl == select_rect.br:  # select a point
            select = action.action_feature_layer.unit_selection_point
            self._world_to_fl_screen.fwd_pt(select_rect.tl).assign_to(
                select.selection_screen_coord)
            # print("world coordination:" ,select_rect.tl)
            # print("feature screen coordination:" ,select.selection_screen_coord)
            # print("feature screen coordination:" ,self._world_to_fl_screen.fwd_pt(select_rect.tl))
            select.type = sc_spatial.ActionSpatialUnitSelectionPoint.Select
        else:
            select = action.action_feature_layer.unit_selection_rect
            rect = select.selection_screen_coord.add()
            self._world_to_fl_screen.fwd_pt(select_rect.bl).assign_to(rect.p0)
            self._world_to_fl_screen.fwd_pt(select_rect.tr).assign_to(rect.p1)
            select.selection_add = False

        # Clear the queued action if something will be selected. An alternative
        # implementation may check whether the selection changed next frame.
        units = self._units_in_area(select_rect)
        if units:
            self.clear_queued_action()

        return action
Пример #19
0
 async def chat_send(self, message, team_only):
     ch = ChatChannel.Team if team_only else ChatChannel.Broadcast
     r = await self._execute(action=sc_pb.RequestAction(
         actions=[sc_pb.Action(action_chat=sc_pb.ActionChat(
             channel=ch.value,
             message=message
         ))]
     ))
Пример #20
0
 def fungal_growth_attack_pos(u, pos):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = \
       ABILITY_ID.EFFECT_FUNGALGROWTH.value
     action.action_raw.unit_command.target_world_space_pos.x = pos['x']
     action.action_raw.unit_command.target_world_space_pos.y = pos['y']
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action
Пример #21
0
 def testReversingUnknownAction(self):
     feats = features.Features(screen_size_px=(84, 80),
                               minimap_size_px=(64, 67),
                               hide_specific_actions=False)
     sc2_action = sc_pb.Action()
     sc2_action.action_feature_layer.unit_command.ability_id = 6  # Cheer
     func_call = feats.reverse_action(sc2_action)
     self.assertEqual(func_call.function, 0)  # No-op
Пример #22
0
 async def move_camera_spatial(self, position: Union[Point2, Point3]):
     """ Moves camera to the target position using the spatial aciton interface """
     from s2clientprotocol import spatial_pb2 as spatial_pb
     assert isinstance(position, (Point2, Point3))
     action = sc_pb.Action(action_render=spatial_pb.ActionSpatial(
         camera_move=spatial_pb.ActionSpatialCameraMove(
             center_minimap=common_pb.PointI(x=position.x, y=position.y))))
     await self._execute(action=sc_pb.RequestAction(actions=[action]))
Пример #23
0
    def attack_weakest_enemy(self, u):
        action = sc_pb.Action()
        action.action_raw.unit_command.ability_id = ATTACK
        target = self.find_weakest_enemy(enemies=self.roaches)

        action.action_raw.unit_command.target_unit_tag = target.tag
        action.action_raw.unit_command.unit_tags.append(u.tag)
        return action
Пример #24
0
 def blinding_cloud_attack_pos(u, pos):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = \
       ABILITY_ID.EFFECT_BLINDINGCLOUD.value
     action.action_raw.unit_command.target_world_space_pos.x = pos['x']
     action.action_raw.unit_command.target_world_space_pos.y = pos['y']
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action
Пример #25
0
 def corrosive_attack_pos(u, pos):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = \
       ABILITY_ID.EFFECT_CORROSIVEBILE.value
     action.action_raw.unit_command.target_world_space_pos.x = pos['x']
     action.action_raw.unit_command.target_world_space_pos.y = pos['y']
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action
Пример #26
0
 def _move_to_target(self, pos):
     scout = self.env.unwrapped.scout()
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = tp.ABILITY_ID.SMART.value
     action.action_raw.unit_command.target_world_space_pos.x = pos[0]
     action.action_raw.unit_command.target_world_space_pos.y = pos[1]
     action.action_raw.unit_command.unit_tags.append(scout.tag)
     return action
Пример #27
0
 def act(dc):
     tech = self._tech_tree.getUpgradeData(upgrade_id)
     if len(dc.idle_units_of_types(tech.whatBuilds)) == 0: return []
     upgrader = random.choice(dc.idle_units_of_types(tech.whatBuilds))
     action = sc_pb.Action()
     action.action_raw.unit_command.unit_tags.append(upgrader.tag)
     action.action_raw.unit_command.ability_id = tech.buildAbility
     return [action]
Пример #28
0
 def produce_unit(self, larvas, unit_type):
     if len(larvas) == 0:
         return []
     larva = random.choice(larvas)
     unit_data = TT.getUnitData(unit_type)
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = unit_data.buildAbility
     action.action_raw.unit_command.unit_tags.append(larva.tag)
     return [action]
Пример #29
0
 def attack_closest_enemy(self, u, enemies):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = ABILITY_ID.ATTACK_ATTACK.value
     if len(enemies) == 0:
         return self.hold_fire(u)
     target = self.find_closest_enemy(u, enemies=enemies)
     action.action_raw.unit_command.target_unit_tag = target.tag
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action
Пример #30
0
 def move_dir(u, direction):
     action = sc_pb.Action()
     action.action_raw.unit_command.ability_id = ABILITY_ID.MOVE.value
     action.action_raw.unit_command.target_world_space_pos.x = \
       u.float_attr.pos_x + direction[0] * 0.5
     action.action_raw.unit_command.target_world_space_pos.y = \
       u.float_attr.pos_y + direction[1] * 0.5
     action.action_raw.unit_command.unit_tags.append(u.tag)
     return action