本文整理汇总了Python中CombatRatingsAI.combine_ratings方法的典型用法代码示例。如果您正苦于以下问题:Python CombatRatingsAI.combine_ratings方法的具体用法?Python CombatRatingsAI.combine_ratings怎么用?Python CombatRatingsAI.combine_ratings使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CombatRatingsAI
的用法示例。
在下文中一共展示了CombatRatingsAI.combine_ratings方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _calculate_threat
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
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))
示例2: area_ratings
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
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
示例3: _portion_of_fleet_needed_here
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
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)
示例4: merge_fleet_a_into_b
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
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)
示例5: merge_fleet_a_into_b
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
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)
示例6: issue_fleet_orders
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
#.........这里部分代码省略.........
secure_type = "Unidentified"
debug("Fleet %d has completed initial stage of its mission "
"to secure system %d (targeted for %s), "
"may release a portion of ships" % (self.fleet.id, last_sys_target, secure_type))
clear_all = False
# for PROTECT_REGION missions, only release fleet if no more threat
if self.type == MissionType.PROTECT_REGION:
# use military logic code below to determine if can release
# any or even all of the ships.
clear_all = False
last_sys_target = self.target.id
debug("Check if PROTECT_REGION mission with target %d is finished.", last_sys_target)
fleet_id = self.fleet.id
if clear_all:
if orders:
debug("Fleet %d has completed its mission; clearing all orders and targets." % self.fleet.id)
debug("Full set of orders were:")
for this_order in orders:
debug("\t\t %s" % this_order)
self.clear_fleet_orders()
self.clear_target()
if aistate.get_fleet_role(fleet_id) in (MissionType.MILITARY, MissionType.SECURE):
allocations = MilitaryAI.get_military_fleets(mil_fleets_ids=[fleet_id],
try_reset=False,
thisround="Fleet %d Reassignment" % fleet_id)
if allocations:
MilitaryAI.assign_military_fleets_to_systems(use_fleet_id_list=[fleet_id],
allocations=allocations)
else: # no orders
debug("No Current Orders")
else:
potential_threat = CombatRatingsAI.combine_ratings(
MilitaryAI.get_system_local_threat(last_sys_target),
MilitaryAI.get_system_neighbor_threat(last_sys_target)
)
threat_present = potential_threat > 0
debug("Fleet threat present? %s", threat_present)
target_system = universe.getSystem(last_sys_target)
if not threat_present and target_system:
for pid in target_system.planetIDs:
planet = universe.getPlanet(pid)
if (planet and
planet.owner != fo.empireID() and
planet.currentMeterValue(fo.meterType.maxDefense) > 0):
debug("Found local planetary threat: %s", planet)
threat_present = True
break
if not threat_present:
debug("No current threat in target system; releasing a portion of ships.")
# at least first stage of current task is done;
# release extra ships for potential other deployments
new_fleets = FleetUtilsAI.split_fleet(self.fleet.id)
if self.type == MissionType.PROTECT_REGION:
self.clear_fleet_orders()
self.clear_target()
new_fleets.append(self.fleet.id)
else:
debug("Threat remains in target system; Considering to release some ships.")
new_fleets = []
fleet_portion_to_remain = self._portion_of_fleet_needed_here()
if fleet_portion_to_remain > 1:
debug("Can not release fleet yet due to large threat.")
elif fleet_portion_to_remain > 0:
debug("Not all ships are needed here - considering releasing a few")
示例7: can_issue_order
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
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
main_fleet_mission = foAI.foAIstate.get_fleet_mission(self.fleet.id)
fleet_rating = CombatRatingsAI.get_fleet_rating(self.fleet.id)
fleet_rating_vs_planets = CombatRatingsAI.get_fleet_rating_against_planets(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 = foAI.foAIstate.character.military_safety_factor()
universe = fo.getUniverse()
if main_fleet_mission.type == MissionType.INVASION and not trooper_move_reqs_met(main_fleet_mission,
self, verbose):
return False
if fleet_rating >= safety_factor * threat and fleet_rating_vs_planets >= p_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"
# TODO: adjust calc for any departing fleets
my_other_fleet_rating = foAI.foAIstate.systemStatus.get(self.target.id, {}).get('myFleetRating', 0)
my_other_fleet_rating_vs_planets = foAI.foAIstate.systemStatus.get(self.target.id, {}).get(
'myFleetRatingVsPlanets', 0)
is_military = foAI.foAIstate.get_fleet_role(self.fleet.id) == MissionType.MILITARY
total_rating = CombatRatingsAI.combine_ratings(my_other_fleet_rating, fleet_rating)
total_rating_vs_planets = CombatRatingsAI.combine_ratings(my_other_fleet_rating_vs_planets,
fleet_rating_vs_planets)
if (my_other_fleet_rating > 3 * safety_factor * threat or
(is_military and total_rating_vs_planets > 2.5*p_threat and total_rating > safety_factor * threat)):
debug(("\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 non aggressive"
" 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
示例8: __update_system_status
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
def __update_system_status(self):
print 10 * "=", "Updating System Threats", 10 * "="
universe = fo.getUniverse()
empire = fo.getEmpire()
empire_id = fo.empireID()
destroyed_object_ids = universe.destroyedObjectIDs(empire_id)
supply_unobstructed_systems = set(empire.supplyUnobstructedSystems)
min_hidden_attack = 4
min_hidden_health = 8
observed_empires = self.misc.setdefault("observed_empires", set())
# TODO: Variables that are recalculated each turn from scratch should not be stored in AIstate
# clear previous game state
for sys_id in self.systemStatus:
self.systemStatus[sys_id]['enemy_ship_count'] = 0
self.systemStatus[sys_id]['myFleetRating'] = 0
self.systemStatus[sys_id]['myFleetRatingVsPlanets'] = 0
# for use in debugging
verbose = False
# assess enemy fleets that may have been momentarily visible
enemies_by_system = {}
my_fleets_by_system = {}
fleet_spot_position = {}
current_turn = fo.currentTurn()
for fleet_id in universe.fleetIDs:
fleet = universe.getFleet(fleet_id)
if not fleet or fleet.empty:
self.delete_fleet_info(fleet_id) # this is safe even if fleet wasn't mine
continue
# TODO: check if currently in system and blockaded before accepting destination as location
this_system_id = fleet.nextSystemID if fleet.nextSystemID != INVALID_ID else fleet.systemID
dead_fleet = fleet_id in destroyed_object_ids
if dead_fleet:
self.delete_fleet_info(fleet_id)
if fleet.ownedBy(empire_id):
if not dead_fleet:
my_fleets_by_system.setdefault(this_system_id, []).append(fleet_id)
fleet_spot_position.setdefault(fleet.systemID, []).append(fleet_id)
continue
# TODO: consider checking death of individual ships. If ships had been moved from this fleet
# into another fleet, we might have witnessed their death in that other fleet but if this fleet
# had not been seen since before that transfer then the ships might also still be listed here.
if dead_fleet:
continue
# we are only interested in immediately recent data
if get_partial_visibility_turn(fleet_id) < (current_turn - 1):
continue
sys_status = self.systemStatus.setdefault(this_system_id, {})
sys_status['enemy_ship_count'] = sys_status.get('enemy_ship_count', 0) + len(fleet.shipIDs)
enemies_by_system.setdefault(this_system_id, []).append(fleet_id)
if not fleet.unowned:
self.misc.setdefault('enemies_sighted', {}).setdefault(current_turn, []).append(fleet_id)
observed_empires.add(fleet.owner)
# assess fleet and planet threats & my local fleets
for sys_id in universe.systemIDs:
sys_status = self.systemStatus.setdefault(sys_id, {})
system = universe.getSystem(sys_id)
if verbose:
print "AIState threat evaluation for %s" % system
# update fleets
sys_status['myfleets'] = my_fleets_by_system.get(sys_id, [])
sys_status['myFleetsAccessible'] = fleet_spot_position.get(sys_id, [])
local_enemy_fleet_ids = enemies_by_system.get(sys_id, [])
sys_status['localEnemyFleetIDs'] = local_enemy_fleet_ids
if system:
sys_status['name'] = system.name
# update threats
monster_ratings = [] # immobile
enemy_ratings = [] # owned & mobile
mob_ratings = [] # mobile & unowned
mobile_fleets = [] # mobile and either owned or unowned
for fid in local_enemy_fleet_ids:
fleet = universe.getFleet(fid) # ensured to exist
fleet_rating = CombatRatingsAI.get_fleet_rating(
fid, enemy_stats=CombatRatingsAI.get_empire_standard_fighter())
if fleet.speed == 0:
monster_ratings.append(fleet_rating)
if verbose:
print "\t immobile enemy fleet %s has rating %.1f" % (fleet, fleet_rating)
continue
if verbose:
print "\t mobile enemy fleet %s has rating %.1f" % (fleet, fleet_rating)
mobile_fleets.append(fid)
if fleet.unowned:
mob_ratings.append(fleet_rating)
else:
enemy_ratings.append(fleet_rating)
enemy_rating = CombatRatingsAI.combine_ratings_list(enemy_ratings)
monster_rating = CombatRatingsAI.combine_ratings_list(monster_ratings)
#.........这里部分代码省略.........
示例9: update_system_status
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
#.........这里部分代码省略.........
if fid in destroyed_object_ids: # TODO: double check are these checks/deletes necessary?
self.delete_fleet_info(fid) # this is safe even if fleet wasn't mine
continue
fleet = universe.getFleet(fid)
if not fleet or fleet.empty:
self.delete_fleet_info(fid) # this is safe even if fleet wasn't mine
continue
# update threats
sys_vis_dict = universe.getVisibilityTurnsMap(sys_id, fo.empireID())
partial_vis_turn = sys_vis_dict.get(fo.visibility.partial, -9999)
mob_ratings = [] # for mobile unowned monster fleets
lost_fleet_rating = 0
enemy_ratings = []
monster_ratings = []
mobile_fleets = []
for fid in local_enemy_fleet_ids:
fleet = universe.getFleet(fid)
if not fleet:
continue
fleet_rating = CombatRatingsAI.get_fleet_rating(fid, enemy_stats=CombatRatingsAI.get_empire_standard_fighter())
if fleet.speed == 0:
monster_ratings.append(fleet_rating)
if verbose:
print "\t immobile enemy fleet %s has rating %.1f" % (fleet, fleet_rating)
else:
if verbose:
print "\t mobile enemy fleet %s has rating %.1f" % (fleet, fleet_rating)
mobile_fleets.append(fid)
if fleet.unowned:
mob_ratings.append(fleet_rating)
else:
enemy_ratings.append(fleet_rating)
enemy_rating = CombatRatingsAI.combine_ratings_list(enemy_ratings)
monster_rating = CombatRatingsAI.combine_ratings_list(monster_ratings)
mob_rating = CombatRatingsAI.combine_ratings_list(mob_ratings)
if fleetsLostBySystem.get(sys_id, []):
lost_fleet_rating = CombatRatingsAI.combine_ratings_list(fleetsLostBySystem[sys_id])
if not system or partial_vis_turn == -9999: # under current visibility rules should not be possible to have any losses or other info here, but just in case...
if verbose:
print "Have never had partial vis for system %d ( %s ) -- basing threat assessment on old info and lost ships" % (sys_id, sys_status.get('name', "name unknown"))
sys_status.setdefault('local_fleet_threats', set())
sys_status['planetThreat'] = 0
sys_status['fleetThreat'] = int(max(CombatRatingsAI.combine_ratings(enemy_rating, mob_rating), 0.98 * sys_status.get('fleetThreat', 0), 1.1 * lost_fleet_rating - monster_rating))
sys_status['monsterThreat'] = int(max(monster_rating, 0.98 * sys_status.get('monsterThreat', 0), 1.1 * lost_fleet_rating - enemy_rating - mob_rating))
sys_status['enemy_threat'] = int(max(enemy_rating, 0.98 * sys_status.get('enemy_threat', 0), 1.1 * lost_fleet_rating - monster_rating - mob_rating))
sys_status['mydefenses'] = {'overall': 0, 'attack': 0, 'health': 0}
sys_status['totalThreat'] = sys_status['fleetThreat']
sys_status['regional_fleet_threats'] = sys_status['local_fleet_threats'].copy()
continue
# have either stale or current info
pattack = 0
phealth = 0
mypattack, myphealth = 0, 0
for pid in system.planetIDs:
prating = self.assess_planet_threat(pid, sighting_age=current_turn - partial_vis_turn)
planet = universe.getPlanet(pid)
if not planet:
continue
if planet.owner == self.empireID: # TODO: check for diplomatic status
mypattack += prating['attack']
myphealth += prating['health']
else:
if [special for special in planet.specials if "_NEST_" in special]:
sys_status['nest_threat'] = 100
示例10: get_military_fleets
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
def get_military_fleets(mil_fleets_ids=None, try_reset=True, thisround="Main"):
"""Get armed military fleets."""
global _military_allocations
universe = fo.getUniverse()
empire_id = fo.empireID()
home_system_id = PlanetUtilsAI.get_capital_sys_id()
all_military_fleet_ids = (mil_fleets_ids if mil_fleets_ids is not None
else FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY))
if try_reset and (fo.currentTurn() + empire_id) % 30 == 0 and thisround == "Main":
try_again(all_military_fleet_ids, try_reset=False, thisround=thisround + " Reset")
return
mil_fleets_ids = list(FleetUtilsAI.extract_fleet_ids_without_mission_types(all_military_fleet_ids))
mil_needing_repair_ids, mil_fleets_ids = avail_mil_needing_repair(mil_fleets_ids, split_ships=True)
avail_mil_rating = sum(map(CombatRatingsAI.get_fleet_rating, mil_fleets_ids))
if not mil_fleets_ids:
if "Main" in thisround:
_military_allocations = []
return []
# for each system, get total rating of fleets assigned to it
already_assigned_rating = {}
systems_status = foAI.foAIstate.systemStatus
enemy_sup_factor = {} # enemy supply
for sys_id in universe.systemIDs:
already_assigned_rating[sys_id] = 0
enemy_sup_factor[sys_id] = min(2, len(systems_status.get(sys_id, {}).get('enemies_nearly_supplied', [])))
for fleet_id in [fid for fid in all_military_fleet_ids if fid not in mil_fleets_ids]:
ai_fleet_mission = foAI.foAIstate.get_fleet_mission(fleet_id)
if not ai_fleet_mission.target: # shouldn't really be possible
continue
last_sys = ai_fleet_mission.target.get_system().id # will count this fleet as assigned to last system in target list # TODO last_sys or target sys?
this_rating = CombatRatingsAI.get_fleet_rating(fleet_id)
already_assigned_rating[last_sys] = CombatRatingsAI.combine_ratings(already_assigned_rating.get(last_sys, 0), this_rating)
for sys_id in universe.systemIDs:
my_defense_rating = systems_status.get(sys_id, {}).get('mydefenses', {}).get('overall', 0)
already_assigned_rating[sys_id] = CombatRatingsAI.combine_ratings(my_defense_rating, already_assigned_rating[sys_id])
if _verbose_mil_reporting and already_assigned_rating[sys_id]:
print "\t System %s already assigned rating %.1f" % (
universe.getSystem(sys_id), already_assigned_rating[sys_id])
# get systems to defend
capital_id = PlanetUtilsAI.get_capital()
if capital_id is not None:
capital_planet = universe.getPlanet(capital_id)
else:
capital_planet = None
# TODO: if no owned planets try to capture one!
if capital_planet:
capital_sys_id = capital_planet.systemID
else: # should be rare, but so as to not break code below, pick a randomish mil-centroid system
capital_sys_id = None # unless we can find one to use
system_dict = {}
for fleet_id in all_military_fleet_ids:
status = foAI.foAIstate.fleetStatus.get(fleet_id, None)
if status is not None:
sys_id = status['sysID']
if not list(universe.getSystem(sys_id).planetIDs):
continue
system_dict[sys_id] = system_dict.get(sys_id, 0) + status.get('rating', 0)
ranked_systems = sorted([(val, sys_id) for sys_id, val in system_dict.items()])
if ranked_systems:
capital_sys_id = ranked_systems[-1][-1]
else:
try:
capital_sys_id = foAI.foAIstate.fleetStatus.items()[0][1]['sysID']
except:
pass
num_targets = max(10, PriorityAI.allotted_outpost_targets)
top_target_planets = ([pid for pid, pscore, trp in AIstate.invasionTargets[:PriorityAI.allottedInvasionTargets] if pscore > 20] +
[pid for pid, (pscore, spec) in foAI.foAIstate.colonisableOutpostIDs.items()[:num_targets] if pscore > 20] +
[pid for pid, (pscore, spec) in foAI.foAIstate.colonisablePlanetIDs.items()[:num_targets] if pscore > 20])
top_target_planets.extend(foAI.foAIstate.qualifyingTroopBaseTargets.keys())
base_col_target_systems = PlanetUtilsAI.get_systems(top_target_planets)
top_target_systems = []
for sys_id in AIstate.invasionTargetedSystemIDs + base_col_target_systems:
if sys_id not in top_target_systems:
if foAI.foAIstate.systemStatus[sys_id]['totalThreat'] > get_tot_mil_rating():
continue
top_target_systems.append(sys_id) # doing this rather than set, to preserve order
try:
# capital defense
allocation_helper = AllocationHelper(already_assigned_rating, avail_mil_rating, try_reset)
if capital_sys_id is not None:
CapitalDefenseAllocator(capital_sys_id, allocation_helper).allocate()
# defend other planets
empire_planet_ids = PlanetUtilsAI.get_owned_planets_by_empire(universe.planetIDs)
empire_occupied_system_ids = list(set(PlanetUtilsAI.get_systems(empire_planet_ids)) - {capital_sys_id})
for sys_id in empire_occupied_system_ids:
PlanetDefenseAllocator(sys_id, allocation_helper).allocate()
# attack / protect high priority targets
for sys_id in top_target_systems:
#.........这里部分代码省略.........
示例11: _minimum_allocation
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
def _minimum_allocation(self, threat):
nearby_forces = CombatRatingsAI.combine_ratings(
self.assigned_rating, self._potential_support())
return max(
CombatRatingsAI.rating_needed(self._regional_threat(), nearby_forces),
CombatRatingsAI.rating_needed(1.4*threat, self.assigned_rating))
示例12: get_fleets_for_mission
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
def get_fleets_for_mission(target_stats, min_stats, cur_stats, starting_system,
fleet_pool_set, fleet_list, species=""):
"""Get fleets for a mission.
Implements breadth-first search through systems starting at the **starting_sytem**.
In each system, local fleets are checked if they are in the allowed **fleet_pool_set** and suitable for the mission.
If so, they are added to the **fleet_list** and **cur_stats** is updated with the currently selected fleet summary.
The search continues until the requirements defined in **target_stats** are met or there are no more systems/fleets.
In that case, if the **min_stats** are covered, the **fleet_list** is returned anyway.
Otherwise, an empty list is returned by the function, in which case the caller can make an evaluation of
an emergency use of the found fleets in fleet_list; if not to be used they should be added back to the main pool.
:param target_stats: stats the fleet should ideally meet
:type target_stats: dict
:param min_stats: minimum stats the final fleet must meet to be accepted
:type min_stats: dict
:param cur_stats: (**mutated**) stat summary of selected fleets
:type cur_stats: dict
:param starting_system: system_id where breadth-first-search is centered
:type starting_system: int
:param fleet_pool_set: (**mutated**) fleets allowed to be selected. Split fleed_ids are added, used ones removed.
:type: fleet_pool_set: set[int]
:param fleet_list: (**mutated**) fleets that are selected for the mission. Gets filled during the call.
:type fleet_list: list[int]
:param species: species for colonization mission
:type species: str
:return: List of selected fleet_ids or empty list if couldn't meet minimum requirements.
:rtype: list[int]
"""
universe = fo.getUniverse()
colonization_roles = (ShipRoleType.CIVILIAN_COLONISATION, ShipRoleType.BASE_COLONISATION)
systems_enqueued = [starting_system]
systems_visited = []
# loop over systems in a breadth-first-search trying to find nearby suitable ships in fleet_pool_set
while systems_enqueued and fleet_pool_set:
this_system_id = systems_enqueued.pop(0)
systems_visited.append(this_system_id)
accessible_fleets = foAI.foAIstate.systemStatus.get(this_system_id, {}).get('myFleetsAccessible', [])
fleets_here = [fid for fid in accessible_fleets if fid in fleet_pool_set]
# loop over all fleets in the system, split them if possible and select suitable ships
while fleets_here:
fleet_id = fleets_here.pop(0)
fleet = universe.getFleet(fleet_id)
if not fleet: # TODO should be checked before passed to the function
fleet_pool_set.remove(fleet_id)
continue
# try splitting fleet
if len(list(fleet.shipIDs)) > 1:
new_fleets = split_fleet(fleet_id)
fleet_pool_set.update(new_fleets)
fleets_here.extend(new_fleets)
# check species for colonization missions
if species:
for ship_id in fleet.shipIDs:
ship = universe.getShip(ship_id)
if (ship and foAI.foAIstate.get_ship_role(ship.design.id) in colonization_roles and
species == ship.speciesName):
break
else: # no suitable species found
continue
# check troop capacity for invasion missions
troop_capacity = 0
if 'troopCapacity' in target_stats:
troop_capacity = count_troops_in_fleet(fleet_id)
if troop_capacity <= 0:
continue
# check if we need additional rating vs planets
this_rating_vs_planets = 0
if 'ratingVsPlanets' in target_stats:
this_rating_vs_planets = foAI.foAIstate.get_rating(fleet_id, against_planets=True)
if this_rating_vs_planets <= 0 and cur_stats.get('rating', 0) >= target_stats.get('rating', 0):
# we already have enough general rating, so do not add any more warships useless against planets
continue
# all checks passed, add ship to selected fleets and update the stats
try:
fleet_pool_set.remove(fleet_id)
except KeyError:
error("After having split a fleet, the original fleet apparently no longer exists.", exc_info=True)
continue
fleet_list.append(fleet_id)
this_rating = foAI.foAIstate.get_rating(fleet_id)
cur_stats['rating'] = CombatRatingsAI.combine_ratings(cur_stats.get('rating', 0), this_rating)
if 'ratingVsPlanets' in target_stats:
cur_stats['ratingVsPlanets'] = CombatRatingsAI.combine_ratings(cur_stats.get('ratingVsPlanets', 0),
this_rating_vs_planets)
if 'troopCapacity' in target_stats:
cur_stats['troopCapacity'] = cur_stats.get('troopCapacity', 0) + troop_capacity
# if we already meet the requirements, we can stop looking for more ships
if (sum(len(universe.getFleet(fid).shipIDs) for fid in fleet_list) >= 1) \
and stats_meet_reqs(cur_stats, target_stats):
return fleet_list
# finished system without meeting requirements. Add neighboring systems to search queue.
for neighbor_id in universe.getImmediateNeighbors(this_system_id, fo.empireID()):
if all((
neighbor_id not in systems_visited,
neighbor_id not in systems_enqueued,
#.........这里部分代码省略.........
示例13: assess_protection_focus
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
def assess_protection_focus(pid, info):
"""Return True if planet should use Protection Focus."""
this_planet = info.planet
sys_status = foAI.foAIstate.systemStatus.get(this_planet.systemID, {})
threat_from_supply = (0.25 * foAI.foAIstate.empire_standard_enemy_rating *
min(2, len(sys_status.get('enemies_nearly_supplied', []))))
print "Planet %s has regional+supply threat of %.1f" % ('P_%d<%s>' % (pid, this_planet.name), threat_from_supply)
regional_threat = sys_status.get('regional_threat', 0) + threat_from_supply
if not regional_threat: # no need for protection
if info.current_focus == PRODUCTION:
print "Advising dropping Protection Focus at %s due to no regional threat" % this_planet
return False
cur_prod_val = weighted_sum_output(info.current_output)
target_prod_val = max(map(weighted_sum_output, [info.possible_output[INDUSTRY], info.possible_output[RESEARCH]]))
prot_prod_val = weighted_sum_output(info.possible_output[PRODUCTION])
local_production_diff = 0.8 * cur_prod_val + 0.2 * target_prod_val - prot_prod_val
fleet_threat = sys_status.get('fleetThreat', 0)
# TODO: relax the below rejection once the overall determination of PFocus is better tuned
if not fleet_threat and local_production_diff > 8:
if info.current_focus == PRODUCTION:
print "Advising dropping Protection Focus at %s due to excessive productivity loss" % this_planet
return False
local_p_defenses = sys_status.get('mydefenses', {}).get('overall', 0)
# TODO have adjusted_p_defenses take other in-system planets into account
adjusted_p_defenses = local_p_defenses * (1.0 if info.current_focus != PRODUCTION else 0.5)
local_fleet_rating = sys_status.get('myFleetRating', 0)
combined_local_defenses = sys_status.get('all_local_defenses', 0)
my_neighbor_rating = sys_status.get('my_neighbor_rating', 0)
neighbor_threat = sys_status.get('neighborThreat', 0)
safety_factor = 1.2 if info.current_focus == PRODUCTION else 0.5
cur_shield = this_planet.currentMeterValue(fo.meterType.shield)
max_shield = this_planet.currentMeterValue(fo.meterType.maxShield)
cur_troops = this_planet.currentMeterValue(fo.meterType.troops)
max_troops = this_planet.currentMeterValue(fo.meterType.maxTroops)
cur_defense = this_planet.currentMeterValue(fo.meterType.defense)
max_defense = this_planet.currentMeterValue(fo.meterType.maxDefense)
def_meter_pairs = [(cur_troops, max_troops), (cur_shield, max_shield), (cur_defense, max_defense)]
use_protection = True
reason = ""
if (fleet_threat and # i.e., an enemy is sitting on us
(info.current_focus != PRODUCTION or # too late to start protection TODO: but maybe regen worth it
# protection focus only useful here if it maintains an elevated level
all([AIDependencies.PROT_FOCUS_MULTIPLIER * a <= b for a, b in def_meter_pairs]))):
use_protection = False
reason = "A"
elif ((info.current_focus != PRODUCTION and cur_shield < max_shield - 2 and
not tech_is_complete(AIDependencies.PLANET_BARRIER_I_TECH)) and
(cur_defense < max_defense - 2 and not tech_is_complete(AIDependencies.DEFENSE_REGEN_1_TECH)) and
(cur_troops < max_troops - 2)):
use_protection = False
reason = "B1"
elif ((info.current_focus == PRODUCTION and cur_shield * AIDependencies.PROT_FOCUS_MULTIPLIER < max_shield - 2 and
not tech_is_complete(AIDependencies.PLANET_BARRIER_I_TECH)) and
(cur_defense * AIDependencies.PROT_FOCUS_MULTIPLIER < max_defense - 2 and
not tech_is_complete(AIDependencies.DEFENSE_REGEN_1_TECH)) and
(cur_troops * AIDependencies.PROT_FOCUS_MULTIPLIER < max_troops - 2)):
use_protection = False
reason = "B2"
elif max(max_shield, max_troops, max_defense) < 3: # joke defenses, don't bother with protection focus
use_protection = False
reason = "C"
elif regional_threat and local_production_diff <= 2.0:
reason = "D"
pass # i.e., use_protection = True
elif safety_factor * regional_threat <= local_fleet_rating:
use_protection = False
reason = "E"
elif (safety_factor * regional_threat <= combined_local_defenses and
(info.current_focus != PRODUCTION or
(0.5 * safety_factor * regional_threat <= local_fleet_rating and
fleet_threat == 0 and neighbor_threat < combined_local_defenses and
local_production_diff > 5))):
use_protection = False
reason = "F"
elif (regional_threat <= CombatRatingsAI.combine_ratings(local_fleet_rating, adjusted_p_defenses) and
safety_factor * regional_threat <=
CombatRatingsAI.combine_ratings_list([my_neighbor_rating, local_fleet_rating, adjusted_p_defenses]) and
local_production_diff > 5):
use_protection = False
reason = "G"
if use_protection or info.current_focus == PRODUCTION:
print ("Advising %sProtection Focus (reason %s) for planet %s, with local_prod_diff of %.1f, comb. local"
" defenses %.1f, local fleet rating %.1f and regional threat %.1f, threat sources: %s") % (
["dropping ", ""][use_protection], reason, this_planet, local_production_diff, combined_local_defenses,
local_fleet_rating, regional_threat, sys_status['regional_fleet_threats'])
return use_protection
示例14: get_military_fleets
# 需要导入模块: import CombatRatingsAI [as 别名]
# 或者: from CombatRatingsAI import combine_ratings [as 别名]
def get_military_fleets(mil_fleets_ids=None, try_reset=True, thisround="Main"):
"""Get armed military fleets."""
global _military_allocations, totMilRating, num_milships
universe = fo.getUniverse()
empire_id = fo.empireID()
home_system_id = PlanetUtilsAI.get_capital_sys_id()
all_military_fleet_ids = (mil_fleets_ids if mil_fleets_ids is not None
else FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY))
if try_reset and (fo.currentTurn() + empire_id) % 30 == 0 and thisround == "Main":
try_again(all_military_fleet_ids, try_reset=False, thisround=thisround + " Reset")
num_milships = sum(foAI.foAIstate.fleetStatus.get(fid, {}).get('nships', 0) for fid in all_military_fleet_ids)
if "Main" in thisround:
totMilRating = sum(CombatRatingsAI.get_fleet_rating(fid) for fid in all_military_fleet_ids)
enemy_rating = foAI.foAIstate.empire_standard_enemy_rating
mil_fleets_ids = list(FleetUtilsAI.extract_fleet_ids_without_mission_types(all_military_fleet_ids))
mil_needing_repair_ids, mil_fleets_ids = avail_mil_needing_repair(mil_fleets_ids, split_ships=True)
avail_mil_rating = sum(map(CombatRatingsAI.get_fleet_rating, mil_fleets_ids))
if "Main" in thisround:
print "=================================================="
print "%s Round Available Military Rating: %d" % (thisround, avail_mil_rating)
print "---------------------------------"
remaining_mil_rating = avail_mil_rating
allocations = []
allocation_groups = {}
if not mil_fleets_ids:
if "Main" in thisround:
_military_allocations = []
return []
# for each system, get total rating of fleets assigned to it
already_assigned_rating = {}
systems_status = foAI.foAIstate.systemStatus
enemy_sup_factor = {} # enemy supply
for sys_id in universe.systemIDs:
already_assigned_rating[sys_id] = 0
enemy_sup_factor[sys_id] = min(2, len(systems_status.get(sys_id, {}).get('enemies_nearly_supplied', [])))
for fleet_id in [fid for fid in all_military_fleet_ids if fid not in mil_fleets_ids]:
ai_fleet_mission = foAI.foAIstate.get_fleet_mission(fleet_id)
if not ai_fleet_mission.target: # shouldn't really be possible
continue
last_sys = ai_fleet_mission.target.get_system().id # will count this fleet as assigned to last system in target list # TODO last_sys or target sys?
this_rating = CombatRatingsAI.get_fleet_rating(fleet_id)
already_assigned_rating[last_sys] = CombatRatingsAI.combine_ratings(already_assigned_rating.get(sys_id, 0), this_rating)
for sys_id in universe.systemIDs:
my_defense_rating = systems_status.get(sys_id, {}).get('mydefenses', {}).get('overall', 0)
already_assigned_rating[sys_id] = CombatRatingsAI.combine_ratings(my_defense_rating, already_assigned_rating[sys_id])
if _verbose_mil_reporting and already_assigned_rating[sys_id]:
print "\t System %s already assigned rating %.1f" % (
universe.getSystem(sys_id), already_assigned_rating[sys_id])
# get systems to defend
capital_id = PlanetUtilsAI.get_capital()
if capital_id is not None:
capital_planet = universe.getPlanet(capital_id)
else:
capital_planet = None
# TODO: if no owned planets try to capture one!
if capital_planet:
capital_sys_id = capital_planet.systemID
else: # should be rare, but so as to not break code below, pick a randomish mil-centroid system
capital_sys_id = None # unless we can find one to use
system_dict = {}
for fleet_id in all_military_fleet_ids:
status = foAI.foAIstate.fleetStatus.get(fleet_id, None)
if status is not None:
sys_id = status['sysID']
if not list(universe.getSystem(sys_id).planetIDs):
continue
system_dict[sys_id] = system_dict.get(sys_id, 0) + status.get('rating', 0)
ranked_systems = sorted([(val, sys_id) for sys_id, val in system_dict.items()])
if ranked_systems:
capital_sys_id = ranked_systems[-1][-1]
else:
try:
capital_sys_id = foAI.foAIstate.fleetStatus.items()[0][1]['sysID']
except:
pass
if False:
if fo.currentTurn() < 20:
threat_bias = 0
elif fo.currentTurn() < 40:
threat_bias = 10
elif fo.currentTurn() < 60:
threat_bias = 80
elif fo.currentTurn() < 80:
threat_bias = 200
else:
threat_bias = 400
else:
threat_bias = 0
#.........这里部分代码省略.........