def generate_targets(self): # if the situation is anything other than a single base in the main, # this *might* be hit once but that scout is going home soon base = self.enemy_structures(BaseStructures).first def distance_to_enemy(ramp): return ramp.top_center.distance_to(base) # TODO: figure out ramp better likely_main_ramp = min(self.game_info.map_ramps, key=distance_to_enemy) def distance_to_ramp(base): return base.distance_to(likely_main_ramp.bottom_center) possible_naturals = [ position for position in self.expansion_locations_dict.keys() if position.is_further_than(1.0, base.position) ] likely_natural = min(possible_naturals, key=distance_to_ramp) corners = [ Point2([8, 8]), Point2([8, -8]), Point2([-8, -8]), Point2([-8, 8]) ] self.targets = list_flatten([[pos + base.position for pos in corners], [likely_natural]])
async def post_update(self): if self.debug: client: "Client" = self.ai._client if self.zealot_position: x = self.zealot_position.x y = self.zealot_position.y z = self.knowledge.get_z(Point2((x, y))) c1 = Point3((x - 0.25, y - 0.25, z)) c2 = Point3((x + 0.25, y + 0.25, z + 2)) client.debug_box_out(c1, c2) correction = Point2((0, 1)) for x in range(0, self.grid.width - 1): for y in range(0, self.grid.height - 1): cell: GridArea = self.grid.get(x, y) color = None if cell.Area == BuildArea.Building: color = self.grid.building_color elif cell.Area == BuildArea.TownHall: color = self.grid.townhall_color elif cell.Area == BuildArea.Pylon: color = self.grid.pylon_color elif cell.Area == BuildArea.Mineral: color = self.grid.mineral_color elif cell.Area == BuildArea.Gas: color = self.grid.gas_color # elif cell.Area == BuildArea.Empty: # color = self.grid.gas_color if color: z = self.knowledge.get_z(Point2((x, y)) + correction) c1 = Point3((x, y, z)) c2 = Point3((x + 1, y + 1, z + 1)) client.debug_box_out(c1, c2, color)
def outmost_resource(self, townhall): resource_positions = near_resource_position(self, townhall) townhall_position = np.array(townhall.position) # Every element in t2r_vectors is a vector starting from townhall.position, ending with a resource field position t2r_vectors = [field - townhall_position for field in resource_positions] random_t2r_vector = t2r_vectors[0] cos_list = [ cos_between_two_vectors(t2r, random_t2r_vector) for t2r in t2r_vectors ] out_most_1 = [ field_info(Point2(x), y, z) for x, y, z in zip(resource_positions, t2r_vectors, cos_list) ] # We will choose the resource field that are most far away from random_t2r_vector, it should be one of the two postition we are looking for out_most_1 = sorted(out_most_1, key=lambda f: f.cos)[0] cos_list = [ cos_between_two_vectors(t2r, out_most_1.t2r) for t2r in t2r_vectors ] # We will choose the resource field that are most far away from out_most_1, it should be the left one of the two postition we are looking for out_most_2 = [ field_info(Point2(x), y, z) for x, y, z in zip(resource_positions, t2r_vectors, cos_list) ] out_most_2 = sorted(out_most_2, key=lambda f: f.cos)[0] return [out_most_1.t2r, out_most_2.t2r]
async def draw_creep_pixelmap(self): self.creep_map = [] for (y, x), value in np.ndenumerate(self.state.creep.data_numpy): p = Point2((x, y)) pos = Point2((p.x, p.y)) if value == 1: self.creep_map.append(pos)
def __init__( self, ai=None, index=None, resources=None, coords=None, ramps=None, is_ours=False, is_enemies=False, ): """ Basic object for storing expansion information """ self.ai = ai self.grid = self.ai.game_info.placement_grid.data_numpy self.index = str(index) self.resources = resources self.coords: Point2 = coords self.turret_positions = [[]] self.turret_queue = None self.grid_points = [[]] x_offset = Point2((20.0, 0.0)) y_offset = Point2((0.0, 20.0)) # need to assert the points are in the map actually self.top_left = Point2(self.coords.offset(-x_offset).offset(y_offset)) self.bottom_right = Point2( self.coords.offset(x_offset).offset(-y_offset)) self.ramps: Union[List[RampExt]] = ramps self.is_ours: bool = is_ours self.is_enemies: bool = is_enemies self.borders = [] for ramp in self.ramps: ramp.name += f"+ of {self}"
def __init__(self, inputBuildList, player: Player): """Initializes bot (see BuildListProcessBotBase). """ # base class BuildListProcessBotBase.__init__(self, inputBuildList, player) self.gridStart: Point2 = Point2() self.loggerChild = logging.getLogger("BuildListProcessBotTerran" + self.playerString) # building grid self.maxColLength = 32 # tells at which point the limit of a col in the grid is reached self.colStop = Point2((0, 0)) self.plannedStructureSizes = dict() # tells how many cols there are # also tells how many elements each of the following data structures has self.numberOfCols = 0 # tells how wide each col is (double the building radius that can be placed in that col) self.colsWidths = [] # tells where each col starts (Point2) self.colsStarts = [] # tells the current build point within the cols (same as start point for now) self.colsNextBuildPoint = []
async def test_do_not_send_excess_workers(self): distribute_workers = DistributeWorkers() ai = mock_ai() nexus1 = mock_unit(ai, UnitTypeId.NEXUS, Point2(MAIN_POINT)) nexus1._proto.assigned_harvesters = 17 nexus2 = mock_unit(ai, UnitTypeId.NEXUS, Point2(NATURAL_POINT)) nexus2._proto.assigned_harvesters = 16 for i in range(0, 17): worker1 = mock_unit(ai, UnitTypeId.PROBE, Point2((20, 10))) set_fake_order(worker1, AbilityId.HARVEST_GATHER, ai.mineral_field[0].tag) for i in range(0, 16): worker1 = mock_unit(ai, UnitTypeId.PROBE, Point2((20, 60))) set_fake_order(worker1, AbilityId.HARVEST_GATHER, ai.mineral_field[1].tag) knowledge = await mock_knowledge(ai) for worker in ai.workers: knowledge.roles.set_task(UnitTask.Gathering, worker) await distribute_workers.start(knowledge) await distribute_workers.execute() assert len(ai.actions) == 0
def draw_regions(self): labeled_array, num_features = label( self.ai.game_info.placement_grid.data_numpy) for i, row in enumerate(labeled_array): for j, col in enumerate(row): try: text = labeled_array[i][j] if self.ai.game_info.placement_grid.data_numpy[i][j] == 1: p = Point2((i, j)) h = self.ai.get_terrain_z_height(p) pos = Point3((p.x, p.y, h)) # edge_points = [(points[[i, j], 0][1], points[[i, j], 1][0]) for i, j in edges] box_r = 0.2 color = Point3((int(text) * 10, 0, 250)) p0 = Point3((pos.x - box_r, pos.y - box_r, pos.z + box_r)) + Point2((0.5, 0.5)) p1 = Point3((pos.x + box_r, pos.y + box_r, pos.z - box_r)) + Point2((0.5, 0.5)) self.ai.client.debug_box_out(p0, p1, color=color) self.ai.client.debug_text_world( "\n".join([ f"{text}", ]), p, color=color, size=12, ) except Exception as e: pass
def test_closer_than(self): self.assertEqual(self.marines.closer_than(20, Point2((10, 10))), self.marines) self.assertEqual(self.marines.closer_than(6, Point2((10, 10))), Units([self.marine3], self.mock_game_state)) self.assertEqual(self.marines.closer_than(2, Point2((10, 10))), self.emptyUnitsGroup)
def draw_ramps(self): for index, ramp in self.ai.map_manager.cached_ramps.items(): self.ai.map_manager.cached_ramps[index] = ramp p = ramp.coords c0 = None c1 = None line_color = Point3((255, 0, 0)) if p is not None: if len(ramp.expansions) > 1: c0 = ramp.expansions[0].coords.to3 c1 = ramp.expansions[1].coords.to3 color = Point3((0, 255, 0)) h2 = self.ai.get_terrain_z_height(p) pos = Point3((p.x, p.y, h2)) p0 = Point3((pos.x - 1.5, pos.y - 1.5, pos.z + 1.5)) + Point2( (0.5, 0.5)) p1 = Point3((pos.x + 1.5, pos.y + 1.5, pos.z - 1.5)) + Point2( (0.5, 0.5)) if isinstance(c0, Point3) and isinstance(c1, Point3): self.ai.client.debug_line_out(c0, c1, color=line_color) self.ai.client.debug_box_out(p0, p1, color=color) self.ai.client.debug_text_world( "\n".join([ f"{ramp.name}", f"Coords: ({p.position.x:.2f},{p.position.y:.2f})", ]), pos, color=(0, 255, 0), size=12, )
def _draw_point_list(self, point_list: List = None, color=None, text=None, box_r=None) -> bool: if not color: color = GREEN if not point_list or (not text and not box_r): return True # print("cant draw nothing !") for p in point_list: p = Point2(p) h = self.ai.get_terrain_z_height(p) pos = Point3((p.x, p.y, h)) if box_r: p0 = Point3( (pos.x - box_r, pos.y - box_r, pos.z + box_r)) + Point2( (0.5, 0.5)) p1 = Point3( (pos.x + box_r, pos.y + box_r, pos.z - box_r)) + Point2( (0.5, 0.5)) self.ai.client.debug_box_out(p0, p1, color=color) if text: self.ai.client.debug_text_world( "\n".join([ f"{text}", ]), pos, color=color, size=30, )
def draw_placement_grid(self, expansion: Expansion): map_area = self.ai.game_info.playable_area for (b, a), value in np.ndenumerate( self.ai.game_info.placement_grid.data_numpy): # skip non placements which are zero if value == 0: continue # Skip values outside of playable map area if not (map_area.x <= a < map_area.x + map_area.width): continue if not (map_area.y <= b < map_area.y + map_area.height): continue p = Point2((a, b)) if expansion.is_in(p): h2 = self.ai.get_terrain_z_height(p) pos = Point3((p.x, p.y, h2)) p0 = Point3( (pos.x - 0.25, pos.y - 0.25, pos.z + 0.25)) + Point2( (0.5, 0.5)) p1 = Point3( (pos.x + 0.25, pos.y + 0.25, pos.z - 0.25)) + Point2( (0.5, 0.5)) color = Point3((0, 255, 0)) self.ai.client.debug_box_out(p0, p1, color=color)
def draw_expansions(self): color = GREEN self.draw_expansion_borders(color) for i, expansion in enumerate(self.ai.map_manager.expansions.values()): # if i%2 == 0: # color = Point3((0, 255, 0)) # else: # color = Point3((255, 0, 0)) p = expansion.coords if isinstance(p, Point2): h2 = self.ai.get_terrain_z_height(p) pos = Point3((p.x, p.y, h2)) p0 = Point3((pos.x - 2, pos.y - 2, pos.z + 2)) + Point2( (0.5, 0.5)) p1 = Point3((pos.x + 2, pos.y + 2, pos.z - 2)) + Point2( (0.5, 0.5)) distance_to_main = p.distance_to( self.ai.start_location.rounded) # if distance_to_main < 18.0: # continue self.ai.client.debug_box_out(p0, p1, color=color) self.ai.client.debug_text_world( "\n".join([ f"{expansion}", f"distance_to_main: {distance_to_main:.2f}", f"Coords: ({p.position.x:.2f},{p.position.y:.2f})", f"Resources: ({len(expansion.resources)})", ]), pos, color=(0, 255, 255), size=8, )
def draw_expansion_borders(self, color: Union[Point3, Tuple]): height_map = self.ai.game_info.terrain_height for expansion in self.ai.map_manager.expansions.values(): height_here = height_map[expansion.coords] main_height = height_map[self.ai.start_location.rounded] natural_height = height_map[ self.ai.main_base_ramp.lower.pop()] # doesnt matter which c = GREEN if expansion.coords.rounded == self.ai.start_location.rounded: c = GREEN elif expansion.coords.rounded.distance_to( self.ai.start_location.rounded) < 33: c = BLUE else: c = RED for p in expansion.borders: p = Point2(p) h2 = self.ai.get_terrain_z_height(p) pos = Point3((p.x, p.y, h2)) p0 = Point3( (pos.x - 0.25, pos.y - 0.25, pos.z + 0.25)) + Point2( (0.5, 0.5)) p1 = Point3( (pos.x + 0.25, pos.y + 0.25, pos.z - 0.25)) + Point2( (0.5, 0.5)) self.ai.client.debug_box_out(p0, p1, color=c) self.ai.client.debug_text_world( f"h:{self.ai.game_info.terrain_height[p]:.2f}", pos, color=RED, size=30, )
async def step(self): if self.bot.start_location.distance2_to(strategic_points[0]) < 3: wait_point = Point2((21.21, 51.56)) hide_point = Point2((19.89, 18.56)) else: wait_point = Point2((67.57, 36.68)) hide_point = Point2((68.16, 69.35)) if self.complete is True: for t in self.inv_troops["disturb"]: temp = self.bot.units.owned.filter(lambda u : u.tag == t) if temp.amount > 0: temp = temp.first if (temp.type_id == UnitTypeId.MARINE and temp.position3d[2] > 11) or \ temp.type_id == UnitTypeId.MEDIVAC and temp.distance_to( wait_point ) < 3: self.assign("defense", temp.tag) if (self.complete is True) and ( self.bot.units.closer_than(5, hide_point).of_type(UnitTypeId.MARINE).amount <= 0 ): self.end = True if (self.complete is False) and (self.bot.known_enemy_units.filter(lambda u : u.is_structure is False).closer_than(8, hide_point).amount > 3): self.opposite_saw = True actions = list() units = self.bot.units.owned for unit_tag in units.tags: a = self.get_orders(unit_tag) if a is not None: actions.append(a) return actions
def fill_and_save(self, position: Point2, blocker_type: BlockerType, area: BuildArea): if blocker_type != BlockerType.Building2x2 and blocker_type != BlockerType.Building4x4: if position.x % 1 != 0.5: position = Point2((position.x + 0.5, position.y)) if position.y % 1 != 0.5: position = Point2((position.x, position.y + 0.5)) else: position = Point2((floor(position.x), floor(position.y))) if area != BuildArea.BuildingPadding: list: List[Point2] = self._building_positions.get(area, []) building_index = len(list) self._building_positions[area] = list list.append(position) else: building_index = -1 def filler(cell: GridArea): if cell.Area == BuildArea.Empty or cell.Area == BuildArea.BuildingPadding: cell.BuildingIndex = building_index cell.Area = area return cell self.grid.fill_area(position, blocker_type, filler)
def on_start(self): """ 새로운 게임마다 초기화 """ self.target_unit_counts = { UnitTypeId.COMMANDCENTER: 0, # 추가 사령부 생산 없음 UnitTypeId.MARINE: 10, UnitTypeId.MARAUDER: 2, UnitTypeId.REAPER: 0, UnitTypeId.GHOST: 1, UnitTypeId.HELLION: 0, UnitTypeId.SIEGETANK: 1, UnitTypeId.THOR: 0, UnitTypeId.MEDIVAC: 1, UnitTypeId.VIKINGFIGHTER: 0, UnitTypeId.BANSHEE: 0, UnitTypeId.RAVEN: 1, UnitTypeId.BATTLECRUISER: 0, } self.evoked = dict() self.cc = self.units(UnitTypeId.COMMANDCENTER).first if self.start_location.distance_to(Point2((32.5, 31.5))) < 5.0: self.enemy_cc = Point2(Point2((95.5, 31.5))) else: self.enemy_cc = Point2(Point2((32.5, 31.5)))
async def do_creep_tumors(self): # Expand creep tumors for creeptumor in self.units(CREEPTUMORBURROWED).ready: abilities = await self.get_available_abilities(creeptumor) if not AbilityId.BUILD_CREEPTUMOR_TUMOR in abilities: continue cur_pos = creeptumor.position.to2 tumor_positions = [Point2((x + cur_pos.x, y + cur_pos.y)) for (x, y) in itertools.product(range(-5, 6), range(-5, 6))] print('potential positions before pathing_grid', len(tumor_positions)) tumor_positions = [Point2((x,y)) for (x,y) in tumor_positions if self.game_info.pathing_grid.is_empty((floor(x), floor(self.game_info.pathing_grid.height - y)))] print('potential positions after pathing_grid', len(tumor_positions)) tumor_positions = sorted(tumor_positions, key=lambda pos: pos.distance_to(self.enemy_start_locations[0])) print('current tumor pos', cur_pos) print('trying positions', tumor_positions) pathing_target = None async def pathing_distance(tumor_pos): nonlocal pathing_target (cur_distance, new_pathing_target) = await self.do_pathing_to_enemy_base(tumor_pos, pathing_target) if new_pathing_target: pathing_target = new_pathing_target return cur_distance tumor_positions_with_distance = [(tumor_pos, await pathing_distance(tumor_pos)) for tumor_pos in tumor_positions] usable_positions = [(pos, d) for (pos, d) in tumor_positions_with_distance if d is not None] sorted_positions = sorted(usable_positions, key=lambda pos_and_d: pos_and_d[1]) built = False print('sorted positions', sorted_positions) for (pos, d) in sorted_positions: err = await self.do(creeptumor(BUILD_CREEPTUMOR_TUMOR, pos)) if not err: print('built creep tumor') built = True break if not built: print('failed to build creep tumor!')
async def test_evacuate_zone_nexus(self): distribute_workers = DistributeWorkers() ai = mock_ai() nexus1 = mock_unit(ai, UnitTypeId.NEXUS, Point2(MAIN_POINT)) nexus1._proto.assigned_harvesters = 1 mock_unit(ai, UnitTypeId.NEXUS, Point2(NATURAL_POINT)) for i in range(0, 17): worker1 = mock_unit(ai, UnitTypeId.PROBE, Point2((20, 60))) set_fake_order(worker1, AbilityId.HARVEST_GATHER, ai.mineral_field[1].tag) worker1 = mock_unit(ai, UnitTypeId.PROBE, Point2((20, 10))) set_fake_order(worker1, AbilityId.HARVEST_GATHER, ai.mineral_field[0].tag) knowledge = await mock_knowledge(ai) for worker in ai.workers: knowledge.roles.set_task(UnitTask.Gathering, worker) knowledge.expansion_zones[0].needs_evacuation = True await distribute_workers.start(knowledge) await distribute_workers.execute() assert len(ai.actions) == 1 assert ai.actions[0].unit.tag == worker1.tag assert ai.actions[0].target.tag == ai.mineral_field[1].tag
async def fix_location(self, location, build_type): if location: position_ok = False can_move_left = True # garante que nao vai ocupar o espaco para Techs e Reactors for i in range(2): position_ok = await self.bot_player.can_place(build_type, location) if position_ok and self.validate_location(location): break else: can_move_left = False location = Point2((location.x+1, location.y)) if not position_ok: location = None else: # garante que tera espaco para Techs e Reactors if build_type in [UnitTypeId.BARRACKS, UnitTypeId.FACTORY, UnitTypeId.STARPORT]: position_ok = False have_right_space = await self.bot_player.can_place(build_type, Point2((location.x+2, location.y))) for i in range(3): position_ok = await self.bot_player.can_place(build_type, location) if position_ok and have_right_space: position_ok = True break elif can_move_left: location = Point2((location.x-2, location.y)) have_right_space = position_ok position_ok = False else: position_ok = False break if not position_ok: location = None return location
def on_start(self): """ 새로운 게임마다 초기화 """ self.step_interval = self.step_interval self.last_step_time = -self.step_interval self.evoked = dict() self.build_order = list() # self.economy_strategy = EconomyStrategy.MARINE.value self.army_strategy = ArmyStrategy.DEFENSE_SIMPLE self.cc = self.units(UnitTypeId.COMMANDCENTER).first # 전체 유닛에서 사령부 검색 # (32.5, 31.5) or (95.5, 31.5) if self.start_location.distance_to(Point2((32.5, 31.5))) < 5.0: # self.enemy_cc = self.enemy_start_locations[0] # 적 시작 위치 self.enemy_cc = Point2(Point2((95.5, 31.5))) # 적 시작 위치 else: self.enemy_cc = Point2(Point2((32.5, 31.5))) # 적 시작 위치 # Learner에 join self.game_id = f"{self.host_name}_{time.time()}" # data = (JOIN, game_id) # self.sock.send_multipart([pickle.dumps(d) for d in data]) # 초반 빌드 오더 생성 (해병: 30) for _ in range(30): self.build_order.append(UnitTypeId.MARINE) # 중반 빌드 오더 (해병: 2, 공성 전차 : 1, 화염차 : 1 - 다섯 번 반복) for _ in range(5): for _ in range(2): self.build_order.append(UnitTypeId.MARINE) self.build_order.append(UnitTypeId.SIEGETANK) self.build_order.append(UnitTypeId.HELLION)
def points_to_build_addon(sp_position: Point2) -> List[Point2]: """ Return all points that need to be checked when trying to build an addon. Returns 4 points. """ addon_offset: Point2 = Point2((2.5, -0.5)) addon_position: Point2 = sp_position + addon_offset addon_points = [(addon_position + Point2((x - 0.5, y - 0.5))).rounded for x in range(0, 2) for y in range(0, 2)] return addon_points
def test_position_pointlike(x1, y1, x2, y2, x3, y3): pos1 = Point2((x1, y1)) pos2 = Point2((x2, y2)) pos3 = Point2((x3, y3)) epsilon = 1e-3 assert pos1.position == pos1 dist = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 assert abs(pos1.distance_to(pos2) - dist) <= epsilon assert abs(pos1.distance_to_point2(pos2) - dist) <= epsilon assert abs(pos1._distance_squared(pos2) ** 0.5 - dist) <= epsilon if epsilon < dist < 1e5: assert pos1.is_closer_than(dist + epsilon, pos2) assert pos1.is_further_than(dist - epsilon, pos2) points = {pos2, pos3} points2 = {pos1, pos2, pos3} # All 3 points need to be different if len(points2) == 3: assert pos1.sort_by_distance(points2) == sorted(points2, key=lambda p: pos1._distance_squared(p)) assert pos1.closest(points2) == pos1 closest_point = min(points, key=lambda p: p._distance_squared(pos1)) dist_closest_point = pos1._distance_squared(closest_point) ** 0.5 furthest_point = max(points, key=lambda p: p._distance_squared(pos1)) dist_furthest_point = pos1._distance_squared(furthest_point) ** 0.5 # Distances between pos1-pos2 and pos1-pos3 might be the same, so the sorting might still be different, that's why I use a set here assert pos1.closest(points) in {p for p in points2 if abs(pos1.distance_to(p) - dist_closest_point) < epsilon} assert abs(pos1.distance_to_closest(points) - pos1._distance_squared(closest_point) ** 0.5) < epsilon assert pos1.furthest(points) in {p for p in points2 if abs(pos1.distance_to(p) - dist_furthest_point) < epsilon} assert abs(pos1.distance_to_furthest(points) - pos1._distance_squared(furthest_point) ** 0.5) < epsilon assert pos1.offset(pos2) == Point2((pos1.x + pos2.x, pos1.y + pos2.y)) if pos1 != pos2: assert pos1.unit_axes_towards(pos2) != Point2((0, 0)) if 0 < x3: temp_pos = pos1.towards(pos2, x3) if x3 <= pos1.distance_to(pos2): # Using "towards" function to go between pos1 and pos2 dist1 = pos1.distance_to(temp_pos) + pos2.distance_to(temp_pos) dist2 = pos1.distance_to(pos2) assert abs(dist1 - dist2) <= epsilon else: # Using "towards" function to go past pos2 dist1 = pos1.distance_to(pos2) + pos2.distance_to(temp_pos) dist2 = pos1.distance_to(temp_pos) assert abs(dist1 - dist2) <= epsilon elif x3 < 0: # Using "towards" function with a negative value temp_pos = pos1.towards(pos2, x3) dist1 = temp_pos.distance_to(pos1) + pos1.distance_to(pos2) dist2 = pos2.distance_to(temp_pos) assert abs(dist1 - dist2) <= epsilon assert pos1 == pos1 assert pos2 == pos2 assert pos3 == pos3 assert isinstance(hash(pos1), int) assert isinstance(hash(pos2), int) assert isinstance(hash(pos3), int)
def _draw_point_list(self, point_list: List = None, color=None, text=None, box_r=None) -> bool: if not color: color = GREEN h = self.get_terrain_z_height(self.townhalls[0]) for p in point_list: p = Point2(p) pos = Point3((p.x, p.y, h)) if box_r: p0 = Point3( (pos.x - box_r, pos.y - box_r, pos.z + box_r)) + Point2( (0.5, 0.5)) p1 = Point3( (pos.x + box_r, pos.y + box_r, pos.z - box_r)) + Point2( (0.5, 0.5)) self.client.debug_box_out(p0, p1, color=color) if text: self.client.debug_text_world( "\n".join([ f"{text}", ]), pos, color=color, size=30, )
def check_tumor_position( self, possible_position: Point2, combined_grid: Any ) -> int: """ Calculate the number of tiles the tumor position would cover. Arg: possible_position (Point2): the point being checked. combined_grid (Any): ndarray that's the pathfinding lib's path map and the creep map added together Returns: int: the number of tiles that would be covered. """ x, y = floor(possible_position[0]), floor(possible_position[1]) future_tiles = 0 for i in range(-10, 11): for j in range(-10, 11): if 8 <= abs(j) <= 10: if abs(i) <= 6 - 2 * (abs(j) - 8): future_tiles += combined_grid[Point2((x + i, y + j))] % 2 elif abs(j) == 7: if abs(i) <= 7: future_tiles += combined_grid[Point2((x + i, y + j))] % 2 elif 3 <= abs(j) <= 6: if abs(i) <= 9 - floor(abs(j) / 5): future_tiles += combined_grid[Point2((x + i, y + j))] % 2 else: if combined_grid[Point2((x + i, y + j))] == 1: future_tiles += 1 return future_tiles
async def landAndReadyToBuildStarportAddOn_mask(self): if self.structures(UnitTypeId.STARPORTFLYING): if self.structures(UnitTypeId.STARPORTFLYING).idle: if self.can_afford(UnitTypeId.STARPORTREACTOR) and self.can_afford( UnitTypeId.STARPORTTECHLAB): for Starport in self.structures( UnitTypeId.STARPORTFLYING).idle: possible_land_positions_offset = sorted( (Point2((x, y)) for x in range(-10, 10) for y in range(-10, 10)), key=lambda point: point.x**2 + point.y**2, ) offset_point: Point2 = Point2((-0.5, -0.5)) possible_land_positions = ( Starport.position.rounded + offset_point + p for p in possible_land_positions_offset) for target_land_position in possible_land_positions: land_and_addon_points: List[Point2] = land_positions( target_land_position) if all( self.in_map_bounds(land_pos) and self.in_placement_grid(land_pos) and self.in_pathing_grid(land_pos) for land_pos in land_and_addon_points): Starport(AbilityId.LAND, target_land_position) return 1 return 0
def __init__(self, map_data: "MapData", array: np.ndarray, ramp: sc2Ramp) -> None: super().__init__(map_data=map_data, array=array) self.is_ramp = True self.ramp = ramp self.offset = Point2((0.5, 0.5)) self.points.add(Point2(self.middle_walloff_depot.rounded)) self._set_sides()
def find_addon_points(self, racks_position: Point2): # -> List[Point2]: # def find_addon_points(): """ Return all points that need to be checked when trying to build an addon. Returns 4 points. """ addon_offset: Point2 = Point2((2.5, -0.5)) addon_position: Point2 = racks_position + addon_offset addon_points = [(addon_position + Point2((x - 0.5, y - 0.5))).rounded for x in range(0, 2) for y in range(0, 2)] return addon_points
def set_rocks(self, grid: sc2pathlibp.PathFinder): for rock in self.ai.destructables: # type: Unit rock_type = rock.type_id if rock.name == "MineralField450": # Attempts to solve the issue with sc2 linux 4.10 vs Windows 4.11 grid.create_block(rock.position, (2, 1)) elif rock_type in breakable_rocks_2x2: grid.create_block(rock.position, (2, 2)) elif rock_type in breakable_rocks_4x4: grid.create_block(rock.position, (4, 3)) grid.create_block(rock.position, (3, 4)) elif rock_type in breakable_rocks_6x6: grid.create_block(rock.position, (6, 4)) grid.create_block(rock.position, (5, 5)) grid.create_block(rock.position, (4, 6)) elif rock_type in breakable_rocks_4x2: grid.create_block(rock.position, (4, 2)) elif rock_type in breakable_rocks_2x4: grid.create_block(rock.position, (2, 4)) elif rock_type in breakable_rocks_6x2: grid.create_block(rock.position, (6, 2)) elif rock_type in breakable_rocks_2x6: grid.create_block(rock.position, (2, 6)) elif rock_type in breakable_rocks_diag_BLUR: for y in range(-4, 6): if y == -4: grid.create_block(rock.position + Point2((y + 2, y)), (1, 1)) elif y == 5: grid.create_block(rock.position + Point2((y - 2, y)), (1, 1)) elif y == -3: grid.create_block(rock.position + Point2((y - 1, y)), (3, 1)) elif y == 4: grid.create_block(rock.position + Point2((y + 1, y)), (3, 1)) else: grid.create_block(rock.position + Point2((y, y)), (5, 1)) elif rock_type in breakable_rocks_diag_ULBR: for y in range(-4, 6): if y == -4: grid.create_block(rock.position + Point2((-y - 2, y)), (1, 1)) elif y == 5: grid.create_block(rock.position + Point2((-y + 2, y)), (1, 1)) elif y == -3: grid.create_block(rock.position + Point2((-y + 1, y)), (3, 1)) elif y == 4: grid.create_block(rock.position + Point2((-y - 1, y)), (3, 1)) else: grid.create_block(rock.position + Point2((-y, y)), (5, 1))
def unit_geometric_median(units: Units, accuracy=0.5) -> Point2: """ Calculates geometric median based on units, returns (0,0) if no units exist """ if len(units) == 0: return Point2((0, 0)) final_array = np.array([np.array([unit.position.x, unit.position.y]) for unit in units]) result = geometric_median(final_array, accuracy) return Point2(result)