当前位置: 首页>>代码示例>>Python>>正文


Python CombatRatingsAI类代码示例

本文整理汇总了Python中CombatRatingsAI的典型用法代码示例。如果您正苦于以下问题:Python CombatRatingsAI类的具体用法?Python CombatRatingsAI怎么用?Python CombatRatingsAI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CombatRatingsAI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: merge_fleet_a_into_b

def merge_fleet_a_into_b(fleet_a_id, fleet_b_id, leave_rating=0, need_rating=0, context=""):
    universe = fo.getUniverse()
    fleet_a = universe.getFleet(fleet_a_id)
    fleet_b = universe.getFleet(fleet_b_id)
    if not fleet_a or not fleet_b:
        return 0
    system_id = fleet_a.systemID
    if fleet_b.systemID != system_id:
        return 0
    remaining_rating = CombatRatingsAI.get_fleet_rating(fleet_a_id)
    transferred_rating = 0
    for ship_id in fleet_a.shipIDs:
        this_ship = universe.getShip(ship_id)
        if not this_ship:
            continue
        this_rating = CombatRatingsAI.ShipCombatStats(ship_id).get_rating()
        remaining_rating = CombatRatingsAI.rating_needed(remaining_rating, this_rating)
        if remaining_rating < leave_rating:  # merging this would leave old fleet under minimum rating, try other ships.
            continue
        transferred = fo.issueFleetTransferOrder(ship_id, fleet_b_id)
        if transferred:
            transferred_rating = CombatRatingsAI.combine_ratings(transferred_rating, this_rating)
        else:
            print "  *** transfer of ship %4d, formerly of fleet %4d, into fleet %4d failed; %s" % (
                ship_id, fleet_a_id, fleet_b_id, (" context is %s" % context) if context else "")
        if need_rating != 0 and need_rating <= transferred_rating:
            break
    fleet_a = universe.getFleet(fleet_a_id)
    if not fleet_a or fleet_a.empty or fleet_a_id in universe.destroyedObjectIDs(fo.empireID()):
        foAI.foAIstate.delete_fleet_info(fleet_a_id)
    foAI.foAIstate.update_fleet_rating(fleet_b_id)
开发者ID:matt474,项目名称:freeorion,代码行数:31,代码来源:FleetUtilsAI.py

示例2: _portion_of_fleet_needed_here

    def _portion_of_fleet_needed_here(self):
        """Calculate the portion of the fleet needed in target system considering enemy forces."""
        # TODO check rating against planets
        if assertion_fails(self.type in COMBAT_MISSION_TYPES, msg=str(self)):
            return 0
        if assertion_fails(self.target and self.target.id != INVALID_ID, msg=str(self)):
            return 0
        system_id = self.target.id
        aistate = get_aistate()
        local_defenses = MilitaryAI.get_my_defense_rating_in_system(system_id)
        potential_threat = CombatRatingsAI.combine_ratings(
            MilitaryAI.get_system_local_threat(system_id),
            MilitaryAI.get_system_neighbor_threat(system_id)
        )
        universe = fo.getUniverse()
        system = universe.getSystem(system_id)

        # tally planetary defenses
        total_defense = total_shields = 0
        for planet_id in system.planetIDs:
            planet = universe.getPlanet(planet_id)
            total_defense += planet.currentMeterValue(fo.meterType.defense)
            total_shields += planet.currentMeterValue(fo.meterType.shield)
        planetary_ratings = total_defense * (total_shields + total_defense)
        potential_threat += planetary_ratings  # TODO: rewrite to return min rating vs planets as well

        # consider safety factor just once here rather than everywhere below
        safety_factor = aistate.character.military_safety_factor()
        potential_threat *= safety_factor

        fleet_rating = CombatRatingsAI.get_fleet_rating(self.fleet.id)
        return CombatRatingsAI.rating_needed(potential_threat, local_defenses) / float(fleet_rating)
开发者ID:adrianbroher,项目名称:freeorion,代码行数:32,代码来源:AIFleetMission.py

示例3: _calculate_threat

 def _calculate_threat(self):
     nearby_forces = CombatRatingsAI.combine_ratings(
         self._potential_support(), self.assigned_rating)
     return (
         self.threat_bias +
         + self.safety_factor * CombatRatingsAI.combine_ratings(self._local_threat(),
                                                                self._neighbor_threat()) +
         + max(0., self._potential_threat() + self._jump2_threat() - nearby_forces))
开发者ID:mel-odious,项目名称:freeorion,代码行数:8,代码来源:MilitaryAI.py

示例4: get_concentrated_tot_mil_rating

def get_concentrated_tot_mil_rating():
    """
    Give an assessment of total miltary rating as if all fleets were merged into a single mega-fleet.

    :return: a military rating value
    :rtype: float
    """
    return CombatRatingsAI.combine_ratings_list([CombatRatingsAI.get_fleet_rating(fleet_id) for fleet_id in
                                                 FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY)])
开发者ID:Vezzra,项目名称:freeorion,代码行数:9,代码来源:MilitaryAI.py

示例5: get_rating

 def get_rating(self, fleet_id, force_new=False, enemy_stats=None, against_planets=False):
     """Returns a dict with various rating info."""
     if fleet_id in self.fleetStatus and not force_new and enemy_stats is None:
         return self.fleetStatus[fleet_id].get('rating', 0)
     else:
         fleet = fo.getUniverse().getFleet(fleet_id)
         if not fleet:
             return {}  # TODO: also ensure any info for that fleet is deleted
         status = {'rating': CombatRatingsAI.get_fleet_rating(fleet_id, enemy_stats),
                   'ratingVsPlanets': CombatRatingsAI.get_fleet_rating_against_planets(fleet_id),
                   'sysID': fleet.systemID, 'nships': len(fleet.shipIDs)}
         self.fleetStatus[fleet_id] = status
         return status['rating'] if not against_planets else status['ratingVsPlanets']
开发者ID:Vezzra,项目名称:freeorion,代码行数:13,代码来源:AIstate.py

示例6: area_ratings

 def area_ratings(self, system_ids):
     """Returns (fleet_threat, max_threat, myFleetRating, threat_fleets) compiled over a group of systems."""
     myrating = threat = max_threat = 0
     threat_fleets = set()
     for sys_id in system_ids:
         sys_status = self.systemStatus.get(sys_id, {})
         # TODO: have distinct treatment for both enemy_threat and fleetThreat, respectively
         fthreat = sys_status.get('enemy_threat', 0)
         max_threat = max(max_threat, fthreat)
         threat = CombatRatingsAI.combine_ratings(threat, fthreat)
         myrating = CombatRatingsAI.combine_ratings(myrating, sys_status.get('myFleetRating', 0))
         # myrating = FleetUtilsAI.combine_ratings(myrating, sys_status.get('all_local_defenses', 0))
         threat_fleets.update(sys_status.get('local_fleet_threats', []))
     return threat, max_threat, myrating, threat_fleets
开发者ID:Vezzra,项目名称:freeorion,代码行数:14,代码来源:AIstate.py

示例7: __update_empire_standard_enemy

    def __update_empire_standard_enemy(self):
        """Update the empire's standard enemy.

        The standard enemy is the enemy that is most often seen.
        """
        # TODO: If no current information available, rate against own fighters
        universe = fo.getUniverse()
        empire_id = fo.empireID()

        # assess enemy fleets that may have been momentarily visible (start with dummy entries)
        dummy_stats = CombatRatingsAI.default_ship_stats().get_stats(hashable=True)
        cur_e_fighters = Counter()  # actual visible enemies
        old_e_fighters = Counter({dummy_stats: 0})  # destroyed enemies TODO: consider seen but out of sight enemies

        for fleet_id in universe.fleetIDs:
            fleet = universe.getFleet(fleet_id)
            if (not fleet or fleet.empty or fleet.ownedBy(empire_id) or fleet.unowned or
                    not (fleet.hasArmedShips or fleet.hasFighterShips)):
                continue

            # track old/dead enemy fighters for rating assessments in case not enough current info
            ship_stats = CombatRatingsAI.FleetCombatStats(fleet_id).get_ship_stats(hashable=True)
            dead_fleet = fleet_id in universe.destroyedObjectIDs(empire_id)
            e_f_dict = old_e_fighters if dead_fleet else cur_e_fighters
            for stats in ship_stats:
                # log only ships that are armed
                if stats[0]:
                    e_f_dict[stats] += 1

        e_f_dict = cur_e_fighters or old_e_fighters
        self.__empire_standard_enemy = sorted([(v, k) for k, v in e_f_dict.items()])[-1][1]
        self.empire_standard_enemy_rating = self.get_standard_enemy().get_rating()
开发者ID:Vezzra,项目名称:freeorion,代码行数:32,代码来源:AIstate.py

示例8: can_issue_order

    def can_issue_order(self, verbose=False):
        if not super(OrderMove, self).can_issue_order(verbose=verbose):
            return False
        # TODO: figure out better way to have invasions (& possibly colonizations) require visibility on target without needing visibility of all intermediate systems
        # if False and main_mission_type not in [MissionType.ATTACK,  # TODO: consider this later
        #                                        MissionType.MILITARY,
        #                                        MissionType.SECURE,
        #                                        MissionType.HIT_AND_RUN,
        #                                        MissionType.EXPLORATION]:
        #     if not universe.getVisibility(target_id, foAI.foAIstate.empireID) >= fo.visibility.partial:
        #         #if not target_id in interior systems
        #         foAI.foAIstate.needsEmergencyExploration.append(fleet.systemID)
        #         return False
        system_id = self.fleet.get_system().id
        if system_id == self.target.get_system().id:
            return True  # TODO: already there, but could consider retreating

        fleet_rating = CombatRatingsAI.get_fleet_rating(self.fleet.id)
        target_sys_status = foAI.foAIstate.systemStatus.get(self.target.id, {})
        f_threat = target_sys_status.get('fleetThreat', 0)
        m_threat = target_sys_status.get('monsterThreat', 0)
        p_threat = target_sys_status.get('planetThreat', 0)
        threat = f_threat + m_threat + p_threat
        safety_factor = MilitaryAI.get_safety_factor()
        universe = fo.getUniverse()
        if fleet_rating >= safety_factor * threat:
            return True
        elif not p_threat and self.target.id in fo.getEmpire().supplyUnobstructedSystems:
                    return True
        else:
            sys1 = universe.getSystem(system_id)
            sys1_name = sys1 and sys1.name or "unknown"
            target_system = self.target.get_system()
            target_system_name = (target_system and target_system.get_object().name) or "unknown"
            my_other_fleet_rating = foAI.foAIstate.systemStatus.get(self.target.id, {}).get('myFleetRating', 0)  # TODO: adjust calc for any departing fleets
            is_military = foAI.foAIstate.get_fleet_role(self.fleet.id) == MissionType.MILITARY

            total_rating = my_other_fleet_rating + fleet_rating
            if any((
                (my_other_fleet_rating > 3 * safety_factor * threat),
                (is_military and total_rating > safety_factor * threat),
                (is_military and total_rating > 0.8 * safety_factor * threat and fleet_rating > 0.2 * threat)
            )):
                if verbose:
                    print "\tAdvancing fleet %d (rating %d) at system %d (%s) into system %d (%s) with threat %d because of sufficient empire fleet strength already at destination" % (
                        self.fleet.id, fleet_rating, system_id, sys1_name, self.target.id, target_system_name, threat)
                return True
            elif threat == p_threat and not self.fleet.get_object().aggressive and not my_other_fleet_rating and not target_sys_status.get('localEnemyFleetIDs', [-1]):
                if verbose:
                    print ("\tAdvancing fleet %d (rating %d) at system %d (%s) into system %d (%s) with planet threat %d because nonaggressive" +
                           " and no other fleets present to trigger combat") % (self.fleet.id, fleet_rating, system_id, sys1_name, self.target.id, target_system_name, threat)
                return True
            else:
                if verbose:
                    print "\tHolding fleet %d (rating %d) at system %d (%s) before travelling to system %d (%s) with threat %d" % (self.fleet.id, fleet_rating, system_id, sys1_name, self.target.id, target_system_name, threat)
                needs_vis = foAI.foAIstate.misc.setdefault('needs_vis', [])
                if self.target.id not in needs_vis:
                    needs_vis.append(self.target.id)
                return False
        return True
开发者ID:TheSilentOne1,项目名称:freeorion,代码行数:60,代码来源:fleet_orders.py

示例9: __init__

    def __init__(self, aggression):
        # Do not allow to create AIstate instances with an invalid version number.
        if not hasattr(AIstate, 'version'):
            raise ConversionError("AIstate must have an integer version attribute for savegame compatibility")
        if not isinstance(AIstate.version, int):
            raise ConversionError("Version attribute of AIstate must be an integer!")
        if AIstate.version < 0:
            raise ConversionError("AIstate savegame compatibility version must be a positive integer!")
            
        # need to store the version explicitly as the class variable "version" is only stored in the 
        # self.__class__.__dict__ while we only pickle the object (i.e. self.__dict__ )
        self.version = AIstate.version
        
        # Debug info
        # unique id for game
        self.uid = self.generate_uid(first=True)
        # unique ids for turns.  {turn: uid}
        self.turn_uids = {}

        self._aggression = aggression

        # 'global' (?) variables
        self.colonisablePlanetIDs = odict()
        self.colonisableOutpostIDs = odict()  #
        self.__aiMissionsByFleetID = {}
        self.__shipRoleByDesignID = {}
        self.__fleetRoleByID = {}
        self.diplomatic_logs = {}
        self.__priorityByType = {}

        # initialize home system knowledge
        universe = fo.getUniverse()
        empire = fo.getEmpire()
        self.empireID = empire.empireID
        homeworld = universe.getPlanet(empire.capitalID)
        self.__origin_home_system_id = homeworld.systemID if homeworld else INVALID_ID
        self.visBorderSystemIDs = {self.__origin_home_system_id}
        self.visInteriorSystemIDs = set()
        self.exploredSystemIDs = set()
        self.unexploredSystemIDs = {self.__origin_home_system_id}
        self.fleetStatus = {}  # keys: 'sysID', 'nships', 'rating'
        # systemStatus keys: 'name', 'neighbors' (sysIDs), '2jump_ring' (sysIDs), '3jump_ring', '4jump_ring', 'enemy_ship_count'
        # 'fleetThreat', 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'totalThreat', 'localEnemyFleetIDs',
        # 'neighborThreat', 'max_neighbor_threat', 'jump2_threat' (up to 2 jumps away), 'jump3_threat', 'jump4_threat', 'regional_threat'
        # 'myDefenses' (planet rating), 'myfleets', 'myFleetsAccessible'(not just next desitination), 'myFleetRating'
        # 'my_neighbor_rating' (up to 1 jump away), 'my_jump2_rating', 'my_jump3_rating', my_jump4_rating'
        # 'local_fleet_threats', 'regional_fleet_threats' <== these are only for mobile fleet threats
        self.systemStatus = {}
        self.needsEmergencyExploration = []
        self.newlySplitFleets = {}
        self.militaryRating = 0
        self.shipCount = 4
        self.misc = {}
        self.qualifyingColonyBaseTargets = {}
        self.qualifyingOutpostBaseTargets = {}
        self.qualifyingTroopBaseTargets = {}
        self.__empire_standard_enemy = CombatRatingsAI.default_ship_stats().get_stats(hashable=True)  # TODO: track on a per-empire basis
        self.empire_standard_enemy_rating = 0  # TODO: track on a per-empire basis
        self.character = create_character(aggression, self.empireID)
开发者ID:MatGB,项目名称:freeorion,代码行数:59,代码来源:AIstate.py

示例10: get_tot_mil_rating

def get_tot_mil_rating():
    """
    Give an assessment of total miltary rating considering all fleets as if distributed to separate systems.

    :return: a military rating value
    :rtype: float
    """
    return sum(CombatRatingsAI.get_fleet_rating(fleet_id)
               for fleet_id in FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY))
开发者ID:Vezzra,项目名称:freeorion,代码行数:9,代码来源:MilitaryAI.py

示例11: __str__

    def __str__(self):
        fleet = self.fleet.get_object()

        fleet_id = self.fleet.id
        return "%-25s [%-11s] ships: %2d; total rating: %4d; target: %s" % (fleet,
                                                                            "NONE" if self.type is None else self.type,
                                                                            (fleet and len(fleet.shipIDs)) or 0,
                                                                            CombatRatingsAI.get_fleet_rating(fleet_id),
                                                                            self.target or 'no target')
开发者ID:adrianbroher,项目名称:freeorion,代码行数:9,代码来源:AIFleetMission.py

示例12: merge_fleet_a_into_b

def merge_fleet_a_into_b(fleet_a_id, fleet_b_id, leave_rating=0, need_rating=0, context=""):
    universe = fo.getUniverse()
    fleet_a = universe.getFleet(fleet_a_id)
    fleet_b = universe.getFleet(fleet_b_id)
    if not fleet_a or not fleet_b:
        return 0
    remaining_rating = CombatRatingsAI.get_fleet_rating(fleet_a_id)
    transferred_rating = 0
    b_has_monster = False
    for ship_id in fleet_b.shipIDs:
        this_ship = universe.getShip(ship_id)
        if not this_ship:
            continue
        if this_ship.isMonster:
            b_has_monster = True
            break
    for ship_id in fleet_a.shipIDs:
        this_ship = universe.getShip(ship_id)
        if not this_ship or this_ship.isMonster != b_has_monster:  # TODO Is there any reason for the monster check?
            continue
        this_rating = CombatRatingsAI.ShipCombatStats(ship_id).get_rating()
        remaining_rating = CombatRatingsAI.rating_needed(remaining_rating, this_rating)
        if remaining_rating < leave_rating:  # merging this would leave old fleet under minimum rating, try other ships.
            continue
        transferred = fo.issueFleetTransferOrder(ship_id, fleet_b_id)
        if transferred:
            transferred_rating = CombatRatingsAI.combine_ratings(transferred_rating, this_rating)
        else:
            print "  *** transfer of ship %4d, formerly of fleet %4d, into fleet %4d failed; %s" % (
                ship_id, fleet_a_id, fleet_b_id, [" context is %s" % context, ""][context == ""])
        if need_rating != 0 and need_rating <= transferred_rating:
            break
    fleet_a = universe.getFleet(fleet_a_id)
    if not fleet_a or fleet_a.empty or fleet_a_id in universe.destroyedObjectIDs(fo.empireID()):
        foAI.foAIstate.delete_fleet_info(fleet_a_id)
    foAI.foAIstate.update_fleet_rating(fleet_b_id)
开发者ID:Mitten-O,项目名称:freeorion,代码行数:36,代码来源:FleetUtilsAI.py

示例13: __init__

    def __init__(self, aggression):
        # Debug info
        # unique id for game
        self.uid = self.generate_uid(first=True)
        # unique ids for turns.  {turn: uid}
        self.turn_uids = {}

        # 'global' (?) variables
        self.colonisablePlanetIDs = odict()
        self.colonisableOutpostIDs = odict()  #
        self.__aiMissionsByFleetID = {}
        self.__shipRoleByDesignID = {}
        self.__fleetRoleByID = {}
        self.diplomatic_logs = {}
        self.__priorityByType = {}

        # initialize home system knowledge
        universe = fo.getUniverse()
        empire = fo.getEmpire()
        self.empireID = empire.empireID
        homeworld = universe.getPlanet(empire.capitalID)
        if homeworld:
            self.__origin_home_system_id = homeworld.systemID
        else:
            self.__origin_home_system_id = INVALID_ID
        self.visBorderSystemIDs = {self.__origin_home_system_id: 1}
        self.visInteriorSystemIDs = {}
        self.exploredSystemIDs = {}
        self.unexploredSystemIDs = {self.__origin_home_system_id: 1}
        self.fleetStatus = {}  # keys: 'sysID', 'nships', 'rating'
        # systemStatus keys: 'name', 'neighbors' (sysIDs), '2jump_ring' (sysIDs), '3jump_ring', '4jump_ring'
        # 'fleetThreat', 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'totalThreat', 'localEnemyFleetIDs',
        # 'neighborThreat', 'max_neighbor_threat', 'jump2_threat' (up to 2 jumps away), 'jump3_threat', 'jump4_threat', 'regional_threat'
        # 'myDefenses' (planet rating), 'myfleets', 'myFleetsAccessible'(not just next desitination), 'myFleetRating'
        # 'my_neighbor_rating' (up to 1 jump away), 'my_jump2_rating', 'my_jump3_rating', my_jump4_rating'
        # 'local_fleet_threats', 'regional_fleet_threats' <== these are only for mobile fleet threats
        self.systemStatus = {}
        self.needsEmergencyExploration = []
        self.newlySplitFleets = {}
        self.militaryRating = 0
        self.shipCount = 4
        self.misc = {}
        self.qualifyingColonyBaseTargets = {}
        self.qualifyingOutpostBaseTargets = {}
        self.qualifyingTroopBaseTargets = {}
        self.__empire_standard_enemy = CombatRatingsAI.default_ship_stats().get_stats(hashable=True)  # TODO: track on a per-empire basis
        self.empire_standard_enemy_rating = 0  # TODO: track on a per-empire basis
        self.character = create_character(aggression, self.empireID)
开发者ID:Mitten-O,项目名称:freeorion,代码行数:48,代码来源:AIstate.py

示例14: _maximum_allocation

    def _maximum_allocation(self, threat):
        """
        Calculate the maximum allocation for the system.

        The default maximum allocation is the missing forces
        to obtain a rating given by the threat weighted with
        the subclass' *max_alloc_factor*.
        Existing military missions are considered.

        Subclasses may choose to override this method and
        implement a different logic.

        :param float threat:
        :rtype: float
        """
        return CombatRatingsAI.rating_needed(
                self._max_alloc_factor * threat,
                self.assigned_rating)
开发者ID:mel-odious,项目名称:freeorion,代码行数:18,代码来源:MilitaryAI.py

示例15: __report_last_turn_fleet_missions

 def __report_last_turn_fleet_missions(self):
     """Print a table reviewing last turn fleet missions to the log file."""
     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 "-"
             ])
     info(mission_table)
开发者ID:Vezzra,项目名称:freeorion,代码行数:22,代码来源:AIstate.py


注:本文中的CombatRatingsAI类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。