INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
UnitTypeId found in sc2/ ids/ unit_typeid Caches all type_ids of the same unit type
def type_id(self) -> UnitTypeId: """ UnitTypeId found in sc2/ids/unit_typeid Caches all type_ids of the same unit type""" unit_type = self._proto.unit_type if unit_type not in self._game_data.unit_types: self._game_data.unit_types[unit_type] = UnitTypeId(unit_type) re...
Does not include upgrades
def ground_dps(self) -> Union[int, float]: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Ground.value, TargetType.Any.value}), None, ) if weapon: ...
Does not include upgrades
def ground_range(self) -> Union[int, float]: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Ground.value, TargetType.Any.value}), None, ) if weapon: ...
Does not include upgrades
def can_attack_air(self) -> bool: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) return weapon is not None ...
Does not include upgrades
def air_dps(self) -> Union[int, float]: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) if weapon: ...
Does not include upgrades
def air_range(self) -> Union[int, float]: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) if weapon: ...
Returns a tuple of form bonus damage armor type if unit does bonus damage against armor type Light = 1 ; Armored = 2 ; Biological = 3 ; Mechanical = 4 ; Robotic = 5 ; Psionic = 6 ; Massive = 7 ; Structure = 8 ; Hover = 9 ; Heroic = 10 ; Summoned = 11
def bonus_damage(self): """ Returns a tuple of form 'bonus damage, armor type' if unit does bonus damage against armor type Light = 1; Armored = 2; Biological = 3; Mechanical = 4; Robotic = 5; Psionic = 6; Massive = 7; Structure = 8; Hover = 9; Heroic = 10; Summoned = 11 """ # TODO Consi...
Does not include shields
def health_percentage(self) -> Union[int, float]: """ Does not include shields """ if self._proto.health_max == 0: return 0 return self._proto.health / self._proto.health_max
Using the 2d distance between self and p. To calculate the 3d distance use unit. position3d. distance_to ( p )
def distance_to(self, p: Union["Unit", Point2, Point3], bot: "BotAI" = None) -> Union[int, float]: """ Using the 2d distance between self and p. To calculate the 3d distance, use unit.position3d.distance_to(p) """ if bot and isinstance(p, Unit): index = bot.distances_tag_dict ...
Returns some time ( more than game loops ) until the unit can fire again returns - 1 for units that can t attack. Usage: if unit. weapon_cooldown == 0: await self. do ( unit. attack ( target )) elif unit. weapon_cooldown < 0: await self. do ( unit. move ( closest_allied_unit_because_cant_attack )) else: await self. do ...
def weapon_cooldown(self) -> Union[int, float]: """ Returns some time (more than game loops) until the unit can fire again, returns -1 for units that can't attack. Usage: if unit.weapon_cooldown == 0: await self.do(unit.attack(target)) elif unit.weapon_cooldown < 0: ...
Units inside a Bunker CommandCenter Nydus Medivac WarpPrism Overlord
def passengers(self) -> Set["PassengerUnit"]: """ Units inside a Bunker, CommandCenter, Nydus, Medivac, WarpPrism, Overlord """ return {PassengerUnit(unit, self._game_data) for unit in self._proto.passengers}
Includes the target s radius when calculating distance to target
def target_in_range(self, target: "Unit", bonus_distance: Union[int, float] = 0) -> bool: """ Includes the target's radius when calculating distance to target """ if self.can_attack_ground and not target.is_flying: unit_attack_range = self.ground_range elif self.can_attack_air and (t...
Checks if a worker or MULE is carrying ( gold - ) minerals.
def is_carrying_minerals(self) -> bool: """ Checks if a worker or MULE is carrying (gold-)minerals. """ return any( buff.value in self._proto.buff_ids for buff in {BuffId.CARRYMINERALFIELDMINERALS, BuffId.CARRYHIGHYIELDMINERALFIELDMINERALS} )
Checks if a worker is carrying vespene.
def is_carrying_vespene(self) -> bool: """ Checks if a worker is carrying vespene. """ return any( buff.value in self._proto.buff_ids for buff in { BuffId.CARRYHARVESTABLEVESPENEGEYSERGAS, BuffId.CARRYHARVESTABLEVESPENEGEYSERGASPROTOSS, ...
Checks if a unit is patrolling.
def is_patrolling(self) -> bool: """ Checks if a unit is patrolling. """ return self.orders and self.orders[0].ability.id is AbilityId.PATROL
Checks if a unit is on its way to a mineral field/ vespene geyser to mine.
def is_gathering(self) -> bool: """ Checks if a unit is on its way to a mineral field / vespene geyser to mine. """ return self.orders and self.orders[0].ability.id is AbilityId.HARVEST_GATHER
Checks if a unit is returning from mineral field/ vespene geyser to deliver resources to townhall.
def is_returning(self) -> bool: """ Checks if a unit is returning from mineral field / vespene geyser to deliver resources to townhall. """ return self.orders and self.orders[0].ability.id is AbilityId.HARVEST_RETURN
Combines the two properties above.
def is_collecting(self) -> bool: """ Combines the two properties above. """ return self.orders and self.orders[0].ability.id in {AbilityId.HARVEST_GATHER, AbilityId.HARVEST_RETURN}
Checks if the unit is an SCV that is currently building.
def is_constructing_scv(self) -> bool: """ Checks if the unit is an SCV that is currently building. """ return self.orders and self.orders[0].ability.id in { AbilityId.TERRANBUILD_ARMORY, AbilityId.TERRANBUILD_BARRACKS, AbilityId.TERRANBUILD_BUNKER, Abilit...
Returns the target tag ( if it is a Unit ) or Point2 ( if it is a Position ) from the first order returns None if the unit is idle
def order_target(self) -> Optional[Union[int, Point2]]: """ Returns the target tag (if it is a Unit) or Point2 (if it is a Position) from the first order, returns None if the unit is idle """ if self.orders: if isinstance(self.orders[0].target, int): return self.order...
Requires UpgradeId to be passed instead of AbilityId
def research(self, upgrade, *args, **kwargs): """ Requires UpgradeId to be passed instead of AbilityId """ return self(self._game_data.upgrades[upgrade.value].research_ability.id, *args, **kwargs)
Filters units that are in attack range of the unit in parameter
def in_attack_range_of(self, unit: Unit, bonus_distance: Union[int, float] = 0) -> "Units": """ Filters units that are in attack range of the unit in parameter """ return self.filter(lambda x: unit.target_in_range(x, bonus_distance=bonus_distance))
Returns the distance between the closest unit from this group to the target unit
def closest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]: """ Returns the distance between the closest unit from this group to the target unit """ assert self.exists if isinstance(position, Unit): position = position.position return position.d...
Returns the distance between the furthest unit from this group to the target unit
def furthest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]: """ Returns the distance between the furthest unit from this group to the target unit """ assert self.exists if isinstance(position, Unit): position = position.position return position...
This function should be a bit faster than using units. sorted ( keyfn = lambda u: u. distance_to ( position ))
def sorted_by_distance_to(self, position: Union[Unit, Point2], reverse: bool = False) -> "Units": """ This function should be a bit faster than using units.sorted(keyfn=lambda u: u.distance_to(position)) """ if len(self) in [0, 1]: return self position = position.position ret...
Filters all units that have their tags not in the other set/ list/ dict
def tags_not_in(self, other: Union[Set[int], List[int], Dict[int, Any]]) -> "Units": """ Filters all units that have their tags not in the 'other' set/list/dict """ # example: self.units(QUEEN).tags_not_in(self.queen_tags_assigned_to_do_injects) if isinstance(other, list): other = se...
Filters all units that are of a specific type
def of_type(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units": """ Filters all units that are of a specific type """ # example: self.units.of_type([ZERGLING, ROACH, HYDRALISK, BROODLORD]) if isinstance(other, UnitTypeId): other = {ot...
Usage: self. units. same_tech ( UnitTypeId. COMMANDCENTER ) or self. units. same_tech ( UnitTypeId. ORBITALCOMMAND ) returns all CommandCenter CommandCenterFlying OrbitalCommand OrbitalCommandFlying PlanetaryFortress This also works with a set/ list/ dict parameter e. g. self. units. same_tech ( { UnitTypeId. COMMANDCE...
def same_tech(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units": """ Usage: 'self.units.same_tech(UnitTypeId.COMMANDCENTER)' or 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)' returns all CommandCenter, CommandCenterFlying, OrbitalCommand, Orb...
Usage: self. units. same_tech ( UnitTypeId. COMMANDCENTER ) returns CommandCenter and CommandCenterFlying self. units. same_tech ( UnitTypeId. ORBITALCOMMAND ) returns OrbitalCommand and OrbitalCommandFlying This also works with a set/ list/ dict parameter e. g. self. units. same_tech ( { UnitTypeId. COMMANDCENTER Unit...
def same_unit(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units": """ Usage: 'self.units.same_tech(UnitTypeId.COMMANDCENTER)' returns CommandCenter and CommandCenterFlying, 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)' returns...
Returns the central point of all units in this list
def center(self) -> Point2: """ Returns the central point of all units in this list """ assert self pos = Point2( ( sum([unit.position.x for unit in self]) / self.amount, sum([unit.position.y for unit in self]) / self.amount, ) ) ...
- depots when low on remaining supply - townhalls contains commandcenter and orbitalcommand - self. units ( TYPE ). not_ready. amount selects all units of that type filters incomplete units and then counts the amount - self. already_pending ( TYPE ) counts how many units are queued - but in this bot below you will find...
async def on_step(self, iteration): self.combinedActions = [] """ - depots when low on remaining supply - townhalls contains commandcenter and orbitalcommand - self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount...
You can use await self. _client. leave () to surrender midst game.
async def leave(self): """ You can use 'await self._client.leave()' to surrender midst game. """ is_resign = self._game_result is None if is_resign: # For all clients that can leave, result of leaving the game either # loss, or the client will ignore the result ...
EXPERIMENTAL: Change self. _client. game_step during the step function to increase or decrease steps per second
async def step(self): """ EXPERIMENTAL: Change self._client.game_step during the step function to increase or decrease steps per second """ result = await self._execute(step=sc_pb.RequestStep(count=self.game_step)) return result
Caution: returns 0 when path not found
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):...
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
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 w...
Query abilities of multiple units
async def query_available_abilities( self, units: Union[List[Unit], "Units"], ignore_resource_requirements: bool = False ) -> List[List[AbilityId]]: """ Query abilities of multiple units """ if not isinstance(units, list): """ Deprecated, accepting a single unit may be removed in...
Writes a message to the chat
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....
Usage example ( will spawn 1 marine in the center of the map for player ID 1 ): await self. _client. debug_create_unit ( [[ UnitTypeId. MARINE 1 self. _game_info. map_center 1 ]] )
async def debug_create_unit(self, unit_spawn_commands: List[List[Union[UnitTypeId, int, Point2, Point3]]]): """ Usage example (will spawn 1 marine in the center of the map for player ID 1): await self._client.debug_create_unit([[UnitTypeId.MARINE, 1, self._game_info.map_center, 1]]) """ assert i...
Moves camera to the target position
async def move_camera(self, position: Union[Unit, Point2, Point3]): """ Moves camera to the target position """ assert isinstance(position, (Unit, Point2, Point3)) if isinstance(position, Unit): position = position.position await self._execute( action=sc_pb.Reques...
Moves camera to the target position using the spatial aciton interface
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( act...
Deprecated may be removed soon
async def debug_text(self, texts: Union[str, list], positions: Union[list, set], color=(0, 255, 0), size_px=16): """ Deprecated, may be removed soon """ if isinstance(positions, (set, list)): if not positions: return if isinstance(texts, str): tex...
Draws a text in the top left corner of the screen ( up to a max of 6 messages it seems ). Don t forget to add await self. _client. send_debug.
def debug_text_simple(self, text: str): """ Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. """ self._debug_texts.append(self.to_debug_message(text))
Draws a text on the screen with coordinates 0 < = x y < = 1. Don t forget to add await self. _client. send_debug.
def debug_text_screen(self, text: str, pos: Union[Point2, Point3, tuple, list], color=None, size: int = 8): """ Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'. """ assert len(pos) >= 2 assert 0 <= pos[0] <= 1 assert 0 <= po...
Draws a text at Point3 position. Don t forget to add await self. _client. send_debug. To grab a unit s 3d position use unit. position3d Usually the Z value of a Point3 is between 8 and 14 ( except for flying units )
def debug_text_world(self, text: str, pos: Union[Unit, Point2, Point3], color=None, size: int = 8): """ Draws a text at Point3 position. Don't forget to add 'await self._client.send_debug'. To grab a unit's 3d position, use unit.position3d Usually the Z value of a Point3 is between 8 and 14 (exc...
Draws a line from p0 to p1. Don t forget to add await self. _client. send_debug.
def debug_line_out(self, p0: Union[Unit, Point2, Point3], p1: Union[Unit, Point2, Point3], color=None): """ Draws a line from p0 to p1. Don't forget to add 'await self._client.send_debug'. """ self._debug_lines.append( debug_pb.DebugLine( line=debug_pb.Line(p0=self.to_debug_p...
Draws a box with p_min and p_max as corners. Don t forget to add await self. _client. send_debug.
def debug_box_out(self, p_min: Union[Unit, Point2, Point3], p_max: Union[Unit, Point2, Point3], color=None): """ Draws a box with p_min and p_max as corners. Don't forget to add 'await self._client.send_debug'. """ self._debug_boxes.append( debug_pb.DebugBox( min=self.to_debu...
Draws a sphere at point p with radius r. Don t forget to add await self. _client. send_debug.
def debug_sphere_out(self, p: Union[Unit, Point2, Point3], r: Union[int, float], color=None): """ Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'. """ self._debug_spheres.append( debug_pb.DebugSphere(p=self.to_debug_point(p), r=r, color=self.to_de...
Sends the debug draw execution. Put this after your debug creation functions.
async def send_debug(self): """ Sends the debug draw execution. Put this after your debug creation functions. """ await self._execute( debug=sc_pb.RequestDebug( debug=[ debug_pb.DebugCommand( draw=debug_pb.DebugDraw( ...
Helper function for color conversion
def to_debug_color(self, color): """ Helper function for color conversion """ if color is None: return debug_pb.Color(r=255, g=255, b=255) else: r = getattr(color, "r", getattr(color, "x", 255)) g = getattr(color, "g", getattr(color, "y", 255)) b =...
Helper function for point conversion
def to_debug_point(self, point: Union[Unit, Point2, Point3]) -> common_pb.Point: """ Helper function for point conversion """ if isinstance(point, Unit): point = point.position3d return common_pb.Point(x=point.x, y=point.y, z=getattr(point, "z", 0))
Helper function to create debug texts
def to_debug_message( self, text: str, color=None, pos: Optional[Union[Point2, Point3]] = None, size: int = 8 ) -> debug_pb.DebugText: """ Helper function to create debug texts """ color = self.to_debug_color(color) pt3d = self.to_debug_point(pos) if isinstance(pos, Point3) else None...
Same as the function above but should be 3 - 4 times faster because of the dropped asserts and conversions and because it doesnt use a loop ( itertools or zip ).
def distance_to_point2(self, p2: "Point2") -> Union[int, float]: """ Same as the function above, but should be 3-4 times faster because of the dropped asserts and conversions and because it doesnt use a loop (itertools or zip). """ return ((self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2) ** 0.5
Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process.
def _distance_squared(self, p2: "Point2") -> Union[int, float]: """ Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """ return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2
This returns the target points sorted as list. You should not pass a set or dict since those are not sortable. If you want to sort your units towards a point use units. sorted_by_distance_to ( point ) instead.
def sort_by_distance(self, ps: Union["Units", List["Point2"]]) -> List["Point2"]: """ This returns the target points sorted as list. You should not pass a set or dict since those are not sortable. If you want to sort your units towards a point, use 'units.sorted_by_distance_to(point)' instead. """ ...
This function assumes the 2d distance is meant
def closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union["Unit", "Point2"]: """ This function assumes the 2d distance is meant """ assert ps if len(ps) == 1: return ps[0] closest_distance_squared = math.inf for p2 in ps: p2pos = p2 ...
This function assumes the 2d distance is meant
def distance_to_closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union[int, float]: """ This function assumes the 2d distance is meant """ assert ps closest_distance_squared = math.inf for p2 in ps: if not isinstance(p2, Point2): p2 = p2.pos...
This function assumes the 2d distance is meant
def furthest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union["Unit", "Pointlike"]: """ This function assumes the 2d distance is meant """ assert ps if len(ps) == 1: return ps[0] furthest_distance_squared = -math.inf for p2 in ps: p2pos = ...
This function assumes the 2d distance is meant
def distance_to_furthest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union[int, float]: """ This function assumes the 2d distance is meant """ assert ps furthest_distance_squared = -math.inf for p2 in ps: if not isinstance(p2, Point2): p2 = p2....
Squared distance to a point.
def distance2_to(self, other: "Point2"): """Squared distance to a point.""" assert isinstance(other, Point2) return (self[0] - other[0]) ** 2 + (self[1] - other[1]) ** 2
self is point1 p is point2 r is the radius for circles originating in both points Used in ramp finding
def circle_intersection(self, p: "Point2", r: Union[int, float]) -> Set["Point2"]: """ self is point1, p is point2, r is the radius for circles originating in both points Used in ramp finding """ assert self != p distanceBetweenPoints = self.distance_to(p) assert r > distanceBetw...
Converts a vector to a direction that can face vertically horizontally or diagonal or be zero e. g. ( 0 0 ) ( 1 - 1 ) ( 1 0 )
def direction_vector(self, other: "Point2") -> "Point2": """ Converts a vector to a direction that can face vertically, horizontally or diagonal or be zero, e.g. (0, 0), (1, -1), (1, 0) """ return self.__class__((_sign(other.x - self.x), _sign(other.y - self.y)))
Returns the central point for points in list
def center(a: Union[Set["Point2"], List["Point2"]]) -> "Point2": """ Returns the central point for points in list """ s = Point2((0, 0)) for p in a: s += p return s / len(a)
Returns the upper points of a ramp.
def upper(self) -> Set[Point2]: """ Returns the upper points of a ramp. """ max_height = max([self.height_at(p) for p in self._points]) return {p for p in self._points if self.height_at(p) == max_height}
Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file.
def upper2_for_ramp_wall(self) -> Set[Point2]: """ Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file. """ if len(self.upper) > 5: # NOTE: this was way too slow on large ramps return set() # HAC...
Barracks position in the middle of the 2 depots
def barracks_in_middle(self) -> Point2: """ Barracks position in the middle of the 2 depots """ if len(self.upper2_for_ramp_wall) == 2: points = self.upper2_for_ramp_wall p1 = points.pop().offset((self.x_offset, self.y_offset)) p2 = points.pop().offset((self.x_offset,...
Finds the 2 depot positions on the outside
def corner_depots(self) -> Set[Point2]: """ Finds the 2 depot positions on the outside """ if len(self.upper2_for_ramp_wall) == 2: points = self.upper2_for_ramp_wall p1 = points.pop().offset((self.x_offset, self.y_offset)) # still an error with pixelmap? p2 = points....
Test if a barracks can fit an addon at natural ramp
def barracks_can_fit_addon(self) -> bool: """ Test if a barracks can fit an addon at natural ramp """ # https://i.imgur.com/4b2cXHZ.png if len(self.upper2_for_ramp_wall) == 2: return self.barracks_in_middle.x + 1 > max(self.corner_depots, key=lambda depot: depot.x).x raise Ex...
Corrected placement so that an addon can fit
def barracks_correct_placement(self) -> Point2: """ Corrected placement so that an addon can fit """ if len(self.upper2_for_ramp_wall) == 2: if self.barracks_can_fit_addon: return self.barracks_in_middle else: return self.barracks_in_middle.offset(...
Calculate ( self. pathing_grid - self. placement_grid ) ( for sets ) and then find ramps by comparing heights.
def _find_ramps(self) -> List[Ramp]: """Calculate (self.pathing_grid - self.placement_grid) (for sets) and then find ramps by comparing heights.""" rampDict = { Point2((x, y)): self.pathing_grid[(x, y)] == 0 and self.placement_grid[(x, y)] == 0 for x in range(self.pathing_grid.wi...
From a set/ list of points this function will try to group points together
def _find_groups( self, points: Set[Point2], minimum_points_per_group: int = 8, max_distance_between_points: int = 2 ) -> List[Set[Point2]]: """ From a set/list of points, this function will try to group points together """ """ Paint clusters of points in rectangular map using flood fill alg...
Splits words from CamelCase text.
def split_camel_case(text) -> list: """Splits words from CamelCase text.""" return list(reduce( lambda a, b: (a + [b] if b.isupper() else a[:-1] + [a[-1] + b]), text, [] ))
Tech - building requirement of buildings - may work for units but unreliably
def tech_requirement(self) -> Optional[UnitTypeId]: """ Tech-building requirement of buildings - may work for units but unreliably """ if self._proto.tech_requirement == 0: return None if self._proto.tech_requirement not in self._game_data.units: return None retur...
Building tech equality e. g. OrbitalCommand is the same as CommandCenter
def tech_alias(self) -> Optional[List[UnitTypeId]]: """ Building tech equality, e.g. OrbitalCommand is the same as CommandCenter """ """ Building tech equality, e.g. Hive is the same as Lair and Hatchery """ return_list = [] for tech_alias in self._proto.tech_alias: if tech_a...
Building type equality e. g. FlyingOrbitalCommand is the same as OrbitalCommand
def unit_alias(self) -> Optional[UnitTypeId]: """ Building type equality, e.g. FlyingOrbitalCommand is the same as OrbitalCommand """ if self._proto.unit_alias == 0: return None if self._proto.unit_alias not in self._game_data.units: return None """ For flying Orb...
This returns 25 for extractor and 200 for spawning pool instead of 75 and 250 respectively
def cost_zerg_corrected(self) -> "Cost": """ This returns 25 for extractor and 200 for spawning pool instead of 75 and 250 respectively """ if self.race == Race.Zerg and Attribute.Structure.value in self.attributes: # a = self._game_data.units(UnitTypeId.ZERGLING) # print(a) ...
This returns 150 minerals for OrbitalCommand instead of 550
def morph_cost(self) -> Optional["Cost"]: """ This returns 150 minerals for OrbitalCommand instead of 550 """ # Fix for BARRACKSREACTOR which has tech alias [REACTOR] which has (0, 0) cost if self.tech_alias is None or self.tech_alias[0] in {UnitTypeId.TECHLAB, UnitTypeId.REACTOR}: r...
This decorator caches the return value for one game loop then clears it if it is accessed in a different game loop Only works on properties of the bot object because it requires access to self. state. game_loop
def property_cache_once_per_frame(f): """ This decorator caches the return value for one game loop, then clears it if it is accessed in a different game loop Only works on properties of the bot object because it requires access to self.state.game_loop """ f.frame = -1 f.cache = None @wraps(f) d...
Launch the analysis.
def go(self): """ Launch the analysis. this will start a total of `max_fetcher` threads. """ myandro = self.settings["my"] def worker(idx, q): """ Worker Thread """ l.debug("Running worker-%d" % idx) while Tru...
This method is called in order to filer a specific app
def filter_file(self, log, fileraw): """ This method is called in order to filer a specific app :param log: an object which corresponds to a unique app :param bytes fileraw: the raw file as bytes :rtype: a tuple with 2 elements, the return value (boolean) if it is necessary to ...
This method is called in order to create an Analysis object
def create_adex(self, log, dexobj): """ This method is called in order to create an Analysis object :param log: an object which corresponds to a unique app :param androguard.core.bytecodes.dvm.DalvikVMFormat dexobj: a :class:`DalvikVMFormat` object :rytpe: a :class:`~androguard...
Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2 node1 excluded. Although if there is a loop starting from node1 it will be included in the path.
def build_path(graph, node1, node2, path=None): """ Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path. """ if path is None: path = [] ...
Merge the inner class ( es ) of a class: e. g class A {... } class A$foo {... } class A$bar {... } == > class A { class foo {... } class bar {... }... }
def merge_inner(clsdict): """ Merge the inner class(es) of a class: e.g class A { ... } class A$foo{ ... } class A$bar{ ... } ==> class A { class foo{...} class bar{...} ... } """ samelist = False done = {} while not samelist: samelist = True classlist = list(clsdict.keys...
Retrieve the java type of a descriptor ( e. g: I )
def get_type(atype, size=None): """ Retrieve the java type of a descriptor (e.g : I) """ res = TYPE_DESCRIPTOR.get(atype) if res is None: if atype[0] == 'L': if atype.startswith('Ljava/lang'): res = atype[1:-1].lstrip('java/lang/').replace('/', '.') el...
Return the parameters type of a descriptor ( e. g ( IC ) V )
def get_params_type(descriptor): """ Return the parameters type of a descriptor (e.g (IC)V) """ params = descriptor.split(')')[0][1:].split() if params: return [param for param in params] return []
Creates a PNG from a given: class: ~androguard. decompiler. dad. graph. Graph.
def create_png(cls_name, meth_name, graph, dir_name='graphs2'): """ Creates a PNG from a given :class:`~androguard.decompiler.dad.graph.Graph`. :param str cls_name: name of the class :param str meth_name: name of the method :param androguard.decompiler.dad.graph.Graph graph: :param str dir_name...
Open and read a file
def read(filename, binary=True): """ Open and read a file :param filename: filename to open and read :param binary: True if the file should be read as binary :return: bytes if binary is True, str otherwise """ with open(filename, 'rb' if binary else 'r') as f: return f.read()
Format the Name type of a X509 Certificate in a human readable form.
def get_certificate_name_string(name, short=False, delimiter=', '): """ Format the Name type of a X509 Certificate in a human readable form. :param name: Name object to return the DN from :param short: Use short form (default: False) :param delimiter: Delimiter string or character between two parts...
Show color - picker dialog to select color.
def onColorPicker(self): """ Show color-picker dialog to select color. Qt will use the native dialog by default. """ dlg = QtGui.QColorDialog(QtGui.QColor(self._color), None) # if self._color: # dlg.setCurrentColor(QtGui.QColor(self._color)) if dlg....
Analyze an android application and setup all stuff for a more quickly analysis! If session is None no session is used at all. This is the default behaviour. If you like to continue your work later it might be a good idea to use a session. A default session can be created by using: meth: ~get_default_session.
def AnalyzeAPK(_file, session=None, raw=False): """ Analyze an android application and setup all stuff for a more quickly analysis! If session is None, no session is used at all. This is the default behaviour. If you like to continue your work later, it might be a good idea to use a session....
Analyze an android dex file and setup all stuff for a more quickly analysis !
def AnalyzeDex(filename, session=None): """ Analyze an android dex file and setup all stuff for a more quickly analysis ! :param filename: the filename of the android dex file or a buffer which represents the dex file :type filename: string :param session: A session (Default None) :rtype: retu...
Analyze an android odex file and setup all stuff for a more quickly analysis !
def AnalyzeODex(filename, session=None): """ Analyze an android odex file and setup all stuff for a more quickly analysis ! :param filename: the filename of the android dex file or a buffer which represents the dex file :type filename: string :param session: The Androguard Session to add the ODex t...
Run the decompiler on a specific analysis
def RunDecompiler(d, dx, decompiler_name): """ Run the decompiler on a specific analysis :param d: the DalvikVMFormat object :type d: :class:`DalvikVMFormat` object :param dx: the analysis of the format :type dx: :class:`VMAnalysis` object :param decompiler: the type of decompiler to use ("...
Use jarsigner to sign an APK file.
def sign_apk(filename, keystore, storepass): """ Use jarsigner to sign an APK file. :param filename: APK file on disk to sign (path) :param keystore: path to keystore :param storepass: your keystorage passphrase """ from subprocess import Popen, PIPE, STDOUT # TODO use apksigner instead...
Return a filename version which has no characters in it which are forbidden. On Windows these are for example </ ?...
def clean_file_name(filename, unique=True, replace="_", force_nt=False): """ Return a filename version, which has no characters in it which are forbidden. On Windows these are for example <, /, ?, ... The intention of this function is to allow distribution of files to different OSes. :param filena...
Load the Permissions for the given apilevel.
def load_permissions(apilevel, permtype='permissions'): """ Load the Permissions for the given apilevel. The permissions lists are generated using this tool: https://github.com/U039b/aosp_permissions_extraction Has a fallback to select the maximum or minimal available API level. For example, if 28...
Load the API/ Permission mapping for the requested API level. If the requetsed level was not found None is returned.
def load_permission_mappings(apilevel): """ Load the API/Permission mapping for the requested API level. If the requetsed level was not found, None is returned. :param apilevel: integer value of the API level, i.e. 24 for Android 7.0 :return: a dictionary of {MethodSignature: [List of Permissions]}...
Split IfNodes in two nodes the first node is the header node the second one is only composed of the jump condition.
def split_if_nodes(graph): """ Split IfNodes in two nodes, the first node is the header node, the second one is only composed of the jump condition. """ node_map = {n: n for n in graph} to_update = set() for node in graph.nodes[:]: if node.type.is_cond: if len(node.get_in...
Simplify the CFG by merging/ deleting statement nodes when possible: If statement B follows statement A and if B has no other predecessor besides A then we can merge A and B into a new statement node. We also remove nodes which do nothing except redirecting the control flow ( nodes which only contains a goto ).
def simplify(graph): """ Simplify the CFG by merging/deleting statement nodes when possible: If statement B follows statement A and if B has no other predecessor besides A, then we can merge A and B into a new statement node. We also remove nodes which do nothing except redirecting the control f...
Dominator algorithm from Lengauer - Tarjan
def dom_lt(graph): """Dominator algorithm from Lengauer-Tarjan""" def _dfs(v, n): semi[v] = n = n + 1 vertex[n] = label[v] = v ancestor[v] = 0 for w in graph.all_sucs(v): if not semi[w]: parent[w] = v n = _dfs(w, n) pred[w]...
Breadth first search
def bfs(start): """ Breadth first search Yields all nodes found from the starting point :param start: start node """ to_visit = [start] visited = {start} while to_visit: node = to_visit.pop(0) yield node if node.exception_analysis: for _, _, exceptio...