Esempio n. 1
0
def import_bot_instance(
    raw_game_data: Response,
    raw_game_info: Response,
    raw_observation: ResponseObservation,
) -> BotAI:
    """
    import_bot_instance DocString
    """
    bot = BotAI()
    game_data = GameData(raw_game_data.data)
    game_info = GameInfo(raw_game_info.game_info)
    game_state = GameState(raw_observation)
    # noinspection PyProtectedMember
    bot._initialize_variables()
    # noinspection PyProtectedMember
    bot._prepare_start(client=None,
                       player_id=1,
                       game_info=game_info,
                       game_data=game_data)
    # noinspection PyProtectedMember
    bot._prepare_first_step()
    # noinspection PyProtectedMember
    bot._prepare_step(state=game_state, proto_game_info=raw_game_info)
    # noinspection PyProtectedMember
    bot._find_expansion_locations()
    return bot
def get_map_specific_bot(map_path: Path) -> BotAI:
    assert map_path in MAPS
    with lzma.open(str(map_path.absolute()), "rb") as f:
        raw_game_data, raw_game_info, raw_observation = pickle.load(f)

    # Build fresh bot object, and load the pickle'd data into the bot object
    bot = BotAI()
    game_data = GameData(raw_game_data.data)
    game_info = GameInfo(raw_game_info.game_info)
    game_state = GameState(raw_observation)
    bot._initialize_variables()
    bot._prepare_start(client=None, player_id=1, game_info=game_info, game_data=game_data)
    bot._prepare_step(state=game_state, proto_game_info=raw_game_info)

    return bot
Esempio n. 3
0
def get_map_specific_bots() -> Iterable[BotAI]:
    folder = os.path.dirname(__file__)
    subfolder_name = "pickle_data"
    pickle_folder_path = os.path.join(folder, subfolder_name)
    files = os.listdir(pickle_folder_path)
    for file in (f for f in files if f.endswith(".xz")):
        with lzma.open(os.path.join(folder, subfolder_name, file), "rb") as f:
            raw_game_data, raw_game_info, raw_observation = pickle.load(f)

        # Build fresh bot object, and load the pickle'd data into the bot object
        bot = BotAI()
        game_data = GameData(raw_game_data.data)
        game_info = GameInfo(raw_game_info.game_info)
        game_state = GameState(raw_observation)
        bot._initialize_variables()
        bot._prepare_start(client=None, player_id=1, game_info=game_info, game_data=game_data)
        bot._prepare_step(state=game_state, proto_game_info=raw_game_info)

        yield bot
Esempio n. 4
0
class Creeper:
    """Spread creep."""

    def __init__(
        self, raw_game_data: Any, raw_game_info: Any, raw_observation: Any
    ) -> None:
        """
        Set up variables for use within Creeper.

        Args:
            raw_game_data (Any): self.game_data from main instance
            raw_game_info (Any): self.game_info from main instance
            raw_observation (Any): self.game_state from main instance

        Returns:
            None
        """
        self.bot = BotAI()
        game_data = GameData(raw_game_data.data)
        game_info = GameInfo(raw_game_info.game_info)
        game_state = GameState(raw_observation)
        self.bot._initialize_variables()
        self.bot._prepare_start(
            client=None, player_id=1, game_info=game_info, game_data=game_data
        )
        self.bot._prepare_step(state=game_state, proto_game_info=raw_game_info)
        self.pathing = PathManager(raw_game_data, raw_game_info, raw_observation)
        self.pf = PathFind(self.pathing.map_grid)

    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 find_position(
        self,
        tumor: Unit,
        tumor_positions: Set[Point2],
        creep_grid: Any,
        pathable_map: Any,
    ) -> Point2:
        """
        Find the location to spread the tumor to.

        Args:
            tumor (Unit): the creep tumor ready to be spread
            tumor_positions (Set[Point2]): list of existing tumor locations
            creep_grid (ndarray): the creep grid from the main bot
            pathable_map (ndarray): the pathfinding lib's pathable map

        Returns:
            Point2: where to spread the tumor.
        """
        path_creep_map = creep_grid + pathable_map
        tposx, tposy = tumor.position.x, tumor.position.y
        max_tiles = 0
        location = None
        for i in range(-10, 11):
            for j in range(-10, 11):
                if 81 <= i ** 2 + j ** 2 <= 105:
                    pos = Point2((tposx + i, tposy + j))
                    if pos not in tumor_positions:
                        if path_creep_map[floor(pos[0])][floor(pos[1])] != 2:
                            continue
                        tiles = self.check_tumor_position((pos), path_creep_map)
                        if tiles > max_tiles:
                            max_tiles = tiles
                            location = pos
        if max_tiles < 75:
            floored_unit_pos = Point2((floor(tposx), floor(tposy)))
            floored_e_base = Point2(
                (
                    floor(self.bot.enemy_start_locations[0].position.x),
                    floor(self.bot.enemy_start_locations[0].position.y),
                )
            )
            path_to_e_base = self.pf.find_path(floored_unit_pos, floored_e_base)[0]
            if path_to_e_base:
                for k in range(9, 5, -1):
                    pos = path_to_e_base[k]
                    if path_creep_map[pos[0]][pos[1]] == 2:
                        location = Point2(pos)
                        break
        if location:
            return location
        else:
            return tumor.position
Esempio n. 5
0
class PathManager:
    """Manage unit pathing."""

    def __init__(
        self, raw_game_data: Any, raw_game_info: Any, raw_observation: Any
    ) -> None:
        """
        Set up variables for use within PathMangager.

        Args:
            raw_game_data (Any): self.game_data from main instance
            raw_game_info (Any): self.game_info from main instance
            raw_observation (Any): self.game_state from main instance

        Returns:
            None
        """
        self.bot = BotAI()
        game_data = GameData(raw_game_data.data)
        game_info = GameInfo(raw_game_info.game_info)
        game_state = GameState(raw_observation)
        self.bot._initialize_variables()
        self.bot._prepare_start(
            client=None, player_id=1, game_info=game_info, game_data=game_data
        )
        self.bot._prepare_step(state=game_state, proto_game_info=raw_game_info)
        map_name = game_info.map_name
        self.pathing_dict: Dict[int, PathDict] = {}
        map_width = game_info.map_size.width
        map_height = game_info.map_size.height
        raw_grid = np.zeros((map_width, map_height))
        for x in range(map_width):
            for y in range(map_height):
                pos = Point2((x, y))
                raw_grid[x][y] = game_info.pathing_grid[pos]
        self.map_grid = np.rot90(raw_grid.astype(int))
        np.save(f"map_grids/{map_name}_grid", self.map_grid)
        self.pf = PathFind(self.map_grid)

    def add_to_path_dict(self, unit: Unit, destination: Point2) -> None:
        """
        Add unit's path to the path storage dictionary.

        Args:
            unit (Unit): the unit for pathing
            destination (Point2): where the unit is going
        Returns:
            None
        """
        self.pathing_dict[unit.tag] = {"path": [], "step": 0}
        raw_unit_pos = unit.position
        floored_unit_pos = Point2((floor(raw_unit_pos.x), floor(raw_unit_pos.y)))
        floored_dest = Point2((floor(destination[0]), floor(destination[1])))
        self.pathing_dict[unit.tag]["path"] = self.pf.find_path(
            floored_unit_pos, floored_dest
        )[0]

    def follow_path(self, unit: Unit, default: Point2) -> Point2:
        """
        Follow the path set or set a new one if none exists.

        Args:
            unit (Unit): the unit moving

        Returns:
            Point2: the location to attack
        """
        if (
            len(
                self.bot.structures.filter(
                    lambda unit: unit.type_id
                    in {UnitTypeId.NYDUSNETWORK, UnitTypeId.NYDUSCANAL}
                )
            )
            < 2
        ):
            if unit.tag not in self.pathing_dict:
                self.add_to_path_dict(unit, tuple(default))
            advance_factor = int(unit.movement_speed) + 2
            self.pathing_dict[unit.tag]["step"] += advance_factor
            curr_step = self.pathing_dict[unit.tag]["step"]
            if curr_step >= len(self.pathing_dict[unit.tag]["path"]):
                curr_step = len(self.pathing_dict[unit.tag]["path"]) - 1
            if curr_step < 0:
                return default
            a_move_to = Point2(self.pathing_dict[unit.tag]["path"][curr_step])
            if curr_step == len(self.pathing_dict[unit.tag]["path"]) - 1:
                del self.pathing_dict[unit.tag]
            return a_move_to