Best Python code snippet using localstack_python
common.py
Source:common.py  
1import numpy as np2from pysc2.lib import actions as sc2_actions3from pysc2.lib import features4from pysc2.lib import actions5_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index6_UNIT_TYPE = features.SCREEN_FEATURES.unit_type.index7_SELECTED = features.SCREEN_FEATURES.selected.index8_PLAYER_FRIENDLY = 19_PLAYER_NEUTRAL = 3  # beacon/minerals10_PLAYER_HOSTILE = 411_NO_OP = actions.FUNCTIONS.no_op.id12_SELECT_UNIT_ID = 113_CONTROL_GROUP_SET = 114_CONTROL_GROUP_RECALL = 015_SELECT_CONTROL_GROUP = actions.FUNCTIONS.select_control_group.id16_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id17_ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id18_SELECT_ARMY = actions.FUNCTIONS.select_army.id19_SELECT_UNIT = actions.FUNCTIONS.select_unit.id20_SELECT_POINT = actions.FUNCTIONS.select_point.id21_NOT_QUEUED = 022_SELECT_ALL = 023def init(env, obs):24    player_relative = obs[0].observation["feature_screen"][_PLAYER_RELATIVE]25    # print("init")26    army_count = env._obs[0].observation.player_common.army_count27    player_y, player_x = (player_relative == _PLAYER_FRIENDLY).nonzero()28    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])29    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])30    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])31    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])32    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])33    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])34    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])35    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])36    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])37    # obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])38    # if(army_count==0):39    #   return obs40    # try:41    #   obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])42    #   obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])43    #   obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])44    #   obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])45    #   obs = env.step(actions=[sc2_actions.FunctionCall(_NO_OP, [])])46    #47    #   obs = env.step(actions=[sc2_actions.FunctionCall(_SELECT_ARMY, [[_SELECT_ALL]])])48    # except Exception as e:49    #   print(e)50    # for i in range(len(player_x)):51    #   if i % 4 != 0:52    #     continue53    #54    #   xy = [player_x[i], player_y[i]]55    #   obs = env.step(actions=[sc2_actions.FunctionCall(_SELECT_POINT, [[0], xy])])56    group_id = 057    group_list = []58    unit_xy_list = []59    last_xy = [0, 0]60    xy_per_marine = {}61    for i in range(len(player_x)):62        if group_id > 9:63            break64        xy = [player_x[i], player_y[i]]65        unit_xy_list.append(xy)66        if len(unit_xy_list) >= 1:67            for idx, xy in enumerate(unit_xy_list):68                if idx == 0:69                    obs = env.step(actions=[70                        sc2_actions.FunctionCall(_SELECT_POINT, [[0], xy])71                    ])72                else:73                    obs = env.step(actions=[74                        sc2_actions.FunctionCall(_SELECT_POINT, [[1], xy])75                    ])76                last_xy = xy77            obs = env.step(actions=[78                sc2_actions.FunctionCall(_SELECT_CONTROL_GROUP,79                                         [[_CONTROL_GROUP_SET], [group_id]])80            ])81            unit_xy_list = []82            xy_per_marine[str(group_id)] = last_xy83            group_list.append(group_id)84            group_id += 185    if len(unit_xy_list) >= 1:86        for idx, xy in enumerate(unit_xy_list):87            if idx == 0:88                obs = env.step(actions=[89                    sc2_actions.FunctionCall(_SELECT_POINT, [[0], xy])90                ])91            else:92                obs = env.step(actions=[93                    sc2_actions.FunctionCall(_SELECT_POINT, [[1], xy])94                ])95            last_xy = xy96        obs = env.step(actions=[97            sc2_actions.FunctionCall(_SELECT_CONTROL_GROUP,98                                     [[_CONTROL_GROUP_SET], [group_id]])99        ])100        xy_per_marine[str(group_id)] = last_xy101        group_list.append(group_id)102        group_id += 1103    return obs, xy_per_marine104def update_group_list2(control_group):105    group_count = 0106    group_list = []107    for control_group_id, data in enumerate(control_group):108        unit_id = data[0]109        count = data[1]110        if unit_id != 0:111            group_count += 1112            group_list.append(control_group_id)113    return group_list114def check_group_list2(extra):115    army_count = 0116    # (64, 64, 3)117    for control_group_id in range(10):118        unit_id = extra[control_group_id, 1]119        count = extra[control_group_id, 2]120        if unit_id != 0:121            army_count += count122    if army_count != extra[0, 0]:123        return True124    return False125def update_group_list(obs):126    control_groups = obs[0].observation["control_groups"]127    group_count = 0128    group_list = []129    for id, group in enumerate(control_groups):130        if group[0] != 0:131            group_count += 1132            group_list.append(id)133    return group_list134def check_group_list(env, obs):135    error = False136    control_groups = obs[0].observation["control_groups"]137    army_count = 0138    for id, group in enumerate(control_groups):139        if group[0] == 48:140            army_count += group[1]141            if group[1] != 1:142                # print("group error group_id : %s count : %s" % (id, group[1]))143                error = True144                return error145    if army_count != env._obs[0].observation.player_common.army_count:146        error = True147        # print("army_count %s !=  %s env._obs.observation.player_common.army_count "148        #      % (army_count, env._obs.observation.player_common.army_count))149    return error150UP, DOWN, LEFT, RIGHT = 'up', 'down', 'left', 'right'151def shift(direction, number, matrix):152    """ shift given 2D matrix in-place the given number of rows or columns153      in the specified (UP, DOWN, LEFT, RIGHT) direction and return it154    """155    if direction in (UP):156        matrix = np.roll(matrix, -number, axis=0)157        matrix[number:, :] = -2158        return matrix159    elif direction in (DOWN):160        matrix = np.roll(matrix, number, axis=0)161        matrix[:number, :] = -2162        return matrix163    elif direction in (LEFT):164        matrix = np.roll(matrix, -number, axis=1)165        matrix[:, number:] = -2166        return matrix167    elif direction in (RIGHT):168        matrix = np.roll(matrix, number, axis=1)169        matrix[:, :number] = -2170        return matrix171    else:172        return matrix173def select_marine(env, obs):174    player_relative = obs[0].observation["feature_screen"][_PLAYER_RELATIVE]175    screen = player_relative176    group_list = update_group_list(obs)177    if check_group_list(env, obs):178        obs, xy_per_marine = init(env, obs)179        group_list = update_group_list(obs)180    # if(len(group_list) == 0):181    #   obs = init(env, player_relative, obs)182    #   group_list = update_group_list(obs)183    player_relative = obs[0].observation["feature_screen"][_PLAYER_RELATIVE]184    friendly_y, friendly_x = (player_relative == _PLAYER_FRIENDLY).nonzero()185    enemy_y, enemy_x = (player_relative == _PLAYER_HOSTILE).nonzero()186    player = []187    danger_closest, danger_min_dist = None, None188    for e in zip(enemy_x, enemy_y):189        for p in zip(friendly_x, friendly_y):190            dist = np.linalg.norm(np.array(p) - np.array(e))191            if not danger_min_dist or dist < danger_min_dist:192                danger_closest, danger_min_dist = p, dist193    marine_closest, marine_min_dist = None, None194    for e in zip(friendly_x, friendly_y):195        for p in zip(friendly_x, friendly_y):196            dist = np.linalg.norm(np.array(p) - np.array(e))197            if not marine_min_dist or dist < marine_min_dist:198                if dist >= 2:199                    marine_closest, marine_min_dist = p, dist200    if danger_min_dist is not None and danger_min_dist <= 5:201        obs = env.step(actions=[202            sc2_actions.FunctionCall(_SELECT_POINT, [[0], danger_closest])203        ])204        selected = obs[0].observation["feature_screen"][_SELECTED]205        player_y, player_x = (selected == _PLAYER_FRIENDLY).nonzero()206        if len(player_y) > 0:207            player = [int(player_x.mean()), int(player_y.mean())]208    elif marine_closest is not None and marine_min_dist <= 3:209        obs = env.step(actions=[210            sc2_actions.FunctionCall(_SELECT_POINT, [[0], marine_closest])211        ])212        selected = obs[0].observation["feature_screen"][_SELECTED]213        player_y, player_x = (selected == _PLAYER_FRIENDLY).nonzero()214        if len(player_y) > 0:215            player = [int(player_x.mean()), int(player_y.mean())]216    else:217        # If there is no marine in danger, select random218        while len(group_list) > 0:219            # units = env._obs.observation.raw_data.units220            # marine_list = []          # for unit in units:221            #   if(unit.alliance == 1):222            #     marine_list.append(unit)223            group_id = np.random.choice(group_list)224            # xy = [int(unit.pos.y - 10), int(unit.pos.x+8)]225            # print("check xy : %s - %s" % (xy, player_relative[xy[0],xy[1]]))226            obs = env.step(actions=[227                sc2_actions.FunctionCall(_SELECT_CONTROL_GROUP, [[228                    _CONTROL_GROUP_RECALL229                ], [int(group_id)]])230            ])231            selected = obs[0].observation["feature_screen"][_SELECTED]232            player_y, player_x = (selected == _PLAYER_FRIENDLY).nonzero()233            if len(player_y) > 0:234                player = [int(player_x.mean()), int(player_y.mean())]235                break236            else:237                group_list.remove(group_id)238    if len(player) == 2:239        if player[0] > 32:240            screen = shift(LEFT, player[0] - 32, screen)241        elif player[0] < 32:242            screen = shift(RIGHT, 32 - player[0], screen)243        if player[1] > 32:244            screen = shift(UP, player[1] - 32, screen)245        elif player[1] < 32:246            screen = shift(DOWN, 32 - player[1], screen)247    return obs, screen, player248def marine_action(env, obs, player, action):249    player_relative = obs[0].observation["feature_screen"][_PLAYER_RELATIVE]250    enemy_y, enemy_x = (player_relative == _PLAYER_HOSTILE).nonzero()251    closest, min_dist = None, None252    if len(player) == 2:253        for p in zip(enemy_x, enemy_y):254            dist = np.linalg.norm(np.array(player) - np.array(p))255            if not min_dist or dist < min_dist:256                closest, min_dist = p, dist257    player_relative = obs[0].observation["feature_screen"][_PLAYER_RELATIVE]258    friendly_y, friendly_x = (player_relative == _PLAYER_FRIENDLY).nonzero()259    closest_friend, min_dist_friend = None, None260    if len(player) == 2:261        for p in zip(friendly_x, friendly_y):262            dist = np.linalg.norm(np.array(player) - np.array(p))263            if not min_dist_friend or dist < min_dist_friend:264                closest_friend, min_dist_friend = p, dist265    if closest is None:266        new_action = [sc2_actions.FunctionCall(_NO_OP, [])]267    elif action == 0 and closest_friend is not None and min_dist_friend < 3:268        # Friendly marine is too close => Sparse!269        mean_friend = [int(friendly_x.mean()), int(friendly_x.mean())]270        diff = np.array(player) - np.array(closest_friend)271        norm = np.linalg.norm(diff)272        if norm != 0:273            diff = diff / norm274        coord = np.array(player) + diff * 4275        if coord[0] < 0:276            coord[0] = 0277        elif coord[0] > 63:278            coord[0] = 63279        if coord[1] < 0:280            coord[1] = 0281        elif coord[1] > 63:282            coord[1] = 63283        new_action = [284            sc2_actions.FunctionCall(_MOVE_SCREEN, [[_NOT_QUEUED], coord])285        ]286    elif action <= 1:  # Attack287        # nearest enemy288        coord = closest289        new_action = [290            sc2_actions.FunctionCall(_ATTACK_SCREEN, [[_NOT_QUEUED], coord])291        ]292        # print("action : %s Attack Coord : %s" % (action, coord))293    elif action == 2:  # Oppsite direcion from enemy294        # nearest enemy opposite295        diff = np.array(player) - np.array(closest)296        norm = np.linalg.norm(diff)297        if norm != 0:298            diff = diff / norm299        coord = np.array(player) + diff * 7300        if coord[0] < 0:301            coord[0] = 0302        elif coord[0] > 63:303            coord[0] = 63304        if coord[1] < 0:305            coord[1] = 0306        elif coord[1] > 63:307            coord[1] = 63308        new_action = [309            sc2_actions.FunctionCall(_MOVE_SCREEN, [[_NOT_QUEUED], coord])310        ]311    elif action == 4:  # UP312        coord = [player[0], player[1] - 3]313        new_action = [314            sc2_actions.FunctionCall(_MOVE_SCREEN, [[_NOT_QUEUED], coord])315        ]316    elif action == 5:  # DOWN317        coord = [player[0], player[1] + 3]318        new_action = [319            sc2_actions.FunctionCall(_MOVE_SCREEN, [[_NOT_QUEUED], coord])320        ]321    elif action == 6:  # LEFT322        coord = [player[0] - 3, player[1]]323        new_action = [324            sc2_actions.FunctionCall(_MOVE_SCREEN, [[_NOT_QUEUED], coord])325        ]326    elif action == 7:  # RIGHT327        coord = [player[0] + 3, player[1]]328        new_action = [329            sc2_actions.FunctionCall(_MOVE_SCREEN, [[_NOT_QUEUED], coord])330        ]331        # print("action : %s Back Coord : %s" % (action, coord))...fixed.py
Source:fixed.py  
...39        return self.value40    @cached_property41    def variance(self):42        return np.zeros_like(self.mean)43    def _no_op(self, *other, **kwargs):44        """45        'no-op' operation46        In many operations fixed messages should just47        return themselves48        """49        return self50    project = _no_op51    from_mode = _no_op52    __pow__ = _no_op53    __mul__ = _no_op54    __div__ = _no_op55    default = _no_op56    _multiply = _no_op57    _divide = _no_op...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
