コード例 #1
0
ファイル: AIstate.py プロジェクト: sjb8100/freeorion
    def __split_new_fleets(self):
        """Split any new fleets.

        This function is supposed to be called once at the beginning of the turn.
        Splitting the auto generated fleets at game start or those created by
        recently built ships allows the AI to assign correct roles to all ships.
        """
        # TODO: check length of fleets for losses or do in AIstate.__cleanRoles
        universe = fo.getUniverse()
        known_fleets = self.get_fleet_roles_map()
        self.newlySplitFleets.clear()

        fleets_to_split = [fleet_id for fleet_id in FleetUtilsAI.get_empire_fleet_ids() if fleet_id not in known_fleets]
        if fleets_to_split:
            debug("Trying to split %d new fleets" % len(fleets_to_split))
        for fleet_id in fleets_to_split:
            fleet = universe.getFleet(fleet_id)
            if not fleet:
                warn("Trying to split fleet %d but seemingly does not exist" % fleet_id)
                continue
            fleet_len = len(fleet.shipIDs)
            if fleet_len == 1:
                continue
            new_fleets = FleetUtilsAI.split_fleet(fleet_id)
            debug("Split fleet %d with %d ships into %d new fleets:" % (fleet_id, fleet_len, len(new_fleets)))
コード例 #2
0
ファイル: AIstate.py プロジェクト: Vezzra/freeorion
    def __split_new_fleets(self):
        """Split any new fleets.

        This function is supposed to be called once at the beginning of the turn.
        Splitting the auto generated fleets at game start or those created by
        recently built ships allows the AI to assign correct roles to all ships.
        """
        # TODO: check length of fleets for losses or do in AIstate.__cleanRoles
        universe = fo.getUniverse()
        known_fleets = self.get_fleet_roles_map()
        self.newlySplitFleets.clear()

        fleets_to_split = [fleet_id for fleet_id in FleetUtilsAI.get_empire_fleet_ids() if fleet_id not in known_fleets]
        if fleets_to_split:
            print "Trying to split %d new fleets" % len(fleets_to_split)
        for fleet_id in fleets_to_split:
            fleet = universe.getFleet(fleet_id)
            if not fleet:
                warn("Trying to split fleet %d but seemingly does not exist" % fleet_id)
                continue
            fleet_len = len(fleet.shipIDs)
            if fleet_len == 1:
                continue
            new_fleets = FleetUtilsAI.split_fleet(fleet_id)
            print "Split fleet %d with %d ships into %d new fleets:" % (fleet_id, fleet_len, len(new_fleets))
コード例 #3
0
ファイル: AIstate.py プロジェクト: Vezzra/freeorion
 def session_start_cleanup(self):
     self.newlySplitFleets = {}
     for fleetID in FleetUtilsAI.get_empire_fleet_ids():
         self.get_fleet_role(fleetID)
         self.update_fleet_rating(fleetID)
         self.ensure_have_fleet_missions([fleetID])
     self.__clean_fleet_roles(just_resumed=True)
     fleetsLostBySystem.clear()
     empireStars.clear()
     self.qualifyingTroopBaseTargets.clear()
コード例 #4
0
ファイル: AIstate.py プロジェクト: sjb8100/freeorion
 def session_start_cleanup(self):
     self.newlySplitFleets = {}
     for fleetID in FleetUtilsAI.get_empire_fleet_ids():
         self.get_fleet_role(fleetID)
         self.update_fleet_rating(fleetID)
         self.ensure_have_fleet_missions([fleetID])
     self.__clean_fleet_roles(just_resumed=True)
     fleetsLostBySystem.clear()
     empireStars.clear()
     self.qualifyingTroopBaseTargets.clear()
コード例 #5
0
    def split_new_fleets(self):
        """Split any new fleets (at new game creation, can have unplanned mix of ship roles)."""
        universe = fo.getUniverse()
        mission_table = Table(
            [
                Text('Fleet'),
                Text('Mission'),
                Text('Ships'),
                Float('Rating'),
                Float('Troops'),
                Text('Target')
            ],
            table_name="Turn %d: Fleet Mission Review from Last Turn" %
            fo.currentTurn())
        for fleet_id, mission in self.get_fleet_missions_map().items():
            fleet = universe.getFleet(fleet_id)
            if not fleet:
                continue
            if not mission:
                mission_table.add_row([fleet])
            else:
                mission_table.add_row([
                    fleet, mission.type or "None",
                    len(fleet.shipIDs),
                    CombatRatingsAI.get_fleet_rating(fleet_id),
                    FleetUtilsAI.count_troops_in_fleet(fleet_id),
                    mission.target or "-"
                ])
        mission_table.print_table()
        # TODO: check length of fleets for losses or do in AIstat.__cleanRoles
        known_fleets = self.get_fleet_roles_map()
        self.newlySplitFleets.clear()

        fleets_to_split = [
            fleet_id for fleet_id in FleetUtilsAI.get_empire_fleet_ids()
            if fleet_id not in known_fleets
        ]

        if fleets_to_split:
            print "Splitting new fleets"
            for fleet_id in fleets_to_split:
                fleet = universe.getFleet(fleet_id)
                if not fleet:
                    print >> sys.stderr, "After splitting fleet: resulting fleet ID %d appears to not exist" % fleet_id
                    continue
                fleet_len = len(list(fleet.shipIDs))
                if fleet_len == 1:
                    continue
                new_fleets = FleetUtilsAI.split_fleet(
                    fleet_id)  # try splitting fleet
                print "\t from splitting fleet ID %4d with %d ships, got %d new fleets:" % (
                    fleet_id, fleet_len, len(new_fleets))
コード例 #6
0
    def refresh(self):
        """Turn start AIstate cleanup/refresh."""
        universe = fo.getUniverse()
        # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
        fleetsLostBySystem.clear()
        invasionTargets[:] = []
        exploration_center = PlanetUtilsAI.get_capital_sys_id()
        # a bad state probably from an old savegame, or else empire has lost (or almost has)
        if exploration_center == INVALID_ID:
            exploration_center = self.__origin_home_system_id

        for system_id, info in sorted(self.systemStatus.items()):
            self.systemStatus[system_id][
                'enemy_ship_count'] = 0  # clear now in prep for update_system_status()
        ExplorationAI.graph_flags.clear()
        if fo.currentTurn() < 50:
            print "-------------------------------------------------"
            print "Border Exploration Update (relative to %s)" % (
                PlanetUtilsAI.sys_name_ids([exploration_center, INVALID_ID
                                            ])[0])
            print "-------------------------------------------------"
        if self.visBorderSystemIDs == {INVALID_ID}:
            self.visBorderSystemIDs.clear()
            self.visBorderSystemIDs.add(exploration_center)
        for sys_id in list(self.visBorderSystemIDs
                           ):  # This set is modified during iteration.
            if fo.currentTurn() < 50:
                print "Considering border system %s" % (
                    PlanetUtilsAI.sys_name_ids([sys_id, INVALID_ID])[0])
            ExplorationAI.follow_vis_system_connections(
                sys_id, exploration_center)
        newly_explored = ExplorationAI.update_explored_systems()
        nametags = []
        for sys_id in newly_explored:
            newsys = universe.getSystem(sys_id)
            # an explored system *should* always be able to be gotten
            nametags.append("ID:%4d -- %-20s" %
                            (sys_id,
                             (newsys and newsys.name) or "name unknown"))
        if newly_explored:
            print "-------------------------------------------------"
            print "Newly explored systems:\n%s" % "\n".join(nametags)
            print "-------------------------------------------------"
        # cleanup fleet roles
        # self.update_fleet_locs()
        self.__clean_fleet_roles()
        self.__clean_fleet_missions(FleetUtilsAI.get_empire_fleet_ids())
        print "Fleets lost by system: %s" % fleetsLostBySystem
        self.update_system_status()
コード例 #7
0
ファイル: AIstate.py プロジェクト: TheSilentOne1/freeorion
    def refresh(self):
        """Turn start AIstate cleanup/refresh."""
        universe = fo.getUniverse()
        # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
        fleetsLostBySystem.clear()
        invasionTargets[:] = []
        exploration_center = PlanetUtilsAI.get_capital_sys_id()
        if exploration_center == -1:  # a bad state probably from an old savegame, or else empire has lost (or almost has)
            exploration_center = self.__origin_home_system_id

        # check if planets in cache is still present. Remove destroyed.
        for system_id, info in sorted(self.systemStatus.items()):
            planet_dict = info.get('planets', {})
            cache_planet_set = set(planet_dict)
            system_planet_set = set(universe.getSystem(system_id).planetIDs)
            diff = cache_planet_set - system_planet_set
            if diff:
                print "Removing destroyed planets from systemStatus for system %s: planets to be removed: %s" % (system_id, sorted(diff))
                for key in diff:
                    del planet_dict[key]

        ExplorationAI.graphFlags.clear()
        if fo.currentTurn() < 50:
            print "-------------------------------------------------"
            print "Border Exploration Update (relative to %s)" % (PlanetUtilsAI.sys_name_ids([exploration_center, -1])[0])
            print "-------------------------------------------------"
        if self.visBorderSystemIDs.keys() == [-1]:
            self.visBorderSystemIDs.clear()
            self.visBorderSystemIDs[exploration_center] = 1
        for sys_id in self.visBorderSystemIDs.keys():  # This dict modified during iteration.
            if fo.currentTurn() < 50:
                print "Considering border system %s" % (PlanetUtilsAI.sys_name_ids([sys_id, -1])[0])
            ExplorationAI.follow_vis_system_connections(sys_id, exploration_center)
        newly_explored = ExplorationAI.update_explored_systems()
        nametags = []
        for sys_id in newly_explored:
            newsys = universe.getSystem(sys_id)
            nametags.append("ID:%4d -- %-20s" % (sys_id, (newsys and newsys.name) or "name unknown"))  # an explored system *should* always be able to be gotten
        if newly_explored:
            print "-------------------------------------------------"
            print "Newly explored systems:\n%s" % "\n".join(nametags)
            print "-------------------------------------------------"
        # cleanup fleet roles
        # self.update_fleet_locs()
        self.__clean_fleet_roles()
        self.__clean_fleet_missions(FleetUtilsAI.get_empire_fleet_ids())
        print "Fleets lost by system: %s" % fleetsLostBySystem
        self.update_system_status()
コード例 #8
0
ファイル: AIstate.py プロジェクト: MatGB/freeorion
 def session_start_cleanup(self):
     self.newlySplitFleets = {}
     for fleetID in FleetUtilsAI.get_empire_fleet_ids():
         self.get_fleet_role(fleetID)
         self.update_fleet_rating(fleetID)
         self.ensure_have_fleet_missions([fleetID])
     self.__clean_fleet_roles(just_resumed=True)
     fleetsLostBySystem.clear()
     popCtrSystemIDs[:] = []  # resets without detroying existing references
     colonizedSystems.clear()
     empireStars.clear()
     popCtrIDs[:] = []
     outpostIDs[:] = []
     outpostSystemIDs[:] = []
     ResourcesAI.lastFociCheck[0] = 0
     self.qualifyingColonyBaseTargets.clear()
     self.qualifyingOutpostBaseTargets.clear()
     self.qualifyingTroopBaseTargets.clear()
コード例 #9
0
 def session_start_cleanup(self):
     self.newlySplitFleets = {}
     for fleetID in FleetUtilsAI.get_empire_fleet_ids():
         self.get_fleet_role(fleetID)
         self.update_fleet_rating(fleetID)
         self.ensure_have_fleet_missions([fleetID])
     self.__clean_fleet_roles(just_resumed=True)
     fleetsLostBySystem.clear()
     popCtrSystemIDs[:] = []  # resets without detroying existing references
     colonizedSystems.clear()
     empireStars.clear()
     popCtrIDs[:] = []
     outpostIDs[:] = []
     outpostSystemIDs[:] = []
     ResourcesAI.lastFociCheck[0] = 0
     self.qualifyingColonyBaseTargets.clear()
     self.qualifyingOutpostBaseTargets.clear()
     self.qualifyingTroopBaseTargets.clear()
コード例 #10
0
ファイル: AIstate.py プロジェクト: Vezzra/freeorion
    def __clean_fleet_missions(self):
        """Assign a new dummy mission to new fleets and clean up existing, now invalid missions."""
        current_empire_fleets = FleetUtilsAI.get_empire_fleet_ids()

        # assign a new (dummy) mission to new fleets
        for fleet_id in current_empire_fleets:
            if self.get_fleet_mission(fleet_id) is None:
                self.__add_fleet_mission(fleet_id)

        # Check all fleet missions for validity and clear invalid targets.
        # If a fleet does not exist anymore, mark mission for deletion.
        # Deleting only after the loop allows us to avoid an expensive copy.
        deleted_fleet_ids = []
        for mission in self.get_all_fleet_missions():
            if mission.fleet.id not in current_empire_fleets:
                deleted_fleet_ids.append(mission.fleet.id)
            else:
                mission.clean_invalid_targets()
        for deleted_fleet_id in deleted_fleet_ids:
            self.__remove_fleet_mission(deleted_fleet_id)
コード例 #11
0
ファイル: AIstate.py プロジェクト: sjb8100/freeorion
    def __clean_fleet_missions(self):
        """Assign a new dummy mission to new fleets and clean up existing, now invalid missions."""
        current_empire_fleets = FleetUtilsAI.get_empire_fleet_ids()

        # assign a new (dummy) mission to new fleets
        for fleet_id in current_empire_fleets:
            if self.get_fleet_mission(fleet_id) is None:
                self.__add_fleet_mission(fleet_id)

        # Check all fleet missions for validity and clear invalid targets.
        # If a fleet does not exist anymore, mark mission for deletion.
        # Deleting only after the loop allows us to avoid an expensive copy.
        deleted_fleet_ids = []
        for mission in self.get_all_fleet_missions():
            if mission.fleet.id not in current_empire_fleets:
                deleted_fleet_ids.append(mission.fleet.id)
            else:
                mission.clean_invalid_targets()
        for deleted_fleet_id in deleted_fleet_ids:
            self.__remove_fleet_mission(deleted_fleet_id)
コード例 #12
0
ファイル: AIstate.py プロジェクト: MatGB/freeorion
    def split_new_fleets(self):
        """Split any new fleets (at new game creation, can have unplanned mix of ship roles)."""
        universe = fo.getUniverse()
        mission_table = Table([Text('Fleet'), Text('Mission'), Text('Ships'), Float('Rating'), Float('Troops'), Text('Target')],
                              table_name="Turn %d: Fleet Mission Review from Last Turn" % fo.currentTurn())
        for fleet_id, mission in self.get_fleet_missions_map().items():
            fleet = universe.getFleet(fleet_id)
            if not fleet:
                continue
            if not mission:
                mission_table.add_row([fleet])
            else:
                mission_table.add_row([
                    fleet,
                    mission.type or "None",
                    len(fleet.shipIDs),
                    CombatRatingsAI.get_fleet_rating(fleet_id),
                    FleetUtilsAI.count_troops_in_fleet(fleet_id),
                    mission.target or "-"
                ])
        mission_table.print_table()
        # TODO: check length of fleets for losses or do in AIstat.__cleanRoles
        known_fleets = self.get_fleet_roles_map()
        self.newlySplitFleets.clear()

        fleets_to_split = [fleet_id for fleet_id in FleetUtilsAI.get_empire_fleet_ids() if fleet_id not in known_fleets]

        if fleets_to_split:
            print "Splitting new fleets"
            for fleet_id in fleets_to_split:
                fleet = universe.getFleet(fleet_id)
                if not fleet:
                    print >> sys.stderr, "After splitting fleet: resulting fleet ID %d appears to not exist" % fleet_id
                    continue
                fleet_len = len(list(fleet.shipIDs))
                if fleet_len == 1:
                    continue
                new_fleets = FleetUtilsAI.split_fleet(fleet_id)  # try splitting fleet
                print "\t from splitting fleet ID %4d with %d ships, got %d new fleets:" % (fleet_id, fleet_len, len(new_fleets))
コード例 #13
0
ファイル: AIstate.py プロジェクト: MatGB/freeorion
    def refresh(self):
        """Turn start AIstate cleanup/refresh."""
        universe = fo.getUniverse()
        # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
        fleetsLostBySystem.clear()
        invasionTargets[:] = []
        exploration_center = PlanetUtilsAI.get_capital_sys_id()
        if exploration_center == INVALID_ID:  # a bad state probably from an old savegame, or else empire has lost (or almost has)
            exploration_center = self.__origin_home_system_id

        for system_id, info in sorted(self.systemStatus.items()):
            self.systemStatus[system_id]['enemy_ship_count'] = 0  # clear now in prep for update_system_status()
        ExplorationAI.graph_flags.clear()
        if fo.currentTurn() < 50:
            print "-------------------------------------------------"
            print "Border Exploration Update (relative to %s)" % (PlanetUtilsAI.sys_name_ids([exploration_center, INVALID_ID])[0])
            print "-------------------------------------------------"
        if self.visBorderSystemIDs == {INVALID_ID}:
            self.visBorderSystemIDs.clear()
            self.visBorderSystemIDs.add(exploration_center)
        for sys_id in list(self.visBorderSystemIDs):  # This set is modified during iteration.
            if fo.currentTurn() < 50:
                print "Considering border system %s" % (PlanetUtilsAI.sys_name_ids([sys_id, INVALID_ID])[0])
            ExplorationAI.follow_vis_system_connections(sys_id, exploration_center)
        newly_explored = ExplorationAI.update_explored_systems()
        nametags = []
        for sys_id in newly_explored:
            newsys = universe.getSystem(sys_id)
            nametags.append("ID:%4d -- %-20s" % (sys_id, (newsys and newsys.name) or "name unknown"))  # an explored system *should* always be able to be gotten
        if newly_explored:
            print "-------------------------------------------------"
            print "Newly explored systems:\n%s" % "\n".join(nametags)
            print "-------------------------------------------------"
        # cleanup fleet roles
        # self.update_fleet_locs()
        self.__clean_fleet_roles()
        self.__clean_fleet_missions(FleetUtilsAI.get_empire_fleet_ids())
        print "Fleets lost by system: %s" % fleetsLostBySystem
        self.update_system_status()
コード例 #14
0
    def refresh(self):
        """Turn start AIstate cleanup/refresh."""
        universe = fo.getUniverse()
        # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
        fleetsLostBySystem.clear()
        invasionTargets[:] = []
        exploration_center = PlanetUtilsAI.get_capital_sys_id()
        if exploration_center == INVALID_ID:  # a bad state probably from an old savegame, or else empire has lost (or almost has)
            exploration_center = self.__origin_home_system_id

        # check if planets in cache is still present. Remove destroyed.
        for system_id, info in sorted(self.systemStatus.items()):
            self.systemStatus[system_id][
                'enemy_ship_count'] = 0  # clear now in prep for update_system_status()
            planet_dict = info.get('planets', {})
            cache_planet_set = set(planet_dict)
            system_planet_set = set(
                *(sys.planetIDs for sys in [universe.getSystem(system_id)]
                  if sys))
            diff = cache_planet_set - system_planet_set
            if diff:
                print "Removing destroyed planets from systemStatus for system %s: planets to be removed: %s" % (
                    system_id, sorted(diff))
                for key in diff:
                    del planet_dict[key]

        ExplorationAI.graphFlags.clear()
        if fo.currentTurn() < 50:
            print "-------------------------------------------------"
            print "Border Exploration Update (relative to %s)" % (
                PlanetUtilsAI.sys_name_ids([exploration_center, INVALID_ID
                                            ])[0])
            print "-------------------------------------------------"
        if self.visBorderSystemIDs.keys() == [INVALID_ID]:
            self.visBorderSystemIDs.clear()
            self.visBorderSystemIDs[exploration_center] = 1
        for sys_id in self.visBorderSystemIDs.keys(
        ):  # This dict modified during iteration.
            if fo.currentTurn() < 50:
                print "Considering border system %s" % (
                    PlanetUtilsAI.sys_name_ids([sys_id, INVALID_ID])[0])
            ExplorationAI.follow_vis_system_connections(
                sys_id, exploration_center)
        newly_explored = ExplorationAI.update_explored_systems()
        nametags = []
        for sys_id in newly_explored:
            newsys = universe.getSystem(sys_id)
            nametags.append(
                "ID:%4d -- %-20s" %
                (sys_id, (newsys and newsys.name) or "name unknown")
            )  # an explored system *should* always be able to be gotten
        if newly_explored:
            print "-------------------------------------------------"
            print "Newly explored systems:\n%s" % "\n".join(nametags)
            print "-------------------------------------------------"
        # cleanup fleet roles
        # self.update_fleet_locs()
        self.__clean_fleet_roles()
        self.__clean_fleet_missions(FleetUtilsAI.get_empire_fleet_ids())
        print "Fleets lost by system: %s" % fleetsLostBySystem
        self.update_system_status()
コード例 #15
0
ファイル: AIstate.py プロジェクト: Vezzra/freeorion
    def __clean_fleet_roles(self, just_resumed=False):
        """Removes fleetRoles if a fleet has been lost, and update fleet Ratings."""
        universe = fo.getUniverse()
        current_empire_fleets = FleetUtilsAI.get_empire_fleet_ids()
        self.shipCount = 0
        destroyed_object_ids = universe.destroyedObjectIDs(fo.empireID())

        fleet_table = Table([
            Text('Fleet'), Float('Rating'), Float('Troops'),
            Text('Location'), Text('Destination')],
            table_name="Fleet Summary Turn %d" % fo.currentTurn()
        )
        # need to loop over a copy as entries are deleted in loop
        for fleet_id in list(self.__fleetRoleByID):
            fleet_status = self.fleetStatus.setdefault(fleet_id, {})
            rating = CombatRatingsAI.get_fleet_rating(fleet_id, self.get_standard_enemy())
            old_sys_id = fleet_status.get('sysID', -2)  # TODO: Introduce helper function instead
            fleet = universe.getFleet(fleet_id)
            if fleet:
                sys_id = fleet.systemID
                if old_sys_id in [-2, -1]:
                    old_sys_id = sys_id
                fleet_status['nships'] = len(fleet.shipIDs)  # TODO: Introduce helper function instead
                self.shipCount += fleet_status['nships']
            else:
                # can still retrieve a fleet object even if fleet was just destroyed, so shouldn't get here
                # however,this has been observed happening, and is the reason a fleet check was added a few lines below.
                # Not at all sure how this came about, but was throwing off threat assessments
                sys_id = old_sys_id

            # check if fleet is destroyed and if so, delete stored information
            if fleet_id not in current_empire_fleets:  # or fleet.empty:
                # TODO(Morlic): Is this condition really correct? Seems like should actually be in destroyed object ids
                if (fleet and self.__fleetRoleByID.get(fleet_id, -1) != -1 and
                        fleet_id not in destroyed_object_ids and
                        any(ship_id not in destroyed_object_ids for ship_id in fleet.shipIDs)):
                    if not just_resumed:
                        fleetsLostBySystem.setdefault(old_sys_id, []).append(max(rating, MilitaryAI.MinThreat))

                self.delete_fleet_info(fleet_id)
                continue

            # if reached here, the fleet does still exist
            this_sys = universe.getSystem(sys_id)
            next_sys = universe.getSystem(fleet.nextSystemID)

            fleet_table.add_row([
                    fleet,
                    rating,
                    FleetUtilsAI.count_troops_in_fleet(fleet_id),
                    this_sys or 'starlane',
                    next_sys or '-',
                ])

            fleet_status['rating'] = rating
            if next_sys:
                fleet_status['sysID'] = next_sys.id
            elif this_sys:
                fleet_status['sysID'] = this_sys.id
            else:
                error("Fleet %s has no valid system." % fleet)
        info(fleet_table)
        # Next string used in charts. Don't modify it!
        print "Empire Ship Count: ", self.shipCount
        print "Empire standard fighter summary: ", CombatRatingsAI.get_empire_standard_fighter().get_stats()
        print "------------------------"
コード例 #16
0
ファイル: AIstate.py プロジェクト: MatGB/freeorion
    def __clean_fleet_roles(self, just_resumed=False):
        """Removes fleetRoles if a fleet has been lost, and update fleet Ratings."""
        for sys_id in self.systemStatus:
            self.systemStatus[sys_id]['myFleetRating'] = 0
            self.systemStatus[sys_id]['myFleetRatingVsPlanets'] = 0

        universe = fo.getUniverse()
        ok_fleets = FleetUtilsAI.get_empire_fleet_ids()
        fleet_list = sorted(list(self.__fleetRoleByID))
        ship_count = 0
        destroyed_object_ids = universe.destroyedObjectIDs(fo.empireID())

        fleet_table = Table([
            Text('Fleet'), Float('Rating'), Float('Troops'),
            Text('Location'), Text('Destination')],
            table_name="Fleet Summary Turn %d" % fo.currentTurn()
        )
        for fleet_id in fleet_list:
            status = self.fleetStatus.setdefault(fleet_id, {})
            rating = CombatRatingsAI.get_fleet_rating(fleet_id, self.get_standard_enemy())
            troops = FleetUtilsAI.count_troops_in_fleet(fleet_id)
            old_sys_id = status.get('sysID', -2)
            fleet = universe.getFleet(fleet_id)
            if fleet:
                sys_id = fleet.systemID
                if old_sys_id in [-2, -1]:
                    old_sys_id = sys_id
                status['nships'] = len(fleet.shipIDs)
                ship_count += status['nships']
            else:
                sys_id = old_sys_id  # can still retrieve a fleet object even if fleet was just destroyed, so shouldn't get here
                # however,this has been observed happening, and is the reason a fleet check was added a few lines below.
                # Not at all sure how this came about, but was throwing off threat assessments
            if fleet_id not in ok_fleets:  # or fleet.empty:
                if (fleet and self.__fleetRoleByID.get(fleet_id, -1) != -1 and fleet_id not in destroyed_object_ids and
                                [ship_id for ship_id in fleet.shipIDs if ship_id not in destroyed_object_ids]):
                    if not just_resumed:
                        fleetsLostBySystem.setdefault(old_sys_id, []).append(max(rating, MilitaryAI.MinThreat))
                if fleet_id in self.__fleetRoleByID:
                    del self.__fleetRoleByID[fleet_id]
                if fleet_id in self.__aiMissionsByFleetID:
                    del self.__aiMissionsByFleetID[fleet_id]
                if fleet_id in self.fleetStatus:
                    del self.fleetStatus[fleet_id]
                continue
            else:  # fleet in ok fleets
                this_sys = universe.getSystem(sys_id)
                next_sys = universe.getSystem(fleet.nextSystemID)

                fleet_table.add_row(
                    [
                        fleet,
                        rating,
                        troops,
                        this_sys or 'starlane',
                        next_sys or '-',
                    ])

                status['rating'] = rating
                if next_sys:
                    status['sysID'] = next_sys.id
                elif this_sys:
                    status['sysID'] = this_sys.id
                else:
                    main_mission = self.get_fleet_mission(fleet_id)
                    main_mission_type = (main_mission.getAIMissionTypes() + [-1])[0]
                    if main_mission_type != -1:
                        targets = main_mission.getAITargets(main_mission_type)
                        if targets:
                            m_mt0 = targets[0]
                            if isinstance(m_mt0.target_type, System):
                                status['sysID'] = m_mt0.target.id  # hmm, but might still be a fair ways from here
        fleet_table.print_table()
        self.shipCount = ship_count
        # Next string used in charts. Don't modify it!
        print "Empire Ship Count: ", ship_count
        print "Empire standard fighter summary: ", CombatRatingsAI.get_empire_standard_fighter().get_stats()
        print "------------------------"
コード例 #17
0
    def __clean_fleet_roles(self, just_resumed=False):
        """Removes fleetRoles if a fleet has been lost, and update fleet Ratings."""
        for sys_id in self.systemStatus:
            self.systemStatus[sys_id]['myFleetRating'] = 0
            self.systemStatus[sys_id]['myFleetRatingVsPlanets'] = 0

        universe = fo.getUniverse()
        ok_fleets = FleetUtilsAI.get_empire_fleet_ids()
        fleet_list = sorted(list(self.__fleetRoleByID))
        ship_count = 0
        destroyed_object_ids = universe.destroyedObjectIDs(fo.empireID())

        fleet_table = Table([
            Text('Fleet'),
            Float('Rating'),
            Float('Troops'),
            Text('Location'),
            Text('Destination')
        ],
                            table_name="Fleet Summary Turn %d" %
                            fo.currentTurn())
        for fleet_id in fleet_list:
            status = self.fleetStatus.setdefault(fleet_id, {})
            rating = CombatRatingsAI.get_fleet_rating(
                fleet_id, self.get_standard_enemy())
            troops = FleetUtilsAI.count_troops_in_fleet(fleet_id)
            old_sys_id = status.get('sysID', -2)
            fleet = universe.getFleet(fleet_id)
            if fleet:
                sys_id = fleet.systemID
                if old_sys_id in [-2, -1]:
                    old_sys_id = sys_id
                status['nships'] = len(fleet.shipIDs)
                ship_count += status['nships']
            else:
                # can still retrieve a fleet object even if fleet was just destroyed, so shouldn't get here
                # however,this has been observed happening, and is the reason a fleet check was added a few lines below.
                # Not at all sure how this came about, but was throwing off threat assessments
                sys_id = old_sys_id
            if fleet_id not in ok_fleets:  # or fleet.empty:
                if (fleet and self.__fleetRoleByID.get(fleet_id, -1) != -1
                        and fleet_id not in destroyed_object_ids
                        and any(ship_id not in destroyed_object_ids
                                for ship_id in fleet.shipIDs)):
                    if not just_resumed:
                        fleetsLostBySystem.setdefault(old_sys_id, []).append(
                            max(rating, MilitaryAI.MinThreat))
                if fleet_id in self.__fleetRoleByID:
                    del self.__fleetRoleByID[fleet_id]
                if fleet_id in self.__aiMissionsByFleetID:
                    del self.__aiMissionsByFleetID[fleet_id]
                if fleet_id in self.fleetStatus:
                    del self.fleetStatus[fleet_id]
                continue
            else:  # fleet in ok fleets
                this_sys = universe.getSystem(sys_id)
                next_sys = universe.getSystem(fleet.nextSystemID)

                fleet_table.add_row([
                    fleet,
                    rating,
                    troops,
                    this_sys or 'starlane',
                    next_sys or '-',
                ])

                status['rating'] = rating
                if next_sys:
                    status['sysID'] = next_sys.id
                elif this_sys:
                    status['sysID'] = this_sys.id
                else:
                    main_mission = self.get_fleet_mission(fleet_id)
                    main_mission_type = (main_mission.getAIMissionTypes() +
                                         [-1])[0]
                    if main_mission_type != -1:
                        targets = main_mission.getAITargets(main_mission_type)
                        if targets:
                            m_mt0 = targets[0]
                            if isinstance(m_mt0.target_type, System):
                                status[
                                    'sysID'] = m_mt0.target.id  # hmm, but might still be a fair ways from here
        fleet_table.print_table()
        self.shipCount = ship_count
        # Next string used in charts. Don't modify it!
        print "Empire Ship Count: ", ship_count
        print "Empire standard fighter summary: ", CombatRatingsAI.get_empire_standard_fighter(
        ).get_stats()
        print "------------------------"
コード例 #18
0
ファイル: AIstate.py プロジェクト: sjb8100/freeorion
    def __clean_fleet_roles(self, just_resumed=False):
        """Removes fleetRoles if a fleet has been lost, and update fleet Ratings."""
        universe = fo.getUniverse()
        current_empire_fleets = FleetUtilsAI.get_empire_fleet_ids()
        self.shipCount = 0
        destroyed_object_ids = universe.destroyedObjectIDs(fo.empireID())

        fleet_table = Table([
            Text('Fleet'), Float('Rating'), Float('Troops'),
            Text('Location'), Text('Destination')],
            table_name="Fleet Summary Turn %d" % fo.currentTurn()
        )
        # need to loop over a copy as entries are deleted in loop
        for fleet_id in list(self.__fleetRoleByID):
            fleet_status = self.fleetStatus.setdefault(fleet_id, {})
            rating = CombatRatingsAI.get_fleet_rating(fleet_id, self.get_standard_enemy())
            old_sys_id = fleet_status.get('sysID', -2)  # TODO: Introduce helper function instead
            fleet = universe.getFleet(fleet_id)
            if fleet:
                sys_id = fleet.systemID
                if old_sys_id in [-2, -1]:
                    old_sys_id = sys_id
                fleet_status['nships'] = len(fleet.shipIDs)  # TODO: Introduce helper function instead
                self.shipCount += fleet_status['nships']
            else:
                # can still retrieve a fleet object even if fleet was just destroyed, so shouldn't get here
                # however,this has been observed happening, and is the reason a fleet check was added a few lines below.
                # Not at all sure how this came about, but was throwing off threat assessments
                sys_id = old_sys_id

            # check if fleet is destroyed and if so, delete stored information
            if fleet_id not in current_empire_fleets:  # or fleet.empty:
                # TODO(Morlic): Is this condition really correct? Seems like should actually be in destroyed object ids
                if (fleet and self.__fleetRoleByID.get(fleet_id, -1) != -1 and
                        fleet_id not in destroyed_object_ids and
                        any(ship_id not in destroyed_object_ids for ship_id in fleet.shipIDs)):
                    if not just_resumed:
                        fleetsLostBySystem.setdefault(old_sys_id, []).append(max(rating, MilitaryAI.MinThreat))

                self.delete_fleet_info(fleet_id)
                continue

            # if reached here, the fleet does still exist
            this_sys = universe.getSystem(sys_id)
            next_sys = universe.getSystem(fleet.nextSystemID)

            fleet_table.add_row([
                    fleet,
                    rating,
                    FleetUtilsAI.count_troops_in_fleet(fleet_id),
                    this_sys or 'starlane',
                    next_sys or '-',
                ])

            fleet_status['rating'] = rating
            if next_sys:
                fleet_status['sysID'] = next_sys.id
            elif this_sys:
                fleet_status['sysID'] = this_sys.id
            else:
                error("Fleet %s has no valid system." % fleet)
        info(fleet_table)
        # Next string used in charts. Don't modify it!
        debug("Empire Ship Count: %s" % self.shipCount)
        debug("Empire standard fighter summary: %s", (CombatRatingsAI.get_empire_standard_fighter().get_stats(), ))
        debug("------------------------")