本文整理汇总了Python中ProductionAI类的典型用法代码示例。如果您正苦于以下问题:Python ProductionAI类的具体用法?Python ProductionAI怎么用?Python ProductionAI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ProductionAI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateOrders
def generateOrders():
print ("Genearting Orders")
universe = fo.getUniverse()
empire = fo.getEmpire()
planetID = empire.capitalID
planet = universe.getPlanet(planetID)
print "EmpireID: " + str(empire.empireID) + " Name: " + empire.name + " Turn: " + str(fo.currentTurn())
print "CapitalID: " + str(planetID) + " Name: " + planet.name + " Species: " + planet.speciesName
# turn cleanup
splitFleet()
identifyShipDesigns()
identifyFleetsRoles()
foAIstate.clean(ExplorationAI.getHomeSystemID(), FleetUtilsAI.getEmpireFleetIDs())
# ...missions
# ...demands/priorities
print("Calling AI Modules")
# call AI modules
PriorityAI.calculatePriorities()
ExplorationAI.assignScoutsToExploreSystems()
ColonisationAI.assignColonyFleetsToColonise()
InvasionAI.assignInvasionFleetsToInvade()
MilitaryAI.assignMilitaryFleetsToSystems()
FleetUtilsAI.generateAIFleetOrdersForAIFleetMissions()
FleetUtilsAI.issueAIFleetOrdersForAIFleetMissions()
ResearchAI.generateResearchOrders()
ProductionAI.generateProductionOrders()
ResourcesAI.generateResourcesOrders()
foAIstate.afterTurnCleanup()
fo.doneTurn()
示例2: cur_best_mil_ship_rating
def cur_best_mil_ship_rating(include_designs=False):
"""Find the best military ship we have available in this turn and return its rating.
:param include_designs: toggles if available designs are considered or only existing ships
:return: float: rating of the best ship
"""
current_turn = fo.currentTurn()
if current_turn in best_ship_rating_cache:
best_rating = best_ship_rating_cache[current_turn]
if include_designs:
best_design_rating = ProductionAI.cur_best_military_design_rating()
best_rating = max(best_rating, best_design_rating)
return best_rating
best_rating = 0.001
universe = fo.getUniverse()
for fleet_id in FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY):
fleet = universe.getFleet(fleet_id)
for ship_id in fleet.shipIDs:
ship = universe.getShip(ship_id)
if ship:
ship_info = [(ship.id, ship.designID, ship.speciesName)]
ship_rating = foAI.foAIstate.rate_psuedo_fleet(ship_info=ship_info)['overall']
best_rating = max(best_rating, ship_rating)
best_ship_rating_cache[current_turn] = best_rating
if include_designs:
best_design_rating = ProductionAI.cur_best_military_design_rating()
best_rating = max(best_rating, best_design_rating)
return max(best_rating, 0.001)
示例3: cur_best_mil_ship_rating
def cur_best_mil_ship_rating(include_designs=False):
"""Find the best military ship we have available in this turn and return its rating.
:param include_designs: toggles if available designs are considered or only existing ships
:return: float: rating of the best ship
"""
current_turn = fo.currentTurn()
if current_turn in _best_ship_rating_cache:
best_rating = _best_ship_rating_cache[current_turn]
if include_designs:
best_design_rating = ProductionAI.cur_best_military_design_rating()
best_rating = max(best_rating, best_design_rating)
return best_rating
best_rating = 0.001
universe = fo.getUniverse()
for fleet_id in FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY):
fleet = universe.getFleet(fleet_id)
for ship_id in fleet.shipIDs:
ship_rating = CombatRatingsAI.ShipCombatStats(ship_id).get_rating(enemy_stats=foAI.foAIstate.get_standard_enemy())
best_rating = max(best_rating, ship_rating)
_best_ship_rating_cache[current_turn] = best_rating
if include_designs:
best_design_rating = ProductionAI.cur_best_military_design_rating()
best_rating = max(best_rating, best_design_rating)
return max(best_rating, 0.001)
示例4: generateOrders
def generateOrders():
empire = fo.getEmpire()
print "Empire: " + empire.name + " TURN: " + str(fo.currentTurn())
print "Capital: " + str(empire.capitalID)
# turn cleanup
splitFleet()
identifyShipDesigns()
identifyFleetsRoles()
foAIstate.clean(ExplorationAI.getHomeSystemID(), FleetUtilsAI.getEmpireFleetIDs())
# ...missions
# ...demands/priorities
# call AI modules
PriorityAI.calculatePriorities()
ExplorationAI.assignScoutsToExploreSystems()
ColonisationAI.assignColonyFleetsToColonise()
InvasionAI.assignInvasionFleetsToInvade()
FleetUtilsAI.generateAIFleetOrdersForAIFleetMissions()
FleetUtilsAI.issueAIFleetOrdersForAIFleetMissions()
ResearchAI.generateResearchOrders()
ProductionAI.generateProductionOrders()
ResourcesAI.generateResourcesOrders()
foAIstate.afterTurnCleanup()
fo.doneTurn()
示例5: assessShipDesignRole
def assessShipDesignRole(design):
if design.parts.__contains__("CO_OUTPOST_POD"):
if design.starlaneSpeed > 0:
return AIShipRoleType.SHIP_ROLE_CIVILIAN_OUTPOST
else:
return AIShipRoleType.SHIP_ROLE_BASE_OUTPOST
if design.parts.__contains__("CO_COLONY_POD") or design.parts.__contains__("CO_SUSPEND_ANIM_POD"):
if design.starlaneSpeed > 0:
return AIShipRoleType.SHIP_ROLE_CIVILIAN_COLONISATION
else:
return AIShipRoleType.SHIP_ROLE_BASE_COLONISATION
if design.parts.__contains__("GT_TROOP_POD"):
if design.starlaneSpeed > 0:
return AIShipRoleType.SHIP_ROLE_MILITARY_INVASION
else:
return AIShipRoleType.SHIP_ROLE_BASE_INVASION
if design.starlaneSpeed == 0:
if design.parts[0] in [ "SH_DEFENSE_GRID", "SH_DEFLECTOR" , "SH_MULTISPEC" ]:
return AIShipRoleType.SHIP_ROLE_BASE_DEFENSE
else:
return AIShipRoleType.SHIP_ROLE_INVALID
stats = foAI.foAIstate.getDesignStats(design)
rating = stats['attack'] * ( stats['structure'] + stats['shields'] )
if ( "SD_SCOUT" in design.name(False) ) or (rating < 0.2* ProductionAI.curBestMilShipRating()):
for part in design.parts:
if "DT_DETECTOR" in part:
return AIShipRoleType.SHIP_ROLE_CIVILIAN_EXPLORATION
if rating > 0: #positive attack stat
return AIShipRoleType.SHIP_ROLE_MILITARY
else:
return AIShipRoleType.SHIP_ROLE_CIVILIAN_EXPLORATION #let this be the default since even without detection part a ship has some inherent
示例6: calculateMilitaryPriority
def calculateMilitaryPriority():
"calculates the demand for military ships by military targeted systems"
global unmetThreat
universe = fo.getUniverse()
empire = fo.getEmpire()
empireID = empire.empireID
capitalID = PlanetUtilsAI.getCapital()
if capitalID is not None and capitalID != -1:
homeworld = universe.getPlanet(capitalID)
else:
return 0# no capitol (not even a capitol-in-the-making), means can't produce any ships
have_mod_weaps = ( empire.getTechStatus("SHP_WEAPON_1_4") == fo.techStatus.complete or
empire.getTechStatus("SHP_WEAPON_2_1") == fo.techStatus.complete or
empire.getTechStatus("SHP_WEAPON_4_1") == fo.techStatus.complete )
allottedInvasionTargets = 1+ int(fo.currentTurn()/25)
targetPlanetIDs = [pid for pid, pscore, trp in AIstate.invasionTargets[:allottedInvasionTargets] ] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:allottedColonyTargets] ] + [pid for pid, pscore in foAI.foAIstate.colonisableOutpostIDs[:allottedColonyTargets] ]
mySystems = set( AIstate.popCtrSystemIDs ).union( AIstate.outpostSystemIDs )
targetSystems = set( PlanetUtilsAI.getSystems(targetPlanetIDs) )
curShipRating = ProductionAI.curBestMilShipRating()
cSRR = curShipRating**0.5
unmetThreat = 0.0
currentTurn=fo.currentTurn()
shipsNeeded=0
defenses_needed = 0
for sysID in mySystems.union(targetSystems) :
status=foAI.foAIstate.systemStatus.get( sysID, {} )
myRating = status.get('myFleetRating', 0)
my_defenses = status.get('mydefenses', {}).get('overall', 0)
baseMonsterThreat = status.get('monsterThreat', 0)
#scale monster threat so that in early - mid game big monsters don't over-drive military production
if currentTurn>200:
monsterThreat = baseMonsterThreat
elif currentTurn>100:
if baseMonsterThreat <2000:
monsterThreat = baseMonsterThreat
else:
monsterThreat = 2000 + (currentTurn/100.0 - 1) *(baseMonsterThreat-2000)
else:
monsterThreat = 0
if sysID in mySystems:
threatRoot = status.get('fleetThreat', 0)**0.5 + 0.8*status.get('max_neighbor_threat', 0)**0.5 + 0.2*status.get('neighborThreat', 0)**0.5 + monsterThreat**0.5 + status.get('planetThreat', 0)**0.5
else:
threatRoot = status.get('fleetThreat', 0)**0.5 + monsterThreat**0.5 + status.get('planetThreat', 0)**0.5
shipsNeeded += math.ceil(( max(0, (threatRoot - (myRating**0.5 + my_defenses**0.5)))**2)/curShipRating)
#militaryPriority = int( 40 + max(0, 75*unmetThreat / curShipRating) )
militaryPriority = int( 40 + max(0, 75*shipsNeeded) )
if not have_mod_weaps:
militaryPriority /= 2
#print "Calculating Military Priority: 40 + 75 * unmetThreat/curShipRating \n\t Priority: %d \t unmetThreat %.0f curShipRating: %.0f"%(militaryPriority, unmetThreat, curShipRating)
print "Calculating Military Priority: 40 + 75 * shipsNeeded \n\t Priority: %d \t shipsNeeded %d \t unmetThreat %.0f curShipRating: %.0f"%(militaryPriority, shipsNeeded, unmetThreat, curShipRating)
return max( militaryPriority, 0)
示例7: calculateMilitaryPriority
def calculateMilitaryPriority():
"calculates the demand for military ships by military targeted systems"
universe = fo.getUniverse()
empire = fo.getEmpire()
empireID = empire.empireID
capitalID = PlanetUtilsAI.getCapital()
if capitalID:
homeworld = universe.getPlanet(capitalID)
else:
return 0# no capitol (not even a capitol-in-the-making), means can't produce any ships
allottedInvasionTargets = 1+ int(fo.currentTurn()/25)
targetPlanetIDs = [pid for pid, pscore, trp in AIstate.invasionTargets[:allottedInvasionTargets] ] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:allottedColonyTargets] ] + [pid for pid, pscore in foAI.foAIstate.colonisableOutpostIDs[:allottedColonyTargets] ]
mySystems = set( AIstate.popCtrSystemIDs ).union( AIstate.outpostSystemIDs )
targetSystems = set( PlanetUtilsAI.getSystems(targetPlanetIDs) )
curShipRating = ProductionAI.curBestMilShipRating()
cSRR = curShipRating**0.5
unmetThreat = 0.0
currentTurn=fo.currentTurn()
shipsNeeded=0
for sysID in mySystems.union(targetSystems) :
status=foAI.foAIstate.systemStatus.get( sysID, {} )
myAttack, myHealth =0, 0
for fid in status.get('myfleets', []) :
rating= foAI.foAIstate.fleetStatus.get(fid, {}).get('rating', {})
myAttack += rating.get('attack', 0)
myHealth += rating.get('health', 0)
myRating = myAttack*myHealth
baseMonsterThreat = status.get('monsterThreat', 0)
if currentTurn>200:
monsterThreat = baseMonsterThreat
elif currentTurn>100:
if baseMonsterThreat <2000:
monsterThreat = baseMonsterThreat
else:
monsterThreat = 2000 + (currentTurn/100.0 - 1) *(baseMonsterThreat-2000)
else:
monsterThreat = 0
threatRoot = status.get('fleetThreat', 0)**0.5 + status.get('planetThreat', 0)**0.5 + monsterThreat**0.5
if sysID in mySystems:
threatRoot += (0.3* status.get('neighborThreat', 0))**0.5
else:
threatRoot += (0.1* status.get('neighborThreat', 0))**0.5
threat = threatRoot**2
unmetThreat += max( 0, threat - myRating )
shipsNeeded += math.ceil( max(0, (threatRoot/cSRR)- (myRating/curShipRating)**0.5 ) )
#militaryPriority = int( 40 + max(0, 75*unmetThreat / curShipRating) )
militaryPriority = int( 40 + max(0, 75*shipsNeeded) )
#print "Calculating Military Priority: 40 + 75 * unmetThreat/curShipRating \n\t Priority: %d \t unmetThreat %.0f curShipRating: %.0f"%(militaryPriority, unmetThreat, curShipRating)
print "Calculating Military Priority: 40 + 75 * shipsNeeded \n\t Priority: %d \t shipsNeeded %d \t unmetThreat %.0f curShipRating: %.0f"%(militaryPriority, shipsNeeded, unmetThreat, curShipRating)
return max( militaryPriority, 0)
示例8: calculateInvasionPriority
def calculateInvasionPriority():
"calculates the demand for troop ships by opponent planets"
global allottedInvasionTargets
troopsPerPod=2
empire=fo.getEmpire()
if foAI.foAIstate.aggression==fo.aggression.beginner and fo.currentTurn()<150:
return 0
allottedInvasionTargets = 1+ int(fo.currentTurn()/25)
totalVal= sum( [pscore for pid, pscore, trp in AIstate.invasionTargets[:allottedInvasionTargets] ] )
troopsNeeded= sum( [(trp+4) for pid, pscore, trp in AIstate.invasionTargets[:allottedInvasionTargets] ] )
if totalVal == 0:
return 0
opponentTroopPods = int(troopsNeeded/troopsPerPod)
productionQueue = empire.productionQueue
queuedTroopPods=0
for queue_index in range(0, len(productionQueue)):
element=productionQueue[queue_index]
if element.buildType == EnumsAI.AIEmpireProductionTypes.BT_SHIP:
if foAI.foAIstate.getShipRole(element.designID) in [ EnumsAI.AIShipRoleType.SHIP_ROLE_MILITARY_INVASION, EnumsAI.AIShipRoleType.SHIP_ROLE_BASE_INVASION] :
design = fo.getShipDesign(element.designID)
queuedTroopPods += element.remaining*element.blocksize * list(design.parts).count("GT_TROOP_POD")
bestShip, bestDesign, buildChoices = ProductionAI.getBestShipInfo( EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_INVASION)
if bestDesign:
troopsPerBestShip = troopsPerPod*( list(bestDesign.parts).count("GT_TROOP_POD") )
else:
troopsPerBestShip=troopsPerPod #may actually not have any troopers available, but this num will do for now
#don't cound troop bases here since if through misplanning cannot be used where made, cannot be redeployed
#troopFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_INVASION) + FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_ORBITAL_INVASION)
troopFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(EnumsAI.AIFleetMissionType.FLEET_MISSION_INVASION)
numTroopPods = sum([ FleetUtilsAI.countPartsFleetwide(fleetID, ["GT_TROOP_POD"]) for fleetID in troopFleetIDs])
troopShipsNeeded = math.ceil((opponentTroopPods - (numTroopPods+ queuedTroopPods ))/troopsPerBestShip)
#invasionPriority = max( 10+ 200*max(0, troopShipsNeeded ) , int(0.1* totalVal) )
invasionPriority = 30+ 150*max(0, troopShipsNeeded )
if invasionPriority < 0:
return 0
if foAI.foAIstate.aggression==fo.aggression.beginner:
return 0.5* invasionPriority
else:
return invasionPriority
示例9: sendInvasionFleets
def sendInvasionFleets(invasionFleetIDs, evaluatedPlanets, missionType):
"sends a list of invasion fleets to a list of planet_value_pairs"
universe=fo.getUniverse()
invasionPool = invasionFleetIDs[:] #need to make a copy
bestShip, bestDesign, buildChoices = ProductionAI.getBestShipInfo( EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_INVASION)
if bestDesign:
troopsPerBestShip = 2*( list(bestDesign.parts).count("GT_TROOP_POD") )
else:
troopsPerBestShip=5 #may actually not have any troopers available, but this num will do for now
#sortedTargets=sorted( [ ( pscore-ptroops/2 , pID, pscore, ptroops) for pID, pscore, ptroops in evaluatedPlanets ] , reverse=True)
invasionPool=set(invasionPool)
for pID, pscore, ptroops in evaluatedPlanets: #
if not invasionPool: return
planet=universe.getPlanet(pID)
if not planet: continue
sysID = planet.systemID
foundFleets = []
podsNeeded= math.ceil( (ptroops+0.05)/2.0)
foundStats={}
minStats= {'rating':0, 'troopPods':podsNeeded}
targetStats={'rating':10,'troopPods':podsNeeded+1}
theseFleets = FleetUtilsAI.getFleetsForMission(1, targetStats , minStats, foundStats, "", systemsToCheck=[sysID], systemsChecked=[], fleetPoolSet=invasionPool, fleetList=foundFleets, verbose=False)
if theseFleets == []:
if not FleetUtilsAI.statsMeetReqs(foundStats, minStats):
print "Insufficient invasion troop allocation for system %d ( %s ) -- requested %s , found %s"%(sysID, universe.getSystem(sysID).name, minStats, foundStats)
invasionPool.update( foundFleets )
continue
else:
theseFleets = foundFleets
aiTarget = AITarget.AITarget(EnumsAI.AITargetType.TARGET_PLANET, pID)
print "assigning invasion fleets %s to target %s"%(theseFleets, aiTarget)
for fleetID in theseFleets:
fleet=universe.getFleet(fleetID)
aiFleetMission = foAI.foAIstate.getAIFleetMission(fleetID)
aiFleetMission.clearAIFleetOrders()
aiFleetMission.clearAITargets( (aiFleetMission.getAIMissionTypes() + [-1])[0] )
aiFleetMission.addAITarget(missionType, aiTarget)
示例10: evaluateInvasionPlanet
def evaluateInvasionPlanet(planetID, missionType, fleetSupplyablePlanetIDs, empire, secureAIFleetMissions, verbose=True):
"return the invasion value (score, troops) of a planet"
detail = []
buildingValues = {"BLD_IMPERIAL_PALACE": 1000,
"BLD_CULTURE_ARCHIVES": 1000,
"BLD_SHIPYARD_BASE": 100,
"BLD_SHIPYARD_ORG_ORB_INC": 200,
"BLD_SHIPYARD_ORG_XENO_FAC": 200,
"BLD_SHIPYARD_ORG_CELL_GRO_CHAMB": 200,
"BLD_SHIPYARD_CON_NANOROBO": 300,
"BLD_SHIPYARD_CON_GEOINT": 400,
"BLD_SHIPYARD_CON_ADV_ENGINE": 1000,
"BLD_SHIPYARD_AST": 300,
"BLD_SHIPYARD_AST_REF": 1000,
"BLD_SHIPYARD_ENRG_SOLAR": 1500,
"BLD_INDUSTRY_CENTER": 500,
"BLD_GAS_GIANT_GEN": 200,
"BLD_SOL_ORB_GEN": 800,
"BLD_BLACK_HOLE_POW_GEN": 2000,
"BLD_ENCLAVE_VOID": 500,
"BLD_NEUTRONIUM_EXTRACTOR": 2000,
"BLD_NEUTRONIUM_SYNTH": 2000,
"BLD_NEUTRONIUM_FORGE": 1000,
"BLD_CONC_CAMP": 100,
"BLD_BIOTERROR_PROJECTOR": 1000,
"BLD_SHIPYARD_ENRG_COMP": 3000,
}
#TODO: add more factors, as used for colonization
universe = fo.getUniverse()
empireID = empire.empireID
maxJumps=8
planet = universe.getPlanet(planetID)
if (planet == None) : #TODO: exclude planets with stealth higher than empireDetection
print "invasion AI couldn't access any info for planet id %d"%planetID
return [0, 0]
sysPartialVisTurn = dictFromMap(universe.getVisibilityTurnsMap(planet.systemID, empireID)).get(fo.visibility.partial, -9999)
planetPartialVisTurn = dictFromMap(universe.getVisibilityTurnsMap(planetID, empireID)).get(fo.visibility.partial, -9999)
if planetPartialVisTurn < sysPartialVisTurn:
print "invasion AI couldn't get current info on planet id %d (was stealthed at last sighting)"%planetID
return [0, 0] #last time we had partial vis of the system, the planet was stealthed to us #TODO: track detection strength, order new scouting when it goes up
specName=planet.speciesName
species=fo.getSpecies(specName)
if not species: #this call iterates over this Empire's available species with which it could colonize after an invasion
planetEval = ColonisationAI.assignColonisationValues([planetID], EnumsAI.AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], None, empire, detail) #evaluatePlanet is imported from ColonisationAI
popVal = max( 0.75*planetEval.get(planetID, [0])[0], ColonisationAI.evaluatePlanet(planetID, EnumsAI.AIFleetMissionType.FLEET_MISSION_OUTPOST, [planetID], None, empire, detail) )
else:
popVal = ColonisationAI.evaluatePlanet(planetID, EnumsAI.AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], specName, empire, detail) #evaluatePlanet is imported from ColonisationAI
bldTally=0
for bldType in [universe.getObject(bldg).buildingTypeName for bldg in planet.buildingIDs]:
bval = buildingValues.get(bldType, 50)
bldTally += bval
detail.append("%s: %d"%(bldType, bval))
pSysID = planet.systemID
capitolID = PlanetUtilsAI.getCapital()
leastJumpsPath = []
clear_path = True
if capitolID:
homeworld = universe.getPlanet(capitolID)
if homeworld:
homeSystemID = homeworld.systemID
evalSystemID = planet.systemID
if (homeSystemID != -1) and (evalSystemID != -1):
leastJumpsPath = list(universe.leastJumpsPath(homeSystemID, evalSystemID, empireID))
maxJumps = len(leastJumpsPath)
system_status = foAI.foAIstate.systemStatus.get(pSysID, {})
sysFThrt = system_status.get('fleetThreat', 1000 )
sysMThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).get('monsterThreat', 0 )
sysPThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).get('planetThreat', 0 )
sysTotThrt = sysFThrt + sysMThrt + sysPThrt
max_path_threat = sysFThrt
mil_ship_rating = ProductionAI.curBestMilShipRating()
for path_sys_id in leastJumpsPath:
path_leg_status = foAI.foAIstate.systemStatus.get(path_sys_id, {})
path_leg_threat = path_leg_status.get('fleetThreat', 1000 ) + path_leg_status.get('monsterThreat', 0 )
if path_leg_threat > 0.5 * mil_ship_rating:
clear_path = False
if path_leg_threat > max_path_threat:
max_path_threat = path_leg_threat
troops = planet.currentMeterValue(fo.meterType.troops)
maxTroops = planet.currentMeterValue(fo.meterType.maxTroops)
this_system = universe.getSystem(pSysID)
secure_targets = [pSysID] + list(this_system.planetIDs)
system_secured = False
for mission in secureAIFleetMissions:
if system_secured:
break
secure_fleet_id = mission.target_id
s_fleet = universe.getFleet(secure_fleet_id)
if (not s_fleet) or (s_fleet.systemID != pSysID):
continue
for ai_target in mission.getAITargets(EnumsAI.AIFleetMissionType.FLEET_MISSION_SECURE):
target_obj = ai_target.target_obj
if (target_obj is not None) and target_obj.id in secure_targets:
#.........这里部分代码省略.........
示例11: getColonyFleets
def getColonyFleets():
global empireSpecies, empireColonizers, empireSpeciesSystems, annexableSystemIDs, annexableRing1, annexableRing2, annexableRing3
global annexablePlanetIDs, curBestMilShipRating
curBestMilShipRating = ProductionAI.curBestMilShipRating()
"get colony fleets"
allColonyFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_COLONISATION)
AIstate.colonyFleetIDs[:] = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allColonyFleetIDs)
# get suppliable systems and planets
universe = fo.getUniverse()
empire = fo.getEmpire()
empireID = empire.empireID
capitalID = PlanetUtilsAI.getCapital()
#capitalID = empire.capitalID
homeworld=None
if capitalID:
homeworld = universe.getPlanet(capitalID)
if homeworld:
speciesName = homeworld.speciesName
homeworldName=homeworld.name
homeSystemID = homeworld.systemID
else:
speciesName = ""
homeworldName=" no remaining homeworld "
homeSystemID = -1
if not speciesName:
speciesName = foAI.foAIstate.origSpeciesName
species = fo.getSpecies(speciesName)
if not species:
print "**************************************************************************************"
print "**************************************************************************************"
print "Problem determining species for colonization planning: capitalID: %s, homeworld %s and species name %s"%(capitalID, homeworldName, speciesName)
else:
print "Plannning colonization for species name %s"%species.name
fleetSupplyableSystemIDs = empire.fleetSupplyableSystemIDs
fleetSupplyablePlanetIDs = PlanetUtilsAI.getPlanetsInSystemsIDs(fleetSupplyableSystemIDs)
print ""
print " fleetSupplyableSystemIDs: " + str(list(fleetSupplyableSystemIDs))
print " fleetSupplyablePlanetIDs: " + str(fleetSupplyablePlanetIDs)
print ""
print "-------\nEmpire Obstructed Starlanes:"
print list(empire.obstructedStarlanes())
annexableSystemIDs.clear()
annexableRing1.clear()
annexableRing2.clear()
annexableRing3.clear()
annexablePlanetIDs.clear()
for sysID in empire.fleetSupplyableSystemIDs:
annexableSystemIDs.add(sysID)
for nID in universe.getImmediateNeighbors(sysID, empireID):
annexableSystemIDs.add(nID)
annexableRing1.add(nID)
annexableRing1.difference_update(empire.fleetSupplyableSystemIDs)
print "First Ring of annexable systems: ", PlanetUtilsAI.sysNameIDs(annexableRing1)
if empire.getTechStatus("CON_ORBITAL_CON") == fo.techStatus.complete:
for sysID in list(annexableRing1):
for nID in universe.getImmediateNeighbors(sysID, empireID):
annexableRing2.add(nID)
annexableRing2.difference_update(annexableSystemIDs)
print "Second Ring of annexable systems: ", PlanetUtilsAI.sysNameIDs(annexableRing2)
annexableSystemIDs.update(annexableRing2)
if foAI.foAIstate.aggression > fo.aggression.cautious:
for sysID in list(annexableRing2):
for nID in universe.getImmediateNeighbors(sysID, empireID):
annexableRing3.add(nID)
annexableRing3.difference_update(annexableSystemIDs)
print "Third Ring of annexable systems: ", PlanetUtilsAI.sysNameIDs(annexableRing3)
annexableSystemIDs.update(annexableRing3)
annexablePlanetIDs.update( PlanetUtilsAI.getPlanetsInSystemsIDs(annexableSystemIDs))
# get outpost and colonization planets
exploredSystemIDs = foAI.foAIstate.getExplorableSystems(AIExplorableSystemType.EXPLORABLE_SYSTEM_EXPLORED)
unExSysIDs = list(foAI.foAIstate.getExplorableSystems(AIExplorableSystemType.EXPLORABLE_SYSTEM_UNEXPLORED))
unExSystems = map(universe.getSystem, unExSysIDs)
print "Unexplored Systems: %s " % [(sysID, (sys and sys.name) or "name unknown") for sysID, sys in zip( unExSysIDs, unExSystems)]
print "Explored SystemIDs: " + str(list(exploredSystemIDs))
exploredPlanetIDs = PlanetUtilsAI.getPlanetsInSystemsIDs(exploredSystemIDs)
print "Explored PlanetIDs: " + str(exploredPlanetIDs)
print ""
#visibleSystemIDs = foAI.foAIstate.visInteriorSystemIDs.keys() + foAI.foAIstate. visBorderSystemIDs.keys()
#visiblePlanetIDs = PlanetUtilsAI.getPlanetsInSystemsIDs(visibleSystemIDs)
#print "VisiblePlanets: %s "%[ (pid, (universe.getPlanet(pid) and universe.getPlanet(pid).name) or "unknown") for pid in visiblePlanetIDs]
#print ""
#accessibleSystemIDs = [sysID for sysID in visibleSystemIDs if universe.systemsConnected(sysID, homeSystemID, empireID) ]
#acessiblePlanetIDs = PlanetUtilsAI.getPlanetsInSystemsIDs(accessibleSystemIDs)
empireOwnedPlanetIDs = PlanetUtilsAI.getOwnedPlanetsByEmpire(universe.planetIDs, empireID)
print "Empire Owned PlanetIDs: " + str(empireOwnedPlanetIDs)
#.........这里部分代码省略.........
示例12: _calculate_invasion_priority
def _calculate_invasion_priority():
"""Calculates the demand for troop ships by opponent planets."""
global allottedInvasionTargets
if not foAI.foAIstate.character.may_invade():
return 0
empire = fo.getEmpire()
enemies_sighted = foAI.foAIstate.misc.get('enemies_sighted', {})
multiplier = 1
num_colonies = len(list(AIstate.popCtrIDs))
colony_growth_barrier = foAI.foAIstate.character.max_number_colonies()
if num_colonies > colony_growth_barrier:
return 0.0
if len(foAI.foAIstate.colonisablePlanetIDs) > 0:
best_colony_score = max(2, foAI.foAIstate.colonisablePlanetIDs.items()[0][1][0])
else:
best_colony_score = 2
allottedInvasionTargets = 1 + int(fo.currentTurn() / 25)
total_val = 0
troops_needed = 0
for pid, pscore, trp in AIstate.invasionTargets[:allottedInvasionTargets]:
if pscore > best_colony_score:
multiplier += 1
total_val += 2 * pscore
else:
total_val += pscore
troops_needed += trp + 4 # ToDo: This seems like it could be improved by some dynamic calculation of buffer
if total_val == 0:
return 0
production_queue = empire.productionQueue
queued_troop_capacity = 0
for queue_index in range(0, len(production_queue)):
element = production_queue[queue_index]
if element.buildType == EmpireProductionTypes.BT_SHIP:
if foAI.foAIstate.get_ship_role(element.designID) in [ShipRoleType.MILITARY_INVASION,
ShipRoleType.BASE_INVASION]:
design = fo.getShipDesign(element.designID)
queued_troop_capacity += element.remaining * element.blocksize * design.troopCapacity
_, best_design, _ = ProductionAI.get_best_ship_info(PriorityType.PRODUCTION_INVASION)
if best_design:
troops_per_best_ship = best_design.troopCapacity
else:
return 1e-6 # if we can not build troop ships, we don't want to build (non-existing) invasion ships
# don't count troop bases here as these cannot be redeployed after misplaning
# troopFleetIDs = FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.INVASION)\
# + FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.ORBITAL_INVASION)
troop_fleet_ids = FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.INVASION)
total_troop_capacity = sum([FleetUtilsAI.count_troops_in_fleet(fid) for fid in troop_fleet_ids])
troop_ships_needed = \
math.ceil((troops_needed - (total_troop_capacity + queued_troop_capacity)) / troops_per_best_ship)
# invasion_priority = max( 10+ 200*max(0, troop_ships_needed ) , int(0.1* total_val) )
invasion_priority = multiplier * (30 + 150*max(0, troop_ships_needed))
if not ColonisationAI.colony_status.get('colonies_under_attack', []):
if not ColonisationAI.colony_status.get('colonies_under_threat', []):
invasion_priority *= 2.0
else:
invasion_priority *= 1.5
if not enemies_sighted:
invasion_priority *= 1.5
if invasion_priority < 0:
return 0
return invasion_priority * foAI.foAIstate.character.invasion_priority_scaling()
示例13: get_invasion_fleets
def get_invasion_fleets():
invasion_timer.start("gathering initial info")
universe = fo.getUniverse()
empire = fo.getEmpire()
empire_id = empire.empireID
all_invasion_fleet_ids = FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.INVASION)
AIstate.invasionFleetIDs = FleetUtilsAI.extract_fleet_ids_without_mission_types(all_invasion_fleet_ids)
home_system_id = PlanetUtilsAI.get_capital_sys_id()
visible_system_ids = foAI.foAIstate.visInteriorSystemIDs.keys() + foAI.foAIstate. visBorderSystemIDs.keys()
if home_system_id != -1:
accessible_system_ids = [sys_id for sys_id in visible_system_ids
if (sys_id != -1) and universe.systemsConnected(sys_id, home_system_id, empire_id)]
else:
print "Warning: Empire has no identifiable homeworld; will treat all visible planets as accessible."
accessible_system_ids = visible_system_ids # TODO: check if any troop ships owned, use their system as home system
acessible_planet_ids = PlanetUtilsAI.get_planets_in__systems_ids(accessible_system_ids)
all_owned_planet_ids = PlanetUtilsAI.get_all_owned_planet_ids(acessible_planet_ids) # includes unpopulated outposts
all_populated_planets = PlanetUtilsAI.get_populated_planet_ids(acessible_planet_ids) # includes unowned natives
empire_owned_planet_ids = PlanetUtilsAI.get_owned_planets_by_empire(universe.planetIDs)
invadable_planet_ids = set(all_owned_planet_ids).union(all_populated_planets) - set(empire_owned_planet_ids)
invasion_targeted_planet_ids = get_invasion_targeted_planet_ids(universe.planetIDs, MissionType.INVASION)
invasion_targeted_planet_ids.extend(get_invasion_targeted_planet_ids(universe.planetIDs, MissionType.ORBITAL_INVASION))
all_invasion_targeted_system_ids = set(PlanetUtilsAI.get_systems(invasion_targeted_planet_ids))
invasion_fleet_ids = FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.INVASION)
num_invasion_fleets = len(FleetUtilsAI.extract_fleet_ids_without_mission_types(invasion_fleet_ids))
print "Current Invasion Targeted SystemIDs: ", PlanetUtilsAI.sys_name_ids(AIstate.invasionTargetedSystemIDs)
print "Current Invasion Targeted PlanetIDs: ", PlanetUtilsAI.planet_name_ids(invasion_targeted_planet_ids)
print invasion_fleet_ids and "Invasion Fleet IDs: %s" % invasion_fleet_ids or "Available Invasion Fleets: 0"
print "Invasion Fleets Without Missions: %s" % num_invasion_fleets
invasion_timer.start("planning troop base production")
# only do base invasions if aggression is typical or above
reserved_troop_base_targets = []
if foAI.foAIstate.aggression > fo.aggression.typical:
available_pp = {}
for el in empire.planetsWithAvailablePP: # keys are sets of ints; data is doubles
avail_pp = el.data()
for pid in el.key():
available_pp[pid] = avail_pp
for pid in invadable_planet_ids: # TODO: reorganize
planet = universe.getPlanet(pid)
if not planet:
continue
sys_id = planet.systemID
sys_partial_vis_turn = universe.getVisibilityTurnsMap(planet.systemID, empire_id).get(fo.visibility.partial, -9999)
planet_partial_vis_turn = universe.getVisibilityTurnsMap(pid, empire_id).get(fo.visibility.partial, -9999)
if planet_partial_vis_turn < sys_partial_vis_turn:
continue
for pid2 in state.get_empire_inhabited_planets_by_system().get(sys_id, []):
if available_pp.get(pid2, 0) < 2: # TODO: improve troop base PP sufficiency determination
break
planet2 = universe.getPlanet(pid2)
if not planet2:
continue
if pid not in foAI.foAIstate.qualifyingTroopBaseTargets and planet2.speciesName in ColonisationAI.empire_ship_builders:
foAI.foAIstate.qualifyingTroopBaseTargets.setdefault(pid, [pid2, -1])
break
for pid in list(foAI.foAIstate.qualifyingTroopBaseTargets):
planet = universe.getPlanet(pid) # TODO: also check that still have a colony in this system that can make troops
if planet and planet.owner == empire_id:
del foAI.foAIstate.qualifyingTroopBaseTargets[pid]
secure_ai_fleet_missions = foAI.foAIstate.get_fleet_missions_with_any_mission_types([MissionType.SECURE])
for pid in (set(foAI.foAIstate.qualifyingTroopBaseTargets.keys()) - set(invasion_targeted_planet_ids)): # TODO: consider overriding standard invasion mission
planet = universe.getPlanet(pid)
if foAI.foAIstate.qualifyingTroopBaseTargets[pid][1] != -1:
reserved_troop_base_targets.append(pid)
if planet:
all_invasion_targeted_system_ids.add(planet.systemID)
continue # already building for here
sys_id = planet.systemID
this_sys_status = foAI.foAIstate.systemStatus.get(sys_id, {})
if (planet.currentMeterValue(fo.meterType.shield) > 0 and
this_sys_status.get('myFleetRating', 0) < 0.8 * this_sys_status.get('totalThreat', 0)):
continue
loc = foAI.foAIstate.qualifyingTroopBaseTargets[pid][0]
best_base_trooper_here = ProductionAI.get_best_ship_info(PriorityType.PRODUCTION_ORBITAL_INVASION, loc)[1]
loc_planet = universe.getPlanet(loc)
if best_base_trooper_here is None: # shouldn't be possible at this point, but just to be safe
print "Could not find a suitable orbital invasion design at %s" % loc_planet
continue
# TODO: have TroopShipDesigner give the expected number of troops including species effects directly
troops_per_ship = best_base_trooper_here.troopCapacity
species_troop_grade = CombatRatingsAI.get_species_troops_grade(loc_planet.speciesName)
troops_per_ship = CombatRatingsAI.weight_attack_troops(troops_per_ship, species_troop_grade)
if not troops_per_ship:
print "The best orbital invasion design at %s seems not to have any troop capacity." % loc_planet
continue
this_score, p_troops = evaluate_invasion_planet(pid, empire, secure_ai_fleet_missions, False)
_, col_design, build_choices = ProductionAI.get_best_ship_info(PriorityType.PRODUCTION_ORBITAL_INVASION, loc)
if not col_design:
continue
#.........这里部分代码省略.........
示例14: evaluate_invasion_planet
#.........这里部分代码省略.........
for path_sys_id in least_jumps_path:
path_leg_status = foAI.foAIstate.systemStatus.get(path_sys_id, {})
path_leg_threat = path_leg_status.get('fleetThreat', 1000) + path_leg_status.get('monsterThreat', 0)
if path_leg_threat > 0.5 * mil_ship_rating:
clear_path = False
if path_leg_threat > max_path_threat:
max_path_threat = path_leg_threat
pop = planet.currentMeterValue(fo.meterType.population)
target_pop = planet.currentMeterValue(fo.meterType.targetPopulation)
troops = planet.currentMeterValue(fo.meterType.troops)
max_troops = planet.currentMeterValue(fo.meterType.maxTroops)
# TODO: refactor troop determination into function for use in mid-mission updates and also consider defender techs
max_troops += AIDependencies.TROOPS_PER_POP * (target_pop - pop)
this_system = universe.getSystem(p_sys_id)
secure_targets = [p_sys_id] + list(this_system.planetIDs)
system_secured = False
for mission in secure_fleet_missions:
if system_secured:
break
secure_fleet_id = mission.fleet.id
s_fleet = universe.getFleet(secure_fleet_id)
if not s_fleet or s_fleet.systemID != p_sys_id:
continue
if mission.type == MissionType.SECURE:
target_obj = mission.target.get_object()
if target_obj is not None and target_obj.id in secure_targets:
system_secured = True
break
system_secured = system_secured and system_status.get('myFleetRating', 0)
if verbose:
print ("Invasion eval of %s\n"
" - maxShields: %.1f\n"
" - sysFleetThreat: %.1f\n"
" - sysMonsterThreat: %.1f") % (
planet, planet.currentMeterValue(fo.meterType.maxShield), system_fleet_treat,
system_monster_threat)
supply_val = 0
enemy_val = 0
if planet.owner != -1: # value in taking this away from an enemy
enemy_val = 20 * (planet.currentMeterValue(fo.meterType.targetIndustry) + 2*planet.currentMeterValue(fo.meterType.targetResearch))
if p_sys_id in ColonisationAI.annexable_system_ids: # TODO: extend to rings
supply_val = 100
elif p_sys_id in ColonisationAI.annexable_ring1:
supply_val = 200
elif p_sys_id in ColonisationAI.annexable_ring2:
supply_val = 300
elif p_sys_id in ColonisationAI.annexable_ring3:
supply_val = 400
if max_path_threat > 0.5 * mil_ship_rating:
if max_path_threat < 3 * mil_ship_rating:
supply_val *= 0.5
else:
supply_val *= 0.2
threat_factor = min(1, 0.2*MilitaryAI.get_tot_mil_rating()/(sys_total_threat+0.001))**2 # devalue invasions that would require too much military force
design_id, _, locs = ProductionAI.get_best_ship_info(PriorityType.PRODUCTION_INVASION)
if not locs or not universe.getPlanet(locs[0]):
# We are in trouble anyway, so just calculate whatever approximation...
build_time = 4
planned_troops = troops if system_secured else min(troops + max_jumps + build_time, max_troops)
planned_troops += .01 # we must attack with more troops than there are defenders
troop_cost = math.ceil((planned_troops+_TROOPS_SAFETY_MARGIN) / 6.0) * 20 * FleetUtilsAI.get_fleet_upkeep()
else:
loc = locs[0]
species_here = universe.getPlanet(loc).speciesName
design = fo.getShipDesign(design_id)
cost_per_ship = design.productionCost(empire_id, loc)
build_time = design.productionTime(empire_id, loc)
troops_per_ship = CombatRatingsAI.weight_attack_troops(design.troopCapacity,
CombatRatingsAI.get_species_troops_grade(species_here))
planned_troops = troops if system_secured else min(troops + max_jumps + build_time, max_troops)
planned_troops += .01 # we must attack with more troops than there are defenders
ships_needed = math.ceil((planned_troops+_TROOPS_SAFETY_MARGIN) / float(troops_per_ship))
troop_cost = ships_needed * cost_per_ship # fleet upkeep is already included in query from server
# apply some bias to expensive operations
normalized_cost = float(troop_cost) / max(fo.getEmpire().productionPoints, 1)
normalized_cost = max(1, normalized_cost)
cost_score = (normalized_cost**2 / 50.0) * troop_cost
base_score = pop_val + supply_val + bld_tally + tech_tally + enemy_val - cost_score
planet_score = retaliation_risk_factor(planet.owner) * threat_factor * max(0, base_score)
if clear_path:
planet_score *= 1.5
if verbose:
print (' - planet score: %.2f\n'
' - troop score: %.2f\n'
' - projected troop cost: %.1f\n'
' - threat factor: %s\n'
' - planet detail: %s\n'
' - popval: %.1f\n'
' - supplyval: %.1f\n'
' - bldval: %s\n'
' - enemyval: %s') % (planet_score, planned_troops, troop_cost,
threat_factor, detail, pop_val, supply_val, bld_tally, enemy_val)
return [planet_score, planned_troops]
示例15: generateOrders
def generateOrders():
global lastTurnTimestamp
universe = fo.getUniverse()
turnStartTime=time() #starting AI timer here, to be sure AI doesn't get blame for any lags in server being able to provide the Universe object
empire = fo.getEmpire()
planetID = PlanetUtilsAI.getCapital()
planet=None
if planetID is not None:
planet = universe.getPlanet(planetID)
print "***************************************************************************"
print "***************************************************************************"
print ("Generating Orders")
print "EmpireID: " + str(empire.empireID) + " Name: " + empire.name+ "_"+str(empire.empireID-1) +"_pid:"+str(fo.playerID())+"_"+fo.playerName()+"_"+aggressions.get(foAIstate.aggression, "?") + " Turn: " + str(fo.currentTurn())
empireColor=empire.colour
print "EmpireColors: %d %d %d %d"%(empireColor.r, empireColor.g, empireColor.b, empireColor.a)
if planet:
print "CapitalID: " + str(planetID) + " Name: " + planet.name + " Species: " + planet.speciesName
else:
print "CapitalID: None Currently Name: None Species: None "
print "***************************************************************************"
print "***************************************************************************"
if fo.currentTurn() == 1:
declareWarOnAll()
# turn cleanup !!! this was formerly done at start of every turn -- not sure why
splitNewFleets()
#updateShipDesigns() #should not be needed anymore;
#updateFleetsRoles()
foAIstate.clean() #checks exploration border & clears roles/missions of missing fleets & updates fleet locs
foAIstate.reportSystemThreats()
# ...missions
# ...demands/priorities
print("Calling AI Modules")
# call AI modules
timer=[time()]
try: PriorityAI.calculatePriorities()
except: print "Error: exception triggered and caught: ", traceback.format_exc() # try traceback.print_exc()
timer.append( time() )
try: ExplorationAI.assignScoutsToExploreSystems()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: ColonisationAI.assignColonyFleetsToColonise()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: InvasionAI.assignInvasionFleetsToInvade()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: MilitaryAI.assignMilitaryFleetsToSystems()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: FleetUtilsAI.generateAIFleetOrdersForAIFleetMissions()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: FleetUtilsAI.issueAIFleetOrdersForAIFleetMissions()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: ResearchAI.generateResearchOrders()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: ProductionAI.generateProductionOrders()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: ResourcesAI.generateResourcesOrders()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
try: foAIstate.afterTurnCleanup()
except: print "Error: exception triggered and caught: ", traceback.format_exc()
timer.append( time() )
times = [timer[i] - timer[i-1] for i in range(1, len(timer) ) ]
turnEndTime=time()
timeFmt = "%30s: %8d msec "
print "AI Module Time Requirements:"
for mod, modTime in zip(__timerEntries, times):
print timeFmt%((30*' '+mod)[-30:], int(1000*modTime))
if __timerFile:
__timerFile.write( __timerFileFmt%tuple( [ fo.currentTurn() ]+map(lambda x: int(1000*x), times )) +'\n')
__timerFile.flush()
if __timerBucketFile:
__timerBucketFile.write( __timerBucketFileFmt%tuple( [ fo.currentTurn(), (turnStartTime-lastTurnTimestamp)*1000, (turnEndTime-turnStartTime)*1000 ]) +'\n')
__timerBucketFile.flush()
lastTurnTimestamp = time()
try: fo.doneTurn()
except: print "Error: exception triggered and caught: ", traceback.format_exc()