From: <dil...@us...> - 2013-01-23 23:18:55
|
Revision: 5672 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5672&view=rev Author: dilvish-fo Date: 2013-01-23 23:18:47 +0000 (Wed, 23 Jan 2013) Log Message: ----------- miscellaneous AI bug fixes & adjustments Modified Paths: -------------- trunk/FreeOrion/default/AI/AIFleetMission.py trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIFleetMission.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetMission.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/AIFleetMission.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -6,6 +6,7 @@ import freeOrionAIInterface as fo import FreeOrionAI as foAI import AIstate +import ProductionAI from AIAbstractMission import AIAbstractMission @@ -166,7 +167,7 @@ if f2MType in [ AIFleetMissionType.FLEET_MISSION_DEFEND, AIFleetMissionType.FLEET_MISSION_SECURE, #actually, currently this is probably the onle one of all four that should really be possibile in this situation ]: - needLeft = 1.5*sum( [ (sysStat.get('fleetThreat', 0)-max(0, sysStat.get('monsterThreat', 0)-200) ) for sysStat in + needLeft = 1.5*sum( [ sysStat.get('fleetThreat', 0) for sysStat in [foAI.foAIstate.systemStatus.get(neighbor, {}) for neighbor in [ nid for nid in foAI.foAIstate.systemStatus.get(systemID, {}).get('neighbors', []) if nid != mMT0ID ] ] ] ) fBRating = foAI.foAIstate.getRating(fid) @@ -270,7 +271,8 @@ else: #check that we're not held up by a Big Monster if aiFleetOrder.getAIFleetOrderType() == AIFleetOrderType.ORDER_MOVE: thisSysID = aiFleetOrder.getTargetAITarget().getTargetID() - if (foAI.foAIstate.systemStatus.setdefault(thisSysID, {}).setdefault('monsterThreat', 0) > 3000) or (fo.currentTurn() <20 and foAI.foAIstate.systemStatus[thisSysID]['monsterThreat'] > 300): #move blocked by Big Monster + thisStatus = foAI.foAIstate.systemStatus.setdefault(thisSysID, {}) + if ( thisStatus.get('monsterThreat', 0) > fo.currentTurn() * ProductionAI.curBestMilShipRating()/4.0 ) : if ( ( (self.getAIMissionTypes() + [-1] )[0] not in [ AIFleetMissionType.FLEET_MISSION_ATTACK, AIFleetMissionType.FLEET_MISSION_MILITARY, AIFleetMissionType.FLEET_MISSION_HIT_AND_RUN, Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -94,7 +94,7 @@ self.exploredSystemIDs = {} self.unexploredSystemIDs = {self.origHomeSystemID:1} self.fleetStatus={} - self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat', 'myfleets', 'neighbors', 'name' + self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'myfleets', 'neighbors', 'name' self.needsEmergencyExploration=[] self.newlySplitFleets={} self.aggression=aggression @@ -270,11 +270,6 @@ print "Can't see into system %d ( %s ) -- basing threat assessment on old info and lost ships"%(sysID, sysStatus.get('name', "name unknown")) sysStatus['planetThreat'] = int( sysStatus.get('planetThreat', 0) ) # if no current info, leave as previous, or 0 if no previous rating sysStatus['fleetThreat'] = int( max(enemyRating, max( sysStatus.get('fleetThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) ))) ) # if no current info, leave as previous, or 0 if no previous rating , or rating of fleets lost - if sysStatus.get('monsterThreat', 0) == 0: - sysStatus['monsterThreat']=0 - else: - sysStatus['monsterThreat']=int( max( sysStatus.get('monsterThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) )) ) # if no current info, leave as previous, or 0 if no previous rating , or rating of fleets lost - #self.systemStatus[sysID] = sysStatus #should no longer be necessary because of use of setdefault continue else: #system considered visible #TODO: reevaluate as visibility rules change threat=0 @@ -285,26 +280,22 @@ sawContents=True #apparently can be logged as visisble for rest of turn even if can no longer get sys contents fleet = universe.getFleet(fleetID) if ( fleet) and (not fleet.ownedBy(self.empireID)): - if fleet.hasMonsters: + if fleet.speed==0: monsterThreat += self.rateFleet(fleetID).get('overall',0)# else: threat += self.rateFleet(fleetID).get('overall',0)#currently treating all unowned fleets as hostile if sawContents: - sysStatus['fleetThreat'] = max( int( threat )+int(monsterThreat), 1.05*sum(fleetsLostBySystem.get(sysID, []) )) #fleetThreat always includes monster threat, and may not have seen stealthed enemies + sysStatus['fleetThreat'] = max( int( threat ), 1.05*sum(fleetsLostBySystem.get(sysID, []) )) #fleetThreat always includes monster threat, and may not have seen stealthed enemies sysStatus['monsterThreat']=int(monsterThreat) else: sysStatus['fleetThreat'] = int( max( sysStatus.get('fleetThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) )) ) - if sysStatus.get('monsterThreat', 0)== 0: - sysStatus['monsterThreat']=0 - else: - sysStatus['monsterThreat']= int( max( sysStatus.get('monsterThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) )) ) - threat=0 + threat=0 for planetID in system.planetIDs: planet = universe.getPlanet(planetID) # even if planet object says we own it, if we can't see it then we must have lost ownership if planet and ( not planet.unowned ) and not (planet.ownedBy(self.empireID) and (universe.getVisibility(planetID, self.empireID) >= fo.visibility.partial) ) : try: - threat += ( planet.currentMeterValue(fo.meterType.defense) ) * ( planet.currentMeterValue(fo.meterType.shield) +1) + threat += ( planet.currentMeterValue(fo.meterType.defense) ) * ( planet.currentMeterValue(fo.meterType.defense)+planet.currentMeterValue(fo.meterType.shield) ) except: print "Error: couldn't read meters for threat assessment of visible planet %d : %s"%(planetID, planet.name) print "Error: exception triggered and caught: ", traceback.format_exc() @@ -335,11 +326,7 @@ for neighborID in neighbors: neighborStatus= self.systemStatus.get(neighborID, {}) nfthreat = neighborStatus.get('fleetThreat', 0) - nmthreat = neighborStatus.get('monsterThreat', 0) - if nmthreat > 1000: # the really big monsters don't travel - threat += 0.5* max(0, (nfthreat - nmthreat) ) - else: - threat += 0.5* nfthreat + threat += 0.5* nfthreat sysStatus['neighborThreat'] = int( threat + 0.5 ) self.systemStatus[sysID] = sysStatus Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -7,10 +7,12 @@ import PlanetUtilsAI import TechsListsAI import ProductionAI +import AIDependencies empireSpecies = {} empireSpeciesSystems={} empireColonizers = {} +activeGrowthSpecials={} annexableSystemIDs=set([]) annexableRing1=set([]) annexableRing2=set([]) @@ -426,7 +428,7 @@ return 0 elif ( planet.size == fo.planetSize.asteroids ): if (species and species.name in [ "SP_EXOBOT", "SP_SUPER_TEST" ]): - for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : #even though as of time of writing only crystals can be in asteroids it seems + for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: retval+=60 else: @@ -479,6 +481,7 @@ if special in planetSpecials: popSizeMod -= 1 + """ for special, tag in [ ("PROBIOTIC_SPECIAL", "ORGANIC"), ("FRUIT_SPECIAL", "ORGANIC"), ("SPICE_SPECIAL", "ORGANIC"), @@ -488,13 +491,11 @@ ("MINERALS_SPECIAL", "LITHIC"), ("METALOIDS_SPECIAL", "LITHIC"), ]: - if special in planetSpecials: - valMod += 5 # extra bonus due to potential applicability to other planets, or to industry - if tag in tagList: - popSizeMod += 1 - # print "planet %s had special %s that triggers pop mod for species %s"%(planet.name, special, species.name) - #else: - # print "planet %s had special %s without pop mod for species %s"%(planet.name, special, species.name) + """ + for special in [ spec for spec in AIDependencies.metabolimBoosts if spec in planetSpecials]: + valMod += 10 # extra bonus due to potential applicability to other planets + for thisTag in [ tag for tag in tagList if tag in AIDependencies.metabolims]: + popSizeMod += len( (set(planetSpecials).union([key for key in activeGrowthSpecials.keys() if len(activeGrowthSpecials[key])>0 ] )).intersection(AIDependencies.metabolimBoostMap.get(thisTag, []) ) ) popSize = planet.size * popSizeMod Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -168,13 +168,13 @@ # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: curAlloc=0.8*alreadyAssignedRating[sid] thisAlloc=0 - if thrt>curAlloc and remainingMilRating > 10+ 1.5*(thrt-curAlloc) and foAI.foAIstate.systemStatus.get(sid, {}).get('monsterThreat', 0) < 0.4*totMilRating: #only record an allocation for this invasion if we have enough rating available + if thrt>curAlloc and remainingMilRating > (10+ 1.5*(thrt-curAlloc)): #only record an allocation for this invasion if we have enough rating available thisAlloc =int(10.99999 + (thrt-curAlloc)*1.5) allocations.append( (sid, thisAlloc, False, 3) ) remainingMilRating -= thisAlloc @@ -194,13 +194,13 @@ # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: curAlloc=0.8*alreadyAssignedRating[sid] thisAlloc=0 - if thrt>curAlloc and remainingMilRating > 10+ 1.5*(thrt-curAlloc) and foAI.foAIstate.systemStatus.get(sid, {}).get('monsterThreat', 0) < 0.4*totMilRating: #only record an allocation for this invasion if we have enough rating available + if thrt>curAlloc and remainingMilRating > 10+ 1.5*(thrt-curAlloc) : #only record an allocation for this invasion if we have enough rating available thisAlloc =int(10.99999 + (thrt-curAlloc)*1.5) allocations.append( (sid, thisAlloc, False, 3) ) remainingMilRating -= thisAlloc @@ -216,13 +216,13 @@ # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, safetyFactor*(threatBias +foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, safetyFactor*(threatBias +foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: curAlloc=0.8*alreadyAssignedRating[sid] thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 1.5*(thrt-curAlloc) and foAI.foAIstate.systemStatus.get(sid, {}).get('monsterThreat', 0) < 0.4*totMilRating: + if (thrt > curAlloc) and remainingMilRating > 1.5*(thrt-curAlloc): thisAlloc = min( min( int(0.99999 + (thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) allocations.append( (sid, thisAlloc, False, 2.0) ) remainingMilRating -= thisAlloc @@ -248,13 +248,13 @@ # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: curAlloc=0.8*alreadyAssignedRating[sid] thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 1.5*(thrt-curAlloc) and foAI.foAIstate.systemStatus.get(sid, {}).get('monsterThreat', 0) < 0.4*totMilRating: + if (thrt > curAlloc) and remainingMilRating > 1.5*(thrt-curAlloc): thisAlloc = min( min( int(0.99999 + (thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) allocations.append( (sid, thisAlloc, False, 10) ) remainingMilRating -= thisAlloc @@ -303,7 +303,7 @@ # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety if len(exploTargetIDs) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in exploTargetIDs ] + otSysThreat = [ ( oSID, safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in exploTargetIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) if availMilRating <1125: @@ -337,7 +337,7 @@ # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety if len(borderTargets) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in borderTargets ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in borderTargets ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -265,8 +265,10 @@ empire = fo.getEmpire() empireID = empire.empireID capitalID = PlanetUtilsAI.getCapital() - homeworld = universe.getPlanet(capitalID) - + if capitalID: + homeworld = universe.getPlanet(capitalID) + else: + return 0# no capitol (not even a capitol-in-the-making), means can't produce any ships targetPlanetIDs = [pid for pid, pscore, trp in AIstate.invasionTargets[:10] ] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] ] + [pid for pid, pscore in foAI.foAIstate.colonisableOutpostIDs[:10] ] mySystems = set( AIstate.popCtrSystemIDs ).union( AIstate.outpostSystemIDs ) Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -29,6 +29,8 @@ def curBestMilShipRating(): + if (fo.currentTurn()+1) in bestMilRatingsHistory: + bestMilRatingsHistory.clear() if fo.currentTurn() not in bestMilRatingsHistory: bestShip, bestDesign, buildChoices = getBestShipInfo( AIPriorityType.PRIORITY_PRODUCTION_MILITARY) if bestDesign is None: @@ -547,6 +549,7 @@ movedCapital=False + bldgExpense=0.0 if not homeworld: print "no capital, should get around to capturing or colonizing a new one"#TODO else: @@ -574,7 +577,6 @@ print "" print "Buildings already in Production Queue:" capitolQueuedBldgs=[] - bldgExpense=0.0 for element in [e for e in productionQueue if (e.buildType == AIEmpireProductionTypes.BT_BUILDING)]: bldgExpense += element.allocation if ( element.locationID==homeworld.id): @@ -963,7 +965,7 @@ for bldg in planet.buildingIDs: if universe.getObject(bldg).buildingTypeName == bldName: res=fo.issueScrapOrder( bldg) - print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.Name, res) + print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) totalPPSpent = fo.getEmpire().productionQueue.totalSpent @@ -974,9 +976,10 @@ print "" print "Possible ship designs to build:" - for shipDesignID in empire.availableShipDesigns: - shipDesign = fo.getShipDesign(shipDesignID) - print " " + str(shipDesign.name(True)) + " cost:" + str(shipDesign.productionCost(empire.empireID, homeworld.id) )+ " time:" + str(shipDesign.productionTime(empire.empireID, homeworld.id)) + if homeworld: + for shipDesignID in empire.availableShipDesigns: + shipDesign = fo.getShipDesign(shipDesignID) + print " " + str(shipDesign.name(True)) + " cost:" + str(shipDesign.productionCost(empire.empireID, homeworld.id) )+ " time:" + str(shipDesign.productionTime(empire.empireID, homeworld.id)) print "" print "Projects already in Production Queue:" @@ -1112,7 +1115,7 @@ else: loc = choice(buildChoices) numShips=1 - perTurnCost = (float(bestDesign.productionCost(empire.empireID, homeworld.id)) / bestDesign.productionTime(empire.empireID, loc)) + perTurnCost = (float(bestDesign.productionCost(empire.empireID, loc)) / bestDesign.productionTime(empire.empireID, loc)) if not ( makingColonyShip ): #TODO: consider whether to allow multiples of colony ships; if not, priority sampling gets skewed while ( totalPP > 40*perTurnCost): numShips *= 2 Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-01-23 04:09:32 UTC (rev 5671) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-01-23 23:18:47 UTC (rev 5672) @@ -262,10 +262,10 @@ "LRN_GRAVITONICS", "CON_CONTGRAV_ARCH", "DEF_GARRISON_3", + "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_II", "GRO_XENO_GENETICS", "SPY_DETECT_2", - "GRO_XENO_HYBRIDS", "SHP_CONT_SYMB", "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", @@ -273,23 +273,23 @@ "CON_SUBTER_CONST", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", + "PRO_SOL_ORB_GEN", + "SHP_WEAPON_9", + "CON_ORBITAL_HAB", + "GRO_XENO_HYBRIDS", "SHP_ASTEROID_HULLS", - "SHP_WEAPON_8", "GRO_TERRAFORM", - "PRO_SOL_ORB_GEN", "LRN_PHYS_BRAIN", "LRN_TRANSLING_THT", "LRN_XENOARCH", "GRO_GENETIC_MED", "SHP_LEAD_PLATE", "SHP_BIOADAPTIVE_SPEC", - "GRO_CYBORG", "PRO_SENTIENT_AUTOMATION", "PRO_EXOBOTS", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_2", "DEF_DEFENSE_NET_3", - "SHP_WEAPON_9", "DEF_SYST_DEF_MINE_1", "DEF_PLAN_BARRIER_SHLD_3", "SPY_DETECT_3", @@ -301,7 +301,9 @@ "SHP_SENT_HULL", "SHP_ZORTRIUM_PLATE", "DEF_SYST_DEF_MINE_2", - "CON_FRC_ENRG_CAMO", + "GRO_CYBORG", + #"CON_FRC_ENRG_STRC", + #"CON_FRC_ENRG_CAMO", "GRO_GENOME_BANK", "SHP_BASIC_DAM_CONT", "CON_CONC_CAMP", @@ -314,11 +316,9 @@ "GRO_GAIA_TRANS", "GRO_ENERGY_META", "CON_ART_PLANET", - "CON_FRC_ENRG_STRC", "PRO_NEUTRONIUM_EXTRACTION", "LRN_STELLAR_TOMOGRAPHY", "LRN_ENCLAVE_VOID", - "CON_ORBITAL_HAB", "LRN_DISTRIB_THOUGHT", "GRO_ENERGY_META", "DEF_SYST_DEF_MINE_3", |
From: <dil...@us...> - 2013-01-27 21:15:19
|
Revision: 5687 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5687&view=rev Author: dilvish-fo Date: 2013-01-27 21:15:11 +0000 (Sun, 27 Jan 2013) Log Message: ----------- adjusting AI to recent tech changes etc. Modified Paths: -------------- trunk/FreeOrion/default/AI/AIFleetMission.py trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PlanetUtilsAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIFleetMission.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetMission.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/AIFleetMission.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -100,6 +100,8 @@ AIFleetMissionType.FLEET_MISSION_DEFEND, AIFleetMissionType.FLEET_MISSION_LAST_STAND , AIFleetMissionType.FLEET_MISSION_MILITARY, + AIFleetMissionType.FLEET_MISSION_INVASION, + AIFleetMissionType.FLEET_MISSION_ORBITAL_INVASION, AIFleetMissionType.FLEET_MISSION_SECURE, AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE, ]: @@ -117,17 +119,26 @@ return #nothing of record to merge with mainMissionTargets = self.getAITargets(mainMissionType) if mainMissionTargets == []: - return + pass + #return #let's let invasion fleets with no target get merged + mMT0=None + mMT0ID = None + else: + mMT0=mainMissionTargets[0] + mMT0ID = mMT0.getTargetID() if len(mainMissionTargets)>1: pass print "\tConsidering merging fleets into fleet %d, but it has multiple targets: %s"%(fleetID, str(mainMissionTargets)) sys1=universe.getSystem(systemID) sysName = (sys1 and sys1.name) or "unknown" - mMT0=mainMissionTargets[0] - mMT0ID = mMT0.getTargetID() + compatibileRolesMap={ AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE: [AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE], + AIFleetMissionType.FLEET_MISSION_MILITARY: [AIFleetMissionType.FLEET_MISSION_MILITARY], + AIFleetMissionType.FLEET_MISSION_ORBITAL_INVASION: [AIFleetMissionType.FLEET_MISSION_ORBITAL_INVASION], + AIFleetMissionType.FLEET_MISSION_INVASION: [AIFleetMissionType.FLEET_MISSION_INVASION], + } for fid in otherFleetsHere: fleetRoleA = foAI.foAIstate.getFleetRole(fid) - if fleetRoleA not in [ AIFleetMissionType.FLEET_MISSION_MILITARY, AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE]: #TODO: if fleetRoles such as LongRange start being used, adjust this + if fleetRoleA not in compatibileRolesMap[fleetRoleB] : #TODO: if fleetRoles such as LongRange start being used, adjust this continue # will only considering subsuming fleets that have a compatible role fleet2 = universe.getFleet(fid) if not (fleet2 and (fleet2.systemID == systemID)): @@ -140,6 +151,9 @@ if ( fleetRoleA== AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE ) or (fleetRoleB== AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE ): if fleetRoleA==fleetRoleB: doMerge=True + elif ( fleetRoleA== AIFleetMissionType.FLEET_MISSION_ORBITAL_INVASION ) or (fleetRoleB== AIFleetMissionType.FLEET_MISSION_ORBITAL_INVASION ): + if fleetRoleA==fleetRoleB: + doMerge=False#TODO: could allow merger if both orb invaders and both same target elif not f2Mission and (fleetB.speed > 0) and (fleet2.speed > 0): doMerge=True else: Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -98,6 +98,7 @@ self.needsEmergencyExploration=[] self.newlySplitFleets={} self.aggression=aggression + self.militaryRating=0 def __del__(self): "destructor" Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -47,7 +47,7 @@ "get colony fleets" allColonyFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_COLONISATION) - AIstate.colonyFleetIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allColonyFleetIDs) + AIstate.colonyFleetIDs[:] = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allColonyFleetIDs) # get suppliable systems and planets universe = fo.getUniverse() @@ -148,10 +148,11 @@ empirePopCtrs = set( PlanetUtilsAI.getPopulatedPlanetIDs( empireOwnedPlanetIDs) ) empireOutpostIDs=set(empireOwnedPlanetIDs) - empirePopCtrs - AIstate.popCtrIDs=empirePopCtrs - AIstate.popCtrSystemIDs=set(PlanetUtilsAI.getSystems(empirePopCtrs)) - AIstate.outpostIDs=empireOutpostIDs - AIstate.outpostSystemIDs=set(PlanetUtilsAI.getSystems(empireOutpostIDs)) + AIstate.popCtrIDs[:]=list(empirePopCtrs) + AIstate.popCtrSystemIDs[:]=list(set(PlanetUtilsAI.getSystems(empirePopCtrs))) + AIstate.outpostIDs[:]=list(empireOutpostIDs) + AIstate.outpostSystemIDs[:]=list(set(PlanetUtilsAI.getSystems(empireOutpostIDs))) + AIstate.colonizedSystems.clear() for pid in empireOwnedPlanetIDs: planet=universe.getPlanet(pid) if planet: @@ -347,6 +348,8 @@ def evaluatePlanet(planetID, missionType, fleetSupplyablePlanetIDs, species, empire): "returns the colonisation value of a planet" # TODO: in planet evaluation consider specials and distance + discountMultiplier = 20.0 + valMod = 0 universe = fo.getUniverse() empireResearchList = [element.tech for element in empire.researchQueue] @@ -364,9 +367,9 @@ if (empire.getTechStatus("PRO_SOL_ORB_GEN") == fo.techStatus.complete) or ( "PRO_SOL_ORB_GEN" in empireResearchList[:8]) : if system.starType in [fo.starType.blue, fo.starType.white]: if len (AIstate.empireStars.get(fo.starType.blue, [])+AIstate.empireStars.get(fo.starType.white, []))==0: - starBonus +=40 - else: - starBonus +=5 #still has extra value as an alternate location for solar generators + starBonus +=20* discountMultiplier + elif planet.systemID not in (AIstate.popCtrSystemIDs + AIstate.outpostSystemIDs) : + starBonus +=1+10*discountMultiplier #still has extra value as an alternate location for solar generators if system.starType in [fo.starType.yellow, fo.starType.orange]: if len ( AIstate.empireStars.get(fo.starType.blue, [])+AIstate.empireStars.get(fo.starType.white, [])+ AIstate.empireStars.get(fo.starType.yellow, [])+AIstate.empireStars.get(fo.starType.orange, []))==0: @@ -374,24 +377,27 @@ else: starBonus +=2 #still has extra value as an alternate location for solar generators if (empire.getTechStatus("PRO_SINGULAR_GEN") == fo.techStatus.complete) or ( "PRO_SINGULAR_GEN" in empireResearchList[:8]) : - if system.starType in [fo.starType.blackHole]: + if system.starType in [fo.starType.blackHole] : if len (AIstate.empireStars.get(fo.starType.blackHole, []))==0: - starBonus +=80 #pretty rare planets, good for generator - else: - starBonus +=20 #still has extra value as an alternate location for generators & for bnlocking enemies generators + starBonus +=80*discountMultiplier #pretty rare planets, good for generator + elif planet.systemID not in (AIstate.popCtrSystemIDs + AIstate.outpostSystemIDs): + starBonus +=40*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators + elif system.starType in [fo.starType.red] and ( len (AIstate.empireStars.get(fo.starType.blackHole, [])) + len (AIstate.empireStars.get(fo.starType.red, [])))==0: + if planet.systemID not in (AIstate.popCtrSystemIDs + AIstate.outpostSystemIDs): + starBonus +=40*discountMultiplier # can be used for artificial black hole if (empire.getTechStatus("PRO_NEUTRONIUM_EXTRACTION") == fo.techStatus.complete) or ( "PRO_NEUTRONIUM_EXTRACTION" in empireResearchList[:8]) : if system.starType in [fo.starType.neutron]: if len (AIstate.empireStars.get(fo.starType.neutron, []))==0: - starBonus +=40 #pretty rare planets, good for armor + starBonus +=40*discountMultiplier #pretty rare planets, good for armor else: - starBonus +=5 #still has extra value as an alternate location for generators & for bnlocking enemies generators + starBonus +=10*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators retval = starBonus planetSpecials = list(planet.specials) if (missionType == AIFleetMissionType.FLEET_MISSION_OUTPOST ): for special in planetSpecials: if "_NEST_" in special: - retval+=10 # get an outpost on the nest quick + retval+=5*discountMultiplier # get an outpost on the nest quick if ( ( planet.size == fo.planetSize.asteroids ) and (empire.getTechStatus("PRO_MICROGRAV_MAN") == fo.techStatus.complete )): if system: astVal=0 @@ -404,7 +410,7 @@ astVal=0 break elif otherPlanet.size!= fo.planetSize.gasGiant and otherPlanet.owner==empire.empireID: - astVal+=20 + astVal+=20 * discountMultiplier retval += astVal if ( ( planet.size == fo.planetSize.gasGiant ) and ( (empire.getTechStatus("PRO_ORBITAL_GEN") == fo.techStatus.complete ) or ( "PRO_ORBITAL_GEN" in empireResearchList[:10]) )): if system: @@ -413,11 +419,11 @@ otherPlanet=universe.getPlanet(pid) if otherPlanet.size == fo.planetSize.asteroids and otherPlanet.owner==empire.empireID: if empire.getTechStatus("PRO_EXOBOTS") == fo.techStatus.complete: - orbGenVal+=30 + orbGenVal+=10*discountMultiplier elif otherPlanet.size!= fo.planetSize.gasGiant and otherPlanet.owner==empire.empireID: - orbGenVal+=50 + orbGenVal+=10*discountMultiplier retval += orbGenVal - if foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0) > curBestMilShipRating: + if foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0) > 2*curBestMilShipRating: retval = retval / 2.0 return int(retval) else: #colonization mission @@ -430,12 +436,12 @@ if (species and species.name in [ "SP_EXOBOT", "SP_SUPER_TEST" ]): for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: - retval+=60 + retval+=25*discountMultiplier else: retval+=20 thrtRatio = foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0) / float(ProductionAI.curBestMilShipRating()) if thrtRatio > 4: - retval = 2* retval / thrtRatio + retval = 2 * retval / thrtRatio elif thrtRatio >= 2: retval = 0.6* retval elif thrtRatio > 0: @@ -456,7 +462,7 @@ popSizeMod=0 popSizeMod += popSizeModMap["env"][planetEnv] if "SELF_SUSTAINING" in tagList: - popSizeMod+=3 + popSizeMod*=2 popSizeMod += starPopMod if (empire.getTechStatus("GRO_SUBTER_HAB") == fo.techStatus.complete) or "TUNNELS_SPECIAL" in planetSpecials: if "TECTONIC_INSTABILITY_SPECIAL" not in planetSpecials: @@ -504,9 +510,27 @@ for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: - miningBonus=150 - - + miningBonus=200 + + proSingVal = [0, 4][(len( AIstate.empireStars.get(fo.starType.blackHole, [])) > 0)] + basePopInd=0.2 + indTechMap={ "GRO_ENERGY_META": 0.5, + "PRO_ROBOTIC_PROD":0.4, + "PRO_FUSION_GEN": 1.0, + "PRO_INDUSTRY_CENTER_I": 1, + "PRO_INDUSTRY_CENTER_II":1, + "PRO_INDUSTRY_CENTER_III":1, + "PRO_SOL_ORB_GEN": 2.0, #assumes will build a gen at a blue/white star + "PRO_SOL_ORB_GEN": 5, # half the max value + "PRO_SINGULAR_GEN": proSingVal, + } + + indVal = 0 + if (empire.getTechStatus("PRO_SENTIENT_AUTOMATION") == fo.techStatus.complete): + indVal += discountMultiplier * 5 + for tech in indTechMap: + if (empire.getTechStatus(tech) == fo.techStatus.complete): + indVal += discountMultiplier * basePopInd * popSize * indTechMap[tech] # used to give preference to closest worlds empireID = empire.empireID capitalID = PlanetUtilsAI.getCapital() @@ -522,12 +546,12 @@ retval=0.0 if popSize<0 and (miningBonus or (fo.currentTurn() >= 10)) : #can still have industry focus bonuses and buildings if foAI.foAIstate.aggression > fo.aggression.typical: - retval = starBonus+asteroidBonus+gasGiantBonus + retval = starBonus+max(asteroidBonus+gasGiantBonus, miningBonus) elif popSize==0 and (miningBonus or( fo.currentTurn() >= 10)): if foAI.foAIstate.aggression > fo.aggression.typical: retval = starBonus+max(asteroidBonus+gasGiantBonus, miningBonus) else: - retval = starBonus+max(asteroidBonus+gasGiantBonus, miningBonus) + valMod + 2*popSize + retval = starBonus+max(indVal+asteroidBonus+gasGiantBonus, miningBonus) + valMod if planet.systemID in annexableRing1: retval += 10 elif planet.systemID in annexableRing2: @@ -584,7 +608,7 @@ def sendColonyShips(colonyFleetIDs, evaluatedPlanets, missionType): "sends a list of colony ships to a list of planet_value_pairs" fleetPool = colonyFleetIDs[:] - potentialTargets = evaluatedPlanets[:] + potentialTargets = [ (pid, (score, specName) ) for (pid, (score, specName) ) in evaluatedPlanets if score > 100 ] print "colony/outpost ship matching -- fleets %s to planets %s"%( fleetPool, evaluatedPlanets) #for planetID_value_pair in evaluatedPlanets: Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -180,7 +180,12 @@ troops = planet.currentMeterValue(fo.meterType.troops) specName=planet.speciesName species=fo.getSpecies(specName) - if not species:# perhaps stealth might make species info inaccessible + productionVal = 8*(planet.currentMeterValue(fo.meterType.targetIndustry)+planet.currentMeterValue(fo.meterType.targetResearch)) + supplyVal=0 + enemyVal=0 + if planet.owner!=-1 : + enemyVal=productionVal #value in taking this away from an enemy + if not species:#TODO: perhaps stealth makes planet inacccesible & should abort try: targetPop=planet.currentMeterValue(fo.meterType.targetPopulation) popVal = 2*targetPop @@ -188,16 +193,16 @@ popVal=0 else: popVal = evaluatePlanet(planetID, AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire) #evaluatePlanet is implorted from ColonisationAI - if planetID not in fleetSupplyablePlanetIDs: - popVal = 2.0*popVal#assign higher value if the colony would extend our supply range + if planetID not in fleetSupplyablePlanetIDs: #extends supply and probably visibility + supplyVal = 20#TODO: better analysis here if supply obstructed by defending ships planetSpecials = list(planet.specials) specialVal=0 if ( ( planet.size == fo.planetSize.asteroids ) and (empire.getTechStatus("PRO_ASTEROID_MINE") == fo.techStatus.complete ) ): - specialVal= 15 # asteroid mining is great, fast return + specialVal= 15 #TODO: should do more eval re asteroid mining here for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: specialVal = 40 - return popVal+specialVal+bldTally, troops + return popVal+supplyVal+specialVal+bldTally+productionVal+enemyVal-8*troops, troops def getPlanetPopulation(planetID): "return planet population" @@ -256,4 +261,8 @@ invasionFleetIDs = AIstate.invasionFleetIDs sendInvasionFleets(invasionFleetIDs, AIstate.invasionTargets, AIFleetMissionType.FLEET_MISSION_INVASION) + allInvasionFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_INVASION) + for fid in FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allInvasionFleetIDs): + thisMission = foAI.foAIstate.getAIFleetMission(fid) + thisMission.checkMergers(context="Post-send consolidation of unassigned troops") Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -5,8 +5,9 @@ from EnumsAI import AIFleetMissionType, AITargetType import FleetUtilsAI import PlanetUtilsAI -from random import choice +from random import choice, random import ExplorationAI +import PriorityAI MinThreat = 6 # the minimum threat level that will be ascribed to an unkown threat capable of killing scouts MilitaryAllocations = [] @@ -47,8 +48,8 @@ print "==================================================" print "Total Military Rating: %d"%totMilRating print "---------------------------------" + foAI.foAIstate.militaryRating=totMilRating - milFleetIDs = list( FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allMilitaryFleetIDs)) availMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), milFleetIDs ) ) print "==================================================" @@ -79,7 +80,10 @@ # get systems to defend capitalID = PlanetUtilsAI.getCapital() - capitalPlanet = universe.getPlanet(capitalID) + if capitalID != None: + capitalPlanet = universe.getPlanet(capitalID) + else: + capitalPlanet=None #TODO: if no owned planets try to capture one! if capitalPlanet: capitalSysID = capitalPlanet.systemID @@ -112,7 +116,7 @@ safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 0.95, 0.95 ][foAI.foAIstate.aggression] - topTargetPlanets = [pid for pid, pscore, trp in AIstate.invasionTargets[:10] if pscore > 500] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] if pscore > 10] + topTargetPlanets = [pid for pid, pscore, trp in AIstate.invasionTargets[:PriorityAI.allottedInvasionTargets] if pscore > 20] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] if pscore > 20] topTargetSystems = [] for sysID in PlanetUtilsAI.getSystems( topTargetPlanets ): if sysID not in topTargetSystems: @@ -123,9 +127,10 @@ #--------Capital Threat ---------- capitalThreat = safetyFactor*(2* threatBias +sum( [ foAI.foAIstate.systemStatus[capitalSysID][thrtKey] for thrtKey in [tkey for tkey in foAI.foAIstate.systemStatus.get(capitalSysID, {}).keys() if 'Threat' in tkey]] )) newAlloc=0 - if (capitalThreat > 0.5*(availMilRating+0.8*alreadyAssignedRating[capitalSysID]) ) and tryReset: - tryAgain(allMilitaryFleetIDs) - return + if tryReset: + if (capitalThreat > 0.5*(availMilRating+0.8*alreadyAssignedRating[capitalSysID]) ) : + tryAgain(allMilitaryFleetIDs) + return if capitalThreat > 0.8*alreadyAssignedRating[capitalSysID]: newAlloc = min(remainingMilRating, int( 0.999 + 1.2*(capitalThreat- 0.8*alreadyAssignedRating[capitalSysID]) ) ) allocations.append( ( capitalSysID, newAlloc, True, 3) ) @@ -174,9 +179,10 @@ for sid, thrt in otSysThreat: curAlloc=0.8*alreadyAssignedRating[sid] thisAlloc=0 - if thrt>curAlloc and remainingMilRating > (10+ 1.5*(thrt-curAlloc)): #only record an allocation for this invasion if we have enough rating available - thisAlloc =int(10.99999 + (thrt-curAlloc)*1.5) - allocations.append( (sid, thisAlloc, False, 3) ) + if 2*thrt>curAlloc and (curAlloc>0 or remainingMilRating > (10+ (2*thrt-curAlloc))): #only record more allocation for this invasion if we already started or have enough rating available + thisAlloc =int(10.99999 + (2*thrt-curAlloc)) + takeAny= curAlloc>0 + allocations.append( (sid, thisAlloc, takeAny ,4) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) Modified: trunk/FreeOrion/default/AI/PlanetUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/PlanetUtilsAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/PlanetUtilsAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -22,6 +22,9 @@ def getCapital(): # if no current capital returns planet with biggest pop universe = fo.getUniverse() empire = fo.getEmpire() + if empire == None: + print "Danger Danger! FO can't find an empire for me!!!!" + return None empireID = empire.empireID capitalID = empire.capitalID homeworld = universe.getPlanet(capitalID) Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -13,6 +13,9 @@ from ProductionAI import curBestMilShipRating, getBestShipInfo import math +allottedInvasionTargets=0 +allottedColonyTargets=0 + def calculatePriorities(): "calculates the priorities of the AI player" print("calculating priorities") @@ -177,13 +180,20 @@ def calculateColonisationPriority(): "calculates the demand for colony ships by colonisable planets" + global allottedColonyTargets + totalPP=fo.getEmpire().productionPoints + colonyCost=250*(1+ 0.1*len( list(AIstate.popCtrIDs) + list(AIstate.outpostIDs) )) + turnsToBuild=8 + allottedPortion = 0.3 + #allottedColonyTargets = 1+ int(fo.currentTurn()/50) + allottedColonyTargets = 1 + int( totalPP*turnsToBuild*allottedPortion/colonyCost) - numColonisablePlanetIDs = len(foAI.foAIstate.colonisablePlanetIDs) + numColonisablePlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisablePlanetIDs if score > 100 ][:allottedColonyTargets] ) if (numColonisablePlanetIDs == 0): return 0 colonyshipIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_COLONISATION) numColonyships = len(FleetUtilsAI.extractFleetIDsWithoutMissionTypes(colonyshipIDs)) - colonisationPriority = 121 * (2+numColonisablePlanetIDs - numColonyships) / (numColonisablePlanetIDs+1) + colonisationPriority = 121 * (1+numColonisablePlanetIDs - numColonyships) / (numColonisablePlanetIDs+1) # print "" # print "Number of Colony Ships : " + str(numColonyships) @@ -198,6 +208,7 @@ "calculates the demand for outpost ships by colonisable planets" numOutpostPlanetIDs = len(foAI.foAIstate.colonisableOutpostIDs) + numOutpostPlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisableOutpostIDs if score > 100 ][:allottedColonyTargets] ) completedTechs = getCompletedTechs() if numOutpostPlanetIDs == 0 or not 'CON_ENV_ENCAPSUL' in completedTechs: return 0 @@ -217,14 +228,16 @@ 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 - totalVal= sum( [pscore for pid, pscore, trp in AIstate.invasionTargets[:10] ] ) - troopsNeeded= sum( [(trp+4) for pid, pscore, trp in AIstate.invasionTargets[:10] ] ) + 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 10 #hsould always have at least a low lvl of production going into troop fleets @@ -250,7 +263,7 @@ 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 ) , totalVal ) + invasionPriority = max( 10+ 200*max(0, troopShipsNeeded ) , int(0.1* totalVal) ) if invasionPriority < 0: return 0 if foAI.foAIstate.aggression==fo.aggression.beginner: Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -11,6 +11,7 @@ import math from ColonisationAI import empireSpecies, empireColonizers, empireSpeciesSystems import TechsListsAI +#import PriorityAI #moved to end of file to prevent circular import problems shipTypeMap = { AIPriorityType.PRIORITY_PRODUCTION_EXPLORATION: AIShipDesignTypes.explorationShip, AIPriorityType.PRIORITY_PRODUCTION_OUTPOST: AIShipDesignTypes.outpostShip, @@ -625,8 +626,9 @@ except: print "Error: exception triggered and caught: ", traceback.format_exc() + numExobotShips=0 #TODO: do real calc here if ("BLD_EXOBOT_SHIP" in possibleBuildingTypes) and ("BLD_EXOBOT_SHIP" not in queuedBldgNames): - if len( empireColonizers.get("SP_EXOBOT", []))==0 : #don't have an exobot shipyard yet + if len( empireColonizers.get("SP_EXOBOT", []))==0 or numExobotShips==0: #don't have an exobot shipyard yet try: res=fo.issueEnqueueBuildingProductionOrder("BLD_EXOBOT_SHIP", empire.capitalID) print "Enqueueing BLD_EXOBOT_SHIP, with result %d"%res @@ -807,7 +809,51 @@ except: print "problem queueing BLD_SOL_ORB_GEN at planet", useloc, "of system ", useSys pass - + + bldName = "BLD_ART_BLACK_HOLE" + if ( ( empire.buildingTypeAvailable(bldName) ) and (foAI.foAIstate.aggression > fo.aggression.typical) and + (len( AIstate.empireStars.get(fo.starType.blackHole, [])) == 0 ) and (len( AIstate.empireStars.get(fo.starType.red, [])) > 0) ): + bldType = fo.getBuildingType(bldName) + alreadyGotOne=False + for pid in list(AIstate.popCtrIDs) + list(AIstate.outpostIDs): + planet=universe.getPlanet(pid) + if planet and bldName in [bld.buildingTypeName for bld in map( universe.getObject, planet.buildingIDs)]: + alreadyGotOne = True + queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] #TODO: check that queued locs or already built one are at red stars + if len (queuedBldLocs)==0 and not alreadyGotOne: # + if not homeworld: + useSys= AIstate.empireStars[fo.starType.red][0] + else: + distanceMap={} + for sysID in AIstate.empireStars.get(fo.starType.red, []): + try: + distanceMap[sysID] = len(universe.leastJumpsPath(homeworld.systemID, sysID, empire.empireID)) + except: + pass + redSysList = sorted( [ (dist, sysID) for sysID, dist in distanceMap.items() ] ) + useLoc=None + for dist, sysID in redSysList: + for loc in AIstate.colonizedSystems[sysID]: + planet=universe.getPlanet(loc) + if planet and planet.speciesName not in [ "", None ]: + species= fo.getSpecies(planet.speciesName) + if species and "PHOTOTROPHIC" in list(species.tags): + break + else: + if len(AIstate.colonizedSystems[sysID]) >0: + useLoc = AIstate.colonizedSystems[sysID][0] + if useLoc !=None: + break + if useLoc !=None: + try: + res=fo.issueEnqueueBuildingProductionOrder(bldName, useLoc) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, useLoc, universe.getPlanet(useLoc).name, res) + if res: + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + print "Requeueing %s to front of build queue, with result %d"%(bldName, res) + except: + print "problem queueing %s at planet"%bldName, useloc, "of system ", useSys + bldName = "BLD_BLACK_HOLE_POW_GEN" if empire.buildingTypeAvailable(bldName) and foAI.foAIstate.aggression > fo.aggression.cautious: bldType = fo.getBuildingType(bldName) @@ -950,9 +996,11 @@ if not planet: continue tPop = planet.currentMeterValue(fo.meterType.targetPopulation) - if (tPop >= 36): + tInd=planet.currentMeterValue(fo.meterType.targetIndustry) + cInd=planet.currentMeterValue(fo.meterType.industry) + if (tPop >= 25): cPop = planet.currentMeterValue(fo.meterType.population) - if (cPop >=0.95*tPop): + if (cPop >=0.95*tPop) and cInd < 1.5* tInd: if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building if planet.focus in [ AIFocusType.FOCUS_INDUSTRY, AIFocusType.FOCUS_MINING ]: fo.issueChangeFocusOrder(pid, AIFocusType.FOCUS_RESEARCH) @@ -961,7 +1009,7 @@ if res: queuedBldLocs.append(pid) res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front - elif (cPop < 20 ): + elif (cPop < 18 ) or cPop < 0.75*tPop: for bldg in planet.buildingIDs: if universe.getObject(bldg).buildingTypeName == bldName: res=fo.issueScrapOrder( bldg) @@ -1037,8 +1085,11 @@ numOutpostTargs=len(foAI.foAIstate.colonisableOutpostIDs ) numOutpostFleets=len( FleetUtilsAI.getEmpireFleetIDsByRole( AIFleetMissionType.FLEET_MISSION_OUTPOST) )# counting existing outpost fleets each as one ship totOutpostFleets = queuedOutpostShips + numOutpostFleets - maxColonyFleets = max( min( numColonyTargs+1+fo.currentTurn()/10 , numTotalFleets/4 ), 3+int(3*len(empireColonizers))) - maxOutpostFleets = min(numOutpostTargs+1+fo.currentTurn()/10, numTotalFleets/4 ) + + #maxColonyFleets = max( min( numColonyTargs+1+fo.currentTurn()/10 , numTotalFleets/4 ), 3+int(3*len(empireColonizers))) + #maxOutpostFleets = min(numOutpostTargs+1+fo.currentTurn()/10, numTotalFleets/4 ) + maxColonyFleets = PriorityAI.allottedColonyTargets + maxOutpostFleets = maxColonyFleets print "Production Queue Priorities:" filteredPriorities = {} @@ -1154,3 +1205,6 @@ queue = fo.getEmpire().productionQueue return queue.totalSpent + + +import PriorityAI Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-01-27 16:52:08 UTC (rev 5686) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-01-27 21:15:11 UTC (rev 5687) @@ -242,22 +242,23 @@ "CON_ENV_ENCAPSUL", "PRO_FUSION_GEN", "SHP_WEAPON_5", - "PRO_ORBITAL_GEN", "PRO_ROBOTIC_PROD", "DEF_DEFENSE_NET_1", "DEF_GARRISON_1", + "CON_ORBITAL_CON", "SHP_WEAPON_6", "GRO_SYMBIOTIC_BIO", "LRN_ARTIF_MINDS", "LRN_FORCE_FIELD", - "SHP_WEAPON_8", "GRO_GENETIC_ENG", "SHP_MULTICELL_CAST", - "CON_ORBITAL_CON", + "PRO_ORBITAL_GEN", + "SHP_WEAPON_7", "PRO_MICROGRAV_MAN", + "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_I", "DEF_GARRISON_2", - "GRO_LIFECYCLE_MAN", + #"GRO_LIFECYCLE_MAN", # ship part is too expensive for now "SHP_ENDOCRINE_SYSTEMS", "LRN_GRAVITONICS", "CON_CONTGRAV_ARCH", @@ -274,6 +275,8 @@ "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", "PRO_SOL_ORB_GEN", + "DEF_DEFENSE_NET_REGEN_1", + "DEF_PLAN_BARRIER_SHLD_2", "SHP_WEAPON_9", "CON_ORBITAL_HAB", "GRO_XENO_HYBRIDS", @@ -287,8 +290,6 @@ "SHP_BIOADAPTIVE_SPEC", "PRO_SENTIENT_AUTOMATION", "PRO_EXOBOTS", - "DEF_DEFENSE_NET_REGEN_1", - "DEF_PLAN_BARRIER_SHLD_2", "DEF_DEFENSE_NET_3", "DEF_SYST_DEF_MINE_1", "DEF_PLAN_BARRIER_SHLD_3", @@ -315,6 +316,8 @@ "DEF_DEFENSE_NET_REGEN_2", "GRO_GAIA_TRANS", "GRO_ENERGY_META", + "LRN_TIME_MECH", + "LRN_ART_BLACK_HOLE", "CON_ART_PLANET", "PRO_NEUTRONIUM_EXTRACTION", "LRN_STELLAR_TOMOGRAPHY", @@ -324,7 +327,6 @@ "DEF_SYST_DEF_MINE_3", "DEF_PLAN_BARRIER_SHLD_4", "SHP_WEAPON_13", - "CON_NDIM_STRC", "SPY_DETECT_4", "SHP_WEAPON_11", "SHP_WEAPON_12", |
From: <dil...@us...> - 2013-01-31 01:27:46
|
Revision: 5695 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5695&view=rev Author: dilvish-fo Date: 2013-01-31 01:27:39 +0000 (Thu, 31 Jan 2013) Log Message: ----------- misc AI adjustments Modified Paths: -------------- trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResearchAI.py trunk/FreeOrion/default/AI/ResourcesAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-01-30 17:49:48 UTC (rev 5694) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-01-31 01:27:39 UTC (rev 5695) @@ -95,7 +95,7 @@ sysID = status['sysID'] if len( list( universe.getSystem(sysID).planetIDs ) ) ==0: continue - systemDict[sysID] = systemDict.get( sysID, 0) + status['rating'] + systemDict[sysID] = systemDict.get( sysID, 0) + status.get('rating', {}).get('overall', 0) rankedSystems = sorted( [(val, sysID) for sysID, val in systemDict.items() ] ) if rankedSystems: capitalSysID = rankedSystems[-1][-1] Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-01-30 17:49:48 UTC (rev 5694) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-01-31 01:27:39 UTC (rev 5695) @@ -122,22 +122,25 @@ planets = map(universe.getPlanet, ownedPlanetIDs) targetRP = sum( map( lambda x: x.currentMeterValue(fo.meterType.targetResearch), planets) ) + styleIndex = empireID%2 + styleAdjustmentMap = {0:0, 1:0} + styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) if industrySurge: researchPriority = 5 else: if (fo.currentTurn() < 20) or not gotAlgo: researchPriority = 60 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance elif fo.currentTurn() < 30: - researchPriority = 30 # mid industry , mid research + researchPriority = 30 +styleAdjustment# mid industry , mid research elif fo.currentTurn() < 40: - researchPriority = 20 # high industry , low research + researchPriority = 20+styleAdjustment # high industry , low research else: researchQueue = list(empire.researchQueue) - researchPriority = 15 # high industry , low research + researchPriority = 15+styleAdjustment # high industry , low research if len(researchQueue) == 0 : researchPriority = 0 # done with research elif len(researchQueue) <5 and researchQueue[-1].allocation > 0 : - researchPriority = 1 # barely not done with research + researchPriority = len(researchQueue) # barely not done with research elif len(researchQueue) <10 and researchQueue[-1].allocation > 0 : researchPriority = 2 # almost done with research elif len(researchQueue) <20 and researchQueue[int(len(researchQueue)/2)].allocation > 0 : @@ -182,8 +185,8 @@ "calculates the demand for colony ships by colonisable planets" global allottedColonyTargets totalPP=fo.getEmpire().productionPoints - colonyCost=250*(1+ 0.1*len( list(AIstate.popCtrIDs) + list(AIstate.outpostIDs) )) - turnsToBuild=8 + colonyCost=250*(1+ 0.04*len( list(AIstate.popCtrIDs) + list(AIstate.outpostIDs) )) + turnsToBuild=8#TODO: check for susp anim pods, build time 10 allottedPortion = 0.3 #allottedColonyTargets = 1+ int(fo.currentTurn()/50) allottedColonyTargets = 1 + int( totalPP*turnsToBuild*allottedPortion/colonyCost) Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-01-30 17:49:48 UTC (rev 5694) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-01-31 01:27:39 UTC (rev 5695) @@ -457,13 +457,13 @@ is1, is2 = "FU_BASIC_TANK", "ST_CLOAK_1" for id in [1, 2, 3, 4]: newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp], "", model) for iw in range(2, 6) ] -# for id in [1, 2, 3, 4]: -# newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp], "", model) for iw in range(6, 9) ] # when farther along, use 2 pods + for id in [1, 2, 3, 4]: + newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp], "", model) for iw in range(6, 9) ] # when farther along, use 2 pods - nb, hull = designNameBases[2]+"%1d_%1d", "SH_ENDOMORPHIC" - cp = "CO_SUSPEND_ANIM_POD" + nb = designNameBases[2]+"%1d_%1d" + cp2 = "CO_SUSPEND_ANIM_POD" for id in [1, 2, 3, 4]: - newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", "", cp, is1], "", model) for iw in range(2, 9) ] + newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp2], "", model) for iw in range(2, 9) ] currentTurn=fo.currentTurn() needsAdding=[] @@ -988,39 +988,49 @@ break #only initiate max of one new build per turn bldName = "BLD_CONC_CAMP" - if foAI.foAIstate.aggression>fo.aggression.typical and empire.buildingTypeAvailable(bldName): - queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] - bldType = fo.getBuildingType(bldName) - for pid in AIstate.popCtrIDs: - planet=universe.getPlanet(pid) - if not planet: - continue - tPop = planet.currentMeterValue(fo.meterType.targetPopulation) - tInd=planet.currentMeterValue(fo.meterType.targetIndustry) - cInd=planet.currentMeterValue(fo.meterType.industry) - if (tPop >= 25): - cPop = planet.currentMeterValue(fo.meterType.population) - if (cPop >=0.95*tPop) and cInd < 1.5* tInd: - if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building - if planet.focus in [ AIFocusType.FOCUS_INDUSTRY, AIFocusType.FOCUS_MINING ]: - fo.issueChangeFocusOrder(pid, AIFocusType.FOCUS_RESEARCH) - res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) - print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) - if res: - queuedBldLocs.append(pid) - res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front - elif (cPop < 18 ) or cPop < 0.75*tPop: - for bldg in planet.buildingIDs: - if universe.getObject(bldg).buildingTypeName == bldName: - res=fo.issueScrapOrder( bldg) - print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) + bldType = fo.getBuildingType(bldName) + for pid in AIstate.popCtrIDs: + planet=universe.getPlanet(pid) + if not planet: + continue + tPop = planet.currentMeterValue(fo.meterType.targetPopulation) + tInd=planet.currentMeterValue(fo.meterType.targetIndustry) + cInd=planet.currentMeterValue(fo.meterType.industry) + cPop = planet.currentMeterValue(fo.meterType.population) + if (cPop < 18 ) or cPop < 0.75*tPop: #check even if not aggressive, etc, just in case acquired planet with a ConcCamp on it + for bldg in planet.buildingIDs: + if universe.getObject(bldg).buildingTypeName == bldName: + res=fo.issueScrapOrder( bldg) + print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) + elif foAI.foAIstate.aggression>fo.aggression.typical and empire.buildingTypeAvailable(bldName) and (tPop >= 25) and ((empire.empireID+pid)%3 == 0): + queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] + if (cPop >=0.95*tPop) and cInd < 1.5* tInd: + if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building + if planet.focus in [ AIFocusType.FOCUS_INDUSTRY, AIFocusType.FOCUS_MINING ]: + fo.issueChangeFocusOrder(pid, AIFocusType.FOCUS_RESEARCH) + res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) + if res: + queuedBldLocs.append(pid) + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + bldName = "BLD_EVACUATION" + bldType = fo.getBuildingType(bldName) + for pid in AIstate.popCtrIDs: + planet=universe.getPlanet(pid) + if not planet: + continue + for bldg in planet.buildingIDs: + if universe.getObject(bldg).buildingTypeName == bldName: + res=fo.issueScrapOrder( bldg) + print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) totalPPSpent = fo.getEmpire().productionQueue.totalSpent print " Total Production Points Spent: " + str(totalPPSpent) - wastedPP = totalPP - totalPPSpent + wastedPP = max(0, totalPP - totalPPSpent) print " Wasted Production Points: " + str(wastedPP) + availPP = totalPP*1.1 - totalPPSpent print "" print "Possible ship designs to build:" @@ -1132,9 +1142,9 @@ #print "\n ship priority selection list: \n %s \n\n"%str(priorityChoices) loopCount = 0 - while (wastedPP > 0) and (loopCount <100) and (priorityChoices != [] ): #make sure don't get stuck in some nonbreaking loop like if all shipyards captured + while (availPP > 0) and (loopCount <100) and (priorityChoices != [] ): #make sure don't get stuck in some nonbreaking loop like if all shipyards captured loopCount +=1 - print "Beginning build enqueue loop %d; %.1f PP available"%(loopCount, wastedPP) + print "Beginning build enqueue loop %d; %.1f PP available"%(loopCount, availPP) thisPriority = choice( priorityChoices ) print "selected priority: ", AIPriorityNames[thisPriority] makingColonyShip=False @@ -1177,12 +1187,21 @@ print "" if numShips>1: fo.issueChangeProductionQuantityOrder(productionQueue.size -1, 1, numShips) - wastedPP -= perTurnCost + availPP -= perTurnCost if makingColonyShip: totColonyFleets +=numShips - res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + if totalPP > 4* perTurnCost: + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + continue if makingOutpostShip: totOutpostFleets +=numShips + if totalPP > 4* perTurnCost: + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + continue + if totalPP > 10* perTurnCost and productionQueue[ productionQueue.size -1].allocation < 0.5* perTurnCost : + leadingBlockPP = sum( [ elem.allocation for elem in [productionQueue[elemi] for elemi in range(0, min(4, productionQueue.size))]]) + if leadingBlockPP > 0.5* totalPP: + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front print "" def getAvailableBuildLocations(shipDesignID): Modified: trunk/FreeOrion/default/AI/ResearchAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResearchAI.py 2013-01-30 17:49:48 UTC (rev 5694) +++ trunk/FreeOrion/default/AI/ResearchAI.py 2013-01-31 01:27:39 UTC (rev 5695) @@ -78,7 +78,7 @@ print "" if fo.currentTurn()==1: if foAI.foAIstate.aggression <=fo.aggression.typical: - newtech = TechsListsAI.primaryMetaTechsList() + newtech = TechsListsAI.primaryMetaTechsList( index=empireID%2 ) else: #newtech = TechsListsAI.aggressiveTechs() newtech = TechsListsAI.primaryMetaTechsList() Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-01-30 17:49:48 UTC (rev 5694) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-01-31 01:27:39 UTC (rev 5695) @@ -411,9 +411,10 @@ ntPP, ntRP= newTargets[pid].get(RFocus, (0, 0)) print "pID (%3d) %22s | c: %5.1f / %5.1f | cT: %5.1f / %5.1f | cF: %8s | nF: %8s | cT: %5.1f / %5.1f | %.2f"%(pid, planetMap[pid].name, cRP, cPP, otRP, otPP, fociMap.get(oldFocus, 'unknown'), fociMap[RFocus] , ntRP, ntPP , ratio) continue # RP is getting too expensive, but might be willing to still allocate from a planet with less PP to lose - newFoci[pid] = RFocus - curTargetRP += (RR-IR) - curTargetPP -= (II-RI) + if planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) > 0: + newFoci[pid] = RFocus + curTargetRP += (RR-IR) + curTargetPP -= (II-RI) print "============================" print "Planet Focus Assignments to achieve target RP/PP ratio of %.2f from current ratio of %.2f ( %.1f / %.1f )"%(priorityRatio, rp/(pp+0.0001), rp, pp) print "Max Industry assignments would result in target RP/PP ratio of %.2f ( %.1f / %.1f )"%( ctRP0/ (ctPP0 + 0.0001), ctRP0, ctPP0 ) Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-01-30 17:49:48 UTC (rev 5694) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-01-31 01:27:39 UTC (rev 5695) @@ -229,115 +229,223 @@ ] return defTechs2 -def primaryMetaTechsList(): +def primaryMetaTechsList(index=0): "primary techs for all categories" - - primaryMetaTechs = [ - "GRO_PLANET_ECOL", - "GRO_SUBTER_HAB", - "SHP_DOMESTIC_MONSTER", - "SHP_ORG_HULL", - "SHP_WEAPON_3", - "LRN_ALGO_ELEGANCE", - "CON_ENV_ENCAPSUL", - "PRO_FUSION_GEN", - "SHP_WEAPON_5", - "PRO_ROBOTIC_PROD", - "DEF_DEFENSE_NET_1", - "DEF_GARRISON_1", - "CON_ORBITAL_CON", - "SHP_WEAPON_6", - "GRO_SYMBIOTIC_BIO", - "LRN_ARTIF_MINDS", - "LRN_FORCE_FIELD", - "GRO_GENETIC_ENG", - "SHP_MULTICELL_CAST", - "PRO_ORBITAL_GEN", - "SHP_WEAPON_7", - "PRO_MICROGRAV_MAN", - "SHP_WEAPON_8", - "PRO_INDUSTRY_CENTER_I", - "DEF_GARRISON_2", - #"GRO_LIFECYCLE_MAN", # ship part is too expensive for now - "SHP_ENDOCRINE_SYSTEMS", - "LRN_GRAVITONICS", - "CON_CONTGRAV_ARCH", - "DEF_GARRISON_3", - "SHP_WEAPON_8", - "PRO_INDUSTRY_CENTER_II", - "GRO_XENO_GENETICS", - "SPY_DETECT_2", - "SHP_CONT_SYMB", - "DEF_DEFENSE_NET_2", - "DEF_PLAN_BARRIER_SHLD_1", - "CON_METRO_INFRA", - "CON_SUBTER_CONST", - "SHP_MONOCELL_EXP", - "SHP_ENDOSYMB_HULL", - "PRO_SOL_ORB_GEN", - "DEF_DEFENSE_NET_REGEN_1", - "DEF_PLAN_BARRIER_SHLD_2", - "SHP_WEAPON_9", - "CON_ORBITAL_HAB", - "GRO_XENO_HYBRIDS", - "SHP_ASTEROID_HULLS", - "GRO_TERRAFORM", - "LRN_PHYS_BRAIN", - "LRN_TRANSLING_THT", - "LRN_XENOARCH", - "GRO_GENETIC_MED", - "SHP_LEAD_PLATE", - "SHP_BIOADAPTIVE_SPEC", - "PRO_SENTIENT_AUTOMATION", - "PRO_EXOBOTS", - "DEF_DEFENSE_NET_3", - "DEF_SYST_DEF_MINE_1", - "DEF_PLAN_BARRIER_SHLD_3", - "SPY_DETECT_3", - "LRN_QUANT_NET", - "SHP_INTSTEL_LOG", - "SHP_REINFORCED_HULL", - "SHP_WEAPON_10", - "SHP_CONT_BIOADAPT", - "SHP_SENT_HULL", - "SHP_ZORTRIUM_PLATE", - "DEF_SYST_DEF_MINE_2", - "GRO_CYBORG", - #"CON_FRC_ENRG_STRC", - #"CON_FRC_ENRG_CAMO", - "GRO_GENOME_BANK", - "SHP_BASIC_DAM_CONT", - "CON_CONC_CAMP", - "PRO_SINGULAR_GEN", - "SHP_ADV_DAM_CONT", - "PRO_INDUSTRY_CENTER_III", - "DEF_GARRISON_4", - "SPY_CLOAK_1", - "DEF_DEFENSE_NET_REGEN_2", - "GRO_GAIA_TRANS", - "GRO_ENERGY_META", - "LRN_TIME_MECH", - "LRN_ART_BLACK_HOLE", - "CON_ART_PLANET", - "PRO_NEUTRONIUM_EXTRACTION", - "LRN_STELLAR_TOMOGRAPHY", - "LRN_ENCLAVE_VOID", - "LRN_DISTRIB_THOUGHT", - "GRO_ENERGY_META", - "DEF_SYST_DEF_MINE_3", - "DEF_PLAN_BARRIER_SHLD_4", - "SHP_WEAPON_13", - "SPY_DETECT_4", - "SHP_WEAPON_11", - "SHP_WEAPON_12", - "SHP_TITAN_HULL" - "DEF_PLAN_BARRIER_SHLD_5", - "SHP_SOLAR_CONT", - "SHP_WEAPON_14", - "SHP_WEAPON_15", - "SHP_WEAPON_16", - "SHP_WEAPON_17", - ] + if index == 0: + primaryMetaTechs = [ + "GRO_PLANET_ECOL", + "GRO_SUBTER_HAB", + "SHP_DOMESTIC_MONSTER", + "SHP_ORG_HULL", + "SHP_WEAPON_3", + "LRN_ALGO_ELEGANCE", + "CON_ENV_ENCAPSUL", + "PRO_FUSION_GEN", + "SHP_WEAPON_5", + "PRO_ROBOTIC_PROD", + "DEF_DEFENSE_NET_1", + "DEF_GARRISON_1", + "CON_ORBITAL_CON", + "SHP_WEAPON_6", + "GRO_SYMBIOTIC_BIO", + "LRN_ARTIF_MINDS", + "LRN_FORCE_FIELD", + "GRO_GENETIC_ENG", + "SHP_MULTICELL_CAST", + "PRO_ORBITAL_GEN", + "SHP_WEAPON_7", + "PRO_MICROGRAV_MAN", + "SHP_WEAPON_8", + "PRO_INDUSTRY_CENTER_I", + "DEF_GARRISON_2", + #"GRO_LIFECYCLE_MAN", # ship part is too expensive for now + "SHP_ENDOCRINE_SYSTEMS", + "LRN_GRAVITONICS", + "CON_CONTGRAV_ARCH", + "DEF_GARRISON_3", + "SHP_WEAPON_8", + "PRO_INDUSTRY_CENTER_II", + "GRO_XENO_GENETICS", + "SPY_DETECT_2", + "SHP_CONT_SYMB", + "DEF_DEFENSE_NET_2", + "DEF_PLAN_BARRIER_SHLD_1", + "CON_METRO_INFRA", + "CON_SUBTER_CONST", + "SHP_MONOCELL_EXP", + "SHP_ENDOSYMB_HULL", + "PRO_SOL_ORB_GEN", + "DEF_DEFENSE_NET_REGEN_1", + "DEF_PLAN_BARRIER_SHLD_2", + "SHP_WEAPON_9", + "CON_ORBITAL_HAB", + "GRO_XENO_HYBRIDS", + "SHP_ASTEROID_HULLS", + "GRO_TERRAFORM", + "LRN_PHYS_BRAIN", + "LRN_TRANSLING_THT", + "LRN_XENOARCH", + "GRO_GENETIC_MED", + "SHP_LEAD_PLATE", + "SHP_BIOADAPTIVE_SPEC", + "PRO_SENTIENT_AUTOMATION", + "PRO_EXOBOTS", + "DEF_DEFENSE_NET_3", + "DEF_SYST_DEF_MINE_1", + "DEF_PLAN_BARRIER_SHLD_3", + "SPY_DETECT_3", + "LRN_QUANT_NET", + "SHP_INTSTEL_LOG", + "SHP_REINFORCED_HULL", + "SHP_WEAPON_10", + "SHP_CONT_BIOADAPT", + "SHP_SENT_HULL", + "SHP_ZORTRIUM_PLATE", + "DEF_SYST_DEF_MINE_2", + "GRO_CYBORG", + #"CON_FRC_ENRG_STRC", + #"CON_FRC_ENRG_CAMO", + "GRO_GENOME_BANK", + "SHP_BASIC_DAM_CONT", + "CON_CONC_CAMP", + "PRO_SINGULAR_GEN", + "SHP_ADV_DAM_CONT", + "PRO_INDUSTRY_CENTER_III", + "DEF_GARRISON_4", + "SPY_CLOAK_1", + "DEF_DEFENSE_NET_REGEN_2", + "GRO_GAIA_TRANS", + "GRO_ENERGY_META", + "LRN_TIME_MECH", + "LRN_ART_BLACK_HOLE", + "CON_ART_PLANET", + "PRO_NEUTRONIUM_EXTRACTION", + "LRN_STELLAR_TOMOGRAPHY", + "LRN_ENCLAVE_VOID", + "LRN_DISTRIB_THOUGHT", + "GRO_ENERGY_META", + "DEF_SYST_DEF_MINE_3", + "DEF_PLAN_BARRIER_SHLD_4", + "SHP_WEAPON_13", + "SPY_DETECT_4", + "SHP_WEAPON_11", + "SHP_WEAPON_12", + "SHP_TITAN_HULL" + "DEF_PLAN_BARRIER_SHLD_5", + "SHP_SOLAR_CONT", + "SHP_WEAPON_14", + "SHP_WEAPON_15", + "SHP_WEAPON_16", + "SHP_WEAPON_17", + ] + elif index == 1: + primaryMetaTechs = [ + "GRO_PLANET_ECOL", + "GRO_SUBTER_HAB", + "SHP_DOMESTIC_MONSTER", + "SHP_ORG_HULL", + "SHP_WEAPON_3", + "LRN_ALGO_ELEGANCE", + "CON_ENV_ENCAPSUL", + "PRO_FUSION_GEN", + "SHP_WEAPON_5", + "PRO_ROBOTIC_PROD", + "DEF_DEFENSE_NET_1", + "DEF_GARRISON_1", + "CON_ORBITAL_CON", + "SHP_WEAPON_6", + "GRO_SYMBIOTIC_BIO", + "LRN_ARTIF_MINDS", + "LRN_FORCE_FIELD", + "DEF_DEFENSE_NET_2", + "DEF_PLAN_BARRIER_SHLD_1", + "SHP_WEAPON_7", + "CON_METRO_INFRA", + "CON_SUBTER_CONST", + "SHP_WEAPON_8", + "PRO_INDUSTRY_CENTER_I", + "DEF_DEFENSE_NET_REGEN_1", + "DEF_PLAN_BARRIER_SHLD_2", + "GRO_GENETIC_ENG", + "SPY_DETECT_2", + "PRO_SENTIENT_AUTOMATION", + "PRO_EXOBOTS", + "DEF_DEFENSE_NET_3", + "DEF_SYST_DEF_MINE_1", + "DEF_PLAN_BARRIER_SHLD_3", + "CON_ORBITAL_HAB", + "GRO_XENO_HYBRIDS", + "SHP_MULTICELL_CAST", + "PRO_ORBITAL_GEN", + "PRO_MICROGRAV_MAN", + "DEF_GARRISON_2", + #"GRO_LIFECYCLE_MAN", # ship part is too expensive for now + "SHP_ENDOCRINE_SYSTEMS", + "LRN_GRAVITONICS", + "CON_CONTGRAV_ARCH", + "DEF_GARRISON_3", + "SHP_WEAPON_8", + "PRO_INDUSTRY_CENTER_II", + "GRO_XENO_GENETICS", + "SHP_CONT_SYMB", + "SHP_MONOCELL_EXP", + "SHP_ENDOSYMB_HULL", + "PRO_SOL_ORB_GEN", + "SHP_WEAPON_9", + "SHP_ASTEROID_HULLS", + "GRO_TERRAFORM", + "LRN_PHYS_BRAIN", + "LRN_TRANSLING_THT", + "LRN_XENOARCH", + "GRO_GENETIC_MED", + "SHP_LEAD_PLATE", + "SHP_BIOADAPTIVE_SPEC", + "SPY_DETECT_3", + "LRN_QUANT_NET", + "SHP_INTSTEL_LOG", + "SHP_REINFORCED_HULL", + "SHP_WEAPON_10", + "SHP_CONT_BIOADAPT", + "SHP_SENT_HULL", + "SHP_ZORTRIUM_PLATE", + "DEF_SYST_DEF_MINE_2", + "GRO_CYBORG", + #"CON_FRC_ENRG_STRC", + #"CON_FRC_ENRG_CAMO", + "GRO_GENOME_BANK", + "SHP_BASIC_DAM_CONT", + "CON_CONC_CAMP", + "PRO_SINGULAR_GEN", + "SHP_ADV_DAM_CONT", + "PRO_INDUSTRY_CENTER_III", + "DEF_GARRISON_4", + "SPY_CLOAK_1", + "DEF_DEFENSE_NET_REGEN_2", + "GRO_GAIA_TRANS", + "GRO_ENERGY_META", + "LRN_TIME_MECH", + "LRN_ART_BLACK_HOLE", + "CON_ART_PLANET", + "PRO_NEUTRONIUM_EXTRACTION", + "LRN_STELLAR_TOMOGRAPHY", + "LRN_ENCLAVE_VOID", + "LRN_DISTRIB_THOUGHT", + "GRO_ENERGY_META", + "DEF_SYST_DEF_MINE_3", + "DEF_PLAN_BARRIER_SHLD_4", + "SHP_WEAPON_13", + "SPY_DETECT_4", + "SHP_WEAPON_11", + "SHP_WEAPON_12", + "SHP_TITAN_HULL" + "DEF_PLAN_BARRIER_SHLD_5", + "SHP_SOLAR_CONT", + "SHP_WEAPON_14", + "SHP_WEAPON_15", + "SHP_WEAPON_16", + "SHP_WEAPON_17", + ] + return primaryMetaTechs MasterTechList=[ #currently with typos, just for reference |
From: <dil...@us...> - 2013-02-05 11:42:31
|
Revision: 5711 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5711&view=rev Author: dilvish-fo Date: 2013-02-05 09:17:37 +0000 (Tue, 05 Feb 2013) Log Message: ----------- added a python charting file (in charting folder with default/AI/) to help visualize AI performance. comments in the file explain nonstandard modules required Added Paths: ----------- trunk/FreeOrion/default/AI/charting/ trunk/FreeOrion/default/AI/charting/charts.py Added: trunk/FreeOrion/default/AI/charting/charts.py =================================================================== --- trunk/FreeOrion/default/AI/charting/charts.py (rev 0) +++ trunk/FreeOrion/default/AI/charting/charts.py 2013-02-05 09:17:37 UTC (rev 5711) @@ -0,0 +1,177 @@ +# installation of scipy probably necessary to get pylab +# +#This script easiest to use if you copy it to the directory your log files are saved to, and then execute it as +# OS_Prompt> python charts.py +# +# alternatively you can edit the DataDir variable below to point to your log files folder, and that should work also +# I do plan to further improve this to test for OS and automatically look in the corresponding default location +from pylab import * +import os +import sys +from glob import glob +import traceback +#import matplotlib.pyplot as plt +import matplotlib.ticker as ticker + +dataDir = "." +graphDir=dataDir + +fileRoot="game1" +saveFile=True +turnsP=None +turnsAI=None +rankings=[] + + +def show_only_some(x, pos): + val=int(x) + if val in [3, 5, 30, 50, 80, 300, 500, 800, 3000, 5000, 8000]: + return str(val) + else: + return '' + + +for plotType in ["PP", "RP"]: + + if plotType=="PP": + caption="Production" + else: + caption="Research" + + figure(figsize=(10, 6)) + ax=gca() + allData={} + species={} + empires=[] + empireColors={} + playerName="" + ymin = 9999 + ymax = 0 + + if not os.path.exists(dataDir+os.sep+"freeorion.log"): + print "can't find freeorion.log" + else: + with open(dataDir+os.sep+"freeorion.log", 'r') as lf: + dat1=lf.read() + playerName="Player" + colorParts= dat1.split("EmpireColors:") + if len( colorParts )>=2: + colorLine=colorParts[1].split('\n')[0].strip() + colors=colorLine.split() + print "Player colors = %s , type = %s"%( colors, type(colors[0])) + if len(colors)==4: + if type(colors[0])==type("0"): + empireColors[playerName]= tuple(map(lambda x: float(x)/255.0, colors)) + else: + empireColors[playerName]= tuple(map(lambda x: float(ord(x[0]))/255.0, colors)) + datalines = [lines.split('\n')[0] for lines in dat1.split("Current Output (turn")][1:] + turnPP = [ ( int( parts[0] ), float( parts[1].split('/')[-1]) ) for parts in [line.split(')') for line in datalines]] + turnsP = [ int( parts[0]) for parts in [line.split(')') for line in datalines]] + PP = [ float( parts[1].split('/')[-1]) for parts in [line.split(')') for line in datalines]] + RP = [ float( parts[1].split('/')[-2].split('(')[-1]) for parts in [line.split(')') for line in datalines]] + if plotType=="PP": + data=PP + else: + data=RP + if data != []: + ymin = min(ymin, min(data)) + ymax = max(ymax, max(data)) + #plot(turnsP[:50],data[:50], 'bo-', label=playerName, linewidth=2.0) + allData[playerName]=data + + logfiles=sorted(glob(dataDir+os.sep+"A*.log")) + empire=0 + for lfile in logfiles: + with open(lfile, 'r') as lf: + try: + dat1=lf.read() + specName=dat1.split("CapitalID:")[1].split("Species:")[1].split('\n')[0].strip() + empireName=dat1.split("EmpireID:")[1].split("Name:")[1].split("Turn:")[0].strip() + empires.append(empireName) + colorParts= dat1.split("EmpireColors:") + if len( colorParts )>=2: + colorLine=colorParts[1].split('\n')[0].strip() + colors=colorLine.split() + if len(colors)==4: + empireColors[empireName]= tuple(map(lambda x: int(x)/255.0, colors)) + print "empire colors for %s are %s -- %s "%(empireName, colors, empireColors[empireName]) + datalines = [lines.split('\n')[0] for lines in dat1.split("Current Output (turn")][1:] + turnPP = [ ( int( parts[0] ), float( parts[1].split('/')[-1]) ) for parts in [line.split(')') for line in datalines]] + turnsAI = [ int( parts[0]) for parts in [line.split(')') for line in datalines]] + PP = [ float( parts[1].split('/')[-1]) for parts in [line.split(')') for line in datalines]] + RP = [ float( parts[1].split('/')[-2].split('(')[-1]) for parts in [line.split(')') for line in datalines]] + if plotType=="PP": + data=PP + rankings.append( (PP[-1], empireName) ) + else: + data=RP + if data != []: + thisMin=min(data) + if thisMin>4: ymin = min(ymin, thisMin) + ymax = max(ymax, max(data)) + #plot(turnsAI[:50],data[:50], label=specName, linewidth=2.0) + species[empireName]=specName + allData[empireName]=data + empire+=1 + except: + print "error processing %s"%lfile + print "Error: exception triggered and caught: ", traceback.format_exc() + + rankings.sort() + legend(loc='upper left',prop={"size":'medium'}) + xlabel('Turn') + ylabel(plotType+' per turn') + title(caption+' Point progression') + #if saveFile: + # savefig(graphDir+os.sep+plotType+"_"+fileRoot+"_toTurn50.png") + #show() + + turns=turnsP or turnsAI or range(1,len(allData.values()[0])+1) + #if len(turns) >50: + #if (allData.get(playerName,[]) or allData.values()[0])[-1]>100: + # ax.set_yscale('log',basey=10) + ax.set_yscale('log',basey=10) + + #ax.axis["right"].set_visible(True) + #figure(figsize=(10, 6)) + if playerName not in allData: + print "can't find playerData in allData" + else: + if playerName in empireColors: + plot(turnsP, allData[playerName], 'o-', color=empireColors[playerName], label=playerName, linewidth=2.0) + else: + plot(turnsP, allData[playerName], 'bx-', label=playerName, linewidth=2.0) + #show() + #for i in range(len(species)): + # name=empires[i] + for rank,name in rankings[::-1]: + if name in empireColors: + plot(range(turns[0], turns[0]+len(allData[name])), allData[name], color=empireColors[name], label=name+" : "+species[name], linewidth=2.0) + else: + plot(range(turns[0], turns[0]+len(allData[name])), allData[name], label="(%d) "%(empires.index(name)+1)+name+" : "+species[name], linewidth=2.0) + legend(loc='upper left', prop={"size":9},labelspacing=0.2) + xlabel('Turn') + ylabel(plotType+' per turn') + title(caption+' Point progression w/ Max Aggression=Maniacal') + x1,x2,y1,y2 = axis() + newY2=y2 + for yi in range(1, 10): + if 1.05*ymax < yi*y2/10: + newY2= yi*y2/10 + break + print "y1: %.1f ; ymin: %.1f ; newY2/100: %.1f"%(y1, ymin, newY2/100) + y1 = max(y1, 4, ymin, newY2/100) + #axis( (x1,min(x2,200),y1,y2)) + #ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) + axis( (x1,x2,y1,newY2)) + grid(b=True, which='major', color='0.25',linestyle='-') + grid(b=True, which='minor', color='0.1', linestyle='--') + ax.yaxis.set_minor_formatter(FuncFormatter(show_only_some)) + ax.yaxis.set_ticks_position('right') + ax.yaxis.set_ticks_position('both') + ax.tick_params(labelleft='on')#for matplotlib versions where 'both' doesn't work + #ax.tick_params(labelright='on') + if saveFile: + savefig(graphDir+os.sep+plotType+"_"+fileRoot+".png") + show() + |
From: <dil...@us...> - 2013-02-07 19:47:16
|
Revision: 5731 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5731&view=rev Author: dilvish-fo Date: 2013-02-07 19:47:09 +0000 (Thu, 07 Feb 2013) Log Message: ----------- a round of AI adjustments Modified Paths: -------------- trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ResearchAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-07 18:09:45 UTC (rev 5730) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-07 19:47:09 UTC (rev 5731) @@ -609,7 +609,7 @@ def sendColonyShips(colonyFleetIDs, evaluatedPlanets, missionType): "sends a list of colony ships to a list of planet_value_pairs" fleetPool = colonyFleetIDs[:] - potentialTargets = [ (pid, (score, specName) ) for (pid, (score, specName) ) in evaluatedPlanets if score > 50 ] + potentialTargets = [ (pid, (score, specName) ) for (pid, (score, specName) ) in evaluatedPlanets if score > 30 ] print "colony/outpost ship matching -- fleets %s to planets %s"%( fleetPool, evaluatedPlanets) #for planetID_value_pair in evaluatedPlanets: Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-07 18:09:45 UTC (rev 5730) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-07 19:47:09 UTC (rev 5731) @@ -201,7 +201,7 @@ specialVal= 15 #TODO: should do more eval re asteroid mining here for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: - specialVal = 0#TODO: fix + specialVal +=10 # return popVal+supplyVal+specialVal+bldTally+productionVal+enemyVal-8*troops, troops def getPlanetPopulation(planetID): Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-07 18:09:45 UTC (rev 5730) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-07 19:47:09 UTC (rev 5731) @@ -113,6 +113,7 @@ else: threatBias = 400 + threatBias = 0 safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 0.95, 0.95 ][foAI.foAIstate.aggression] Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-07 18:09:45 UTC (rev 5730) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-07 19:47:09 UTC (rev 5731) @@ -83,13 +83,13 @@ planets = map(universe.getPlanet, ownedPlanetIDs) targetPP = sum( map( lambda x: x.currentMeterValue(fo.meterType.targetIndustry), planets) ) - if fo.currentTurn() < 20: + if fo.currentTurn() < 30: industryPriority = 20 # mid industry , high research at beginning of game to get easy gro tech - elif fo.currentTurn() < 30: + elif fo.currentTurn() < 45: industryPriority = 25 # mid industry , mid research - elif fo.currentTurn() < 40: + elif fo.currentTurn() < 60: industryPriority = 40 # high industry , mid research - elif fo.currentTurn() < 50: + elif fo.currentTurn() < 80: industryPriority = 50 # high industry , mid research else: industryPriority = 60 # high industry , low-mid research @@ -126,13 +126,13 @@ styleAdjustmentMap = {0:0, 1:0} styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) if industrySurge: - researchPriority = 5 + researchPriority = 10+styleAdjustment else: - if (fo.currentTurn() < 20) or not gotAlgo: + if (fo.currentTurn() < 30) or not gotAlgo: researchPriority = 60 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance - elif fo.currentTurn() < 30: + elif fo.currentTurn() < 45: researchPriority = 30 +styleAdjustment# mid industry , mid research - elif fo.currentTurn() < 40: + elif fo.currentTurn() < 60: researchPriority = 20+styleAdjustment # high industry , low research else: researchQueue = list(empire.researchQueue) @@ -185,13 +185,13 @@ "calculates the demand for colony ships by colonisable planets" global allottedColonyTargets totalPP=fo.getEmpire().productionPoints - colonyCost=120*(1+ 0.05*len( list(AIstate.popCtrIDs) + list(AIstate.outpostIDs) )) + colonyCost=120*(1+ 0.04*len( list(AIstate.popCtrIDs) + list(AIstate.outpostIDs) )) turnsToBuild=8#TODO: check for susp anim pods, build time 10 - allottedPortion = 0.3 + allottedPortion = 0.5 #allottedColonyTargets = 1+ int(fo.currentTurn()/50) allottedColonyTargets = 1 + int( totalPP*turnsToBuild*allottedPortion/colonyCost) - numColonisablePlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisablePlanetIDs if score > 100 ][:allottedColonyTargets] ) + numColonisablePlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisablePlanetIDs if score > 50 ][:allottedColonyTargets] ) if (numColonisablePlanetIDs == 0): return 0 colonyshipIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_COLONISATION) @@ -209,9 +209,10 @@ def calculateOutpostPriority(): "calculates the demand for outpost ships by colonisable planets" + baseOutpostCost=80 numOutpostPlanetIDs = len(foAI.foAIstate.colonisableOutpostIDs) - numOutpostPlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisableOutpostIDs if score > 60 ][:allottedColonyTargets] ) + numOutpostPlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisableOutpostIDs if score > 1.0*baseOutpostCost/3.0 ][:allottedColonyTargets] ) completedTechs = getCompletedTechs() if numOutpostPlanetIDs == 0 or not 'CON_ENV_ENCAPSUL' in completedTechs: return 0 Modified: trunk/FreeOrion/default/AI/ResearchAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResearchAI.py 2013-02-07 18:09:45 UTC (rev 5730) +++ trunk/FreeOrion/default/AI/ResearchAI.py 2013-02-07 19:47:09 UTC (rev 5731) @@ -81,7 +81,7 @@ newtech = TechsListsAI.primaryMetaTechsList( index=empireID%2 ) else: #newtech = TechsListsAI.aggressiveTechs() - newtech = TechsListsAI.primaryMetaTechsList() + newtech = TechsListsAI.primaryMetaTechsList(empireID%2) #pLTsToEnqueue = (set(newtech)-(set(completedTechs)|set(researchQueueList))) pLTsToEnqueue = newtech[:] techBase = set(completedTechs+researchQueueList) Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-07 18:09:45 UTC (rev 5730) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-07 19:47:09 UTC (rev 5731) @@ -253,12 +253,12 @@ "GRO_GENETIC_ENG", "SHP_MULTICELL_CAST", "PRO_ORBITAL_GEN", + "SPY_DETECT_2", "SHP_WEAPON_7", - "PRO_MICROGRAV_MAN", "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_I", "DEF_GARRISON_2", - #"GRO_LIFECYCLE_MAN", # ship part is too expensive for now + "GRO_LIFECYCLE_MAN", "SHP_ENDOCRINE_SYSTEMS", "LRN_GRAVITONICS", "CON_CONTGRAV_ARCH", @@ -266,7 +266,6 @@ "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_II", "GRO_XENO_GENETICS", - "SPY_DETECT_2", "SHP_CONT_SYMB", "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", @@ -280,6 +279,7 @@ "SHP_WEAPON_9", "CON_ORBITAL_HAB", "GRO_XENO_HYBRIDS", + "PRO_MICROGRAV_MAN", "SHP_ASTEROID_HULLS", "GRO_TERRAFORM", "LRN_PHYS_BRAIN", @@ -319,11 +319,12 @@ "LRN_TIME_MECH", "LRN_ART_BLACK_HOLE", "CON_ART_PLANET", + "LRN_STELLAR_TOMOGRAPHY", "PRO_NEUTRONIUM_EXTRACTION", - "LRN_STELLAR_TOMOGRAPHY", "LRN_ENCLAVE_VOID", "LRN_DISTRIB_THOUGHT", "GRO_ENERGY_META", + "LRN_PSY_DOM", "DEF_SYST_DEF_MINE_3", "DEF_PLAN_BARRIER_SHLD_4", "SHP_WEAPON_13", @@ -357,6 +358,7 @@ "GRO_SYMBIOTIC_BIO", "LRN_ARTIF_MINDS", "LRN_FORCE_FIELD", + "SPY_DETECT_2", "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", "SHP_WEAPON_7", @@ -367,7 +369,8 @@ "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_2", "GRO_GENETIC_ENG", - "SPY_DETECT_2", + "LRN_PHYS_BRAIN", + "LRN_TRANSLING_THT", "PRO_SENTIENT_AUTOMATION", "PRO_EXOBOTS", "DEF_DEFENSE_NET_3", @@ -377,7 +380,6 @@ "GRO_XENO_HYBRIDS", "SHP_MULTICELL_CAST", "PRO_ORBITAL_GEN", - "PRO_MICROGRAV_MAN", "DEF_GARRISON_2", "GRO_LIFECYCLE_MAN", "SHP_ENDOCRINE_SYSTEMS", @@ -391,17 +393,23 @@ "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", "PRO_SOL_ORB_GEN", + "PRO_SINGULAR_GEN", + "SPY_DETECT_3", + "LRN_XENOARCH", "SHP_WEAPON_9", + "PRO_MICROGRAV_MAN", + "LRN_QUANT_NET", + "LRN_TIME_MECH", + "LRN_STELLAR_TOMOGRAPHY", + "PRO_NEUTRONIUM_EXTRACTION", + "LRN_ENCLAVE_VOID", + "LRN_PSY_DOM", + "LRN_ART_BLACK_HOLE", "SHP_ASTEROID_HULLS", "GRO_TERRAFORM", - "LRN_PHYS_BRAIN", - "LRN_TRANSLING_THT", - "LRN_XENOARCH", "GRO_GENETIC_MED", "SHP_LEAD_PLATE", "SHP_BIOADAPTIVE_SPEC", - "SPY_DETECT_3", - "LRN_QUANT_NET", "SHP_INTSTEL_LOG", "SHP_REINFORCED_HULL", "SHP_WEAPON_10", @@ -415,7 +423,6 @@ "GRO_GENOME_BANK", "SHP_BASIC_DAM_CONT", "CON_CONC_CAMP", - "PRO_SINGULAR_GEN", "SHP_ADV_DAM_CONT", "PRO_INDUSTRY_CENTER_III", "DEF_GARRISON_4", @@ -423,12 +430,7 @@ "DEF_DEFENSE_NET_REGEN_2", "GRO_GAIA_TRANS", "GRO_ENERGY_META", - "LRN_TIME_MECH", - "LRN_ART_BLACK_HOLE", "CON_ART_PLANET", - "PRO_NEUTRONIUM_EXTRACTION", - "LRN_STELLAR_TOMOGRAPHY", - "LRN_ENCLAVE_VOID", "LRN_DISTRIB_THOUGHT", "GRO_ENERGY_META", "DEF_SYST_DEF_MINE_3", |
From: <dil...@us...> - 2013-02-10 23:07:53
|
Revision: 5751 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5751&view=rev Author: dilvish-fo Date: 2013-02-10 23:07:46 +0000 (Sun, 10 Feb 2013) Log Message: ----------- AI mods to try keeping up with the Jonses. Modified Paths: -------------- trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-10 20:58:39 UTC (rev 5750) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-10 23:07:46 UTC (rev 5751) @@ -123,16 +123,17 @@ targetRP = sum( map( lambda x: x.currentMeterValue(fo.meterType.targetResearch), planets) ) styleIndex = empireID%2 - styleAdjustmentMap = {0:0, 1:0} + styleAdjustmentMap = {0:0, 1:0}#TODO: decide if I want to do anything with this styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) + cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] if industrySurge: researchPriority = 10+styleAdjustment else: - if (fo.currentTurn() < 30) or not gotAlgo: + if (fo.currentTurn() < cutoffs[0]) or not gotAlgo: researchPriority = 60 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance - elif fo.currentTurn() < 45: + elif fo.currentTurn() < cutoffs[1]: researchPriority = 30 +styleAdjustment# mid industry , mid research - elif fo.currentTurn() < 60: + elif fo.currentTurn() < cutoffs[2]: researchPriority = 20+styleAdjustment # high industry , low research else: researchQueue = list(empire.researchQueue) @@ -185,14 +186,14 @@ "calculates the demand for colony ships by colonisable planets" global allottedColonyTargets totalPP=fo.getEmpire().productionPoints - colonyCost=120*(1+ 0.04*len( list(AIstate.popCtrIDs) + list(AIstate.outpostIDs) )) + colonyCost=120*(1+ 0.06*len( list(AIstate.popCtrIDs) )) turnsToBuild=8#TODO: check for susp anim pods, build time 10 - allottedPortion = 0.5 + allottedPortion = 0.4 #allottedColonyTargets = 1+ int(fo.currentTurn()/50) allottedColonyTargets = 1 + int( totalPP*turnsToBuild*allottedPortion/colonyCost) numColonisablePlanetIDs = len( [ pid for (pid, (score, specName) ) in foAI.foAIstate.colonisablePlanetIDs if score > 50 ][:allottedColonyTargets] ) - if (numColonisablePlanetIDs == 0): return 0 + if (numColonisablePlanetIDs == 0): return 1 colonyshipIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_COLONISATION) numColonyships = len(FleetUtilsAI.extractFleetIDsWithoutMissionTypes(colonyshipIDs)) @@ -203,7 +204,7 @@ # print "Number of Colonisable planets : " + str(numColonisablePlanetIDs) # print "Priority for colony ships : " + str(colonisationPriority) - if colonisationPriority < 0: return 0 + if colonisationPriority < 1: return 1 return colonisationPriority @@ -226,7 +227,7 @@ # print "Number of Colonisable outposts: " + str(numOutpostPlanetIDs) print "Priority for outpost ships : " + str(outpostPriority) - if outpostPriority < 0: return 0 + if outpostPriority < 1: return 1 return outpostPriority @@ -244,7 +245,7 @@ troopsNeeded= sum( [(trp+4) for pid, pscore, trp in AIstate.invasionTargets[:allottedInvasionTargets] ] ) if totalVal == 0: - return 10 #hsould always have at least a low lvl of production going into troop fleets + return 0 opponentTroopPods = int(troopsNeeded/troopsPerPod) productionQueue = empire.productionQueue @@ -267,7 +268,8 @@ 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 = max( 10+ 200*max(0, troopShipsNeeded ) , int(0.1* totalVal) ) + invasionPriority = 10+ 100*max(1, troopShipsNeeded ) if invasionPriority < 0: return 0 if foAI.foAIstate.aggression==fo.aggression.beginner: Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-10 20:58:39 UTC (rev 5750) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-10 23:07:46 UTC (rev 5751) @@ -1128,13 +1128,12 @@ if filteredPriorities == {}: print "No non-building-production priorities with nonzero score, setting to default: Military" filteredPriorities [AIPriorityType.PRIORITY_PRODUCTION_MILITARY ] = 1 - while (topscore >900): - topscore = 0 - for pty in filteredPriorities: - score = filteredPriorities[pty] ** 0.5 - filteredPriorities[pty] = score - if score > topscore: - topscore=score + if topscore <= 100: + scalingPower = 1.0 + else: + scalingPower = math.log(100)/math.log(topscore) + for pty in filteredPriorities: + filteredPriorities[pty] = filteredPriorities[pty] **scalingPower bestShips={} for priority in list(filteredPriorities): Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-10 20:58:39 UTC (rev 5750) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-10 23:07:46 UTC (rev 5751) @@ -258,8 +258,8 @@ "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_I", "DEF_GARRISON_2", + "SHP_ENDOCRINE_SYSTEMS", "GRO_LIFECYCLE_MAN", - "SHP_ENDOCRINE_SYSTEMS", "LRN_GRAVITONICS", "CON_CONTGRAV_ARCH", "DEF_GARRISON_3", @@ -359,6 +359,7 @@ "LRN_ARTIF_MINDS", "LRN_FORCE_FIELD", "SPY_DETECT_2", + "PRO_ORBITAL_GEN", "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", "SHP_WEAPON_7", @@ -379,7 +380,6 @@ "CON_ORBITAL_HAB", "GRO_XENO_HYBRIDS", "SHP_MULTICELL_CAST", - "PRO_ORBITAL_GEN", "DEF_GARRISON_2", "GRO_LIFECYCLE_MAN", "SHP_ENDOCRINE_SYSTEMS", |
From: <dil...@us...> - 2013-02-11 17:37:22
|
Revision: 5755 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5755&view=rev Author: dilvish-fo Date: 2013-02-11 17:37:13 +0000 (Mon, 11 Feb 2013) Log Message: ----------- AI research adjustment Modified Paths: -------------- trunk/FreeOrion/default/AI/ResourcesAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-02-11 16:16:06 UTC (rev 5754) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-02-11 17:37:13 UTC (rev 5755) @@ -411,7 +411,7 @@ ntPP, ntRP= newTargets[pid].get(RFocus, (0, 0)) print "pID (%3d) %22s | c: %5.1f / %5.1f | cT: %5.1f / %5.1f | cF: %8s | nF: %8s | cT: %5.1f / %5.1f | %.2f"%(pid, planetMap[pid].name, cRP, cPP, otRP, otPP, fociMap.get(oldFocus, 'unknown'), fociMap[RFocus] , ntRP, ntPP , ratio) continue # RP is getting too expensive, but might be willing to still allocate from a planet with less PP to lose - if planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) > 0: + if planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) >0: #only set to research if pop won't die out newFoci[pid] = RFocus curTargetRP += (RR-IR) curTargetPP -= (II-RI) @@ -463,18 +463,20 @@ "generate resources focus orders" timer= [ time() ] - # calculate top resource priority - #topResourcePriority() + ## calculate top resource priority + ##topResourcePriority() timer.append( time() ) - # set resource foci of planets - #setCapitalIDResourceFocus() + ## set resource foci of planets + ##setCapitalIDResourceFocus() timer.append( time() ) + #------------------------------ #setGeneralPlanetResourceFocus() setPlanetResourceFoci() timer.append( time() ) - #setAsteroidsResourceFocus() + #------------------------------- + ##setAsteroidsResourceFocus() timer.append( time() ) - #setGasGiantsResourceFocus() + ##setGasGiantsResourceFocus() timer.append( time() ) printResourcesPriority() Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-11 16:16:06 UTC (rev 5754) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-11 17:37:13 UTC (rev 5755) @@ -231,6 +231,7 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" + index=1 if index == 0: primaryMetaTechs = [ "GRO_PLANET_ECOL", @@ -344,24 +345,24 @@ "GRO_PLANET_ECOL", "GRO_SUBTER_HAB", "SHP_DOMESTIC_MONSTER", + "LRN_ALGO_ELEGANCE", "SHP_ORG_HULL", "SHP_WEAPON_3", - "LRN_ALGO_ELEGANCE", + "DEF_DEFENSE_NET_1", "CON_ENV_ENCAPSUL", + "LRN_ARTIF_MINDS", "PRO_FUSION_GEN", + "LRN_FORCE_FIELD", "SHP_WEAPON_5", "PRO_ROBOTIC_PROD", - "DEF_DEFENSE_NET_1", "DEF_GARRISON_1", - "CON_ORBITAL_CON", "SHP_WEAPON_6", "GRO_SYMBIOTIC_BIO", - "LRN_ARTIF_MINDS", - "LRN_FORCE_FIELD", - "SPY_DETECT_2", "PRO_ORBITAL_GEN", "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", + "SPY_DETECT_2", + "CON_ORBITAL_CON", "SHP_WEAPON_7", "CON_METRO_INFRA", "CON_SUBTER_CONST", @@ -369,6 +370,7 @@ "PRO_INDUSTRY_CENTER_I", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_2", + "PRO_SOL_ORB_GEN", "GRO_GENETIC_ENG", "LRN_PHYS_BRAIN", "LRN_TRANSLING_THT", @@ -392,7 +394,6 @@ "SHP_CONT_SYMB", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", - "PRO_SOL_ORB_GEN", "PRO_SINGULAR_GEN", "SPY_DETECT_3", "LRN_XENOARCH", |
From: <dil...@us...> - 2013-02-12 02:18:45
|
Revision: 5756 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5756&view=rev Author: dilvish-fo Date: 2013-02-12 02:18:38 +0000 (Tue, 12 Feb 2013) Log Message: ----------- correction for AI handling of some mid-tier ship designs Modified Paths: -------------- trunk/FreeOrion/default/AI/FreeOrionAI.py trunk/FreeOrion/default/AI/ProductionAI.py Modified: trunk/FreeOrion/default/AI/FreeOrionAI.py =================================================================== --- trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-02-11 17:37:13 UTC (rev 5755) +++ trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-02-12 02:18:38 UTC (rev 5756) @@ -230,7 +230,7 @@ print "***************************************************************************" print "***************************************************************************" print ("Generating Orders") - print "EmpireID: " + str(empire.empireID) + " Name: " + empire.name+ "_"+str(empire.empireID) +"_"+aggressions.get(foAIstate.aggression, "?") + " Turn: " + str(fo.currentTurn()) + print "EmpireID: " + str(empire.empireID) + " Name: " + empire.name+ "_"+str(empire.empireID-1) +"_"+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: Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-11 17:37:13 UTC (rev 5755) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-12 02:18:38 UTC (rev 5756) @@ -312,7 +312,7 @@ else: maxEM= 10 - nb, hull = designNameBases[3]+"-%1d", "SH_ENDOMORPHIC" + nb, hull = designNameBases[3]+"-1-%1d", "SH_ENDOMORPHIC" newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + 2*[ is1], "", model) for iw in [5, 6, 7 ] ] nb = designNameBases[3]+"-2-%1d" @@ -324,22 +324,22 @@ nb = designNameBases[3]+"-4-%1d" #newMarkDesigns += [ (nb%iw, desc, hull, 2*[srb%iw]+[ar1] + [ is1, is2], "", model) for iw in [7, 8, 10, 11, 12 ] ] - nb = designNameBases[4]+"-5-%1d" + nb = designNameBases[3]+"-5-%1d" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar2] + 2*[ is2], "", model) for iw in range(7, maxEM+1) ] - nb = designNameBases[4]+"-6-%1d" + nb = designNameBases[3]+"-6-%1d" if foAI.foAIstate.aggression <=fo.aggression.turtle: newMarkDesigns += [ (nb%iw, desc, hull, 2*[srb%iw] +[ar3, ar3]+ 2*[ is2], "", model) for iw in range(8, maxEM+1) ] else: newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw] +[ar3]+ 2*[ is2], "", model) for iw in range(8, maxEM+1) ] - nb = designNameBases[4]+"-7-%1d" + nb = designNameBases[3]+"-7-%1d" newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] - nb = designNameBases[4]+"-8-%1d" + nb = designNameBases[3]+"-8-%1d" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar2] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] - nb = designNameBases[4]+"-9-%1d" + nb = designNameBases[3]+"-9-%1d" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar3] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] if foAI.foAIstate.aggression >=fo.aggression.typical: |
From: <dil...@us...> - 2013-02-13 04:28:24
|
Revision: 5758 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5758&view=rev Author: dilvish-fo Date: 2013-02-13 04:28:17 +0000 (Wed, 13 Feb 2013) Log Message: ----------- AI fix to eliminate (or at least reduce) AI streaming fleets into known death Modified Paths: -------------- trunk/FreeOrion/default/AI/AIFleetMission.py trunk/FreeOrion/default/AI/AIFleetOrder.py trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/FreeOrionAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/MoveUtilsAI.py trunk/FreeOrion/default/AI/PlanetUtilsAI.py Modified: trunk/FreeOrion/default/AI/AIFleetMission.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetMission.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/AIFleetMission.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -254,6 +254,9 @@ # TODO: priority ordersCompleted = True print "Checking orders for fleet %d"%(self.getAITargetID()) + #print "\t Full Orders are:" + #for aiFleetOrder2 in self.getAIFleetOrders(): + # print "\t\t %s"%aiFleetOrder2 for aiFleetOrder in self.getAIFleetOrders(): print " %s"%(aiFleetOrder) clearAll=False Modified: trunk/FreeOrion/default/AI/AIFleetOrder.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetOrder.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/AIFleetOrder.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -292,7 +292,7 @@ fleetRating = foAI.foAIstate.getRating(fleetID).get('overall', 0) threat = foAI.foAIstate.systemStatus.get(targetID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(targetID, {}).get('planetThreat', 0) - safetyFactor = 1.0 + safetyFactor = 1.1 if fleetRating >= safetyFactor* threat: return True else: Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -604,6 +604,10 @@ sys=universe.getSystem(sysID) sysName=(sys and sys.name) or "unknown" print "Fleet %d with role %s was used up, lost or destroyed at sys (%d) %s"%(fleetID, self.__fleetRoleByID[fleetID], sysID, sysName) #perhaps diff message for successful colony fleets + #print "\t\tFleet %d Full set of Orders were:"%fleetID + #for aiFleetOrder2 in self.__aiMissionsByFleetID[fleetID].getAIFleetOrders(): + # print "\t\t %s"%aiFleetOrder2 + if fleetID in self.__fleetRoleByID: del self.__fleetRoleByID[fleetID] if fleetID in self.__aiMissionsByFleetID: Modified: trunk/FreeOrion/default/AI/FreeOrionAI.py =================================================================== --- trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -230,7 +230,7 @@ print "***************************************************************************" print "***************************************************************************" print ("Generating Orders") - print "EmpireID: " + str(empire.empireID) + " Name: " + empire.name+ "_"+str(empire.empireID-1) +"_"+aggressions.get(foAIstate.aggression, "?") + " Turn: " + str(fo.currentTurn()) + 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: Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -9,7 +9,7 @@ import ExplorationAI import PriorityAI -MinThreat = 6 # the minimum threat level that will be ascribed to an unkown threat capable of killing scouts +MinThreat = 10 # the minimum threat level that will be ascribed to an unkown threat capable of killing scouts MilitaryAllocations = [] minMilAllocations = {} totMilRating=0 Modified: trunk/FreeOrion/default/AI/MoveUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/MoveUtilsAI.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/MoveUtilsAI.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -4,6 +4,7 @@ import AITarget import AIFleetOrder from ColonisationAI import annexableSystemIDs, annexableRing1, annexableRing2, annexableRing3 +import PlanetUtilsAI def getAIFleetOrdersFromSystemAITargets(fleetAITarget, aiTargets): result = [] @@ -15,7 +16,9 @@ # for every system which fleet wanted to visit, determine systems to visit and create move orders for aiTarget in aiTargets: # determine systems required to visit(with possible return to supplied system) + #print "checking system targets" systemAITargets = canTravelToSystem(fleetAITarget.getTargetID(), lastSystemAITarget, aiTarget, empireID) + #print "making path with %d targets: "%len(systemAITargets) , PlanetUtilsAI.sysNameIDs( [sysTarg. getTargetID() for sysTarg in systemAITargets]) if len(systemAITargets) > 0: # for every system required to visit create move order for systemAITarget in systemAITargets: @@ -42,27 +45,37 @@ fuel = int(fleet.fuel) if fuel < 1.0 or fromSystemAITarget.getTargetID() == toSystemAITarget.getTargetID: return [] - if foAI.foAIstate.aggression<=fo.aggression.typical: + if foAI.foAIstate.aggression<=fo.aggression.typical or True: #TODO: sort out if shortestPath leaves off some intermediate destinations pathFunc=universe.leastJumpsPath else: pathFunc=universe.shortestPath startSysID = fromSystemAITarget.getTargetID() targetSysID = toSystemAITarget.getTargetID() - shortPath= pathFunc(startSysID, targetSysID, empireID) + shortPath= list( pathFunc(startSysID, targetSysID, empireID) ) suppliedStops = [ sid for sid in shortPath if sid in fleetSupplyableSystemIDs ] unsuppliedStops = [sid for sid in shortPath if sid not in suppliedStops ] - if len( unsuppliedStops) == 0: - return [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] - elif targetSysID in fleetSupplyableSystemIDs and len( unsuppliedStops) < fuel -1: - return [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] - elif targetSysID in fleetSupplyableSystemIDs.union(annexableRing1) and len( unsuppliedStops) < fuel -1: - return [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] - elif foAI.foAIstate.aggression >=fo.aggression.typical and targetSysID in fleetSupplyableSystemIDs.union(annexableRing2) and len( unsuppliedStops) < fuel -2: - return [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] - elif foAI.foAIstate.aggression >=fo.aggression.aggressive and targetSysID in fleetSupplyableSystemIDs.union(annexableRing3) and len( unsuppliedStops) < fuel -3: - return [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] + retPath=[] + print "getting path from %s to %s "%(PlanetUtilsAI.sysNameIDs([ startSysID ]), PlanetUtilsAI.sysNameIDs([ targetSysID ]) ), + print " ::: found initial path %s having suppliedStops %s and unsuppliedStops %s ; tot fuel available is %.1f"%( PlanetUtilsAI.sysNameIDs( shortPath[:] ), suppliedStops, unsuppliedStops, fuel) + if False: + if targetSysID in fleetSupplyableSystemIDs: + print "target has FleetSupply" + elif targetSysID in annexableRing1: + print "target in Ring 1" + elif targetSysID in annexableRing2: + print "target in Ring 2, has enough aggression is ", foAI.foAIstate.aggression >=fo.aggression.typical + elif targetSysID in annexableRing3: + print "target in Ring 2, has enough aggression is ", foAI.foAIstate.aggression >=fo.aggression.aggressive + if ( len( unsuppliedStops) == 0 or + targetSysID in fleetSupplyableSystemIDs and len( unsuppliedStops) < fuel or + targetSysID in annexableRing1 and len( unsuppliedStops) < fuel or + foAI.foAIstate.aggression >=fo.aggression.typical and targetSysID in annexableRing2 and len( unsuppliedStops) < fuel -1 or + foAI.foAIstate.aggression >=fo.aggression.aggressive and targetSysID in annexableRing3 and len( unsuppliedStops) < fuel -2 ): + retPath = [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] else: - return canTravelToSystemAndReturnToResupply(fleetID, fromSystemAITarget, toSystemAITarget, empireID) + print " getting path from 'canTravelToSystemAndReturnToResupply' ", + retPath = canTravelToSystemAndReturnToResupply(fleetID, fromSystemAITarget, toSystemAITarget, empireID, verbose=True) + return retPath def canTravelToSystemAndReturnToResupply(fleetID, fromSystemAITarget, toSystemAITarget, empireID, verbose=False): "check if fleet can travel from starting system to wanted system" @@ -82,14 +95,14 @@ # try to find path without going resupply first supplySystemAITarget = getNearestSuppliedSystem(toSystemAITarget.getTargetID(), empireID) - systemAITargets = __findPathWithFuelToSystemWithPossibleReturn(fromSystemAITarget, toSystemAITarget, empireID, systemAITargets, fleetSupplyableSystemIDs, maxFuel, fuel, supplySystemAITarget) + __findPathWithFuelToSystemWithPossibleReturn(fromSystemAITarget, toSystemAITarget, empireID, systemAITargets, fleetSupplyableSystemIDs, maxFuel, fuel, supplySystemAITarget) # resupply in system first is required to find path if not(fromSystemAITarget.getTargetID() in fleetSupplyableSystemIDs) and len(systemAITargets) == 0: # add supply system to visit fromSystemAITarget = getNearestSuppliedSystem(fromSystemAITarget.getTargetID(), empireID) systemAITargets.append(fromSystemAITarget) # find path from supplied system to wanted system - systemAITargets = __findPathWithFuelToSystemWithPossibleReturn(fromSystemAITarget, toSystemAITarget, empireID, systemAITargets, fleetSupplyableSystemIDs, maxFuel, maxFuel, supplySystemAITarget) + __findPathWithFuelToSystemWithPossibleReturn(fromSystemAITarget, toSystemAITarget, empireID, systemAITargets, fleetSupplyableSystemIDs, maxFuel, maxFuel, supplySystemAITarget) return systemAITargets @@ -118,6 +131,7 @@ result = True # try to find if there is possible path to wanted system from system + newTargets = resultSystemAITargets[:] if fromSystemAITarget.isValid() and toSystemAITarget.isValid() and supplySystemAITarget.isValid(): universe = fo.getUniverse() leastJumpsPath = universe.leastJumpsPath(fromSystemAITarget.getTargetID(), toSystemAITarget.getTargetID(), empireID) @@ -132,8 +146,8 @@ # leastJumpPath can differ from shortestPath # TODO: use Graph Theory to optimize - if (not systemID == toSystemAITarget.getTargetID()) and (systemID in fleetSupplyableSystemIDs): - resultSystemAITargets.append(AITarget.AITarget(AITargetType.TARGET_SYSTEM, systemID)) + if True or ((not systemID == toSystemAITarget.getTargetID()) and (systemID in fleetSupplyableSystemIDs)):#TODO: restructure + newTargets.append(AITarget.AITarget(AITargetType.TARGET_SYSTEM, systemID)) if fuel < 0: result = False @@ -150,12 +164,12 @@ if minJumps > fuel: # print "fleetID:" + str(fleetID) + " fuel:" + str(fuel) + " required: " + str(minJumps) result = False - else: - resultSystemAITargets.append(toSystemAITarget) + #else: + #resultSystemAITargets.append(toSystemAITarget) if result == False: - resultSystemAITargets = [] - + return [] + resultSystemAITargets[:] = newTargets return resultSystemAITargets def getResupplyAIFleetOrder(fleetAITarget, currentSystemAITarget): Modified: trunk/FreeOrion/default/AI/PlanetUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/PlanetUtilsAI.py 2013-02-13 04:27:07 UTC (rev 5757) +++ trunk/FreeOrion/default/AI/PlanetUtilsAI.py 2013-02-13 04:28:17 UTC (rev 5758) @@ -8,6 +8,8 @@ sys = universe.getSystem(sysID) if sys: res.append( "%s:%d"%(sys.name, sysID ) ) + else: + res.append("unkown:%d"%sysID ) return res def planetNameIDs(planetIDs): @@ -17,6 +19,8 @@ planet = universe.getSystem(pid) if planet: res.append( "%s:%d"%(planet.name, pid ) ) + else: + res.append("unkown:%d"%pid ) return res def getCapital(): # if no current capital returns planet with biggest pop |
From: <dil...@us...> - 2013-02-14 09:51:00
|
Revision: 5763 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5763&view=rev Author: dilvish-fo Date: 2013-02-14 09:50:48 +0000 (Thu, 14 Feb 2013) Log Message: ----------- Misc AI revisions, adding support for Fractal Ships among other things; also a revised charting script that also plots empire ship counts Modified Paths: -------------- trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/EnumsAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResourcesAI.py trunk/FreeOrion/default/AI/TechsListsAI.py trunk/FreeOrion/default/AI/charting/charts.py Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -576,12 +576,17 @@ universe = fo.getUniverse() okFleets=FleetUtilsAI.getEmpireFleetIDs() fleetList = sorted( list( self.__fleetRoleByID )) + unaccountedFleets = set( okFleets ) - set( fleetList ) + shipCount=0 print "----------------------------------------------------------------------------------" print "in CleanFleetRoles" print "fleetList : %s"%fleetList print "-----------" print "FleetUtils empire-owned fleetList : %s"%okFleets print "-----------" + if unaccountedFleets: + print "Fleets unaccounted for in Empire Records: ", unaccountedFleets + print "-----------" print "statusList %s"%[self.fleetStatus[fid] for fid in sorted( self.fleetStatus.keys() ) ] print "-----------" for fleetID in fleetList: @@ -595,6 +600,7 @@ if fleet: sysID = fleet.systemID status['nships']=len(fleet.shipIDs) + shipCount += status['nships'] else: sysID = oldSysID #can still retrieve a fleet object even if fleet was just destroyed if (fleetID not in okFleets):# or fleet.empty: @@ -641,6 +647,9 @@ #if sysID != -1: # self.systemStatus.setdefault(sysID, {}).setdefault('myFleetRating', 0) # self.systemStatus[sysID]['myFleetRating'] += newRating #moved to updateSystemStatus + print "------------------------" + print "Empire Ship Count: ", shipCount + print "------------------------" def getExplorableSystems(self, explorableSystemsType): "get all explorable systems determined by type " Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -358,6 +358,7 @@ system = universe.getSystem(planet.systemID) tagList=[] starBonus=0 + colonyStarBonus=0 if species: tagList = [tag for tag in species.tags] starPopMod=0 @@ -388,9 +389,15 @@ if (empire.getTechStatus("PRO_NEUTRONIUM_EXTRACTION") == fo.techStatus.complete) or ( "PRO_NEUTRONIUM_EXTRACTION" in empireResearchList[:8]) : if system.starType in [fo.starType.neutron]: if len (AIstate.empireStars.get(fo.starType.neutron, []))==0: - starBonus +=40*discountMultiplier #pretty rare planets, good for armor + starBonus +=80*discountMultiplier #pretty rare planets, good for armor else: - starBonus +=10*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators + starBonus +=20*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators + if (empire.getTechStatus("SHP_ENRG_BOUND_MAN") == fo.techStatus.complete) or ( "SHP_ENRG_BOUND_MAN" in empireResearchList[:6]) : + if system.starType in [fo.starType.blackHole, fo.starType.blue] : + if len (AIstate.empireStars.get(fo.starType.blackHole, []) + AIstate.empireStars.get(fo.starType.blue, []) ) ==0: + colonyStarBonus +=100*discountMultiplier #pretty rare planets, good for generator + elif planet.systemID not in (AIstate.popCtrSystemIDs + AIstate.outpostSystemIDs): + colonyStarBonus +=50*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators retval = starBonus planetSpecials = list(planet.specials) @@ -427,6 +434,7 @@ retval = retval / 2.0 return int(retval) else: #colonization mission + retval += colonyStarBonus asteroidBonus=0 gasGiantBonus=0 miningBonus=0 Modified: trunk/FreeOrion/default/AI/EnumsAI.py =================================================================== --- trunk/FreeOrion/default/AI/EnumsAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/EnumsAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -201,7 +201,7 @@ colonyShip = {"SD_COLONY_SHIP":"A", "Seeder":"B", "Nest-Maker":"C", "Den-Maker":"D"} outpostShip = {"SD_OUTPOST_SHIP":"A", "Outposter":"B"} troopShip = {"SD_TROOP_SHIP":"A", "Basic-Troopers":"B", "Medium-Troopers":"C", "Heavy-Troopers":"D", "Very-Heavy-Troopers":"D"} - attackShip= {"SD_MARK":"A", "Lynx":"B","Griffon":"C", "Wyvern":"D", "Manticore":"E", "Devil":"F", "Reaver":"G"} + attackShip= {"SD_MARK":"A", "Lynx":"B","Griffon":"C", "Wyvern":"D", "Manticore":"E", "Devil":"F", "Reaver":"G", "Obliterator":"H"} colonyBase={"SD_COLONY_BASE":"A", "NestBase":"B"} outpostBase={"SD_OUTPOST_BASE":"A", "OutpostBase":"B"} troopBase={"SpaceInvaders":"A"} Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -88,11 +88,11 @@ print "" if sortedPlanets: - print "Invadable planetIDs, ID | Score | Race | Troops | Name:" + print "Invadable planets\nIDs, ID | Score | Name | Race | Troops" for pid, pscore, ptroops in sortedPlanets: planet = universe.getPlanet(pid) if planet: - print "%6d | %6d | %s | %s | %d"%(pid, pscore, planet.name, planet.speciesName, ptroops) + print "%6d | %6d | %16s | %16s | %d"%(pid, pscore, planet.name, planet.speciesName, ptroops) else: print "%6d | %6d | Error: invalid planet ID"%(pid, pscore) else: @@ -146,7 +146,7 @@ "BLD_SHIPYARD_ENRG_COMP": 500, "BLD_SHIPYARD_ENRG_SOLAR": 1500, "BLD_INDUSTRY_CENTER": 500, - "BLD_GAS_GIANT_GEN": 50, + "BLD_GAS_GIANT_GEN": 200, "BLD_SOL_ORB_GEN": 800, "BLD_BLACK_HOLE_POW_GEN": 2000, "BLD_ENCLAVE_VOID": 500, @@ -155,11 +155,12 @@ "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 - distanceFactor = 0 + maxJumps=8 planet = universe.getPlanet(planetID) if (planet == None) : #TODO: exclude planets with stealth higher than empireDetection print "invasion AI couldn't get current info on planet %d"%planetID @@ -169,18 +170,20 @@ for bldType in [universe.getObject(bldg).buildingTypeName for bldg in planet.buildingIDs]: bldTally += buildingValues.get(bldType, 50) - # capitalID = PlanetUtilsAI.getCapital() - # homeworld = universe.getPlanet(capitalID) - # if homeworld: - # homeSystemID = homeworld.systemID - # evalSystemID = planet.systemID - # leastJumpsPath = len(universe.leastJumpsPath(homeSystemID, evalSystemID, empireID)) - # distanceFactor = 4.0/(leastJumpsPath + 1) + capitolID = PlanetUtilsAI.getCapital() + if capitolID: + homeworld = universe.getPlanet(capitolID) + if homeworld: + homeSystemID = homeworld.systemID + evalSystemID = planet.systemID + leastJumpsPath = len(universe.leastJumpsPath(homeSystemID, evalSystemID, empireID)) + maxJumps = leastJumpsPath troops = planet.currentMeterValue(fo.meterType.troops) + maxTroops = planet.currentMeterValue(fo.meterType.maxTroops) specName=planet.speciesName species=fo.getSpecies(specName) - productionVal = 8*(planet.currentMeterValue(fo.meterType.targetIndustry)+planet.currentMeterValue(fo.meterType.targetResearch)) + productionVal = 20*(planet.currentMeterValue(fo.meterType.targetPopulation)/planet.currentMeterValue(fo.meterType.population) )*max(planet.currentMeterValue(fo.meterType.targetIndustry), 2*planet.currentMeterValue(fo.meterType.targetResearch)) supplyVal=0 enemyVal=0 if planet.owner!=-1 : @@ -202,7 +205,8 @@ for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: specialVal +=10 # - return popVal+supplyVal+specialVal+bldTally+productionVal+enemyVal-8*troops, troops + buildTime=4 + return max(0, popVal+supplyVal+specialVal+bldTally+productionVal+enemyVal-8*troops), min(troops+maxJumps+buildTime, maxTroops) def getPlanetPopulation(planetID): "return planet population" Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -115,7 +115,7 @@ threatBias = 0 - safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 0.95, 0.95 ][foAI.foAIstate.aggression] + safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 1.0, 0.9 ][foAI.foAIstate.aggression] topTargetPlanets = [pid for pid, pscore, trp in AIstate.invasionTargets[:PriorityAI.allottedInvasionTargets] if pscore > 20] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] if pscore > 20] topTargetSystems = [] Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -125,7 +125,8 @@ styleIndex = empireID%2 styleAdjustmentMap = {0:0, 1:0}#TODO: decide if I want to do anything with this styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) - cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] + #cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] #1 doing better + cutoffs = [ [40, 65, 90 ], [40, 75, 100 ] ][styleIndex ] #1 doing better if industrySurge: researchPriority = 10+styleAdjustment else: Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -155,11 +155,11 @@ for ari in [1, 2]: nb, hull = designNameBases[ari+2]+"%1d-%1d", "SH_ORGANIC" - newTroopDesigns += [ (nb%(2, ari+1), desc, hull, ["SR_WEAPON_2", arL[ari], tp, tp], "", model) ] - newTroopDesigns += [ (nb%(3, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp], "", model) ] + #newTroopDesigns += [ (nb%(2, ari+1), desc, hull, ["SR_WEAPON_2", arL[ari], tp, tp], "", model) ] + #newTroopDesigns += [ (nb%(3, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp], "", model) ] nb, hull = designNameBases[ari+2]+"%1d-%1d", "SH_STATIC_MULTICELLULAR" - newTroopDesigns += [ (nb%(4, ari+1), desc, hull, ["SR_WEAPON_2", arL[ari], tp, tp, tp], "", model) ] - newTroopDesigns += [ (nb%(5, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp], "", model) ] + #newTroopDesigns += [ (nb%(4, ari+1), desc, hull, ["SR_WEAPON_2", arL[ari], tp, tp, tp], "", model) ] + #newTroopDesigns += [ (nb%(5, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp], "", model) ] nb, hull = designNameBases[ari+2]+"%1d-%1d", "SH_ENDOMORPHIC" newTroopDesigns += [ (nb%(6, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp, tp], "", model) ] newTroopDesigns += [ (nb%(7, ari+1), desc, hull, ["SR_WEAPON_8", arL[ari], tp, tp, tp, tp], "", model) ] @@ -296,14 +296,14 @@ ar2= "AR_ZORTRIUM_PLATE" ar3= "AR_NEUTRONIUM_PLATE" nb, hull = designNameBases[1]+"-%1d", "SH_BASIC_MEDIUM" - newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, ""], "", model) for iw in range(1, 9) ] + newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, ""], "", model) for iw in range(1, 6) ] - newMarkDesigns += [ ((nb%iw)+'N', desc, hull, [ srb%iw, ar3, ""], "", model) for iw in range(1, 8) ] + #newMarkDesigns += [ ((nb%iw)+'N', desc, hull, [ srb%iw, ar3, ""], "", model) for iw in range(1, 8) ] nb, hull = designNameBases[2]+"-1-%1d", "SH_ORGANIC" newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is1], "", model) for iw in range(2, 9) ] nb, hull = designNameBases[2]+"-2-%1d", "SH_STATIC_MULTICELLULAR" - newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is1, is2], "", model) for iw in range(7, 9) ] + newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is1, is2], "", model) for iw in range(6, 9) ] if foAI.foAIstate.aggression in [fo.aggression.beginner, fo.aggression.turtle]: maxEM= 8 @@ -312,55 +312,66 @@ else: maxEM= 10 - nb, hull = designNameBases[3]+"-1-%1d", "SH_ENDOMORPHIC" + nb, hull = designNameBases[3]+"-1-%1x", "SH_ENDOMORPHIC" newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + 2*[ is1], "", model) for iw in [5, 6, 7 ] ] - nb = designNameBases[3]+"-2-%1d" + nb = designNameBases[3]+"-2-%1x" newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + [ is2, is2], "", model) for iw in range(6, maxEM+1) ] - nb = designNameBases[3]+"3-%1d" + nb = designNameBases[3]+"3-%1x" #newMarkDesigns += [ (nb%iw, desc, hull, 2*[srb%iw]+[ar1] + [ is1, is1], "", model) for iw in [5, 6, 7, 8, 10, 11, 12 ] ] - nb = designNameBases[3]+"-4-%1d" + nb = designNameBases[3]+"-4-%1x" #newMarkDesigns += [ (nb%iw, desc, hull, 2*[srb%iw]+[ar1] + [ is1, is2], "", model) for iw in [7, 8, 10, 11, 12 ] ] - nb = designNameBases[3]+"-5-%1d" + nb = designNameBases[3]+"-5-%1x" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar2] + 2*[ is2], "", model) for iw in range(7, maxEM+1) ] - nb = designNameBases[3]+"-6-%1d" + nb = designNameBases[3]+"-6-%1x" if foAI.foAIstate.aggression <=fo.aggression.turtle: newMarkDesigns += [ (nb%iw, desc, hull, 2*[srb%iw] +[ar3, ar3]+ 2*[ is2], "", model) for iw in range(8, maxEM+1) ] else: newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw] +[ar3]+ 2*[ is2], "", model) for iw in range(8, maxEM+1) ] - nb = designNameBases[3]+"-7-%1d" + nb = designNameBases[3]+"-7-%1x" newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] - nb = designNameBases[3]+"-8-%1d" + nb = designNameBases[3]+"-8-%1x" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar2] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] - nb = designNameBases[3]+"-9-%1d" + nb = designNameBases[3]+"-9-%1x" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar3] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] if foAI.foAIstate.aggression >=fo.aggression.typical: - nb, hull = designNameBases[4]+"-%1d-%1d", "SH_ENDOSYMBIOTIC" - newMarkDesigns += [ (nb%(1, iw), desc, hull, 3*[srb%iw]+[ar2] + 3*[ is2], "", model) for iw in range(7, 12) ] - newMarkDesigns += [ (nb%(2, iw), desc, hull, 3*[srb%iw]+[ar3] + 3*[ is2], "", model) for iw in range(8, 12) ] - newMarkDesigns += [ (nb%(3, iw), desc, hull, 3*[srb%iw]+[ar2] + 3*[ is3], "", model) for iw in range(7, 12) ] - newMarkDesigns += [ (nb%(4, iw), desc, hull, 3*[srb%iw]+[ar3] + 3*[ is3], "", model) for iw in range(8, 12) ] + nb, hull = designNameBases[4]+"-%1x-%1x", "SH_ENDOSYMBIOTIC" + newMarkDesigns += [ (nb%(1, iw), desc, hull, 4*[srb%iw] + 3*[ is2], "", model) for iw in range(7, 14) ] + newMarkDesigns += [ (nb%(2, iw), desc, hull, 4*[srb%iw] + 3*[ is3], "", model) for iw in range(7, 14) ] + + newMarkDesigns += [ (nb%(3, iw), desc, hull, 3*[srb%iw]+[ar2] + 3*[ is2], "", model) for iw in range(7, 14) ] + newMarkDesigns += [ (nb%(4, iw), desc, hull, 3*[srb%iw]+[ar3] + 3*[ is2], "", model) for iw in range(8, 14) ] + newMarkDesigns += [ (nb%(5, iw), desc, hull, 3*[srb%iw]+[ar2] + 3*[ is3], "", model) for iw in range(7, 14) ] + newMarkDesigns += [ (nb%(6, iw), desc, hull, 3*[srb%iw]+[ar3] + 3*[ is3], "", model) for iw in range(8, 14) ] #bioadaptive - nb, hull = designNameBases[4]+"-%1d-%1d", "SH_BIOADAPTIVE" - newMarkDesigns += [ (nb%(5, iw), desc, hull, 3*[srb%iw] + 3*[ is2], "", model) for iw in range(9, 14) ] - newMarkDesigns += [ (nb%(6, iw), desc, hull, 2*[srb%iw]+[ar2] + 3*[ is2], "", model) for iw in range(9, 14) ] - newMarkDesigns += [ (nb%(7, iw), desc, hull, 3*[srb%iw] + 3*[ is3], "", model) for iw in range(9, 14) ] - newMarkDesigns += [ (nb%(8, iw), desc, hull, 2*[srb%iw]+[ar3] + 3*[ is3], "", model) for iw in range(9, 14) ] + nb, hull = designNameBases[4]+"-%1x-%1x", "SH_BIOADAPTIVE" + newMarkDesigns += [ (nb%(7, iw), desc, hull, 3*[srb%iw] + 3*[ is2], "", model) for iw in range(9, 14) ] + newMarkDesigns += [ (nb%(8, iw), desc, hull, 2*[srb%iw]+[ar2] + 3*[ is2], "", model) for iw in range(9, 14) ] + newMarkDesigns += [ (nb%(9, iw), desc, hull, 3*[srb%iw] + 3*[ is3], "", model) for iw in range(9, 14) ] + newMarkDesigns += [ (nb%(10, iw), desc, hull, 2*[srb%iw]+[ar3] + 3*[ is3], "", model) for iw in range(9, 14) ] if foAI.foAIstate.aggression >fo.aggression.typical: - nb, hull = designNameBases[5]+"-%1d-%1d", "SH_SENTIENT" - newMarkDesigns += [ (nb%(1, iw), desc, hull, 4*[srb%iw]+2*[ar2] + 3*[ is2], "", model) for iw in range(10, 17) ] - newMarkDesigns += [ (nb%(2, iw), desc, hull, 5*[srb%iw]+[ar3] + 3*[ is2], "", model) for iw in range(10, 17) ] - newMarkDesigns += [ (nb%(3, iw), desc, hull, 5*[srb%iw]+[ar2] + 3*[ is3], "", model) for iw in range(10, 17) ] - newMarkDesigns += [ (nb%(4, iw), desc, hull, 5*[srb%iw]+[ar3] + 3*[ is3], "", model) for iw in range(10, 17) ] - + nb, hull = designNameBases[5]+"-%1x-%02x", "SH_SENTIENT" + newMarkDesigns += [ (nb%(1, iw), desc, hull, 4*[srb%iw]+2*[ar2] + 3*[ is2], "", model) for iw in range(10, 18) ] + newMarkDesigns += [ (nb%(2, iw), desc, hull, 5*[srb%iw]+[ar3] + 3*[ is2], "", model) for iw in range(10, 18) ] + newMarkDesigns += [ (nb%(3, iw), desc, hull, 5*[srb%iw]+[ar2] + 3*[ is3], "", model) for iw in range(10, 18) ] + newMarkDesigns += [ (nb%(4, iw), desc, hull, 5*[srb%iw]+[ar3] + 3*[ is3], "", model) for iw in range(10, 18) ] + + if foAI.foAIstate.aggression >fo.aggression.typical: + nb, hull = designNameBases[6]+"-%1x-%02x", "SH_FRACTAL_ENERGY" + newMarkDesigns += [ (nb%(1, iw), desc, hull, 8*[srb%iw]+3*[ar2] + 3*[ is2], "", model) for iw in range(10, 18) ] + newMarkDesigns += [ (nb%(2, iw), desc, hull, 9*[srb%iw]+3*[ar3] + 2*[ is2], "", model) for iw in range(10, 18) ] + newMarkDesigns += [ (nb%(3, iw), desc, hull, 8*[srb%iw]+3*[ar2] + 3*[ is3], "", model) for iw in range(10, 18) ] + newMarkDesigns += [ (nb%(4, iw), desc, hull, 9*[srb%iw]+3*[ar3] + 2*[ is3], "", model) for iw in range(10, 18) ] + + currentTurn=fo.currentTurn() needsAdding=[] namesToAdd=[] @@ -666,14 +677,14 @@ #TODO: add totalPP checks below, so don't overload queue - maxDefensePortion = [0.7, 0.7, 0.6, 0.5, 0.3, 0.2 ][ foAI.foAIstate.aggression] + maxDefensePortion = [0.7, 0.4, 0.3, 0.2, 0.1, 0.0 ][ foAI.foAIstate.aggression] aggrIndex=max(1, foAI.foAIstate.aggression) - if (fo.currentTurn() %( aggrIndex))==0: + if ( (fo.currentTurn() %( aggrIndex))==0) and foAI.foAIstate.aggression < fo.aggression.maniacal: sysOrbitalDefenses={} queuedDefenses={} orbitalDefenseNames = shipTypeNames( AIPriorityType.PRIORITY_PRODUCTION_ORBITAL_DEFENSE ) defenseAllocation=0.0 - targetOrbitals= int( ((fo.currentTurn()+4)/( 8.0*(aggrIndex)**1.5))**0.8) + targetOrbitals= min( int( ((fo.currentTurn()+4)/( 8.0*(aggrIndex)**1.5))**0.8) , fo.aggression.maniacal - aggrIndex ) print "Orbital Defense Check -- target Defense Orbitals: ", targetOrbitals for element in productionQueue: if ( element.buildType == AIEmpireProductionTypes.BT_SHIP) and (foAI.foAIstate.getShipRole(element.designID) == AIShipRoleType.SHIP_ROLE_BASE_DEFENSE): @@ -708,10 +719,10 @@ res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front defenseAllocation += productionQueue[0].allocation break - + queuedShipyardLocs = [element.locationID for element in productionQueue if (element.name=="BLD_SHIPYARD_BASE") ] - colonySystems={} - colonyPlanets={} + systemColonies={} + colonySystems={} for specName in empireColonizers: if (len( empireColonizers[specName])==0) and (specName in empireSpecies): #no current shipyards for this species#TODO: also allow orbital incubators and/or asteroid ships for pID in empireSpecies.get(specName, []): #SP_EXOBOT may not actually have a colony yet but be in empireColonizers @@ -727,15 +738,65 @@ for pid in empireSpecies.get(specName, []): planet=universe.getPlanet(pid) if planet: - colonySystems.setdefault(planet.systemID, {}).setdefault('pids', []).append(pid) - colonyPlanets[pid]=planet.systemID + systemColonies.setdefault(planet.systemID, {}).setdefault('pids', []).append(pid) + colonySystems[pid]=planet.systemID + + popCtrs = list(AIstate.popCtrIDs) + enrgyShipyardLocs=[] + for bldName in [ "BLD_SHIPYARD_ENRG_COMP" ]: + if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >200 or fo.currentTurn() > 150 ): + queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] + bldType = fo.getBuildingType(bldName) + for pid in popCtrs: + if len(queuedBldLocs)>1: #build a max of 2 at once + break + if colonySystems.get(pid, -1) not in ( AIstate.empireStars.get(fo.starType.blackHole, []) + AIstate.empireStars.get(fo.starType.blue, []) ): + continue + enrgyShipyardLocs.append(pid) + if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building + res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) + if res: + queuedBldLocs.append(pid) + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + bldgExpense += productionQueue[0].allocation + print "Requeueing %s to front of build queue, with result %d"%(bldName, res) - popCtrs = list(AIstate.popCtrIDs) + for bldName in [ "BLD_SHIPYARD_BASE" ]: + if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >50 or fo.currentTurn() > 80 ): + queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] + bldType = fo.getBuildingType(bldName) + for pid in enrgyShipyardLocs: + if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building + res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) + if res: + queuedBldLocs.append(pid) + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + bldgExpense += productionQueue[0].allocation + print "Requeueing %s to front of build queue, with result %d"%(bldName, res) + for bldName in [ "BLD_SHIPYARD_ORG_ORB_INC" , "BLD_SHIPYARD_ORG_XENO_FAC" ]: if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >40 or fo.currentTurn() > 40 ): queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] bldType = fo.getBuildingType(bldName) for pid in popCtrs: + if len(queuedBldLocs)>1+int(totalPP/200.0) : # limit build at once + break + if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building + res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) + if res: + queuedBldLocs.append(pid) + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + bldgExpense += productionQueue[0].allocation + print "Requeueing %s to front of build queue, with result %d"%(bldName, res) + + for bldName in [ "BLD_SHIPYARD_ORG_CELL_GRO_CHAMB" ]: + if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >50 or fo.currentTurn() > 80 ): + queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] + bldType = fo.getBuildingType(bldName) + for pid in popCtrs: if len(queuedBldLocs)>1: #build a max of 2 at once break if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building @@ -1040,7 +1101,7 @@ wastedPP = max(0, totalPP - totalPPSpent) print " Wasted Production Points: " + str(wastedPP) - availPP = totalPP*1.1 - totalPPSpent + availPP = totalPP*1.05 - totalPPSpent print "" print "Possible ship designs to build:" Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -67,28 +67,33 @@ newFocus= IFocus for pid in empirePlanetIDs: + canFocus= planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) >0 currentFocus[pid] = planetMap[pid].focus - if currentFocus[pid] == MFocus: - mtarget=planetMap[pid].currentMeterValue(fo.meterType.targetIndustry) + #if currentFocus[pid] == MFocus: + # mtarget=planetMap[pid].currentMeterValue(fo.meterType.targetIndustry) currentOutput.setdefault(pid, {} )[ IFocus] = planetMap[pid].currentMeterValue(fo.meterType.industry) currentOutput[pid][ RFocus] = planetMap[pid].currentMeterValue(fo.meterType.research) - fo.issueChangeFocusOrder(pid, IFocus) #may not be able to take, but try + if canFocus: + fo.issueChangeFocusOrder(pid, IFocus) #may not be able to take, but try universe.updateMeterEstimates(empirePlanetIDs) for pid in empirePlanetIDs: + canFocus= planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) >0 itarget=planetMap[pid].currentMeterValue(fo.meterType.targetIndustry) rtarget=planetMap[pid].currentMeterValue(fo.meterType.targetResearch) newTargets.setdefault(pid, {}).setdefault(IFocus, (0, 0)) newTargets[pid][IFocus] = ( itarget, rtarget ) - if currentFocus[pid] == MFocus: - newTargets[pid][MFocus] = ( mtarget, rtarget ) - fo.issueChangeFocusOrder(pid, RFocus) #may not be able to take, but try + #if currentFocus[pid] == MFocus: + # newTargets[pid][MFocus] = ( mtarget, rtarget ) + if canFocus: + fo.issueChangeFocusOrder(pid, RFocus) #may not be able to take, but try universe.updateMeterEstimates(empirePlanetIDs) for pid in empirePlanetIDs: + canFocus= planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) >0 itarget=planetMap[pid].currentMeterValue(fo.meterType.targetIndustry) rtarget=planetMap[pid].currentMeterValue(fo.meterType.targetResearch) newTargets.setdefault(pid, {}).setdefault(RFocus, (0, 0)) newTargets[pid][RFocus] = ( itarget, rtarget ) - if currentFocus[pid] != RFocus: + if canFocus and currentFocus[pid] != RFocus: fo.issueChangeFocusOrder(pid, currentFocus[pid]) #put it back to what it was universe.updateMeterEstimates(empirePlanetIDs) return targetPP, targetRP @@ -361,8 +366,8 @@ for pid in newTargets: II, IR = newTargets[pid][IFocus] RI, RR = newTargets[pid][RFocus] - if currentFocus[pid] == MFocus: - II = max( II, newTargets[pid][MFocus][0] ) + #if currentFocus[pid] == MFocus: + # II = max( II, newTargets[pid][MFocus][0] ) curTargetPP += II #icurTargets initially calculated by Industry focus, which will be our default focus curTargetRP += IR newFoci[pid] = IFocus @@ -393,8 +398,8 @@ break II, IR = newTargets[pid][IFocus] RI, RR = newTargets[pid][RFocus] - if currentFocus[pid] == MFocus: - II = max( II, newTargets[pid][MFocus][0] ) + #if currentFocus[pid] == MFocus: + # II = max( II, newTargets[pid][MFocus][0] ) if gotAlgo and ( (ratio > 2.0 and curTargetPP < 15) or (ratio > 2.5 and curTargetPP < 25 and II > 5) or @@ -422,6 +427,7 @@ print "%34s|%20s|%15s |%15s|%15s |%15s "%(" Planet ", " current RP/PP ", " current target RP/PP ", "current Focus "," newFocus ", " new target RP/PP ") totalChanged=0 for pid in newTargets: + canFocus= planetMap[pid].currentMeterValue(fo.meterType.targetPopulation) >0 oldFocus=currentFocus[pid] changeFocus=False newFocus = newFoci[pid] @@ -429,13 +435,13 @@ if newFocus==RFocus and oldFocus!=RFocus: changeFocus = True elif newFocus == IFocus: - if ( MFocus in planetMap[pid].availableFoci ) and ( newTargets[pid].setdefault(MFocus, (25, IR))[0] > newTargets[pid][IFocus][0]): - newFocus=MFocus + #if ( MFocus in planetMap[pid].availableFoci ) and ( newTargets[pid].setdefault(MFocus, (25, IR))[0] > newTargets[pid][IFocus][0]): + # newFocus=MFocus if newFocus !=oldFocus: changeFocus = True else: pass #not supporting growth focus yet - if changeFocus: + if canFocus and changeFocus: totalChanged+=1 fo.issueChangeFocusOrder(pid, newFocus) otPP, otRP= newTargets[pid].get(oldFocus, (0, 0)) Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -231,36 +231,52 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" - index=1 + #index=1 if index == 0: primaryMetaTechs = [ "GRO_PLANET_ECOL", "GRO_SUBTER_HAB", "SHP_DOMESTIC_MONSTER", + "LRN_ALGO_ELEGANCE", "SHP_ORG_HULL", - "SHP_WEAPON_3", - "LRN_ALGO_ELEGANCE", + "SHP_WEAPON_2", + "SHP_WEAPON_5", + "LRN_ARTIF_MINDS", + "GRO_SYMBIOTIC_BIO", + "DEF_DEFENSE_NET_1", "CON_ENV_ENCAPSUL", "PRO_FUSION_GEN", - "SHP_WEAPON_5", + "LRN_FORCE_FIELD", "PRO_ROBOTIC_PROD", - "DEF_DEFENSE_NET_1", "DEF_GARRISON_1", + "SHP_WEAPON_6", + "DEF_DEFENSE_NET_2", + "DEF_PLAN_BARRIER_SHLD_1", + "SPY_DETECT_2", "CON_ORBITAL_CON", - "SHP_WEAPON_6", - "GRO_SYMBIOTIC_BIO", - "LRN_ARTIF_MINDS", - "LRN_FORCE_FIELD", - "GRO_GENETIC_ENG", - "SHP_MULTICELL_CAST", "PRO_ORBITAL_GEN", - "SPY_DETECT_2", "SHP_WEAPON_7", + "CON_METRO_INFRA", + "CON_SUBTER_CONST", "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_I", + "DEF_DEFENSE_NET_REGEN_1", + "DEF_PLAN_BARRIER_SHLD_2", + "PRO_SOL_ORB_GEN", + "GRO_GENETIC_ENG", + "LRN_PHYS_BRAIN", + "LRN_TRANSLING_THT", + "PRO_SENTIENT_AUTOMATION", + "PRO_EXOBOTS", + "DEF_DEFENSE_NET_3", + "DEF_SYST_DEF_MINE_1", + "DEF_PLAN_BARRIER_SHLD_3", + "CON_ORBITAL_HAB", + "GRO_XENO_HYBRIDS", + "SHP_MULTICELL_CAST", "DEF_GARRISON_2", + "GRO_LIFECYCLE_MAN", "SHP_ENDOCRINE_SYSTEMS", - "GRO_LIFECYCLE_MAN", "LRN_GRAVITONICS", "CON_CONTGRAV_ARCH", "DEF_GARRISON_3", @@ -268,34 +284,25 @@ "PRO_INDUSTRY_CENTER_II", "GRO_XENO_GENETICS", "SHP_CONT_SYMB", - "DEF_DEFENSE_NET_2", - "DEF_PLAN_BARRIER_SHLD_1", - "CON_METRO_INFRA", - "CON_SUBTER_CONST", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", - "PRO_SOL_ORB_GEN", - "DEF_DEFENSE_NET_REGEN_1", - "DEF_PLAN_BARRIER_SHLD_2", + "PRO_SINGULAR_GEN", + "SPY_DETECT_3", + "LRN_XENOARCH", "SHP_WEAPON_9", - "CON_ORBITAL_HAB", - "GRO_XENO_HYBRIDS", "PRO_MICROGRAV_MAN", + "LRN_QUANT_NET", + "LRN_TIME_MECH", + "LRN_STELLAR_TOMOGRAPHY", + "PRO_NEUTRONIUM_EXTRACTION", + "LRN_ENCLAVE_VOID", + "LRN_PSY_DOM", + "LRN_ART_BLACK_HOLE", "SHP_ASTEROID_HULLS", "GRO_TERRAFORM", - "LRN_PHYS_BRAIN", - "LRN_TRANSLING_THT", - "LRN_XENOARCH", "GRO_GENETIC_MED", "SHP_LEAD_PLATE", "SHP_BIOADAPTIVE_SPEC", - "PRO_SENTIENT_AUTOMATION", - "PRO_EXOBOTS", - "DEF_DEFENSE_NET_3", - "DEF_SYST_DEF_MINE_1", - "DEF_PLAN_BARRIER_SHLD_3", - "SPY_DETECT_3", - "LRN_QUANT_NET", "SHP_INTSTEL_LOG", "SHP_REINFORCED_HULL", "SHP_WEAPON_10", @@ -309,30 +316,24 @@ "GRO_GENOME_BANK", "SHP_BASIC_DAM_CONT", "CON_CONC_CAMP", - "PRO_SINGULAR_GEN", "SHP_ADV_DAM_CONT", "PRO_INDUSTRY_CENTER_III", "DEF_GARRISON_4", "SPY_CLOAK_1", "DEF_DEFENSE_NET_REGEN_2", + "SHP_ENRG_BOUND_MAN ", "GRO_GAIA_TRANS", "GRO_ENERGY_META", - "LRN_TIME_MECH", - "LRN_ART_BLACK_HOLE", "CON_ART_PLANET", - "LRN_STELLAR_TOMOGRAPHY", - "PRO_NEUTRONIUM_EXTRACTION", - "LRN_ENCLAVE_VOID", "LRN_DISTRIB_THOUGHT", "GRO_ENERGY_META", - "LRN_PSY_DOM", "DEF_SYST_DEF_MINE_3", "DEF_PLAN_BARRIER_SHLD_4", "SHP_WEAPON_13", "SPY_DETECT_4", "SHP_WEAPON_11", "SHP_WEAPON_12", - "SHP_TITAN_HULL" + #"SHP_TITAN_HULL" "DEF_PLAN_BARRIER_SHLD_5", "SHP_SOLAR_CONT", "SHP_WEAPON_14", @@ -429,6 +430,7 @@ "DEF_GARRISON_4", "SPY_CLOAK_1", "DEF_DEFENSE_NET_REGEN_2", + "SHP_ENRG_BOUND_MAN ", "GRO_GAIA_TRANS", "GRO_ENERGY_META", "CON_ART_PLANET", Modified: trunk/FreeOrion/default/AI/charting/charts.py =================================================================== --- trunk/FreeOrion/default/AI/charting/charts.py 2013-02-14 00:50:54 UTC (rev 5762) +++ trunk/FreeOrion/default/AI/charting/charts.py 2013-02-14 09:50:48 UTC (rev 5763) @@ -1,10 +1,4 @@ # installation of scipy probably necessary to get pylab -# -#This script easiest to use if you copy it to the directory your log files are saved to, and then execute it as -# OS_Prompt> python charts.py -# -# alternatively you can edit the DataDir variable below to point to your log files folder, and that should work also -# I do plan to further improve this to test for OS and automatically look in the corresponding default location from pylab import * import os import sys @@ -31,7 +25,7 @@ return '' -for plotType in ["PP", "RP"]: +for plotType in ["PP", "RP", "ShipCount"]: if plotType=="PP": caption="Production" @@ -69,10 +63,14 @@ turnsP = [ int( parts[0]) for parts in [line.split(')') for line in datalines]] PP = [ float( parts[1].split('/')[-1]) for parts in [line.split(')') for line in datalines]] RP = [ float( parts[1].split('/')[-2].split('(')[-1]) for parts in [line.split(')') for line in datalines]] + shipCount = [int(lines.split('\n')[0]) for lines in dat1.split("Empire Ship Count:")[1:]] + if plotType=="PP": data=PP - else: + elif plotType=="RP": data=RP + else: + data = shipCount if data != []: ymin = min(ymin, min(data)) ymax = max(ymax, max(data)) @@ -100,14 +98,17 @@ turnsAI = [ int( parts[0]) for parts in [line.split(')') for line in datalines]] PP = [ float( parts[1].split('/')[-1]) for parts in [line.split(')') for line in datalines]] RP = [ float( parts[1].split('/')[-2].split('(')[-1]) for parts in [line.split(')') for line in datalines]] + shipCount = [1+int(lines.split('\n')[0]) for lines in dat1.split("Empire Ship Count:")[1:]] if plotType=="PP": data=PP rankings.append( (PP[-1], empireName) ) + elif plotType=="RP": + data=RP else: - data=RP + data = shipCount if data != []: - thisMin=min(data) - if thisMin>4: ymin = min(ymin, thisMin) + thisMin=min(data) + if thisMin>0: ymin = min(ymin, thisMin) ymax = max(ymax, max(data)) #plot(turnsAI[:50],data[:50], label=specName, linewidth=2.0) species[empireName]=specName @@ -120,8 +121,8 @@ rankings.sort() legend(loc='upper left',prop={"size":'medium'}) xlabel('Turn') - ylabel(plotType+' per turn') - title(caption+' Point progression') + ylabel(plotType) + title(caption+' Progression') #if saveFile: # savefig(graphDir+os.sep+plotType+"_"+fileRoot+"_toTurn50.png") #show() @@ -138,9 +139,11 @@ print "can't find playerData in allData" else: if playerName in empireColors: - plot(turnsP, allData[playerName], 'o-', color=empireColors[playerName], label=playerName, linewidth=2.0) + print "plotting with color for player: ", playerName, "data min/max: ", min(allData[playerName]), ' | ', max(allData[playerName]) + plot(turnsP, allData[playerName], 'o-', color=empireColors[playerName], label=playerName, linewidth=2.0) else: - plot(turnsP, allData[playerName], 'bx-', label=playerName, linewidth=2.0) + print "plotting withOUT color for player: ", playerName, "data min/max: ", min(allData[playerName]), ' | ', max(allData[playerName]) + plot(turnsP, allData[playerName], 'bx-', label=playerName, linewidth=2.0) #show() #for i in range(len(species)): # name=empires[i] @@ -151,8 +154,8 @@ plot(range(turns[0], turns[0]+len(allData[name])), allData[name], label="(%d) "%(empires.index(name)+1)+name+" : "+species[name], linewidth=2.0) legend(loc='upper left', prop={"size":9},labelspacing=0.2) xlabel('Turn') - ylabel(plotType+' per turn') - title(caption+' Point progression w/ Max Aggression=Maniacal') + ylabel(plotType) + title(caption+' Progression w/ Max Aggression=Maniacal') x1,x2,y1,y2 = axis() newY2=y2 for yi in range(1, 10): |
From: <dil...@us...> - 2013-02-17 00:11:36
|
Revision: 5766 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5766&view=rev Author: dilvish-fo Date: 2013-02-17 00:11:23 +0000 (Sun, 17 Feb 2013) Log Message: ----------- another round of AI adjustments Modified Paths: -------------- trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/FreeOrionAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-16 16:42:00 UTC (rev 5765) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-17 00:11:23 UTC (rev 5766) @@ -37,6 +37,19 @@ "gaia": [ 0, 3, 3, 3, 3 ], } +def resetCAIGlobals(): + global curBestMilShipRating + empireSpecies.clear() + empireSpeciesSystems.clear() + empireColonizers.clear() + activeGrowthSpecials.clear() + annexableSystemIDs.clear() + annexableRing1.clear() + annexableRing2.clear() + annexableRing3.clear() + annexablePlanetIDs.clear() + curBestMilShipRating = 20 + def getColonyFleets(): global empireSpecies, empireColonizers, empireSpeciesSystems, annexableSystemIDs, annexableRing1, annexableRing2, annexableRing3 @@ -349,6 +362,8 @@ "returns the colonisation value of a planet" # TODO: in planet evaluation consider specials and distance discountMultiplier = 20.0 + priorityScaling=1.0 + valMod = 0 universe = fo.getUniverse() @@ -419,7 +434,7 @@ elif otherPlanet.size!= fo.planetSize.gasGiant and otherPlanet.owner==empire.empireID: astVal+=20 * discountMultiplier retval += astVal - if ( ( planet.size == fo.planetSize.gasGiant ) and ( (empire.getTechStatus("PRO_ORBITAL_GEN") == fo.techStatus.complete ) or ( "PRO_ORBITAL_GEN" in empireResearchList[:10]) )): + if ( ( planet.size == fo.planetSize.gasGiant ) and ( (empire.getTechStatus("PRO_ORBITAL_GEN") == fo.techStatus.complete ) or ( "PRO_ORBITAL_GEN" in empireResearchList[:3]) )): if system: orbGenVal=0 for pid in system.planetIDs: @@ -438,15 +453,20 @@ asteroidBonus=0 gasGiantBonus=0 miningBonus=0 + maxGGGs=8 + perGGG=9*discountMultiplier planetSize = planet.size if system: for pid in [id for id in system.planetIDs if id != planetID]: p2 = universe.getPlanet(pid) if p2: if p2.size== fo.planetSize.asteroids : - asteroidBonus = 30 + if ( (empire.getTechStatus("PRO_MICROGRAV_MAN") == fo.techStatus.complete ) or ( "PRO_MICROGRAV_MAN" in empireResearchList[:3]) ): + asteroidBonus = 5*discountMultiplier if p2.size== fo.planetSize.gasGiant : - gasGiantBonus += 50 + if ( (empire.getTechStatus("PRO_ORBITAL_GEN") == fo.techStatus.complete ) or ( "PRO_ORBITAL_GEN" in empireResearchList[:3]) ): + gasGiantBonus += perGGG + gasGiantBonus = min( gasGiantBonus, maxGGGs * perGGG ) if (planet.size==fo.planetSize.gasGiant): if not (species and species.name == "SP_SUPER_TEST"): return 0 @@ -507,7 +527,7 @@ ]: """ for special in [ spec for spec in AIDependencies.metabolimBoosts if spec in planetSpecials]: - valMod += 10 # extra bonus due to potential applicability to other planets + valMod += 3*discountMultiplier # extra bonus due to potential applicability to other planets for thisTag in [ tag for tag in tagList if tag in AIDependencies.metabolims]: popSizeMod += len( (set(planetSpecials).union([key for key in activeGrowthSpecials.keys() if len(activeGrowthSpecials[key])>0 ] )).intersection(AIDependencies.metabolimBoostMap.get(thisTag, []) ) ) @@ -529,7 +549,6 @@ "PRO_INDUSTRY_CENTER_II":1, "PRO_INDUSTRY_CENTER_III":1, "PRO_SOL_ORB_GEN": 2.0, #assumes will build a gen at a blue/white star - "PRO_SOL_ORB_GEN": 5, # half the max value "PRO_SINGULAR_GEN": proSingVal, } @@ -558,7 +577,7 @@ retval = starBonus+asteroidBonus+gasGiantBonus elif popSize==0: if foAI.foAIstate.aggression > fo.aggression.typical and (fo.currentTurn() >= 10): - retval = 0.5*( starBonus+asteroidBonus+gasGiantBonus) #actually is kind of a pain if the pop goes close to zero but not actually zero + retval = 0.6*( starBonus+asteroidBonus+gasGiantBonus) #actually is kind of a pain if the pop goes close to zero but not actually zero else: retval = starBonus+indVal+asteroidBonus+gasGiantBonus + valMod if planet.systemID in annexableRing1: @@ -567,7 +586,14 @@ retval += 20 elif planet.systemID in annexableRing3: retval += 10 + if (gasGiantBonus ==0): + if ( indVal + valMod < 10*discountMultiplier): + if fo.currentTurn() < 15: + priorityScaling = 0 + elif fo.currentTurn() < 50: + priorityScaling = 0.5 + retval *= priorityScaling thrtRatio = (foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0)+0.2*foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('neighborThreat', 0)) / float(curBestMilShipRating) if thrtRatio > 4: retval = 0.3*retval Modified: trunk/FreeOrion/default/AI/FreeOrionAI.py =================================================================== --- trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-02-16 16:42:00 UTC (rev 5765) +++ trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-02-17 00:11:23 UTC (rev 5766) @@ -40,7 +40,7 @@ # called when a new game is started (but not when a game is loaded). should clear any pre-existing state # and set up whatever is needed for AI to generate orders -def startNewGame(aggression=fo.aggression.beginner): +def startNewGame(aggression=fo.aggression.aggressive): global __timerFile, lastTurnTimestamp, __timerBucketFile print "New game started, AI Agression level %d"%aggression @@ -150,7 +150,7 @@ except: print "failed to parse saved state string" #assigning new state - foAIstate = AIstate.AIstate(aggression=fo.aggression.beginner) + foAIstate = AIstate.AIstate(aggression=fo.aggression.aggressive) foAIstate.sessionStartCleanup() print "Error: exception triggered and caught: ", traceback.format_exc() if __timerFile: Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-16 16:42:00 UTC (rev 5765) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-17 00:11:23 UTC (rev 5766) @@ -195,7 +195,7 @@ except: popVal=0 else: - popVal = evaluatePlanet(planetID, AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire) #evaluatePlanet is implorted from ColonisationAI + popVal = evaluatePlanet(planetID, AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire) #evaluatePlanet is imported from ColonisationAI if planetID not in fleetSupplyablePlanetIDs: #extends supply and probably visibility supplyVal = 20#TODO: better analysis here if supply obstructed by defending ships planetSpecials = list(planet.specials) Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-16 16:42:00 UTC (rev 5765) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-17 00:11:23 UTC (rev 5766) @@ -88,8 +88,8 @@ elif fo.currentTurn() < 45: industryPriority = 25 # mid industry , mid research elif fo.currentTurn() < 60: - industryPriority = 40 # high industry , mid research - elif fo.currentTurn() < 80: + industryPriority = 30 # high industry , mid research + elif fo.currentTurn() < 100: industryPriority = 50 # high industry , mid research else: industryPriority = 60 # high industry , low-mid research @@ -126,19 +126,19 @@ styleAdjustmentMap = {0:0, 1:0}#TODO: decide if I want to do anything with this styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) #cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] #1 doing better - cutoffs = [ [40, 65, 90 ], [40, 75, 100 ] ][styleIndex ] #1 doing better - if industrySurge: + cutoffs = [ [40, 65, 90 ], [40, 90, 150 ] ][styleIndex ] #1 doing better + if industrySurge and False: researchPriority = 10+styleAdjustment else: if (fo.currentTurn() < cutoffs[0]) or not gotAlgo: - researchPriority = 60 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance + researchPriority = 50 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance elif fo.currentTurn() < cutoffs[1]: - researchPriority = 30 +styleAdjustment# mid industry , mid research + researchPriority = 40 +styleAdjustment# mid industry , mid research elif fo.currentTurn() < cutoffs[2]: - researchPriority = 20+styleAdjustment # high industry , low research + researchPriority = 30+styleAdjustment # high industry , low research else: researchQueue = list(empire.researchQueue) - researchPriority = 15+styleAdjustment # high industry , low research + researchPriority = 20+styleAdjustment # high industry , low research if len(researchQueue) == 0 : researchPriority = 0 # done with research elif len(researchQueue) <5 and researchQueue[-1].allocation > 0 : Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-16 16:42:00 UTC (rev 5765) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-17 00:11:23 UTC (rev 5766) @@ -210,10 +210,13 @@ db = "DT_DETECTOR_%1d" is1, is2 = "FU_BASIC_TANK", "ST_CLOAK_1" for id in [1, 2, 3, 4]: - newScoutDesigns += [ (nb%(id, iw), desc, hull, [ db%id, srb%iw, srb%iw, is1], "", model) for iw in range(1, 9) ] + newScoutDesigns += [ (nb%(id, 0), desc, "SH_BASIC_SMALL", [ db%id], "", model) ] + #for id in [1, 2, 3, 4]: + # newScoutDesigns += [ (nb%(id, iw), desc, hull, [ db%id, srb%iw, srb%iw, is1], "", model) for iw in range(1, 9) ] nb, hull = designNameBases[2]+"%1d-%1d", "SH_ENDOMORPHIC" for id in [1, 2, 3, 4]: - newScoutDesigns += [ (nb%(id, iw), desc, hull, [ db%id, srb%iw, srb%iw, srb%iw, is1, is2], "", model) for iw in range(1, 9) ] + newScoutDesigns += [ (nb%(id, 0), desc, hull, [ db%id, "", "", "", is1, is1], "", model) for iw in range(1, 9) ] + #newScoutDesigns += [ (nb%(id, iw), desc, hull, [ db%id, srb%iw, srb%iw, srb%iw, is1, is2], "", model) for iw in range(1, 9) ] currentTurn=fo.currentTurn() needsAdding=[] @@ -692,6 +695,8 @@ defenseAllocation += element.allocation print "Queued Defenses:", [( PlanetUtilsAI.sysNameIDs([sysID]), num) for sysID, num in queuedDefenses.items()] for sysID in empireSpeciesSystems: + if foAI.foAIstate.systemStatus.get(sysID, {}).get('fleetThreat', 1) > 0: + continue#don't build orbital shields if enemy fleet present if defenseAllocation > maxDefensePortion * totalPP: break #print "checking ", PlanetUtilsAI.sysNameIDs([sysID]) Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-16 16:42:00 UTC (rev 5765) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-17 00:11:23 UTC (rev 5766) @@ -232,7 +232,7 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" #index=1 - if index == 0: + if index == 1: primaryMetaTechs = [ "GRO_PLANET_ECOL", "GRO_SUBTER_HAB", @@ -253,8 +253,8 @@ "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", "SPY_DETECT_2", + "PRO_ORBITAL_GEN", "CON_ORBITAL_CON", - "PRO_ORBITAL_GEN", "SHP_WEAPON_7", "CON_METRO_INFRA", "CON_SUBTER_CONST", @@ -264,6 +264,8 @@ "DEF_PLAN_BARRIER_SHLD_2", "PRO_SOL_ORB_GEN", "GRO_GENETIC_ENG", + "LRN_GRAVITONICS", + "CON_CONTGRAV_ARCH", "LRN_PHYS_BRAIN", "LRN_TRANSLING_THT", "PRO_SENTIENT_AUTOMATION", @@ -277,8 +279,6 @@ "DEF_GARRISON_2", "GRO_LIFECYCLE_MAN", "SHP_ENDOCRINE_SYSTEMS", - "LRN_GRAVITONICS", - "CON_CONTGRAV_ARCH", "DEF_GARRISON_3", "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_II", @@ -341,7 +341,7 @@ "SHP_WEAPON_16", "SHP_WEAPON_17", ] - elif index == 1: + elif index == 0: primaryMetaTechs = [ "GRO_PLANET_ECOL", "GRO_SUBTER_HAB", @@ -372,6 +372,8 @@ "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_2", "PRO_SOL_ORB_GEN", + "LRN_GRAVITONICS", + "CON_CONTGRAV_ARCH", "GRO_GENETIC_ENG", "LRN_PHYS_BRAIN", "LRN_TRANSLING_THT", @@ -386,8 +388,6 @@ "DEF_GARRISON_2", "GRO_LIFECYCLE_MAN", "SHP_ENDOCRINE_SYSTEMS", - "LRN_GRAVITONICS", - "CON_CONTGRAV_ARCH", "DEF_GARRISON_3", "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_II", |
From: <dil...@us...> - 2013-02-17 09:10:12
|
Revision: 5767 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5767&view=rev Author: dilvish-fo Date: 2013-02-17 09:10:05 +0000 (Sun, 17 Feb 2013) Log Message: ----------- Some more AI adjustments Modified Paths: -------------- trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/MoveUtilsAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResearchAI.py trunk/FreeOrion/default/AI/ResourcesAI.py trunk/FreeOrion/default/AI/TechsListsAI.py trunk/FreeOrion/default/AI/charting/charts.py Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -392,12 +392,14 @@ starBonus +=10 else: starBonus +=2 #still has extra value as an alternate location for solar generators + if system.starType in [fo.starType.blackHole] : + starBonus +=50*discountMultiplier #whether have tech yet or not, assign some base value if (empire.getTechStatus("PRO_SINGULAR_GEN") == fo.techStatus.complete) or ( "PRO_SINGULAR_GEN" in empireResearchList[:8]) : if system.starType in [fo.starType.blackHole] : if len (AIstate.empireStars.get(fo.starType.blackHole, []))==0: - starBonus +=80*discountMultiplier #pretty rare planets, good for generator + starBonus +=200*discountMultiplier #pretty rare planets, good for generator elif planet.systemID not in (AIstate.popCtrSystemIDs + AIstate.outpostSystemIDs): - starBonus +=40*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators + starBonus +=100*discountMultiplier #still has extra value as an alternate location for generators & for bnlocking enemies generators elif system.starType in [fo.starType.red] and ( len (AIstate.empireStars.get(fo.starType.blackHole, [])) + len (AIstate.empireStars.get(fo.starType.red, [])))==0: if planet.systemID not in (AIstate.popCtrSystemIDs + AIstate.outpostSystemIDs): starBonus +=40*discountMultiplier # can be used for artificial black hole Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -239,7 +239,7 @@ if not planet: continue sysID = planet.systemID foundFleets = [] - podsNeeded= int(math.ceil( (ptroops+2)/2)+0.0001) + podsNeeded= int(math.ceil( (ptroops+1.1)/2.0)+0.0001) foundStats={} minStats= {'rating':0, 'troopPods':podsNeeded} targetStats={'rating':10,'troopPods':podsNeeded+2} Modified: trunk/FreeOrion/default/AI/MoveUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/MoveUtilsAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/MoveUtilsAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -55,8 +55,8 @@ suppliedStops = [ sid for sid in shortPath if sid in fleetSupplyableSystemIDs ] unsuppliedStops = [sid for sid in shortPath if sid not in suppliedStops ] retPath=[] - print "getting path from %s to %s "%(PlanetUtilsAI.sysNameIDs([ startSysID ]), PlanetUtilsAI.sysNameIDs([ targetSysID ]) ), - print " ::: found initial path %s having suppliedStops %s and unsuppliedStops %s ; tot fuel available is %.1f"%( PlanetUtilsAI.sysNameIDs( shortPath[:] ), suppliedStops, unsuppliedStops, fuel) + #print "getting path from %s to %s "%(PlanetUtilsAI.sysNameIDs([ startSysID ]), PlanetUtilsAI.sysNameIDs([ targetSysID ]) ), + #print " ::: found initial path %s having suppliedStops %s and unsuppliedStops %s ; tot fuel available is %.1f"%( PlanetUtilsAI.sysNameIDs( shortPath[:] ), suppliedStops, unsuppliedStops, fuel) if False: if targetSysID in fleetSupplyableSystemIDs: print "target has FleetSupply" @@ -73,7 +73,7 @@ foAI.foAIstate.aggression >=fo.aggression.aggressive and targetSysID in annexableRing3 and len( unsuppliedStops) < fuel -2 ): retPath = [ AITarget.AITarget(AITargetType.TARGET_SYSTEM, sid) for sid in shortPath] else: - print " getting path from 'canTravelToSystemAndReturnToResupply' ", + #print " getting path from 'canTravelToSystemAndReturnToResupply' ", retPath = canTravelToSystemAndReturnToResupply(fleetID, fromSystemAITarget, toSystemAITarget, empireID, verbose=True) return retPath Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -95,6 +95,9 @@ industryPriority = 60 # high industry , low-mid research + industryPriority = 50 # try a flat number, adjust research + + # increase demand for industry industry production is low #industryPriority = 380 / (industryProduction + 0.001) @@ -125,20 +128,20 @@ styleIndex = empireID%2 styleAdjustmentMap = {0:0, 1:0}#TODO: decide if I want to do anything with this styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) - #cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] #1 doing better - cutoffs = [ [40, 65, 90 ], [40, 90, 150 ] ][styleIndex ] #1 doing better + cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] #1 doing better + #cutoffs = [ [40, 65, 90 ], [40, 90, 150 ] ][styleIndex ] #1 doing better if industrySurge and False: researchPriority = 10+styleAdjustment else: if (fo.currentTurn() < cutoffs[0]) or not gotAlgo: researchPriority = 50 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance elif fo.currentTurn() < cutoffs[1]: - researchPriority = 40 +styleAdjustment# mid industry , mid research + researchPriority = 50 +styleAdjustment# mid industry , mid research elif fo.currentTurn() < cutoffs[2]: - researchPriority = 30+styleAdjustment # high industry , low research + researchPriority = 50+styleAdjustment # high industry , low research else: researchQueue = list(empire.researchQueue) - researchPriority = 20+styleAdjustment # high industry , low research + researchPriority = 30+styleAdjustment # high industry , low research if len(researchQueue) == 0 : researchPriority = 0 # done with research elif len(researchQueue) <5 and researchQueue[-1].allocation > 0 : @@ -150,7 +153,6 @@ elif len(researchQueue) <20: researchPriority = 10 # high industry , low research - print "" print "Research Production (current/target) : ( %.1f / %.1f )"%(totalRP, targetRP) print "Priority for Research: " + str(researchPriority) Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -565,6 +565,7 @@ movedCapital=False bldgExpense=0.0 + bldgRatio = [ 0.5, 0.4, 0.3 ][fo.empireID()%3] if not homeworld: print "no capital, should get around to capturing or colonizing a new one"#TODO else: @@ -612,7 +613,7 @@ print queuedBldgNames=[ bldg.name for bldg in capitolQueuedBldgs ] - if ( totalPP >40 or fo.currentTurn() > 40 ) and ("BLD_INDUSTRY_CENTER" in possibleBuildingTypes) and ("BLD_INDUSTRY_CENTER" not in (capitalBldgs+queuedBldgNames)) and (bldgExpense<0.5*totalPP): + if ( totalPP >40 or fo.currentTurn() > 40 ) and ("BLD_INDUSTRY_CENTER" in possibleBuildingTypes) and ("BLD_INDUSTRY_CENTER" not in (capitalBldgs+queuedBldgNames)) and (bldgExpense<bldgRatio*totalPP): res=fo.issueEnqueueBuildingProductionOrder("BLD_INDUSTRY_CENTER", empire.capitalID) print "Enqueueing BLD_INDUSTRY_CENTER, with result %d"%res if res: @@ -627,7 +628,7 @@ print "Error: exception triggered and caught: ", traceback.format_exc() for bldName in [ "BLD_SHIPYARD_ORG_ORB_INC" ]: - if (bldName in possibleBuildingTypes) and (bldName not in (capitalBldgs+queuedBldgNames)) and (bldgExpense<0.5*totalPP): + if (bldName in possibleBuildingTypes) and (bldName not in (capitalBldgs+queuedBldgNames)) and (bldgExpense<bldgRatio*totalPP): try: res=fo.issueEnqueueBuildingProductionOrder(bldName, empire.capitalID) print "Enqueueing %s at capitol, with result %d"%(bldName, res) @@ -639,7 +640,7 @@ print "Error: exception triggered and caught: ", traceback.format_exc() for bldName in [ "BLD_SHIPYARD_ORG_XENO_FAC", "BLD_SHIPYARD_ORG_CELL_GRO_CHAMB" ]: - if ( totalPP >30 or fo.currentTurn() > 30 ) and (bldName in possibleBuildingTypes) and (bldName not in (capitalBldgs+queuedBldgNames)) and (bldgExpense<0.5*totalPP): + if ( totalPP >30 or fo.currentTurn() > 30 ) and (bldName in possibleBuildingTypes) and (bldName not in (capitalBldgs+queuedBldgNames)) and (bldgExpense<bldgRatio*totalPP): try: res=fo.issueEnqueueBuildingProductionOrder(bldName, empire.capitalID) print "Enqueueing %s at capitol, with result %d"%(bldName, res) @@ -749,7 +750,7 @@ popCtrs = list(AIstate.popCtrIDs) enrgyShipyardLocs=[] for bldName in [ "BLD_SHIPYARD_ENRG_COMP" ]: - if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >200 or fo.currentTurn() > 150 ): + if empire.buildingTypeAvailable(bldName) and (bldgExpense<bldgRatio*totalPP) and ( totalPP >200 or fo.currentTurn() > 150 ): queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] bldType = fo.getBuildingType(bldName) for pid in popCtrs: @@ -768,7 +769,7 @@ print "Requeueing %s to front of build queue, with result %d"%(bldName, res) for bldName in [ "BLD_SHIPYARD_BASE" ]: - if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >50 or fo.currentTurn() > 80 ): + if empire.buildingTypeAvailable(bldName) and (bldgExpense<bldgRatio*totalPP) and ( totalPP >50 or fo.currentTurn() > 80 ): queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] bldType = fo.getBuildingType(bldName) for pid in enrgyShipyardLocs: @@ -782,7 +783,7 @@ print "Requeueing %s to front of build queue, with result %d"%(bldName, res) for bldName in [ "BLD_SHIPYARD_ORG_ORB_INC" , "BLD_SHIPYARD_ORG_XENO_FAC" ]: - if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >40 or fo.currentTurn() > 40 ): + if empire.buildingTypeAvailable(bldName) and (bldgExpense<bldgRatio*totalPP) and ( totalPP >40 or fo.currentTurn() > 40 ): queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] bldType = fo.getBuildingType(bldName) for pid in popCtrs: @@ -798,7 +799,7 @@ print "Requeueing %s to front of build queue, with result %d"%(bldName, res) for bldName in [ "BLD_SHIPYARD_ORG_CELL_GRO_CHAMB" ]: - if empire.buildingTypeAvailable(bldName) and (bldgExpense<0.5*totalPP) and ( totalPP >50 or fo.currentTurn() > 80 ): + if empire.buildingTypeAvailable(bldName) and (bldgExpense<bldgRatio*totalPP) and ( totalPP >50 or fo.currentTurn() > 80 ): queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] bldType = fo.getBuildingType(bldName) for pid in popCtrs: Modified: trunk/FreeOrion/default/AI/ResearchAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResearchAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/ResearchAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -26,8 +26,8 @@ print "%25s %25s %25s"%tline print"" + researchQueueList = getResearchQueueTechs() if tRP >= 20 and foAI.foAIstate.aggression > fo.aggression.cautious: - researchQueueList = getResearchQueueTechs() if (empire.getTechStatus("LRN_PSIONICS") != fo.techStatus.complete) and ( "LRN_PSIONICS" not in researchQueueList[:5] ) : for specName in ColonisationAI.empireSpecies: thisSpec=fo.getSpecies(specName) @@ -124,6 +124,7 @@ res=fo.issueEnqueueTechOrder(ccTech, insertIdx) print "Empire is very aggressive, so attempted to fast-track %s, got result %d"%(ccTech, res) print"" + generateDefaultResearchOrders() print "\n\nAll techs:" alltechs = fo.techs() # returns names of all techs @@ -134,8 +135,14 @@ for tname in [tn for tn in alltechs if tn not in coveredTechs]: print tname - elif fo.currentTurn() >50: + elif fo.currentTurn() >100: generateDefaultResearchOrders() + + #researchQueueList = getResearchQueueTechs() + if len (AIstate.empireStars.get(fo.starType.blackHole, []))!=0 and foAI.foAIstate.aggression > fo.aggression.cautious: + if (empire.getTechStatus("PRO_SINGULAR_GEN") != fo.techStatus.complete) and ( "PRO_SINGULAR_GEN" not in researchQueueList[:2]) : + res=fo.issueEnqueueTechOrder("PRO_SINGULAR_GEN",0) + print "have a black hole star outpost/colony, so attempted to fast-track %s, got result %d"%("PRO_SINGULAR_GEN", res) def generateResearchOrders_old(): "generate research orders" Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -332,7 +332,7 @@ empireID = empire.empireID currentTurn = fo.currentTurn() freq = (1.0 + currentTurn/4.0)**(1.0/3) - if random() > 1.0/freq: + if ( currentTurn > 120 ) and ( random() > 1.0/freq ) : timer = 6*[time()] else: timer= [ time() ] # getPlanets Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -239,16 +239,16 @@ "SHP_DOMESTIC_MONSTER", "LRN_ALGO_ELEGANCE", "SHP_ORG_HULL", - "SHP_WEAPON_2", + "SHP_WEAPON_3", "SHP_WEAPON_5", "LRN_ARTIF_MINDS", "GRO_SYMBIOTIC_BIO", "DEF_DEFENSE_NET_1", + "DEF_GARRISON_1", "CON_ENV_ENCAPSUL", "PRO_FUSION_GEN", "LRN_FORCE_FIELD", "PRO_ROBOTIC_PROD", - "DEF_GARRISON_1", "SHP_WEAPON_6", "DEF_DEFENSE_NET_2", "DEF_PLAN_BARRIER_SHLD_1", @@ -352,9 +352,9 @@ "DEF_DEFENSE_NET_1", "CON_ENV_ENCAPSUL", "LRN_ARTIF_MINDS", + "SHP_WEAPON_5", "PRO_FUSION_GEN", "LRN_FORCE_FIELD", - "SHP_WEAPON_5", "PRO_ROBOTIC_PROD", "DEF_GARRISON_1", "SHP_WEAPON_6", Modified: trunk/FreeOrion/default/AI/charting/charts.py =================================================================== --- trunk/FreeOrion/default/AI/charting/charts.py 2013-02-17 00:11:23 UTC (rev 5766) +++ trunk/FreeOrion/default/AI/charting/charts.py 2013-02-17 09:10:05 UTC (rev 5767) @@ -155,7 +155,7 @@ legend(loc='upper left', prop={"size":9},labelspacing=0.2) xlabel('Turn') ylabel(plotType) - title(caption+' Progression w/ Max Aggression=Maniacal') + title(caption+' Progression ') x1,x2,y1,y2 = axis() newY2=y2 for yi in range(1, 10): |
From: <dil...@us...> - 2013-02-20 06:23:50
|
Revision: 5770 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5770&view=rev Author: dilvish-fo Date: 2013-02-20 06:23:36 +0000 (Wed, 20 Feb 2013) Log Message: ----------- an AI update Modified Paths: -------------- trunk/FreeOrion/default/AI/AIFleetOrder.py trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResearchAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIFleetOrder.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetOrder.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/AIFleetOrder.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -7,6 +7,8 @@ AIFleetOrderTypeNames=AIFleetOrderType() AIFleetMissionTypeNames = AIFleetMissionType() +dumpTurn=0 + class AIFleetOrder(object): "Stores information about orders which can be executed" @@ -76,6 +78,10 @@ planet = universe.getPlanet(self.getTargetAITarget().getTargetID()) if planet.unowned: targetAITargetTypeValid = True + else:#try to get order cancelled out + self.__setExecuted() + self.__setExecutionCompleted() + # colonise elif AIFleetOrderType.ORDER_COLONISE == self.getAIFleetOrderType(): # with ship @@ -93,6 +99,9 @@ planet = universe.getPlanet(self.getTargetAITarget().getTargetID()) if planet.unowned or (planet.ownedBy(fo.empireID()) and planet.currentMeterValue(fo.meterType.population)==0 ): targetAITargetTypeValid = True + else:#try to get order cancelled out + self.__setExecuted() + self.__setExecutionCompleted() # invade elif AIFleetOrderType.ORDER_INVADE == self.getAIFleetOrderType(): # with ship @@ -111,6 +120,9 @@ planetPopulation = planet.currentMeterValue(fo.meterType.population) if not planet.unowned or planetPopulation > 0: targetAITargetTypeValid = True + else:#try to get order cancelled out + self.__setExecuted() + self.__setExecutionCompleted() # military elif AIFleetOrderType.ORDER_MILITARY == self.getAIFleetOrderType(): # with ship @@ -180,7 +192,8 @@ def canIssueOrder(self, considerMergers=False, verbose=False): "if FleetOrder can be issued now" - if self.isExecuted(): + #for some orders, may need to re-issue if invasion/outposting/colonization was interrupted + if self.isExecuted() and self.getAIFleetOrderType() not in [ AIFleetOrderType.ORDER_OUTPOST, AIFleetOrderType.ORDER_COLONISE, AIFleetOrderType.ORDER_INVADE ]: return False if not self.isValid(): return False @@ -246,7 +259,7 @@ shipID = FleetUtilsAI.getShipIDWithRole(fleetID, AIShipRoleType.SHIP_ROLE_BASE_INVASION) ship = universe.getShip(shipID) planet = universe.getPlanet(self.getTargetAITarget().getTargetID()) - if (ship != None) and (fleet.systemID == planet.systemID) and ship.canInvade: + if (ship != None) and (fleet.systemID == planet.systemID) and ship.canInvade and ( planet.currentMeterValue(fo.meterType.shield) ==0 or planet.owner==-1):# native planets currently shouldnt have shields, but a bug sometimes makes it look like they do return True return False # @@ -290,7 +303,7 @@ targ1 = universe.getSystem(targetID) targ1Name = (targ1 and targ1.name) or "unknown" fleetRating = foAI.foAIstate.getRating(fleetID).get('overall', 0) - threat = foAI.foAIstate.systemStatus.get(targetID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(targetID, {}).get('planetThreat', 0) + threat = foAI.foAIstate.systemStatus.get(targetID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(targetID, {}).get('planetThreat', 0)+ foAI.foAIstate.systemStatus.get(targetID, {}).get('monsterThreat', 0) safetyFactor = 1.1 if fleetRating >= safetyFactor* threat: @@ -313,6 +326,7 @@ return True def issueOrder(self, considerMergers=False): + global dumpTurn if not self.canIssueOrder(considerMergers=False): #appears to be redundant with check in IAFleetMission? print "\tcan't issue %s"%self else: @@ -320,6 +334,10 @@ self.__setExecuted() # outpost if AIFleetOrderType.ORDER_OUTPOST == self.getAIFleetOrderType(): + planet=universe.getPlanet( self.getTargetAITarget().getTargetID() ) + if not planet.unowned: + self.__setExecutionCompleted() + return shipID = None if AITargetType.TARGET_SHIP == self.getSourceAITarget().getAITargetType(): shipID = self.getSourceAITarget().getTargetID() @@ -328,7 +346,9 @@ shipID = FleetUtilsAI.getShipIDWithRole(fleetID, AIShipRoleType.SHIP_ROLE_CIVILIAN_OUTPOST) if shipID is None: shipID = FleetUtilsAI.getShipIDWithRole(fleetID, AIShipRoleType.SHIP_ROLE_BASE_OUTPOST) - fo.issueColonizeOrder(shipID, self.getTargetAITarget().getTargetID()) + result=fo.issueColonizeOrder(shipID, self.getTargetAITarget().getTargetID()) + if result==0: + self.__executed = False # colonise elif AIFleetOrderType.ORDER_COLONISE == self.getAIFleetOrderType(): shipID = None @@ -345,6 +365,8 @@ planetName = (planet and planet.name) or "apparently invisible" result = fo.issueColonizeOrder(shipID, planetID) print "Ordered colony ship ID %d to colonize %s, got result %d"%(shipID, planetName, result) + if result==0: + self.__executed = False # invade elif AIFleetOrderType.ORDER_INVADE == self.getAIFleetOrderType(): result = False @@ -361,13 +383,25 @@ ship = universe.getShip(shipID) if (foAI.foAIstate.getShipRole(ship.design.id) in [AIShipRoleType.SHIP_ROLE_MILITARY_INVASION, AIShipRoleType.SHIP_ROLE_BASE_INVASION]): result = fo.issueInvadeOrder(shipID, planetID) or result #will track if at least one invasion troops successfully deployed - print "Ordered troop ship ID %d to invade %s, got result %d"%(shipID, planetName, result) + detailStr = "" if result == 0: + pstealth = planet.currentMeterValue(fo.meterType.stealth) + pop = planet.currentMeterValue(fo.meterType.population) + shields = planet.currentMeterValue(fo.meterType.shield) + owner = planet.owner + detailStr= " -- planet has %.1f stealth, shields %.1f, %.1f population and is owned by empire %d"%(pstealth, shields, pop, owner) + print "Ordered troop ship ID %d to invade %s, got result %d"%(shipID, planetName, result), detailStr + if result == 0: if 'needsEmergencyExploration' not in dir(foAI.foAIstate): foAI.foAIstate.needsEmergencyExploration=[] if fleet.systemID not in foAI.foAIstate.needsEmergencyExploration: foAI.foAIstate.needsEmergencyExploration.append(fleet.systemID) print "Due to trouble invading, adding system %d to Emergency Exploration List"%fleet.systemID + self.__executed = False + if shields >0 and owner==-1 and dumpTurn<fo.currentTurn(): + dumpTurn=fo.currentTurn() + print "Universe Dump to debug invasions:" + universe.dump() break # military elif AIFleetOrderType.ORDER_MILITARY == self.getAIFleetOrderType(): @@ -381,7 +415,7 @@ targetSysID = self.getTargetAITarget().getTargetID() fleet = fo.getUniverse().getFleet(fleetID) systemStatus = foAI.foAIstate.systemStatus.get(targetSysID, {}) - if (fleet )and ( fleet.systemID==targetSysID ) and ((systemStatus.get('fleetThreat', 0) + systemStatus.get('planetThreat', 0))==0): + if (fleet )and ( fleet.systemID==targetSysID ) and ((systemStatus.get('fleetThreat', 0) + systemStatus.get('planetThreat', 0)+ systemStatus.get('monsterThreat', 0))==0): self.__setExecutionCompleted() # move or resupply Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -621,7 +621,7 @@ if fleetID in self.fleetStatus: del self.fleetStatus[fleetID] continue - else:#fleet not in ok fleets + else:#fleet in ok fleets sys1 = universe.getSystem(sysID) sys1Name = (sys1 and sys1.name ) or "unknown" sys2 = universe.getSystem(fleet.nextSystemID) Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -20,8 +20,6 @@ annexablePlanetIDs=set([]) curBestMilShipRating = 20 -# makes these mapped to string version of values in case any sizes become reals instead of int -planetSIzes= { str(fo.planetSize.tiny): 1, str(fo.planetSize.small): 2, str(fo.planetSize.medium): 3, str(fo.planetSize.large): 4, str(fo.planetSize.huge): 5, str(fo.planetSize.asteroids): 3, str(fo.planetSize.gasGiant): 3 } environs = { str(fo.planetEnvironment.uninhabitable): 0, str(fo.planetEnvironment.hostile): 1, str(fo.planetEnvironment.poor): 2, str(fo.planetEnvironment.adequate): 3, str(fo.planetEnvironment.good):4 } photoMap= { fo.starType.blue:3 , fo.starType.white:1.5 , fo.starType.red:-1 , fo.starType.neutron: -1 , fo.starType.blackHole: -10 , fo.starType.noStar: -10 } # mods per environ uninhab hostile poor adequate good @@ -447,7 +445,7 @@ elif otherPlanet.size!= fo.planetSize.gasGiant and otherPlanet.owner==empire.empireID: orbGenVal+=10*discountMultiplier retval += orbGenVal - if foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0) > 2*curBestMilShipRating: + if ( foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('monsterThreat', 0) )> 2*curBestMilShipRating: retval = retval / 2.0 return int(retval) else: #colonization mission @@ -596,7 +594,7 @@ priorityScaling = 0.5 retval *= priorityScaling - thrtRatio = (foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0)+0.2*foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('neighborThreat', 0)) / float(curBestMilShipRating) + thrtRatio = (foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0)+foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('monsterThreat', 0)+0.2*foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('neighborThreat', 0)) / float(curBestMilShipRating) if thrtRatio > 4: retval = 0.3*retval elif thrtRatio >= 2: @@ -606,26 +604,7 @@ return retval -def getPlanetHospitality(planetID, species): - "returns a value depending on the planet type" - universe = fo.getUniverse() - - planet = universe.getPlanet(planetID) - if planet == None: return 0 - - planetEnvironment = species.getPlanetEnvironment(planet.type) - # print ":: planet:" + str(planetID) + " type:" + str(planet.type) + " size:" + str(planet.size) + " env:" + str(planetEnvironment) - - # reworked with races - if planetEnvironment == fo.planetEnvironment.good: return 2.75 - if planetEnvironment == fo.planetEnvironment.adequate: return 1 - if planetEnvironment == fo.planetEnvironment.poor: return 0.5 - if planetEnvironment == fo.planetEnvironment.hostile: return 0.25 - if planetEnvironment == fo.planetEnvironment.uninhabitable: return 0.1 - - return 0 - def removeLowValuePlanets(evaluatedPlanets): "removes all planets with a colonisation value < minimalColoniseValue" Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -6,7 +6,7 @@ import PlanetUtilsAI import AITarget import math -from ProductionAI import getBestShipInfo +from ProductionAI import getBestShipInfo, curBestMilShipRating from ColonisationAI import evaluatePlanet, annexableSystemIDs, annexableRing1, annexableRing2, annexableRing3 import ColonisationAI @@ -85,6 +85,7 @@ sortedPlanets = [(pid, pscore, ptroops) for (pid, (pscore, ptroops)) in evaluatedPlanets.items() ] sortedPlanets.sort(lambda x, y: cmp(x[1], y[1]), reverse=True) + sortedPlanets = [(pid, pscore%10000, ptroops) for (pid, pscore, ptroops) in sortedPlanets ] print "" if sortedPlanets: @@ -183,11 +184,43 @@ maxTroops = planet.currentMeterValue(fo.meterType.maxTroops) specName=planet.speciesName species=fo.getSpecies(specName) - productionVal = 20*(planet.currentMeterValue(fo.meterType.targetPopulation)/planet.currentMeterValue(fo.meterType.population) )*max(planet.currentMeterValue(fo.meterType.targetIndustry), 2*planet.currentMeterValue(fo.meterType.targetResearch)) + popTSize = planet.currentMeterValue(fo.meterType.targetPopulation)#TODO: adjust for empire tech + planetSpecials = list(planet.specials) + pSysID = planet.systemID#TODO: check star value + + indVal = 0 + basePopInd=0.2 + prodFactor = 1 + discountMultiplier=20 + for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : + if special in planetSpecials: + prodFactor+=1 + + proSingVal = [0, 4][(len( AIstate.empireStars.get(fo.starType.blackHole, [])) > 0)] + indTechMap={ "GRO_ENERGY_META": 0.5, + "PRO_ROBOTIC_PROD":0.4, + "PRO_FUSION_GEN": 1.0, + "PRO_INDUSTRY_CENTER_I": 1, + "PRO_INDUSTRY_CENTER_II":1, + "PRO_INDUSTRY_CENTER_III":1, + "PRO_SOL_ORB_GEN": 2.0, #assumes will build a gen at a blue/white star + "PRO_SINGULAR_GEN": proSingVal, + } + for tech in indTechMap: + if (empire.getTechStatus(tech) == fo.techStatus.complete): + prodFactor += indTechMap[tech] + indVal = discountMultiplier * basePopInd *prodFactor*popTSize + if (empire.getTechStatus("PRO_SENTIENT_AUTOMATION") == fo.techStatus.complete): + indVal += discountMultiplier * 5 + + pmaxShield = planet.currentMeterValue(fo.meterType.maxShield) + sysFThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).get('fleetThreat', 1000 ) + sysMThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).get('monsterThreat', 0 ) + print "invasion eval of %s %d --- maxShields %.1f -- sysFleetThreat %.1f -- sysMonsterThreat %.1f"%(planet.name, planetID, pmaxShield, sysFThrt, sysMThrt) supplyVal=0 enemyVal=0 - if planet.owner!=-1 : - enemyVal=productionVal #value in taking this away from an enemy + if planet.owner!=-1 : #value in taking this away from an enemy + enemyVal= 20* max(planet.currentMeterValue(fo.meterType.targetIndustry), 2*planet.currentMeterValue(fo.meterType.targetResearch)) if not species:#TODO: perhaps stealth makes planet inacccesible & should abort try: targetPop=planet.currentMeterValue(fo.meterType.targetPopulation) @@ -196,8 +229,15 @@ popVal=0 else: popVal = evaluatePlanet(planetID, AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire) #evaluatePlanet is imported from ColonisationAI - if planetID not in fleetSupplyablePlanetIDs: #extends supply and probably visibility - supplyVal = 20#TODO: better analysis here if supply obstructed by defending ships + if planetID in fleetSupplyablePlanetIDs: #TODO: extend to rings + supplyVal = 100 + if planet.owner== -1: + #if (pmaxShield <10): + if ( sysFThrt < 0.5*curBestMilShipRating() ): + if ( sysMThrt < 3*curBestMilShipRating()): + supplyVal = 10000 + else: + supplyVal = 50 planetSpecials = list(planet.specials) specialVal=0 if ( ( planet.size == fo.planetSize.asteroids ) and (empire.getTechStatus("PRO_ASTEROID_MINE") == fo.techStatus.complete ) ): @@ -206,7 +246,7 @@ if special in planetSpecials: specialVal +=10 # buildTime=4 - return max(0, popVal+supplyVal+specialVal+bldTally+productionVal+enemyVal-8*troops), min(troops+maxJumps+buildTime, maxTroops) + return max(0, popVal+supplyVal+specialVal+bldTally+indVal+enemyVal-20*troops), min(troops+maxJumps+buildTime, maxTroops) def getPlanetPopulation(planetID): "return planet population" @@ -230,10 +270,10 @@ 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) + #sortedTargets=sorted( [ ( pscore-ptroops/2 , pID, pscore, ptroops) for pID, pscore, ptroops in evaluatedPlanets ] , reverse=True) invasionPool=set(invasionPool) - for modscrore, pID, pscore, ptroops in sortedTargets: # evaluatedPlanets is a dictionary + for pID, pscore, ptroops in evaluatedPlanets: # if not invasionPool: return planet=universe.getPlanet(pID) if not planet: continue Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -115,7 +115,7 @@ threatBias = 0 - safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 1.0, 0.9 ][foAI.foAIstate.aggression] + safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 1.0, 0.95 ][foAI.foAIstate.aggression] topTargetPlanets = [pid for pid, pscore, trp in AIstate.invasionTargets[:PriorityAI.allottedInvasionTargets] if pscore > 20] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] if pscore > 20] topTargetSystems = [] @@ -146,7 +146,7 @@ print "Empire-Occupied Systems: %s"%( [ "| %d %s |"%(eoSysID, universe.getSystem(eoSysID).name) for eoSysID in empireOccupiedSystemIDs ] ) print "-----------------" if len( empireOccupiedSystemIDs ) > 0: - ocSysTotThreat = [ ( oSID, threatBias +safetyFactor*sum( [ foAI.foAIstate.systemStatus.get(oSID, {}).get(thrtKey, 0) for thrtKey in ['fleetThreat', 'planetThreat', 'neighborThreat']] ) ) for oSID in empireOccupiedSystemIDs ] + ocSysTotThreat = [ ( oSID, threatBias +safetyFactor*sum( [ foAI.foAIstate.systemStatus.get(oSID, {}).get(thrtKey, 0) for thrtKey in ['fleetThreat', 'monsterThreat','planetThreat', 'neighborThreat']] ) ) for oSID in empireOccupiedSystemIDs ] totocSysThreat = sum( [thrt for sid, thrt in ocSysTotThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in ocSysTotThreat] ) allocationFactor = min( 1.2, remainingMilRating /max(0.01, ( totocSysThreat -totCurAlloc) )) @@ -181,7 +181,7 @@ curAlloc=0.8*alreadyAssignedRating[sid] thisAlloc=0 if 2*thrt>curAlloc and (curAlloc>0 or remainingMilRating > (10+ (2*thrt-curAlloc))): #only record more allocation for this invasion if we already started or have enough rating available - thisAlloc =int(10.99999 + (2*thrt-curAlloc)) + thisAlloc =int(10.99999 + (1.5*thrt-curAlloc)) takeAny= curAlloc>0 allocations.append( (sid, thisAlloc, takeAny ,4) ) remainingMilRating -= thisAlloc @@ -201,7 +201,7 @@ # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, max(10, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: @@ -281,7 +281,7 @@ # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety if len(interiorTargets) >0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) ) for oSID in interiorTargets ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)) ) for oSID in interiorTargets ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: @@ -374,7 +374,7 @@ # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety if len(monsterDens) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) ) ) for oSID in monsterDens ] + otSysThreat = [ ( oSID, safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) ) ) for oSID in monsterDens ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -128,20 +128,22 @@ styleIndex = empireID%2 styleAdjustmentMap = {0:0, 1:0}#TODO: decide if I want to do anything with this styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) - cutoffs = [ [30, 45, 60 ], [40, 75, 100 ] ][styleIndex ] #1 doing better + cutoffs = [ [30, 40, 60 ], [35, 50, 70 ] ][styleIndex ] #1 doing better + settings = [ [50, 40, 35, 30 ], [50, 40, 30, 25 ] ][styleIndex ] + #cutoffs = [ [40, 65, 90 ], [40, 90, 150 ] ][styleIndex ] #1 doing better if industrySurge and False: researchPriority = 10+styleAdjustment else: if (fo.currentTurn() < cutoffs[0]) or not gotAlgo: - researchPriority = 50 # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance + researchPriority = settings[0] # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance elif fo.currentTurn() < cutoffs[1]: - researchPriority = 50 +styleAdjustment# mid industry , mid research + researchPriority = settings[1] +styleAdjustment# mid industry , mid research elif fo.currentTurn() < cutoffs[2]: - researchPriority = 50+styleAdjustment # high industry , low research + researchPriority = settings[2]+styleAdjustment # high industry , low research else: researchQueue = list(empire.researchQueue) - researchPriority = 30+styleAdjustment # high industry , low research + researchPriority = settings[3]+styleAdjustment # high industry , low research if len(researchQueue) == 0 : researchPriority = 0 # done with research elif len(researchQueue) <5 and researchQueue[-1].allocation > 0 : @@ -272,7 +274,7 @@ troopShipsNeeded = math.ceil((opponentTroopPods - (numTroopPods+ queuedTroopPods ))/troopsPerBestShip) #invasionPriority = max( 10+ 200*max(0, troopShipsNeeded ) , int(0.1* totalVal) ) - invasionPriority = 10+ 100*max(1, troopShipsNeeded ) + invasionPriority = 20+ 120*max(0, troopShipsNeeded ) if invasionPriority < 0: return 0 if foAI.foAIstate.aggression==fo.aggression.beginner: @@ -291,7 +293,8 @@ homeworld = universe.getPlanet(capitalID) else: return 0# no capitol (not even a capitol-in-the-making), means can't produce any ships - targetPlanetIDs = [pid for pid, pscore, trp in AIstate.invasionTargets[:10] ] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] ] + [pid for pid, pscore in foAI.foAIstate.colonisableOutpostIDs[:10] ] + 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) ) @@ -299,6 +302,7 @@ curShipRating = curBestMilShipRating() unmetThreat = 0.0 + currentTurn=fo.currentTurn() for sysID in mySystems.union(targetSystems) : status=foAI.foAIstate.systemStatus.get( sysID, {} ) myAttack, myHealth =0, 0 @@ -307,12 +311,21 @@ myAttack += rating.get('attack', 0) myHealth += rating.get('health', 0) myRating = myAttack*myHealth - threat = 0.0 + 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 if sysID in mySystems: - threat += status.get('fleetThreat', 0) + status.get('planetThreat', 0) + 0.3* status.get('neighborThreat', 0) + threat = status.get('fleetThreat', 0) + status.get('planetThreat', 0) + 0.3* status.get('neighborThreat', 0) else: - threat += status.get('fleetThreat', 0) + status.get('planetThreat', 0) + 0.1* status.get('neighborThreat', 0) - unmetThreat += max( 0, threat - myRating ) + threat = status.get('fleetThreat', 0) + status.get('planetThreat', 0) + 0.1* status.get('neighborThreat', 0) + unmetThreat += max( 0, threat + monsterThreat - myRating ) militaryPriority = int( 40 + max(0, 75*unmetThreat / curShipRating) ) return max( militaryPriority, 0) Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -469,15 +469,13 @@ cp = "CO_COLONY_POD" db = "DT_DETECTOR_%1d" is1, is2 = "FU_BASIC_TANK", "ST_CLOAK_1" - for id in [1, 2, 3, 4]: - newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp], "", model) for iw in range(2, 6) ] - for id in [1, 2, 3, 4]: - newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp], "", model) for iw in range(6, 9) ] # when farther along, use 2 pods + for id in [1, 2, 3]: + newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, srb%iw, db%id, cp], "", model) for iw in [1, 2, 5, 8] ] nb = designNameBases[2]+"%1d_%1d" cp2 = "CO_SUSPEND_ANIM_POD" - for id in [1, 2, 3, 4]: - newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp2], "", model) for iw in range(2, 9) ] + for id in [1, 2, 3]: + newColonyDesigns += [ (nb%(id, iw), desc, hull, [ srb%iw, db%id, "", cp2], "", model) for iw in [5, 6, 7, 8] ] currentTurn=fo.currentTurn() needsAdding=[] @@ -565,7 +563,7 @@ movedCapital=False bldgExpense=0.0 - bldgRatio = [ 0.5, 0.4, 0.3 ][fo.empireID()%3] + bldgRatio = [ 0.4, 0.35, 0.30 ][fo.empireID()%3] if not homeworld: print "no capital, should get around to capturing or colonizing a new one"#TODO else: @@ -1106,15 +1104,16 @@ print " Total Production Points Spent: " + str(totalPPSpent) wastedPP = max(0, totalPP - totalPPSpent) - print " Wasted Production Points: " + str(wastedPP) + print " Wasted Production Points: " + str(wastedPP)#TODO: add resource group analysis availPP = totalPP*1.05 - totalPPSpent print "" - print "Possible ship designs to build:" - if homeworld: - for shipDesignID in empire.availableShipDesigns: - shipDesign = fo.getShipDesign(shipDesignID) - print " " + str(shipDesign.name(True)) + " cost:" + str(shipDesign.productionCost(empire.empireID, homeworld.id) )+ " time:" + str(shipDesign.productionTime(empire.empireID, homeworld.id)) + if False: + print "Possible ship designs to build:" + if homeworld: + for shipDesignID in empire.availableShipDesigns: + shipDesign = fo.getShipDesign(shipDesignID) + print " " + str(shipDesign.name(True)) + " cost:" + str(shipDesign.productionCost(empire.empireID, homeworld.id) )+ " time:" + str(shipDesign.productionTime(empire.empireID, homeworld.id)) print "" print "Projects already in Production Queue:" Modified: trunk/FreeOrion/default/AI/ResearchAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResearchAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/ResearchAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -80,8 +80,7 @@ if foAI.foAIstate.aggression <=fo.aggression.typical: newtech = TechsListsAI.primaryMetaTechsList( index=empireID%2 ) else: - #newtech = TechsListsAI.aggressiveTechs() - newtech = TechsListsAI.primaryMetaTechsList(empireID%2) + newtech = TechsListsAI.primaryMetaTechsList( index=empireID%2 ) #pLTsToEnqueue = (set(newtech)-(set(completedTechs)|set(researchQueueList))) pLTsToEnqueue = newtech[:] techBase = set(completedTechs+researchQueueList) @@ -90,6 +89,7 @@ if (tech not in techBase): thisTech=fo.getTech(tech) if thisTech is None: + print "Error: desired tech '%s' appears to not exist"%tech continue missingPrereqs = [preReq for preReq in thisTech.recursivePrerequisites(empireID) if preReq not in techBase] techsToAdd.extend( missingPrereqs+[tech] ) @@ -131,8 +131,8 @@ for tname in alltechs: print tname print "\n-------------------------------\nAll unqueued techs:" - coveredTechs = newtech+completedTechs - for tname in [tn for tn in alltechs if tn not in coveredTechs]: + #coveredTechs = newtech+completedTechs + for tname in [tn for tn in alltechs if tn not in techBase]: print tname elif fo.currentTurn() >100: Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-19 15:49:26 UTC (rev 5769) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-02-20 06:23:36 UTC (rev 5770) @@ -231,7 +231,7 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" - #index=1 + index=0 if index == 1: primaryMetaTechs = [ "GRO_PLANET_ECOL", @@ -311,17 +311,15 @@ "SHP_ZORTRIUM_PLATE", "DEF_SYST_DEF_MINE_2", "GRO_CYBORG", - #"CON_FRC_ENRG_STRC", - #"CON_FRC_ENRG_CAMO", "GRO_GENOME_BANK", "SHP_BASIC_DAM_CONT", "CON_CONC_CAMP", "SHP_ADV_DAM_CONT", "PRO_INDUSTRY_CENTER_III", "DEF_GARRISON_4", - "SPY_CLOAK_1", "DEF_DEFENSE_NET_REGEN_2", - "SHP_ENRG_BOUND_MAN ", + "SPY_STEALTH_1", + "SHP_ENRG_BOUND_MAN", "GRO_GAIA_TRANS", "GRO_ENERGY_META", "CON_ART_PLANET", @@ -333,7 +331,6 @@ "SPY_DETECT_4", "SHP_WEAPON_11", "SHP_WEAPON_12", - #"SHP_TITAN_HULL" "DEF_PLAN_BARRIER_SHLD_5", "SHP_SOLAR_CONT", "SHP_WEAPON_14", @@ -420,17 +417,15 @@ "SHP_ZORTRIUM_PLATE", "DEF_SYST_DEF_MINE_2", "GRO_CYBORG", - #"CON_FRC_ENRG_STRC", - #"CON_FRC_ENRG_CAMO", "GRO_GENOME_BANK", "SHP_BASIC_DAM_CONT", "CON_CONC_CAMP", "SHP_ADV_DAM_CONT", "PRO_INDUSTRY_CENTER_III", "DEF_GARRISON_4", - "SPY_CLOAK_1", + "SPY_STEALTH_1", "DEF_DEFENSE_NET_REGEN_2", - "SHP_ENRG_BOUND_MAN ", + "SHP_ENRG_BOUND_MAN", "GRO_GAIA_TRANS", "GRO_ENERGY_META", "CON_ART_PLANET", @@ -442,7 +437,6 @@ "SPY_DETECT_4", "SHP_WEAPON_11", "SHP_WEAPON_12", - "SHP_TITAN_HULL" "DEF_PLAN_BARRIER_SHLD_5", "SHP_SOLAR_CONT", "SHP_WEAPON_14", @@ -450,10 +444,13 @@ "SHP_WEAPON_16", "SHP_WEAPON_17", ] + #"CON_FRC_ENRG_STRC", + #"CON_FRC_ENRG_CAMO", + #"SHP_TITAN_HULL" return primaryMetaTechs -MasterTechList=[ #currently with typos, just for reference +MasterTechList=[ # just for reference "CON_ARCH_MONOFILS", "CON_ARCH_PSYCH", "CON_ART_HEAVENLY", @@ -474,16 +471,25 @@ "CON_STARGATE", "CON_SUBTER_CONST", "CON_TRANS_ARCH", - "DEF_DEFENSE_NET", + "DEF_DEFENSE_NET_1", + "DEF_DEFENSE_NET_2", + "DEF_DEFENSE_NET_3", + "DEF_DEFENSE_NET_REGEN_1", + "DEF_DEFENSE_NET_REGEN_2", "DEF_GARRISON_1", "DEF_GARRISON_2", "DEF_GARRISON_3", "DEF_GARRISON_4", - "DEF_HI_ENRG_FOCUS", "DEF_PLANET_CLOAK", - "DEF_PLAN_BARRIER_SHLD", + "DEF_PLAN_BARRIER_SHLD_1", + "DEF_PLAN_BARRIER_SHLD_2", + "DEF_PLAN_BARRIER_SHLD_3", + "DEF_PLAN_BARRIER_SHLD_4", + "DEF_PLAN_BARRIER_SHLD_5", "DEF_ROOT_DEFENSE", - "DEF_SYST_DEF_MINE", + "DEF_SYST_DEF_MINE_1", + "DEF_SYST_DEF_MINE_2", + "DEF_SYST_DEF_MINE_3", "GRO_ADV_ECOMAN", "GRO_BIOTERROR", "GRO_CYBORG", @@ -535,170 +541,87 @@ "PRO_INDUSTRY_CENTER_III", "PRO_MICROGRAV_MAN", "PRO_NANOTECH_PROD", - "PRO_NEUTRONIUM", + "PRO_NDIM_ASSMB", + "PRO_NEUTRONIUM_EXTRACTION", "PRO_ORBITAL_GEN", "PRO_ROBOTIC_PROD", + "PRO_SENTIENT_AUTOMATION", "PRO_SINGULAR_GEN", "PRO_SOL_ORB_GEN", + "PRO_ZERO_GEN", "SHP_ADV_DAM_CONT", - "SHP_ASTEROID_", - "SHP_ASTEROID_R", + "SHP_ANTIMATTER_TANK", + "SHP_ASTEROID_HULLS", + "SHP_ASTEROID_REFORM", "SHP_BASIC_DAM_CONT", - "SHP_BIONEUR_S", + "SHP_BIOADAPTIVE_SPEC", "SHP_BIOTERM", - "SHP_CONTGRAV_MA", - "SHP_CONT_BIOADAP", + "SHP_CAMO_AST_HULL", + "SHP_CONTGRAV_MAINT", + "SHP_CONT_BIOADAPT", "SHP_CONT_SYMB", - "SHP_DEUTERIU", - "SHP_DOMESTIC_MON", - "SHP_ENDOSYMB_H", - "SHP_ENRG_BOUND_", + "SHP_DEATH_SPORE", + "SHP_DEUTERIUM_TANK", + "SHP_DIAMOND_PLATE", + "SHP_DOMESTIC_MONSTER", + "SHP_ENDOCRINE_SYSTEMS", + "SHP_ENDOSYMB_HULL", + "SHP_ENRG_BOUND_MAN", "SHP_FLEET_REPAIR", - "SHP_FRC_ENRG_C", + "SHP_FRC_ENRG_COMP", "SHP_GAL_EXPLO", - "SHP_IMPROVED_E", + "SHP_IMPROVED_ENGINE_COUPLINGS", "SHP_INTSTEL_LOG", - "SHP_LEAD_PLATE", - "SHP_MASSPROP_SPE", + "SHP_LEAD_PLATE", + "SHP_MASSPROP_SPEC", "SHP_MIDCOMB_LOG", - "SHP_MINIAST_SWAR", + "SHP_MIL_ROBO_CONT", + "SHP_MINIAST_SWARM", "SHP_MONOCELL_EXP", - "SHP_MULTICELL_", - "SHP_MULTISPEC", - "SHP_NANORO", + "SHP_MONOMOLEC_LATTICE", + "SHP_MULTICELL_CAST", + "SHP_MULTISPEC_SHIELD", + "SHP_NANOROBO_MAINT", "SHP_NOVA_BOMB", + "SHP_N_DIMENSIONAL_ENGINE_MATRIX", "SHP_ORG_HULL", - "SHP_REINFORCED", - "SHP_ROOT_AGGRES", - "SHP_SCAT_AST_HU", + "SHP_QUANT_ENRG_MAG", + "SHP_REINFORCED_HULL", + "SHP_ROOT_AGGRESSION", + "SHP_SCAT_AST_HULL", "SHP_SENT_HULL", + "SHP_SINGULARITY_ENGINE_CORE", "SHP_SOLAR_CONT", - "SHP_TRANSSPACE_D", + "SHP_SPACE_FLUX_DRIVE", + "SHP_TRANSSPACE_DRIVE", "SHP_WEAPON_10", + "SHP_WEAPON_11", "SHP_WEAPON_12", + "SHP_WEAPON_13", "SHP_WEAPON_14", + "SHP_WEAPON_15", "SHP_WEAPON_16", + "SHP_WEAPON_17", "SHP_WEAPON_2", - "SHP_WEAPON_4", - "SHP_WEAPON_6", - "SHP_WEAPON_8", - "SHP_ZORTRIUM_PLATE", - "SPY_DETECT_1", - "SPY_DETECT_3", - "SPY_DETECT_5", - "SPY_LIGHTHOUSE", - "SPY_ROOT_DECEPTI", - "SPY_STEALTH_1", - "SPY_STEALTH_3" -] - -def aggressiveTechs(): - "primary techs for all categories" - - aggressiveTechsList = [ - "GRO_PLANET_ECOL", - "GRO_SUBTER_HAB", - "SHP_DOMESTIC_MONSTER", - "SHP_ORG_HULL", "SHP_WEAPON_3", - "LRN_ALGO_ELEGANCE", - "GRO_SYMBIOTIC_BIO", - "CON_ENV_ENCAPSUL", - "PRO_FUSION_GEN", + "SHP_WEAPON_4", "SHP_WEAPON_5", - "PRO_ORBITAL_GEN", - "PRO_ROBOTIC_PROD", - "DEF_DEFENSE_NET_1", - "DEF_GARRISON_1", "SHP_WEAPON_6", - "LRN_ARTIF_MINDS", - "LRN_FORCE_FIELD", - "GRO_GENETIC_ENG", - "SHP_MULTICELL_CAST", - "CON_ORBITAL_CON", - "PRO_MICROGRAV_MAN", - "PRO_INDUSTRY_CENTER_I", - "DEF_GARRISON_2", - "GRO_LIFECYCLE_MAN", - "SHP_ENDOCRINE_SYSTEMS", - "GRO_XENO_GENETICS", - "LRN_GRAVITONICS", - "CON_CONTGRAV_ARCH", - "DEF_GARRISON_3", - "PRO_INDUSTRY_CENTER_II", - "SPY_DETECT_2", - "GRO_XENO_HYBRIDS", "SHP_WEAPON_7", - "SHP_CONT_SYMB", - "DEF_DEFENSE_NET_2", - "DEF_PLAN_BARRIER_SHLD_1", - "LRN_PHYS_BRAIN", - "LRN_TRANSLING_THT", - "SHP_ENDOSYMB_HULL", - "SHP_ASTEROID_HULLS", "SHP_WEAPON_8", - "GRO_TERRAFORM", - "PRO_SOL_ORB_GEN", - "CON_METRO_INFRA", - "CON_SUBTER_CONST", - "GRO_GENETIC_MED", - "SHP_LEAD_PLATE", - "SHP_MONOCELL_EXP", - "LRN_XENOARCH", - "GRO_CYBORG", - "PRO_SENTIENT_AUTOMATION", - "PRO_EXOBOTS", - "DEF_DEFENSE_NET_REGEN_1", - "DEF_PLAN_BARRIER_SHLD_2", - "DEF_DEFENSE_NET_3", - "SHP_BIOADAPTIVE_SPEC", "SHP_WEAPON_9", - "DEF_SYST_DEF_MINE_1", - "DEF_PLAN_BARRIER_SHLD_3", - "LRN_QUANT_NET", - "SHP_INTSTEL_LOG", - "SHP_REINFORCED_HULL", - "SHP_WEAPON_10", - "CON_NDIM_STRC", - "SHP_CONT_BIOADAPT", - "SHP_SENT_HULL", "SHP_ZORTRIUM_PLATE", - "DEF_SYST_DEF_MINE_2", - "GRO_GENOME_BANK", - "SHP_BASIC_DAM_CONT", - "CON_ARCH_PSYCH", - "CON_CONC_CAMP", - "PRO_SINGULAR_GEN", - "CON_FRC_ENRG_CAMO", - "SHP_ADV_DAM_CONT", - "PRO_INDUSTRY_CENTER_III", - "DEF_GARRISON_4", - "SPY_CLOAK_1", + "SPY_DETECT_1", + "SPY_DETECT_2", "SPY_DETECT_3", - "DEF_DEFENSE_NET_REGEN_2", - "GRO_GAIA_TRANS", - "GRO_ENERGY_META", - "CON_ART_PLANET", - "CON_FRC_ENRG_STRC", - "PRO_NEUTRONIUM_EXTRACTION", - "LRN_STELLAR_TOMOGRAPHY", - "LRN_ENCLAVE_VOID", - "CON_ORBITAL_HAB", - "LRN_PSIONICS", - "LRN_DISTRIB_THOUGHT", - "GRO_ENERGY_META", - "DEF_SYST_DEF_MINE_3", - "DEF_PLAN_BARRIER_SHLD_4", - "SHP_WEAPON_13", "SPY_DETECT_4", - "SHP_WEAPON_11", - "SHP_WEAPON_12", - "SHP_TITAN_HULL" - "DEF_PLAN_BARRIER_SHLD_5", - "SHP_SOLAR_CONT", - "SHP_WEAPON_14", - "SHP_WEAPON_15", - "SHP_WEAPON_16", - "SHP_WEAPON_17", + "SPY_DETECT_5", + "SPY_DIST_MOD", + "SPY_LIGHTHOUSE", + "SPY_PLANET_STEALTH_MOD", + "SPY_ROOT_DECEPTION", + "SPY_STEALTH_1", + "SPY_STEALTH_2", + "SPY_STEALTH_3", + "SPY_STEALTH_4", ] - return aggressiveTechsList |
From: <dil...@us...> - 2013-03-07 15:21:07
|
Revision: 5840 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5840&view=rev Author: dilvish-fo Date: 2013-03-07 15:21:00 +0000 (Thu, 07 Mar 2013) Log Message: ----------- AI adjustment for non-stacking GGG & change to tech priority Modified Paths: -------------- trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-07 15:13:09 UTC (rev 5839) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-07 15:21:00 UTC (rev 5840) @@ -394,6 +394,7 @@ detail = [] discountMultiplier = 20.0 priorityScaling=1.0 + maxGGGs=1 universe = fo.getUniverse() empireResearchList = [element.tech for element in empire.researchQueue] @@ -499,17 +500,21 @@ detail.append( "Asteroids %.1f"%(discountMultiplier*20 ) ) if ( ( planet.size == fo.planetSize.gasGiant ) and ( (empire.getTechStatus("PRO_ORBITAL_GEN") == fo.techStatus.complete ) or ( "PRO_ORBITAL_GEN" in empireResearchList[:3]) )): if system: + GGList=[] orbGenVal=0 + GGDetail=[] for pid in system.planetIDs: otherPlanet=universe.getPlanet(pid) - if otherPlanet.size == fo.planetSize.asteroids and otherPlanet.owner==empire.empireID: - if empire.getTechStatus("PRO_EXOBOTS") == fo.techStatus.complete: - orbGenVal+=10*discountMultiplier - detail.append( "GGG %s %.1f"%(otherPlanet.name, discountMultiplier*10 ) ) - elif otherPlanet.size!= fo.planetSize.gasGiant and otherPlanet.owner==empire.empireID and (AIFocusType.FOCUS_INDUSTRY in list(otherPlanet.availableFoci)+[otherPlanet.focus]): + if otherPlanet.size== fo.planetSize.gasGiant: + GGList.append(pid) + if pid!=planetID and otherPlanet.owner==empire.empireID and (AIFocusType.FOCUS_INDUSTRY in list(otherPlanet.availableFoci)+[otherPlanet.focus]): orbGenVal+=10*discountMultiplier - detail.append( "GGG %s %.1f"%(otherPlanet.name, discountMultiplier*10 ) ) - retval += orbGenVal + GGDetail.append( "GGG %s %.1f"%(otherPlanet.name, discountMultiplier*10 ) ) + if planetID in sorted(GGList)[:maxGGGs]: + retval += orbGenVal + detail.extend( GGDetail ) + else: + detail.append( "Won't GGG") if ( foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('monsterThreat', 0) )> 2*curBestMilShipRating: retval = retval / 2.0 detail.append( "threat halving value" ) @@ -521,7 +526,6 @@ asteroidBonus=0 gasGiantBonus=0 miningBonus=0 - maxGGGs=8 perGGG=9*discountMultiplier planetSize = planet.size if system and AIFocusType.FOCUS_INDUSTRY in species.foci: Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-07 15:13:09 UTC (rev 5839) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-07 15:21:00 UTC (rev 5840) @@ -835,6 +835,7 @@ print "Requeueing %s to front of build queue, with result %d"%(bldName, res) bldName = "BLD_GAS_GIANT_GEN" + maxGGGs=1 if empire.buildingTypeAvailable(bldName) and foAI.foAIstate.aggression > fo.aggression.beginner: queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] bldType = fo.getBuildingType(bldName) @@ -842,6 +843,16 @@ if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building thisPlanet=universe.getPlanet(pid) if thisPlanet.systemID in ColonisationAI.empireSpeciesSystems: + GGList=[] + canUseGGG=False + system=universe.getSystem(thisPlanet.systemID) + for opid in system.planetIDs: + otherPlanet=universe.getPlanet(opid) + if otherPlanet.size== fo.planetSize.gasGiant: + GGList.append(opid) + if opid!=pid and otherPlanet.owner==empire.empireID and (EnumsAI.AIFocusType.FOCUS_INDUSTRY in list(otherPlanet.availableFoci)+[otherPlanet.focus]): + canUseGGG=True + if pid in sorted(GGList)[:maxGGGs] and canUseGGG: res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) if res: queuedBldLocs.append(pid) Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-07 15:13:09 UTC (rev 5839) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-07 15:21:00 UTC (rev 5840) @@ -231,7 +231,8 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" - index=1-index + #index=1-index + index=0 if index == 0: primaryMetaTechs = [ "SHP_WEAPON_2", @@ -254,18 +255,21 @@ "CON_ORBITAL_CON", "SPY_DETECT_2", "DEF_DEFENSE_NET_2", - "DEF_PLAN_BARRIER_SHLD_1", "LRN_GRAVITONICS", "SHP_WEAPON_7", "CON_METRO_INFRA", + "GRO_GENETIC_ENG", "CON_SUBTER_CONST", + "SHP_MULTICELL_CAST", + "SHP_ENDOCRINE_SYSTEMS", "SHP_WEAPON_8", + "DEF_PLAN_BARRIER_SHLD_1", "PRO_INDUSTRY_CENTER_I", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_2", "PRO_SOL_ORB_GEN", "CON_CONTGRAV_ARCH", - "GRO_GENETIC_ENG", + "GRO_MEDICAL_PATH", "LRN_PHYS_BRAIN", "LRN_TRANSLING_THT", "PRO_SENTIENT_AUTOMATION", @@ -274,23 +278,21 @@ "DEF_SYST_DEF_MINE_1", "DEF_PLAN_BARRIER_SHLD_3", "CON_ORBITAL_HAB", - "GRO_XENO_HYBRIDS", - "SHP_MULTICELL_CAST", "DEF_GARRISON_2", "GRO_LIFECYCLE_MAN", - "SHP_ENDOCRINE_SYSTEMS", "DEF_GARRISON_3", "SHP_WEAPON_8", "PRO_INDUSTRY_CENTER_II", - "GRO_XENO_GENETICS", + "SPY_DETECT_3", "SHP_CONT_SYMB", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", + "GRO_XENO_GENETICS", "PRO_SINGULAR_GEN", - "SPY_DETECT_3", "LRN_XENOARCH", "SHP_WEAPON_9", "PRO_MICROGRAV_MAN", + "GRO_XENO_HYBRIDS", "LRN_QUANT_NET", "LRN_TIME_MECH", "LRN_STELLAR_TOMOGRAPHY", |
From: <dil...@us...> - 2013-03-07 15:33:55
|
Revision: 5841 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5841&view=rev Author: dilvish-fo Date: 2013-03-07 15:33:49 +0000 (Thu, 07 Mar 2013) Log Message: ----------- correction to previous AI commit Modified Paths: -------------- trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-07 15:21:00 UTC (rev 5840) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-07 15:33:49 UTC (rev 5841) @@ -852,15 +852,15 @@ GGList.append(opid) if opid!=pid and otherPlanet.owner==empire.empireID and (EnumsAI.AIFocusType.FOCUS_INDUSTRY in list(otherPlanet.availableFoci)+[otherPlanet.focus]): canUseGGG=True - if pid in sorted(GGList)[:maxGGGs] and canUseGGG: - res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) - if res: - queuedBldLocs.append(pid) - cost, time = empire.productionCostAndTime( productionQueue[productionQueue.size -1] ) - bldgExpense += cost/time # productionQueue[productionQueue.size -1].blocksize * - res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front - print "Requeueing %s to front of build queue, with result %d"%(bldName, res) - print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) + if pid in sorted(GGList)[:maxGGGs] and canUseGGG: + res=fo.issueEnqueueBuildingProductionOrder(bldName, pid) + if res: + queuedBldLocs.append(pid) + cost, time = empire.productionCostAndTime( productionQueue[productionQueue.size -1] ) + bldgExpense += cost/time # productionQueue[productionQueue.size -1].blocksize * + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + print "Requeueing %s to front of build queue, with result %d"%(bldName, res) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, pid, universe.getPlanet(pid).name, res) bldName = "BLD_SOL_ORB_GEN" if empire.buildingTypeAvailable(bldName) and foAI.foAIstate.aggression > fo.aggression.turtle: Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-07 15:21:00 UTC (rev 5840) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-07 15:33:49 UTC (rev 5841) @@ -232,7 +232,7 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" #index=1-index - index=0 + #index=0 if index == 0: primaryMetaTechs = [ "SHP_WEAPON_2", |
From: <dil...@us...> - 2013-03-08 22:26:34
|
Revision: 5846 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5846&view=rev Author: dilvish-fo Date: 2013-03-08 22:26:26 +0000 (Fri, 08 Mar 2013) Log Message: ----------- AI update with some minor "diplomacy" -- peace proposals will not always be accepted and will likely be accompanied by rude comments. Plus some substantive tweaks on invasions, etc. Modified Paths: -------------- trunk/FreeOrion/default/AI/AIDependencies.py trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/FreeOrionAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ResourcesAI.py Modified: trunk/FreeOrion/default/AI/AIDependencies.py =================================================================== --- trunk/FreeOrion/default/AI/AIDependencies.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/AIDependencies.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -10,5 +10,9 @@ for boost in metabolimBoostMap[metab] : metabolimBoosts[boost]=metab +colonyPodCost = 120 +colonyPodUpkeep = 0.06 +outpostPodCost = 80 +shipUpkeep = 0.05 Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -100,6 +100,7 @@ self.newlySplitFleets={} self.aggression=aggression self.militaryRating=0 + self.shipCount = 4 def __del__(self): "destructor" @@ -155,6 +156,13 @@ print "Fleets lost by system: %s"%fleetsLostBySystem self.updateSystemStatus() ExplorationAI.updateScoutFleets() #should do this after clearing dead fleets, currently should be already done here + + def assessSelfRating(self): + return 1 + + def assessRating(self, empireID): + """Returns assessed Rating of specified empire""" + return 1 def updateFleetLocs(self): universe=fo.getUniverse() @@ -297,7 +305,10 @@ pattack = 0 phealth = 0 for pid in system.planetIDs: - if pid in popCtrIDs+outpostIDs:#TODO: check for diplomatic status + #if pid in popCtrIDs+outpostIDs:#TODO: check for diplomatic status, needs to be exposed to python + # continue + thisPlanet=universe.getPlanet(pid) + if (thisPlanet.owner == self.empireID): continue thisAttack, thisHP = self.assessPlanetThreat(pid, sightingAge=currentTurn-partialVisTurn) pattack += thisAttack @@ -679,6 +690,7 @@ #if sysID != -1: # self.systemStatus.setdefault(sysID, {}).setdefault('myFleetRating', 0) # self.systemStatus[sysID]['myFleetRating'] += newRating #moved to updateSystemStatus + self.shipCount = shipCount print "------------------------" print "Empire Ship Count: ", shipCount print "------------------------" Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -44,6 +44,8 @@ "gaia": [ 0, 3, 3, 3, 3 ], } +def dictFromMap(map): + return dict( [ (el.key(), el.data() ) for el in map ] ) def resetCAIGlobals(): global curBestMilShipRating empireSpecies.clear() @@ -291,7 +293,7 @@ # print "Evaluated Outpost PlanetIDs: " + str(evaluatedOutpostPlanetIDs) evaluatedColonyPlanets = assignColonisationValues(evaluatedColonyPlanetIDs, AIFleetMissionType.FLEET_MISSION_COLONISATION, fleetSupplyablePlanetIDs, species, empire) - removeLowValuePlanets(evaluatedColonyPlanets) + #removeLowValuePlanets(evaluatedColonyPlanets) sortedPlanets = evaluatedColonyPlanets.items() sortedPlanets.sort(lambda x, y: cmp(x[1], y[1]), reverse=True) @@ -371,20 +373,21 @@ planetValues = {} if (missionType == AIFleetMissionType.FLEET_MISSION_OUTPOST ): + print "\n=========\nAssigning Outpost Values\n=========" trySpecies = [ "" ] else: + print "\n=========\nAssigning Colony Values\n=========" trySpecies = list( empireColonizers ) for planetID in planetIDs: pv = [] for specName in trySpecies: thisSpecies=fo.getSpecies(specName) detail = [] - pv.append( (evaluatePlanet(planetID, missionType, fleetSupplyablePlanetIDs, thisSpecies, empire, detail), specName) ) + pv.append( (evaluatePlanet(planetID, missionType, fleetSupplyablePlanetIDs, thisSpecies, empire, detail), specName, list(detail)) ) best = sorted(pv)[-1:] if best!=[]: - planetValues[planetID] = best[0] - if True and (missionType == AIFleetMissionType.FLEET_MISSION_OUTPOST ): - print detail + planetValues[planetID] = best[0][:2] + print best[0][2] return planetValues def evaluatePlanet(planetID, missionType, fleetSupplyablePlanetIDs, species, empire, detail = []): @@ -399,7 +402,10 @@ universe = fo.getUniverse() empireResearchList = [element.tech for element in empire.researchQueue] planet = universe.getPlanet(planetID) - if (planet == None): return 0 + if (planet == None): + VisMap = dictFromMap(universe.getVisibilityTurnsMap(planetID, empire.empireID)) + print "Planet %d object not available; visMap: %s"%(planetID, VisMap) + return 0 detail.append("%s : "%planet.name ) system = universe.getSystem(planet.systemID) tagList=[] @@ -436,7 +442,7 @@ else: starBonus +=2 #still has extra value as an alternate location for solar generators detail.append( "PRO_SOL_ORB_GEN %.1f"%2 ) - if system.starType in [fo.starType.blackHole] : + if system.starType in [fo.starType.blackHole] and fo.currentTurn() > 100: if not alreadyGotThisOne: starBonus +=10*discountMultiplier #whether have tech yet or not, assign some base value detail.append( "Black Hole %.1f"%(10* discountMultiplier) ) @@ -476,6 +482,12 @@ if "ECCENTRIC_ORBIT_SPECIAL" in planet.specials: fixedRes += discountMultiplier*2*3 detail.append( "ECCENTRIC_ORBIT_SPECIAL %.1f"%(discountMultiplier*2*3 ) ) + + if ( "ANCIENT_RUINS_SPECIAL" in planet.specials ): + retval += discountMultiplier*20 + detail.append("Undepleted Ruins") + + if (missionType == AIFleetMissionType.FLEET_MISSION_OUTPOST ): retval += fixedRes for special in planetSpecials: @@ -494,7 +506,7 @@ astVal=0 break elif otherPlanet.size!= fo.planetSize.gasGiant and otherPlanet.owner==empire.empireID: - astVal+=20 * discountMultiplier + astVal+=5 * discountMultiplier retval += astVal if astVal >0: detail.append( "Asteroids %.1f"%(discountMultiplier*20 ) ) @@ -508,8 +520,8 @@ if otherPlanet.size== fo.planetSize.gasGiant: GGList.append(pid) if pid!=planetID and otherPlanet.owner==empire.empireID and (AIFocusType.FOCUS_INDUSTRY in list(otherPlanet.availableFoci)+[otherPlanet.focus]): - orbGenVal+=10*discountMultiplier - GGDetail.append( "GGG %s %.1f"%(otherPlanet.name, discountMultiplier*10 ) ) + orbGenVal+=2*10*discountMultiplier + GGDetail.append( "GGG for %s %.1f"%(otherPlanet.name, discountMultiplier*10 ) ) if planetID in sorted(GGList)[:maxGGGs]: retval += orbGenVal detail.extend( GGDetail ) @@ -525,8 +537,9 @@ retval += colonyStarBonus asteroidBonus=0 gasGiantBonus=0 + GGPresent=False miningBonus=0 - perGGG=9*discountMultiplier + perGGG=2*10*discountMultiplier planetSize = planet.size if system and AIFocusType.FOCUS_INDUSTRY in species.foci: for pid in [id for id in system.planetIDs if id != planetID]: @@ -534,25 +547,30 @@ if p2: if p2.size== fo.planetSize.asteroids : if ( (empire.getTechStatus("PRO_MICROGRAV_MAN") == fo.techStatus.complete ) or ( "PRO_MICROGRAV_MAN" in empireResearchList[:3]) ): - asteroidBonus = 5*discountMultiplier + asteroidBonus = 2*5*discountMultiplier + detail.append( "Asteroid mining from %s %.1f"%(p2.name, 2*discountMultiplier*5 ) ) if p2.size== fo.planetSize.gasGiant : + GGPresent=True if ( (empire.getTechStatus("PRO_ORBITAL_GEN") == fo.techStatus.complete ) or ( "PRO_ORBITAL_GEN" in empireResearchList[:3]) ): gasGiantBonus += perGGG + detail.append( "GGG from %s %.1f"%(p2.name, perGGG ) ) gasGiantBonus = min( gasGiantBonus, maxGGGs * perGGG ) if (planet.size==fo.planetSize.gasGiant): if not (species and species.name == "SP_SUPER_TEST"): + detail.append("Can't Settle GG" ) return 0 else: - planetEnv = fo.planetEnvironment.good#I think - planetSize=4 #I think + planetEnv = fo.planetEnvironment.adequate#I think + planetSize=6 #I think elif ( planet.size == fo.planetSize.asteroids ): planetSize=3 #I think if not species or (species.name not in [ "SP_EXOBOT", "SP_SUPER_TEST" ]): + detail.append( "Can't settle Asteroids" ) return 0 elif species.name == "SP_EXOBOT": planetEnv =fo.planetEnvironment.poor elif species.name == "SP_SUPER_TEST": - planetEnv = fo.planetEnvironment.good#I think + planetEnv = fo.planetEnvironment.adequate#I think else: return 0 else: @@ -563,7 +581,10 @@ popSizeMod += popSizeModMap["env"][planetEnv] if "SELF_SUSTAINING" in tagList: popSizeMod*=2 - popSizeMod += starPopMod + detail.append("SelfSustaining" ) + if "PHOTOTROPHIC" in tagList: + popSizeMod += starPopMod + detail.append("Phototropic Star Bonus %0.1f"%starPopMod) if (empire.getTechStatus("GRO_SUBTER_HAB") == fo.techStatus.complete) or "TUNNELS_SPECIAL" in planetSpecials: if "TECTONIC_INSTABILITY_SPECIAL" not in planetSpecials: popSizeMod += popSizeModMap["subHab"][planetEnv] @@ -582,18 +603,34 @@ if "GAIA_SPECIAL" in planet.specials: popSizeMod += 3 + detail.append("Gaia") for special in [ "SLOW_ROTATION_SPECIAL", "SOLID_CORE_SPECIAL"] : if special in planetSpecials: popSizeMod -= 1 + detail.append(special) + applicableBoosts=set([]) for thisTag in [ tag for tag in tagList if tag in AIDependencies.metabolims]: - popSizeMod += len( (set(planetSpecials).union([key for key in activeGrowthSpecials.keys() if len(activeGrowthSpecials[key])>0 ] )).intersection(AIDependencies.metabolimBoostMap.get(thisTag, []) ) ) + metabBoosts= AIDependencies.metabolimBoostMap.get(thisTag, []) + for key in activeGrowthSpecials.keys(): + if ( len(activeGrowthSpecials[key])>0 ) and ( key in metabBoosts ): + applicableBoosts.update(key) + detail.append("%s boost active") + for boost in metabBoosts: + if boost in planetSpecials: + applicableBoosts.update(boost) + detail.append("%s boost present") + + popSizeMod += len(applicableBoosts) + #popSizeMod += len( (set(planetSpecials).union([key for key in activeGrowthSpecials.keys() if len(activeGrowthSpecials[key])>0 ] )).intersection(AIDependencies.metabolimBoostMap.get(thisTag, []) ) ) popSize = planetSize * popSizeMod if "DIM_RIFT_MASTER_SPECIAL" in planet.specials: popSize -= 4 + detail.append("DIM_RIFT_MASTER_SPECIAL") + detail.append("maxPop %.1f"%popSize) for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : if special in planetSpecials: @@ -621,6 +658,7 @@ if AIFocusType.FOCUS_INDUSTRY in species.foci: indVal += discountMultiplier * basePopInd * popSize*miningBonus indVal += discountMultiplier * basePopInd * popSize * indMult + detail.append("indVal %.1f"%indVal) # used to give preference to closest worlds empireID = empire.empireID capitalID = PlanetUtilsAI.getCapital() @@ -634,15 +672,19 @@ distanceFactor = 0 for special in [ spec for spec in planetSpecials if spec in AIDependencies.metabolimBoosts]: - growthVal += discountMultiplier * basePopInd * indMult * empireMetabolisms.get( AIDependencies.metabolimBoosts[special] , 0)# due to growth applicability to other planets + gbonus = discountMultiplier * basePopInd * indMult * empireMetabolisms.get( AIDependencies.metabolimBoosts[special] , 0)# due to growth applicability to other planets + growthVal += gbonus + detail.append( "Bonus for %s: %.1f"%(special, gbonus)) basePopRes = 0.2 #will also be doubling value of research, below if AIFocusType.FOCUS_RESEARCH in species.foci: researchBonus += discountMultiplier*2*basePopRes*popSize if ( "ANCIENT_RUINS_SPECIAL" in planet.specials ) or ( "ANCIENT_RUINS_DEPLETED_SPECIAL" in planet.specials ): researchBonus += discountMultiplier*2*basePopRes*popSize*5 + detail.append("Ruins Research") if "COMPUTRONIUM_SPECIAL" in planet.specials: researchBonus += discountMultiplier*2*10 #TODO: do actual calc + detail.append("COMPUTRONIUM_SPECIAL") retval=0.0 if popSize<0: @@ -659,12 +701,6 @@ retval += 20 elif planet.systemID in annexableRing3: retval += 10 - if (gasGiantBonus ==0) and (fixedRes==0): - if ( max( indVal, researchBonus, growthVal) < 10*discountMultiplier): - if fo.currentTurn() < 15: - priorityScaling = 0 - elif fo.currentTurn() < 50: - priorityScaling = 0.5 retval *= priorityScaling thrtRatio = (foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0)+foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('monsterThreat', 0)+0.2*foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('neighborThreat', 0)) / float(curBestMilShipRating) @@ -697,14 +733,24 @@ def sendColonyShips(colonyFleetIDs, evaluatedPlanets, missionType): "sends a list of colony ships to a list of planet_value_pairs" fleetPool = colonyFleetIDs[:] - potentialTargets = [ (pid, (score, specName) ) for (pid, (score, specName) ) in evaluatedPlanets if score > 30 ] + if (missionType == AIFleetMissionType.FLEET_MISSION_OUTPOST ): + cost = 20+AIDependencies.outpostPodCost * ( 1 + len(AIstate.popCtrIDs)*AIDependencies.colonyPodUpkeep ) + else: + cost = 20+AIDependencies.colonyPodCost * ( 1 + len(AIstate.popCtrIDs)*AIDependencies.colonyPodUpkeep ) + if fo.currentTurn() < 30: + cost *= 0.4 #will be making fast tech progress so value is underestimated + elif fo.currentTurn() < 60: + cost *= 0.8 #will be making fast-ish tech progress so value is underestimated + potentialTargets = [ (pid, (score, specName) ) for (pid, (score, specName) ) in evaluatedPlanets if score > (0.8 * cost) ] + print "colony/outpost ship matching -- fleets %s to planets %s"%( fleetPool, evaluatedPlanets) #for planetID_value_pair in evaluatedPlanets: fleetPool=set(fleetPool) universe=fo.getUniverse() while (len(fleetPool) > 0 ) and ( len(potentialTargets) >0): thisTarget = potentialTargets.pop(0) + thisScore=thisTarget[1][0] thisPlanetID=thisTarget[0] thisSysID = universe.getPlanet(thisPlanetID).systemID if (foAI.foAIstate.systemStatus.setdefault(thisSysID, {}).setdefault('monsterThreat', 0) > 2000) or (fo.currentTurn() <20 and foAI.foAIstate.systemStatus[thisSysID]['monsterThreat'] > 200): Modified: trunk/FreeOrion/default/AI/FreeOrionAI.py =================================================================== --- trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/FreeOrionAI.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -3,6 +3,7 @@ import sys import traceback from time import time +import random import freeOrionAIInterface as fo # interface used to interact with FreeOrion AI client @@ -202,9 +203,16 @@ if (message.type == fo.diplomaticMessageType.peaceProposal and message.recipient == fo.empireID()): replySender = message.recipient replyRecipient = message.sender - reply = fo.diplomaticMessage(replySender, replyRecipient, fo.diplomaticMessageType.acceptProposal) - print "Sending diplomatic message to empire " + str(replyRecipient) + " of type " + str(reply.type) - fo.sendDiplomaticMessage(reply) + proposalSenderPlayer = fo.empirePlayerID(message.sender) + fo.sendChatMessage(proposalSenderPlayer, "So, the Terran Hairless Plains Ape advising your empire wishes to scratch its belly for a while?") + if ( (foAIstate.aggression==fo.aggression.beginner ) or + (foAIstate.aggression!=fo.aggression.maniacal ) and ( random.random() < 1.0/ (((foAIstate.aggression +0.01)*fo.currentTurn()/2)**0.5) )): + fo.sendChatMessage(proposalSenderPlayer, "OK, Peace offer accepted.") + reply = fo.diplomaticMessage(replySender, replyRecipient, fo.diplomaticMessageType.acceptProposal) + print "Sending diplomatic message to empire " + str(replyRecipient) + " of type " + str(reply.type) + fo.sendDiplomaticMessage(reply) + else: + fo.sendChatMessage(proposalSenderPlayer, "Maybe later. We are currently getting busy with Experimental Test Subject yo-Ma-ma.") # called when this player receives and update about the diplomatic status between players, which may # or may not include this player. Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -1,6 +1,7 @@ import freeOrionAIInterface as fo import FreeOrionAI as foAI import AIstate +import AIDependencies import EnumsAI import FleetUtilsAI import PlanetUtilsAI @@ -132,6 +133,7 @@ def evaluateInvasionPlanet(planetID, missionType, fleetSupplyablePlanetIDs, empire): "return the invasion value of a planet" + detail = [] buildingValues = {"BLD_IMPERIAL_PALACE": 1000, "BLD_CULTURE_ARCHIVES": 1000, "BLD_SHIPYARD_BASE": 100, @@ -165,10 +167,19 @@ if (planet == None) : #TODO: exclude planets with stealth higher than empireDetection print "invasion AI couldn't get current info on planet %d"%planetID return 0, 0 - + + specName=planet.speciesName + species=fo.getSpecies(specName) + if not species:#TODO: probably stealth makes planet inacccesible & should abort + return 0, 0 + else: + popVal = ColonisationAI.evaluatePlanet(planetID, EnumsAI.AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire, detail) #evaluatePlanet is imported from ColonisationAI + bldTally=0 for bldType in [universe.getObject(bldg).buildingTypeName for bldg in planet.buildingIDs]: - bldTally += buildingValues.get(bldType, 50) + bval = buildingValues.get(bldType, 50) + bldTally += bval + detail.append("%s: %d"%(bldType, bval)) capitolID = PlanetUtilsAI.getCapital() if capitolID: @@ -181,37 +192,11 @@ troops = planet.currentMeterValue(fo.meterType.troops) maxTroops = planet.currentMeterValue(fo.meterType.maxTroops) - specName=planet.speciesName - species=fo.getSpecies(specName) + popTSize = planet.currentMeterValue(fo.meterType.targetPopulation)#TODO: adjust for empire tech planetSpecials = list(planet.specials) pSysID = planet.systemID#TODO: check star value - indVal = 0 - basePopInd=0.2 - prodFactor = 1 - discountMultiplier=20 - for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : - if special in planetSpecials: - prodFactor+=1 - - proSingVal = [0, 4][(len( AIstate.empireStars.get(fo.starType.blackHole, [])) > 0)] - indTechMap={ "GRO_ENERGY_META": 0.5, - "PRO_ROBOTIC_PROD":0.4, - "PRO_FUSION_GEN": 1.0, - "PRO_INDUSTRY_CENTER_I": 1, - "PRO_INDUSTRY_CENTER_II":1, - "PRO_INDUSTRY_CENTER_III":1, - "PRO_SOL_ORB_GEN": 2.0, #assumes will build a gen at a blue/white star - "PRO_SINGULAR_GEN": proSingVal, - } - for tech in indTechMap: - if (empire.getTechStatus(tech) == fo.techStatus.complete): - prodFactor += indTechMap[tech] - indVal = discountMultiplier * basePopInd *prodFactor*popTSize - if (empire.getTechStatus("PRO_SENTIENT_AUTOMATION") == fo.techStatus.complete): - indVal += discountMultiplier * 5 - pmaxShield = planet.currentMeterValue(fo.meterType.maxShield) sysFThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).get('fleetThreat', 1000 ) sysMThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).get('monsterThreat', 0 ) @@ -219,33 +204,27 @@ supplyVal=0 enemyVal=0 if planet.owner!=-1 : #value in taking this away from an enemy - enemyVal= 20* max(planet.currentMeterValue(fo.meterType.targetIndustry), 2*planet.currentMeterValue(fo.meterType.targetResearch)) - if not species:#TODO: perhaps stealth makes planet inacccesible & should abort - try: - targetPop=planet.currentMeterValue(fo.meterType.targetPopulation) - popVal = 2*targetPop - except: - popVal=0 - else: - popVal = ColonisationAI.evaluatePlanet(planetID, EnumsAI.AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire) #evaluatePlanet is imported from ColonisationAI + enemyVal= 20* (planet.currentMeterValue(fo.meterType.targetIndustry) + 2*planet.currentMeterValue(fo.meterType.targetResearch)) if planetID in fleetSupplyablePlanetIDs: #TODO: extend to rings supplyVal = 100 if planet.owner== -1: #if (pmaxShield <10): if ( sysFThrt < 0.5*ProductionAI.curBestMilShipRating() ): if ( sysMThrt < 3*ProductionAI.curBestMilShipRating()): - supplyVal = 10000 - else: supplyVal = 50 - planetSpecials = list(planet.specials) - specialVal=0 - if ( ( planet.size == fo.planetSize.asteroids ) and (empire.getTechStatus("PRO_ASTEROID_MINE") == fo.techStatus.complete ) ): - specialVal= 15 #TODO: should do more eval re asteroid mining here - for special in [ "MINERALS_SPECIAL", "CRYSTALS_SPECIAL", "METALOIDS_SPECIAL"] : - if special in planetSpecials: - specialVal +=10 # + else: + supplyVal = 20 + else: + supplyVal *= int( min(1, ProductionAI.curBestMilShipRating() / sysFThrt ) ) buildTime=4 - return max(0, popVal+supplyVal+specialVal+bldTally+indVal+enemyVal-20*troops), min(troops+maxJumps+buildTime, maxTroops) + plannedTroops = min(troops+maxJumps+buildTime, maxTroops) + if ( empire.getTechStatus("SHP_ORG_HULL") != fo.techStatus.complete ): + troopCost = math.ceil( plannedTroops/6.0) * ( 40*( 1+foAI.foAIstate.shipCount * AIDependencies.shipUpkeep ) ) + else: + troopCost = math.ceil( plannedTroops/6.0) * ( 20*( 1+foAI.foAIstate.shipCount * AIDependencies.shipUpkeep ) ) + invscore = max(0, popVal+supplyVal+bldTally+enemyVal-0.8*troopCost), plannedTroops + print invscore, "projected Troop Cost:", troopCost, "planet detail ", detail, popVal, supplyVal, bldTally, enemyVal + return invscore def getPlanetPopulation(planetID): "return planet population" Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -335,6 +335,7 @@ unmetThreat += max( 0, threat + monsterThreat - myRating ) militaryPriority = int( 40 + max(0, 75*unmetThreat / curShipRating) ) + print "Calculating Military Priority: 40 + 75 * unmetThreat/curShipRating \n\t Priority: %d \t unmetThreat %.0f curShipRating: %.0f"%(militaryPriority, unmetThreat, curShipRating) return max( militaryPriority, 0) def calculateTopProductionQueuePriority(): Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-08 13:53:59 UTC (rev 5845) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-08 22:26:26 UTC (rev 5846) @@ -144,8 +144,8 @@ empire = fo.getEmpire() empireID = empire.empireID currentTurn = fo.currentTurn() - freq = (1.0 + currentTurn/4.0)**(1.0/3) - if ( currentTurn > 120 ) and ( abs(currentTurn - lastFociCheck[0] ) <1.5*freq) and ( random() > 1.0/freq ) : + freq = min(3, ( max(5, currentTurn-120) )/4.0)**(1.0/3) + if ( abs(currentTurn - lastFociCheck[0] ) <1.5*freq) and ( random() < 1.0/freq ) : timer = 6*[time()] else: lastFociCheck[0]=currentTurn @@ -191,7 +191,7 @@ if curFocus != GFocus: result = fo.issueChangeFocusOrder(spPID, GFocus) if result == 1: - if pid in empirePlanetIDs: + if spPID in empirePlanetIDs: del empirePlanetIDs[ empirePlanetIDs.index( spPID ) ] print "%s focus of planet %s (%d) at Growth Focus"%( ["set", "left" ][ curFocus == GFocus ] , planetMap[spPID].name, spPID) break @@ -204,25 +204,31 @@ ratios = [] #for each planet, calculate RP:PP value ratio at which industry/Mining focus and research focus would have the same total value, & sort by that # include a bias to slightly discourage changing foci - curTargetPP = 0 - curTargetRP = 0 + curTargetPP = 0.001 + curTargetRP = 0.001 newFoci = {} timer.append( time() ) #loop hasForce = empire.getTechStatus("CON_FRC_ENRG_STRC") == fo.techStatus.complete for pid in newTargets: II, IR = newTargets[pid][IFocus] RI, RR = newTargets[pid][RFocus] - #if currentFocus[pid] == MFocus: - # II = max( II, newTargets[pid][MFocus][0] ) + CI, CR = currentOutput[pid][ IFocus], currentOutput[pid][ RFocus] + #consider straddling balance range within which 1RP costs 1PP + if True and (foAI.foAIstate.aggression >= fo.aggression.aggressive) and ( empireID %2 == 1): + if (CR<RR) and ( (CR-IR) >= (II-CI) ) and (priorityRatio > ( (curTargetRP+CR+1)/ max(0.001, curTargetPP +CI -1))): + curTargetPP += CI -1 # + curTargetRP += CR+1 + newFoci[pid] = RFocus + continue curTargetPP += II #icurTargets initially calculated by Industry focus, which will be our default focus curTargetRP += IR newFoci[pid] = IFocus - if foAI.foAIstate.aggression < fo.aggression.maniacal: - if currentFocus[pid] in [ IFocus, MFocus] : - II += min( 2, II /4.0 ) - elif currentFocus[pid] == RFocus: - RR += min( 2, RR/4.0 ) - #calculate factor F at which II + F * RI == RI + F * RR =====> F = ( II-RI ) / (RR-IR) + #if foAI.foAIstate.aggression < fo.aggression.maniacal: + # if currentFocus[pid] in [ IFocus, MFocus] : + # II += min( 2, II /4.0 ) + # elif currentFocus[pid] == RFocus: + # RR += min( 2, RR/4.0 ) + #calculate factor F at which II + F * RI == RI + F * RR =====> F = ( II-RI ) / (RR-IR) thisFactor = ( II-RI ) / max( 0.01, RR-IR) # don't let denominator be zero for planets where focus doesn't change RP if foAI.foAIstate.aggression >fo.aggression.aggressive: if currentOutput[pid][ IFocus] > II +RI - RR: |
From: <dil...@us...> - 2013-03-09 15:54:10
|
Revision: 5847 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5847&view=rev Author: dilvish-fo Date: 2013-03-09 15:54:03 +0000 (Sat, 09 Mar 2013) Log Message: ----------- Adjusting AI for GGG no longer working for dead or dying outposts, & other tweaks Modified Paths: -------------- trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/PriorityAI.py Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-08 22:26:26 UTC (rev 5846) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-09 15:54:03 UTC (rev 5847) @@ -687,13 +687,7 @@ detail.append("COMPUTRONIUM_SPECIAL") retval=0.0 - if popSize<0: - if foAI.foAIstate.aggression > fo.aggression.typical and (fo.currentTurn() >= 10): - retval = starBonus+asteroidBonus+gasGiantBonus +fixedRes - elif popSize==0: - if foAI.foAIstate.aggression > fo.aggression.typical and (fo.currentTurn() >= 10): - retval = 0.6*( starBonus+max(asteroidBonus+gasGiantBonus, growthVal)+fixedRes+fixedInd) #actually is kind of a pain if the pop goes close to zero but not actually zero - else: + if popSize > 0: retval = starBonus+max(indVal+asteroidBonus+gasGiantBonus, researchBonus, growthVal)+fixedInd + fixedRes if planet.systemID in annexableRing1: retval += 10 @@ -704,11 +698,15 @@ retval *= priorityScaling thrtRatio = (foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0)+foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('monsterThreat', 0)+0.2*foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('neighborThreat', 0)) / float(curBestMilShipRating) - if thrtRatio > 4: - retval = 0.3*retval - elif thrtRatio >= 2: - retval = 0.7* retval - elif thrtRatio > 0: + if False: + if thrtRatio > 4: + retval = 0.3*retval + elif thrtRatio >= 2: + retval = 0.7* retval + elif thrtRatio > 0: + retval = 0.85* retval + + if thrtRatio > 1: retval = 0.85* retval return retval Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-08 22:26:26 UTC (rev 5846) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-09 15:54:03 UTC (rev 5847) @@ -307,9 +307,11 @@ 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 @@ -328,14 +330,20 @@ 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: - threat = status.get('fleetThreat', 0) + status.get('planetThreat', 0) + 0.3* status.get('neighborThreat', 0) + threatRoot += (0.3* status.get('neighborThreat', 0))**0.5 else: - threat = status.get('fleetThreat', 0) + status.get('planetThreat', 0) + 0.1* status.get('neighborThreat', 0) - unmetThreat += max( 0, threat + monsterThreat - myRating ) + 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) ) - print "Calculating Military Priority: 40 + 75 * unmetThreat/curShipRating \n\t Priority: %d \t unmetThreat %.0f curShipRating: %.0f"%(militaryPriority, unmetThreat, curShipRating) + #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) def calculateTopProductionQueuePriority(): |
From: <dil...@us...> - 2013-03-14 16:27:12
|
Revision: 5864 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5864&view=rev Author: dilvish-fo Date: 2013-03-14 16:27:00 +0000 (Thu, 14 Mar 2013) Log Message: ----------- minor AI adjustment Modified Paths: -------------- trunk/FreeOrion/default/AI/AIFleetMission.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResearchAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIFleetMission.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetMission.py 2013-03-14 15:56:44 UTC (rev 5863) +++ trunk/FreeOrion/default/AI/AIFleetMission.py 2013-03-14 16:27:00 UTC (rev 5864) @@ -203,7 +203,7 @@ elif aiFleetMissionType in [EnumsAI.AIFleetMissionType.FLEET_MISSION_OUTPOST, EnumsAI.AIFleetMissionType.FLEET_MISSION_ORBITAL_OUTPOST]: universe = fo.getUniverse() fleet = universe.getFleet(self.getAITargetID()) - if not fleet.hasColonyShips: + if not fleet.hasOutpostShips: return False if aiTarget.getAITargetType() == EnumsAI.AITargetType.TARGET_PLANET: planet = universe.getPlanet(aiTarget.getTargetID()) Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-14 15:56:44 UTC (rev 5863) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-14 16:27:00 UTC (rev 5864) @@ -1112,7 +1112,7 @@ if universe.getObject(bldg).buildingTypeName == bldName: res=fo.issueScrapOrder( bldg) print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) - elif foAI.foAIstate.aggression>fo.aggression.typical and empire.buildingTypeAvailable(bldName) and (tPop >= 32) and ((empire.empireID+pid)%3 == 0): + elif foAI.foAIstate.aggression>fo.aggression.typical and empire.buildingTypeAvailable(bldName) and (tPop >= 32) : queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] if (cPop >=0.95*tPop) and cInd < 1.5* tInd: if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building Modified: trunk/FreeOrion/default/AI/ResearchAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResearchAI.py 2013-03-14 15:56:44 UTC (rev 5863) +++ trunk/FreeOrion/default/AI/ResearchAI.py 2013-03-14 16:27:00 UTC (rev 5864) @@ -173,9 +173,10 @@ #researchQueueList = getResearchQueueTechs() if len (AIstate.empireStars.get(fo.starType.blackHole, []))!=0 and foAI.foAIstate.aggression > fo.aggression.cautious: - if (empire.getTechStatus("PRO_SINGULAR_GEN") != fo.techStatus.complete) and ( "PRO_SINGULAR_GEN" not in researchQueueList[:2]) : - res=fo.issueEnqueueTechOrder("PRO_SINGULAR_GEN",0) - print "have a black hole star outpost/colony, so attempted to fast-track %s, got result %d"%("PRO_SINGULAR_GEN", res) + for singTech in [ "CON_ARCH_PSYCH", "CON_CONC_CAMP", "LRN_GRAVITONICS" , "PRO_SINGULAR_GEN"]: + if (empire.getTechStatus(singTech) != fo.techStatus.complete) and ( singTech not in researchQueueList[:4]) : + res=fo.issueEnqueueTechOrder(singTech,0) + print "have a black hole star outpost/colony, so attempted to fast-track %s, got result %d"%(singTech, res) def generateResearchOrders_old(): "generate research orders" Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-14 15:56:44 UTC (rev 5863) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-14 16:27:00 UTC (rev 5864) @@ -354,9 +354,9 @@ "DEF_DEFENSE_NET_1", "DEF_GARRISON_1", "GRO_SYMBIOTIC_BIO", + "PRO_ROBOTIC_PROD", "PRO_FUSION_GEN", "LRN_FORCE_FIELD", - "PRO_ROBOTIC_PROD", "SHP_WEAPON_6", "PRO_ORBITAL_GEN", "GRO_GENETIC_ENG", |
From: <dil...@us...> - 2013-03-24 07:23:32
|
Revision: 5901 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5901&view=rev Author: dilvish-fo Date: 2013-03-24 07:23:22 +0000 (Sun, 24 Mar 2013) Log Message: ----------- AI Adjustment Modified Paths: -------------- trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResourcesAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-03-23 18:25:51 UTC (rev 5900) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-03-24 07:23:22 UTC (rev 5901) @@ -94,13 +94,14 @@ self.expInteriorSystemIDs= {} self.exploredSystemIDs = {} self.unexploredSystemIDs = {self.origHomeSystemID:1} - self.fleetStatus={} - self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'myfleets', 'neighbors', 'name' + self.fleetStatus={} #keys: 'sysID', 'nships' + self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'myfleets', 'neighbors', 'name', 'myDefenses' self.needsEmergencyExploration=[] self.newlySplitFleets={} self.aggression=aggression self.militaryRating=0 self.shipCount = 4 + self.misc={} def __del__(self): "destructor" @@ -124,6 +125,7 @@ del self.militaryFleetIDs del self.needsEmergencyExploration del self.newlySplitFleets + del self.misc def clean(self): global invasionTargets @@ -211,7 +213,7 @@ universe = fo.getUniverse() planet = universe.getPlanet(pid) if not planet: - return 0, 0 + return {'overall': 0, 'attack':0 , 'health':0 } cShields = planet.currentMeterValue(fo.meterType.shield) tShields = planet.currentMeterValue(fo.meterType.maxShield) cDefense = planet.currentMeterValue(fo.meterType.defense) @@ -220,8 +222,8 @@ defense = min(tDefense, cDefense+2*sightingAge)#TODO: base off regen tech cInfra = planet.currentMeterValue(fo.meterType.construction) tInfra = planet.currentMeterValue(fo.meterType.targetConstruction) - infra = min(tInfra, cInfra+2*sightingAge)#TODO: base off regen tech - return (defense , (defense + shields + infra ) ) + infra = min(tInfra, cInfra+sightingAge) + return {'overall': defense*(defense + shields + infra ), 'attack':defense , 'health':(defense + shields + infra ) } def updateSystemStatus(self, sysIDList=None): print"-------\nUpdating System Threats\n---------" @@ -235,7 +237,7 @@ #assess enemy fleets that may have been momentarily visible enemyFleetIDs = [] enemiesBySystem = {} - myFleetsBySystem={}#not really used currently + myFleetsBySystem={} sawEnemiesAtSystem={} currentTurn = fo.currentTurn() for fleetID in universe.fleetIDs: @@ -244,109 +246,105 @@ fleet = universe.getFleet(fleetID) if (fleet == None): continue if not(fleet.empty) : + thisSysID = (fleet.nextSystemID!= -1 and fleet.nextSystemID) or fleet.systemID if fleet.ownedBy(empireID): - if fleet.systemID != -1: - myFleetsBySystem.setdefault( fleet.systemID, [] ).append( fleetID )#currently, not used, info gotten through system.fleetIDs + if (fleetID not in destroyedObjIDs): + myFleetsBySystem.setdefault( thisSysID, [] ).append( fleetID ) else: partialVisTurn = dictFromMap(universe.getVisibilityTurnsMap(fleetID, empireID)).get(fo.visibility.partial, -9999) if partialVisTurn >= currentTurn -1 : #only interested in immediately recent data sawEnemiesAtSystem[fleet.systemID] = True if (fleetID not in destroyedObjIDs): enemyFleetIDs.append( fleetID ) - thisSysID = (fleet.systemID!= -1 and fleet.systemID) or fleet.nextSystemID enemiesBySystem.setdefault( thisSysID, [] ).append( fleetID ) #assess fleet and planet threats & my local fleets for sysID in sysIDList: sysStatus = self.systemStatus.setdefault(sysID, {}) - sysStatus['myfleets']=[] system = universe.getSystem(sysID) #update fleets - localEnemyFleetIDs=[] + sysStatus['myfleets']=myFleetsBySystem.get(sysID, []) + localEnemyFleetIDs=enemiesBySystem.get(sysID, []) if system: + sysStatus['name']=system.name for fid in system.fleetIDs: - if fid in destroyedObjIDs: + if fid in destroyedObjIDs: #TODO: double check are these checks/deletes necessary? self.deleteFleetInfo(fid)#this is safe even if fleet wasn't mine continue fleet = universe.getFleet(fid) if not fleet or fleet.empty: self.deleteFleetInfo(fid)#this is safe even if fleet wasn't mine continue - if fleet.ownedBy(empire.empireID): - sysStatus['myfleets'].append(fid) - else: - localEnemyFleetIDs.append( fid ) - glimpsedEnemies=[] - for fid in enemiesBySystem.get(sysID, []): - if fid not in localEnemyFleetIDs: - localEnemyFleetIDs.append(fid) - glimpsedEnemies.append(fid) + #update threats sysVisDict = dictFromMap(universe.getVisibilityTurnsMap(sysID, fo.empireID())) partialVisTurn = sysVisDict.get(fo.visibility.partial, -9999) + enemyRatings=[] enemyRating=0 - monsterRating=0 + monsterRatings=[] + lostFleetRating=0 + enemyRatings = [self.rateFleet(fid) for fid in localEnemyFleetIDs ] + enemyAttack = sum( [rating.get('attack', 0) for rating in enemyRatings]) + enemyHealth = sum( [rating.get('health', 0) for rating in enemyRatings]) + enemyRating = enemyAttack * enemyHealth if fleetsLostBySystem.get(sysID, []) != []: - print (" Assessing threats on turn %d ; noting that fleets were just lost in system %d , enemy fleets were %s seen as of turn %d, of which %s survived and %s were"+ - " just briefly glimpsed")%( currentTurn, sysID, ["not", ""][sawEnemiesAtSystem.get(sysID, False)], partialVisTurn, localEnemyFleetIDs, glimpsedEnemies) - if partialVisTurn >= currentTurn -1: - enemyRatings = [self.rateFleet(fid) for fid in localEnemyFleetIDs ] - monsterRatings = [self.rateFleet(fid) for fid in localEnemyFleetIDs ] - enemyRating = sum( [rating.get('attack', 0) for rating in enemyRatings]) * sum( [rating.get('health', 0) for rating in enemyRatings]) - monsterRating = sum( [rating.get('attack', 0) for rating in enemyRatings]) * sum( [rating.get('health', 0) for rating in enemyRatings]) + print " Assessing threats on turn %d ; noting that fleets were just lost in system %d , enemy fleets were %s seen as of turn %d, of which %s survived"%( + currentTurn, sysID, ["not", ""][sawEnemiesAtSystem.get(sysID, False)], partialVisTurn, localEnemyFleetIDs) + lostFleetAttack = sum( [rating.get('attack', 0) for rating in fleetsLostBySystem.get(sysID, {}) ] ) + lostFleetHealth = sum( [rating.get('health', 0) for rating in fleetsLostBySystem.get(sysID, {} ) ] ) + lostFleetRating= lostFleetAttack * lostFleetHealth if (not system) or partialVisTurn==-9999: print "Have never had partial vis for system %d ( %s ) -- basing threat assessment on old info and lost ships"%(sysID, sysStatus.get('name', "name unknown")) - sysStatus['planetThreat'] = int( sysStatus.get('planetThreat', 0) ) # if no current info, leave as previous, or 0 if no previous rating - sysStatus['fleetThreat'] = int( max(enemyRating, max( sysStatus.get('fleetThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) ))) ) # if no current info, leave as previous, or 0 if no previous rating , or rating of fleets lost + sysStatus['planetThreat'] = 0 + sysStatus['fleetThreat'] = int( max(enemyRating, sysStatus.get('fleetThreat', 0) , 1.1*lostFleetRating) ) + sysStatus['monsterThreat']=0 + sysStatus['mydefenses'] = {'overall':0, 'attack':0, 'health':0 } + sysStatus['totalThreat'] = sysStatus['fleetThreat'] continue - elif not partialVisTurn == currentTurn: #(universe.getVisibility(sysID, self.empireID) >= fo.visibility.partial): + + #have either stale or current info + pthreat = 0 + pattack = 0 + phealth = 0 + mypattack, myphealth = 0, 0 + for pid in system.planetIDs: + prating = self.assessPlanetThreat(pid, sightingAge=currentTurn-partialVisTurn) + 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: + pattack += prating['attack'] + phealth += prating['health'] + sysStatus['planetThreat'] = pattack*phealth + sysStatus['mydefenses'] = {'overall':mypattack*myphealth, 'attack':mypattack, 'health':myphealth } + + if max( sysStatus.get('totalThreat', 0), pattack*phealth ) >= 0.6* lostFleetRating: #previous threat assessment could account for losses, ignore the losses now + lostFleetRating=0 + + if not partialVisTurn == currentTurn: #(universe.getVisibility(sysID, self.empireID) >= fo.visibility.partial): print "Stale visibility for system %d ( %s ) -- last seen %d, current Turn %d -- basing threat assessment on old info and lost ships"%(sysID, sysStatus.get('name', "name unknown"), partialVisTurn, currentTurn) - pthreat = 0#TODO: track planet threat like fleet threat, with attack & shield info for each planet, & owner - pattack = 0 - phealth = 0 - for pid in system.planetIDs: - #if pid in popCtrIDs+outpostIDs:#TODO: check for diplomatic status, needs to be exposed to python - # continue - thisPlanet=universe.getPlanet(pid) - if (thisPlanet.owner == self.empireID): - continue - thisAttack, thisHP = self.assessPlanetThreat(pid, sightingAge=currentTurn-partialVisTurn) - pattack += thisAttack - phealth += thisHP - sysStatus['planetThreat'] = pattack*phealth - sysStatus['fleetThreat'] = int( max(enemyRating, max( sysStatus.get('fleetThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) ))) ) # if no current info, leave as previous, or 0 if no previous rating , or rating of fleets lost - continue + sysStatus['fleetThreat'] = int( enemyRating + 1.1*lostFleetRating) + sysStatus['totalThreat'] = (pattack + enemyAttack + sysStatus.get('monsterThreat', 0)**0.5) * (phealth + enemyHealth + sysStatus.get('monsterThreat', 0)**0.5) else: #system considered visible #TODO: reevaluate as visibility rules change - threat=0 - monsterThreat=0 - #sawContents= len( list(system.allObjectIDs)) > 0 - sawContents=True - for fleetID in system.fleetIDs: - sawContents=True #apparently can be logged as visisble for rest of turn even if can no longer get sys contents + enemyattack, enemyhealth, enemythreat=0, 0, 0 + monsterattack, monsterhealth, monsterthreat = 0, 0, 0 + for fleetID in localEnemyFleetIDs: fleet = universe.getFleet(fleetID) if ( fleet) and (not fleet.ownedBy(self.empireID)): + rating=self.rateFleet(fleetID) if fleet.speed==0: - monsterThreat += self.rateFleet(fleetID).get('overall',0)# + monsterattack += rating['attack'] + monsterhealth += rating['health'] else: - threat += self.rateFleet(fleetID).get('overall',0)#currently treating all unowned fleets as hostile - if sawContents: - sysStatus['fleetThreat'] = max( int( threat ), 1.05*sum(fleetsLostBySystem.get(sysID, []) )) #fleetThreat always includes monster threat, and may not have seen stealthed enemies - sysStatus['monsterThreat']=int(monsterThreat) - else: - sysStatus['fleetThreat'] = int( max( sysStatus.get('fleetThreat', 0) , 1.05*sum(fleetsLostBySystem.get(sysID, []) )) ) - pthreat = 0#TODO: track planet threat like fleet threat, with attack & shield info for each planet, & owner - pattack = 0 - phealth = 0 - for pid in system.planetIDs: - if pid in popCtrIDs+outpostIDs:#TODO: check for diplomatic status - continue - thisAttack, thisHP = self.assessPlanetThreat(pid, sightingAge=0) - pattack += thisAttack - phealth += thisHP - sysStatus['planetThreat'] = pattack*phealth - #self.systemStatus[sysID] = sysStatus #no longer necessary because using setdefault + enemyattack += rating['attack'] + enemyhealth += rating['health'] + sysStatus['fleetThreat'] = int( max( enemyattack*enemyhealth, lostFleetRating)) #fleetThreat always includes monster threat, and may not have seen stealthed enemies + sysStatus['monsterThreat']= monsterattack * monsterhealth + sysStatus['totalThreat'] = int(max( lostFleetRating, ( enemyattack+monsterattack+pattack ) * (enemyhealth+ monsterhealth+ phealth ) ) ) - #assess secondary threats (one half of threats of surrounding systems and update my fleet rating + #assess secondary threats (threats of surrounding systems) and update my fleet rating for sysID in sysIDList: sysStatus = self.systemStatus[sysID] myattack, myhealth=0, 0 @@ -361,19 +359,15 @@ neighborDict = dictFromMap( universe.getSystemNeighborsMap(sysID, self.empireID) ) neighbors = neighborDict.keys() sysStatus['neighbors'] = neighborDict - if (not system) : - sysStatus['neighborThreat'] = 0.9*sysStatus.get('neighborThreat', 0) # if no current info, leave as previous with partial reduction, or 0 if no previous rating - self.systemStatus[sysID] = sysStatus - continue - else: + if system: threat=0 for neighborID in neighbors: neighborStatus= self.systemStatus.get(neighborID, {}) nfthreat = neighborStatus.get('fleetThreat', 0) - threat += 0.5* nfthreat - + threat += nfthreat sysStatus['neighborThreat'] = int( threat + 0.5 ) - self.systemStatus[sysID] = sysStatus + else: + sysStatus['neighborThreat'] = 0.9*sysStatus.get('neighborThreat', 0) # if no current info, leave as previous with partial reduction, or 0 if no previous rating def afterTurnCleanup(self): "removes not required information to save from AI state after AI complete its turn" @@ -611,7 +605,6 @@ def __cleanFleetRoles(self, justResumed=False): "removes fleetRoles if a fleet has been lost, and update fleet Ratings" - global fleetsLostBySystem for sysID in self.systemStatus: self.systemStatus[sysID]['myFleetRating']=0 @@ -632,9 +625,10 @@ print "-----------" print "statusList %s"%[self.fleetStatus[fid] for fid in sorted( self.fleetStatus.keys() ) ] print "-----------" + minThreatRating = {'overall':MinThreat, 'attack':MinThreat**0.5, 'health':MinThreat**0.5} for fleetID in fleetList: - status=self.fleetStatus.get(fleetID, {} ) - rating = status.get('rating', {}) + status=self.fleetStatus.setdefault(fleetID, {} ) + rating = status.get('rating', {'overall':0, 'attack':0, 'health':0} ) newRating = self.rateFleet(fleetID) oldSysID = status.get('sysID', -2) fleet = universe.getFleet(fleetID) @@ -642,20 +636,22 @@ # fleet.setAggressive(True) if fleet: sysID = fleet.systemID + if oldSysID in [-2, -1]: + oldSysID = sysID status['nships']=len(fleet.shipIDs) shipCount += status['nships'] else: - sysID = oldSysID #can still retrieve a fleet object even if fleet was just destroyed + sysID = oldSysID #can still retrieve a fleet object even if fleet was just destroyed, so shouldn't get here if (fleetID not in okFleets):# or fleet.empty: if not ( (self.__fleetRoleByID.get(fleetID, -1) ==-1) ): if not justResumed: - fleetsLostBySystem.setdefault(sysID, []).append( max(rating.get('overall', 0), MinThreat) ) + if rating.get('overall', 0) > MinThreat: + fleetsLostBySystem.setdefault(oldSysID, []).append( rating ) + else: + fleetsLostBySystem.setdefault(oldSysID, []).append( minThreatRating ) sys=universe.getSystem(sysID) sysName=(sys and sys.name) or "unknown" print "Fleet %d with role %s was used up, lost or destroyed at sys (%d) %s"%(fleetID, self.__fleetRoleByID[fleetID], sysID, sysName) #perhaps diff message for successful colony fleets - #print "\t\tFleet %d Full set of Orders were:"%fleetID - #for aiFleetOrder2 in self.__aiMissionsByFleetID[fleetID].getAIFleetOrders(): - # print "\t\t %s"%aiFleetOrder2 if fleetID in self.__fleetRoleByID: del self.__fleetRoleByID[fleetID] @@ -666,16 +662,23 @@ continue else:#fleet in ok fleets sys1 = universe.getSystem(sysID) - sys1Name = (sys1 and sys1.name ) or "unknown" - sys2 = universe.getSystem(fleet.nextSystemID) - sys2Name = (sys2 and sys2.name ) or "unknown" + if sysID==-1: + sys1Name = 'starlane' + else: + sys1Name = (sys1 and sys1.name ) or "unknown" + nextSysID = fleet.nextSystemID + sys2 = universe.getSystem(nextSysID) + if nextSysID==-1: + sys2Name= 'starlane' + else: + sys2Name = (sys2 and sys2.name ) or "unknown" print "Fleet %d (%s) oldRating: %6d | newRating %6d | at system %d (%s) | next system %d (%s)"%(fleetID, fleet.name, rating.get('overall', 0), newRating.get('overall', 0), fleet.systemID, sys1Name, fleet.nextSystemID, sys2Name) status['rating'] = newRating - if sysID !=-1: + if nextSysID !=-1: + status['sysID'] = nextSysID + elif sysID !=-1: status['sysID'] = sysID - elif fleet.nextSystemID !=-1: - status['sysID'] = fleet.nextSystemID else: mainFleetMission=self.getAIFleetMission(fleetID) mainMissionType = (mainFleetMission.getAIMissionTypes() + [-1])[0] @@ -685,11 +688,6 @@ mMT0=mainMissionTargets[0] if mMT0.getAITargetType()==AITargetType.TARGET_SYSTEM: status['sysID'] = mMT0.getTargetID() #hmm, but might still be a fair ways from here - #status['sysID'] = (fleet.systemID != -1 and fleet.systemID ) or fleet.nextSystemID #universe should still give fleet & fleet.systemID even if just destroyed - self.fleetStatus[fleetID] = status - #if sysID != -1: - # self.systemStatus.setdefault(sysID, {}).setdefault('myFleetRating', 0) - # self.systemStatus[sysID]['myFleetRating'] += newRating #moved to updateSystemStatus self.shipCount = shipCount print "------------------------" print "Empire Ship Count: ", shipCount Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-23 18:25:51 UTC (rev 5900) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-24 07:23:22 UTC (rev 5901) @@ -178,7 +178,7 @@ for pid in empireOwnedPlanetIDs: planet=universe.getPlanet(pid) if planet: - AIstate.colonizedSystems.setdefault(planet.systemID, []).append(pid) # track these to plan Solar Generators and Singularity Generators + AIstate.colonizedSystems.setdefault(planet.systemID, []).append(pid) # track these to plan Solar Generators and Singularity Generators, etc. AIstate.empireStars.clear() for sysID in AIstate.colonizedSystems: system = universe.getSystem(sysID) Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-03-23 18:25:51 UTC (rev 5900) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-03-24 07:23:22 UTC (rev 5901) @@ -8,6 +8,8 @@ from random import choice, random import ExplorationAI import PriorityAI +import ProductionAI +import ColonisationAI MinThreat = 10 # the minimum threat level that will be ascribed to an unkown threat capable of killing scouts MilitaryAllocations = [] @@ -23,6 +25,11 @@ getMilitaryFleets(tryReset=tryReset) return +def ratingNeeded(target, current=0): + if current >= target: + return 0 + else: + return target + current - (4*target*current)**0.5 def getMilitaryFleets(tryReset=True): "get armed military fleets" @@ -61,15 +68,19 @@ print "---------------------------------" remainingMilRating = availMilRating allocations = [] + allocationGroups={} if milFleetIDs == []: MilitaryAllocations = [] return + #for each system, get total rating of fleets assigned to it alreadyAssignedRating={} + assignedAttack={} + assignedHP={} for sysID in universe.systemIDs: - alreadyAssignedRating[sysID]=0 - + assignedAttack[sysID]=0 + assignedHP[sysID]=0 for fleetID in [fid for fid in allMilitaryFleetIDs if fid not in milFleetIDs]: aiFleetMission = foAI.foAIstate.getAIFleetMission(fleetID) sysTargets= [] @@ -80,7 +91,13 @@ if not sysTargets: #shouldn't really be possible continue lastSys = sysTargets[-1].getTargetID() # will count this fleet as assigned to last system in target list - alreadyAssignedRating[lastSys] += foAI.foAIstate.getRating(fleetID).get('overall', 0) #TODO: would preferably tally attack and health and take product + assignedAttack[lastSys] += foAI.foAIstate.getRating(fleetID).get('attack', 0) + assignedHP[lastSys] += foAI.foAIstate.getRating(fleetID).get('health', 0) + for sysID in universe.systemIDs: + mydefenses = foAI.foAIstate.systemStatus.get(sysID, {}).get( 'mydefenses', {} ) + mypattack = mydefenses.get('attack', 0) + myphealth = mydefenses.get('health', 0) + alreadyAssignedRating[sysID] = ( assignedAttack[sysID] + mypattack ) * ( assignedHP[sysID] + myphealth ) # get systems to defend capitalID = PlanetUtilsAI.getCapital() @@ -106,39 +123,42 @@ else: capitalSysID = foAI.foAIstate.fleetStatus.items()[0]['sysID'] - if fo.currentTurn() < 20: + if False: + if fo.currentTurn() < 20: + threatBias = 0 + elif fo.currentTurn() < 40: + threatBias = 10 + elif fo.currentTurn() < 60: + threatBias = 80 + elif fo.currentTurn() < 80: + threatBias = 200 + else: + threatBias = 400 + else: threatBias = 0 - elif fo.currentTurn() < 40: - threatBias = 10 - elif fo.currentTurn() < 60: - threatBias = 80 - elif fo.currentTurn() < 80: - threatBias = 200 - else: - threatBias = 400 - - threatBias = 0 safetyFactor = [ 4.0, 3.0, 1.5, 1.0, 1.0, 0.95 ][foAI.foAIstate.aggression] topTargetPlanets = [pid for pid, pscore, trp in AIstate.invasionTargets[:PriorityAI.allottedInvasionTargets] if pscore > 20] + [pid for pid, pscore in foAI.foAIstate.colonisablePlanetIDs[:10] if pscore > 20] topTargetSystems = [] - for sysID in PlanetUtilsAI.getSystems( topTargetPlanets ): + for sysID in AIstate.invasionTargetedSystemIDs + PlanetUtilsAI.getSystems( topTargetPlanets ): if sysID not in topTargetSystems: topTargetSystems.append(sysID) #doing this rather than set, to preserve order # allocation format: ( sysID, newAllocation, takeAny, maxMultiplier ) #================================ #--------Capital Threat ---------- - capitalThreat = safetyFactor*(2* threatBias +sum( [ foAI.foAIstate.systemStatus[capitalSysID][thrtKey] for thrtKey in [tkey for tkey in foAI.foAIstate.systemStatus.get(capitalSysID, {}).keys() if 'Threat' in tkey]] )) + capitalThreat = safetyFactor*(2* threatBias +sum( [ foAI.foAIstate.systemStatus[capitalSysID][thrtKey] for thrtKey in ['totalThreat', 'neighborThreat']] )) + neededRating = ratingNeeded(1.4*capitalThreat, alreadyAssignedRating[capitalSysID]) newAlloc=0 if tryReset: - if (capitalThreat > 0.5*(availMilRating+0.8*alreadyAssignedRating[capitalSysID]) ) : + if (neededRating > 0.5*availMilRating) : tryAgain(allMilitaryFleetIDs) return - if capitalThreat > 0.8*alreadyAssignedRating[capitalSysID]: - newAlloc = min(remainingMilRating, int( 0.999 + 1.2*(capitalThreat- 0.8*alreadyAssignedRating[capitalSysID]) ) ) - allocations.append( ( capitalSysID, newAlloc, True, 3) ) + if neededRating > 0: + newAlloc = min(remainingMilRating, neededRating ) + allocations.append( ( capitalSysID, newAlloc, True, 2*capitalThreat) ) + allocationGroups.setdefault('capitol', []).append( ( capitalSysID, newAlloc, True, 2*capitalThreat) ) remainingMilRating -= newAlloc print "Empire Capital System: (%d) %s -- threat : %d, military allocation: existing: %d ; new: %d"%(capitalSysID, universe.getSystem(capitalSysID).name , capitalThreat, alreadyAssignedRating[capitalSysID], newAlloc) print "-----------------" @@ -150,20 +170,22 @@ print "Empire-Occupied Systems: %s"%( [ "| %d %s |"%(eoSysID, universe.getSystem(eoSysID).name) for eoSysID in empireOccupiedSystemIDs ] ) print "-----------------" if len( empireOccupiedSystemIDs ) > 0: - ocSysTotThreat = [ ( oSID, threatBias +safetyFactor*sum( [ foAI.foAIstate.systemStatus.get(oSID, {}).get(thrtKey, 0) for thrtKey in ['fleetThreat', 'monsterThreat','planetThreat', 'neighborThreat']] ) ) for oSID in empireOccupiedSystemIDs ] + ocSysTotThreat = [ ( oSID, threatBias +safetyFactor*sum( [ foAI.foAIstate.systemStatus.get(oSID, {}).get(thrtKey, 0) for thrtKey in ['totalThreat', 'neighborThreat']] )) + for oSID in empireOccupiedSystemIDs ] totocSysThreat = sum( [thrt for sid, thrt in ocSysTotThreat] ) - totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in ocSysTotThreat] ) - allocationFactor = min( 1.2, remainingMilRating /max(0.01, ( totocSysThreat -totCurAlloc) )) + totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in ocSysTotThreat] ) + allocationFactor = min( 1.5, remainingMilRating /max(0.01, ( totocSysThreat -totCurAlloc) )) ocSysAlloc = 0 for sid, thrt in ocSysTotThreat: - curAlloc=0.8*alreadyAssignedRating[sid] - if (thrt > 0.8*(remainingMilRating+curAlloc )) and tryReset: + neededRating = ratingNeeded( 1.2*thrt, alreadyAssignedRating[sid]) + if (neededRating > 0.8*(remainingMilRating )) and tryReset: tryAgain(allMilitaryFleetIDs) return thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 0: - thisAlloc = max(0, min( min( int(0.99999 + (thrt-curAlloc)*allocationFactor ), 0.5*availMilRating) , remainingMilRating)) - allocations.append( (sid, thisAlloc, True, 2) ) + if ( neededRating>0 ) and remainingMilRating > 0: + thisAlloc = max(0, min( neededRating, 0.5*availMilRating, remainingMilRating)) + allocations.append( (sid, thisAlloc, True, 2*thrt) ) + allocationGroups.setdefault('occupied', []).append( (sid, thisAlloc, True, 2*thrt) ) remainingMilRating -= thisAlloc ocSysAlloc += thisAlloc print "Provincial Empire-Occupied Sytems under total threat: %d -- total mil allocation: existing %d ; new: %d"%(totocSysThreat, totCurAlloc, ocSysAlloc ) @@ -178,16 +200,20 @@ # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neightborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) - totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.4*thrt, curAlloc) thisAlloc=0 - if 2*thrt>curAlloc and (curAlloc>0 or remainingMilRating > (10+ (2*thrt-curAlloc))): #only record more allocation for this invasion if we already started or have enough rating available - thisAlloc =int(10.99999 + (1.5*thrt-curAlloc)) - takeAny= curAlloc>0 - allocations.append( (sid, thisAlloc, takeAny ,4) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= alreadyAssignedRating[sid] > 0 + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*3*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('topTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -195,25 +221,29 @@ print "Top Colony and Invasion Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) print "-----------------" - #================================ #--------Targeted Systems ---------- #TODO: do native invasions highest priority - otherTargetedSystemIDs = [sysID for sysID in AIstate.invasionTargetedSystemIDs if sysID not in topTargetSystems] + otherTargetedSystemIDs = [sysID for sysID in set( PlanetUtilsAI.getSystems(AIstate.opponentPlanetIDs)) if sysID not in topTargetSystems] print "Other Invasion Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) print "-----------------" # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, max(10, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) ) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neighborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) - totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.4*thrt, curAlloc) thisAlloc=0 - if thrt>curAlloc and remainingMilRating > 10+ 1.5*(thrt-curAlloc) : #only record an allocation for this invasion if we have enough rating available - thisAlloc =int(10.99999 + (thrt-curAlloc)*1.5) - allocations.append( (sid, thisAlloc, False, 3) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= alreadyAssignedRating[sid] > 0 + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -224,18 +254,22 @@ otherTargetedSystemIDs = [sysID for sysID in list(set(AIstate.colonyTargetedSystemIDs + AIstate.outpostTargetedSystemIDs)) if sysID not in topTargetSystems] print "Other Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) print "-----------------" - # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, safetyFactor*(threatBias +foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, safetyFactor*(threatBias +foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neighborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) - totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.2*thrt, curAlloc) thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 1.5*(thrt-curAlloc): - thisAlloc = min( min( int(0.99999 + (thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) - allocations.append( (sid, thisAlloc, False, 2.0) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= alreadyAssignedRating[sid] > 0 + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -244,30 +278,34 @@ print "-----------------" otherTargetedSystemIDs = [] - fleetSuppliableSystemIDs = empire.fleetSupplyableSystemIDs + targetableIDs = ColonisationAI.annexableSystemIDs.union( empire.fleetSupplyableSystemIDs ) for sysID in AIstate.opponentSystemIDs: - if sysID in fleetSuppliableSystemIDs: + if sysID in targetableIDs: otherTargetedSystemIDs.append(sysID) else: for nID in universe.getImmediateNeighbors(sysID, empireID): - if nID in fleetSuppliableSystemIDs: + if nID in targetableIDs: otherTargetedSystemIDs.append(sysID) break print "Blockade Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) print "-----------------" - # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in otherTargetedSystemIDs ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+ 0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neighborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) - totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.2*thrt, curAlloc) thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 1.5*(thrt-curAlloc): - thisAlloc = min( min( int(0.99999 + (thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) - allocations.append( (sid, thisAlloc, False, 10) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= alreadyAssignedRating[sid] > 0 + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Blockade Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -277,23 +315,28 @@ currentMilSystems = [sid for sid, alloc, takeAny, mm in allocations ] interiorIDs = list( foAI.foAIstate.expInteriorSystemIDs) - interiorTargets1 = [sid for sid in interiorIDs if ( ( sid not in currentMilSystems )) ] - interiorTargets = [sid for sid in interiorIDs if ( (threatBias + foAI.foAIstate.systemStatus.get(sid, {}).get('fleetThreat', 0) >0.8*alreadyAssignedRating[sid] ) ) ] + interiorTargets1 = (targetableIDs.union(interiorIDs)).difference( currentMilSystems ) + interiorTargets = [sid for sid in interiorTargets1 if ( (threatBias + foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0) >0.8*alreadyAssignedRating[sid] ) ) ] print "" - print "Other Empire-Interior Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in interiorTargets1 ] ) + print "Other Empire-Proximal Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in interiorTargets1 ] ) print "-----------------" # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety if len(interiorTargets) >0: otSysAlloc = 0 - otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)) ) for oSID in interiorTargets ] + otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)) ) for oSID in interiorTargets ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) - totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.2*thrt, curAlloc) thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 0 : - thisAlloc = min( min( int(0.99999 +( thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) - allocations.append( (sid, thisAlloc, True, 1.2) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= alreadyAssignedRating[sid] > 0 + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Other interior system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -307,7 +350,8 @@ monsterDens=[] - exploTargetIDs, _ = ExplorationAI.getCurrentExplorationInfo(verbose=False) + #exploTargetIDs, _ = ExplorationAI.getCurrentExplorationInfo(verbose=False) + exploTargetIDs=[] print "" print "Exploration-targeted Systems: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in exploTargetIDs ] ) print "-----------------" @@ -322,14 +366,16 @@ else: maxMilRating = 0.5*availMilRating for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.2*thrt, curAlloc) thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 0: - if foAI.foAIstate.systemStatus.get(sid, {}).get('monsterThreat', 0) > 2000: - monsterDens.append(sid) - continue # consider dealing with big monsters later - thisAlloc = min( min( int(0.99999 + (thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) - allocations.append( (sid, thisAlloc, False, 2) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= False + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('exploreTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Exploration-targeted %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -352,15 +398,16 @@ tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [0.8*alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) for sid, thrt in otSysThreat: - curAlloc=0.8*alreadyAssignedRating[sid] + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.2*thrt, curAlloc) thisAlloc=0 - if (thrt > curAlloc) and remainingMilRating > 0: - if foAI.foAIstate.systemStatus.get(sid, {}).get('monsterThreat', 0) > 2000: - if sid not in monsterDens: - monsterDens.append(sid) - continue # consider dealing with big monsters later - thisAlloc = min( min( int(0.99999 + (thrt-curAlloc)*1.5), remainingMilRating ), 0.5*availMilRating) - allocations.append( (sid, thisAlloc, False, 5) ) + #only record more allocation for this invasion if we already started or have enough rating available + takeAny= False + if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): + thisAlloc = max(0, min( neededRating, remainingMilRating)) + maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) + allocationGroups.setdefault('accessibleTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc print "Other Empire-Accessible system %4d ( %10s ) has local biased threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) @@ -372,6 +419,7 @@ print "No Other Empire-Accessible Systems with biased local threat " print "-----------------" + #monster den treatment probably unnecessary now print "" print "Big-Monster Dens: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in monsterDens ] ) print "-----------------" @@ -396,20 +444,23 @@ if remainingMilRating <=6: newAllocations = [ (sid, alc, alc, ta) for (sid, alc, ta, mm) in allocations ] else: + #oldAllocations = dict( [ (entry[0], entry ) for entry in allocations ] ) try: - totAlloc = sum( [alloc for sid, alloc, takeAny, maxMul in allocations ] ) + totAlloc = sum( [alloc for sid, alloc, takeAny, maxAlloc in allocations ] ) except: - print "error unpacking sid, alloc, takeAny, maxMul from ", allocations + print "error unpacking sid, alloc, takeAny, maxAlloc from ", allocations factor =(2.0* remainingMilRating ) / ( totAlloc + 0.1) - print "Remaining military strength allocation %d will be allocated as %.1f %% surplus allocation to top current priorities"%(remainingMilRating, 100*factor) + #print "Remaining military strength allocation %d will be allocated as %.1f %% surplus allocation to top current priorities"%(remainingMilRating, 100*factor) + print "Remaining military strength allocation %d will be allocated as surplus allocation to top current priorities"%(remainingMilRating) newAllocations = [] - for sid, alloc, takeAny, maxMul in allocations: - if remainingMilRating <= 0 : - newAllocations.append( ( sid, alloc, alloc, takeAny ) ) - else: - thisAlloc = int( max( maxMul-1, factor )* alloc ) - newAllocations.append( ( sid, alloc+thisAlloc, alloc, takeAny ) ) - remainingMilRating -= thisAlloc + for cat in ['capitol', 'topTargets', 'otherTargets', 'accessibleTargets', 'occupied', 'exploreTargets']: + for sid, alloc, takeAny, maxAlloc in allocationGroups.get(cat, []): + if remainingMilRating <= 0 : + newAllocations.append( ( sid, alloc, alloc, takeAny ) ) + else: + newRating = min(remainingMilRating+alloc, max(alloc, ratingNeeded( maxAlloc, alreadyAssignedRating[sid]) ) ) + newAllocations.append( ( sid, newRating, alloc, takeAny ) ) + remainingMilRating -= ( newRating - alloc ) MilitaryAllocations = newAllocations minMilAllocations = dict( [ (sid, alloc) for sid, alloc, takeAny, mm in allocations ] ) Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-23 18:25:51 UTC (rev 5900) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-24 07:23:22 UTC (rev 5901) @@ -281,7 +281,7 @@ troopShipsNeeded = math.ceil((opponentTroopPods - (numTroopPods+ queuedTroopPods ))/troopsPerBestShip) #invasionPriority = max( 10+ 200*max(0, troopShipsNeeded ) , int(0.1* totalVal) ) - invasionPriority = 20+ 120*max(0, troopShipsNeeded ) + invasionPriority = 30+ 150*max(0, troopShipsNeeded ) if invasionPriority < 0: return 0 if foAI.foAIstate.aggression==fo.aggression.beginner: Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-23 18:25:51 UTC (rev 5900) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-24 07:23:22 UTC (rev 5901) @@ -13,7 +13,21 @@ import ColonisationAI import EnumsAI +bestMilRatingsHistory={} +shipTypeMap = { EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_EXPLORATION: EnumsAI.AIShipDesignTypes.explorationShip, + EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_OUTPOST: EnumsAI.AIShipDesignTypes.outpostShip, + EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_COLONISATION: EnumsAI.AIShipDesignTypes.colonyShip, + EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_INVASION: EnumsAI.AIShipDesignTypes.troopShip, + EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_MILITARY: EnumsAI.AIShipDesignTypes.attackShip, + EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_ORBITAL_DEFENSE: EnumsAI.AIShipDesignTypes.defenseBase, + EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_ORBITAL_INVASION: EnumsAI.AIShipDesignTypes.troopBase, + } +#TODO: dynamic lookup of hull stats +hullStats = { + + } + #get key routines declared for import by others before completing present imports, to avoid circularity problems def curBestMilShipRating(): if (fo.currentTurn()+1) in bestMilRatingsHistory: @@ -52,25 +66,6 @@ return shipDesignID, shipDesign, getAvailableBuildLocations(shipDesignID) return None, None, None #must be missing a Shipyard or other orbital (or missing tech) - - - -shipTypeMap = { EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_EXPLORATION: EnumsAI.AIShipDesignTypes.explorationShip, - EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_OUTPOST: EnumsAI.AIShipDesignTypes.outpostShip, - EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_COLONISATION: EnumsAI.AIShipDesignTypes.colonyShip, - EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_INVASION: EnumsAI.AIShipDesignTypes.troopShip, - EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_MILITARY: EnumsAI.AIShipDesignTypes.attackShip, - EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_ORBITAL_DEFENSE: EnumsAI.AIShipDesignTypes.defenseBase, - EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_ORBITAL_INVASION: EnumsAI.AIShipDesignTypes.troopBase, - } - -bestMilRatingsHistory={} -#TODO: dynamic lookup of hull stats -hullStats = { - - } - - def shipTypeNames(shipProdPriority): empire = fo.getEmpire() designIDs=[] @@ -1107,14 +1102,16 @@ tInd=planet.currentMeterValue(fo.meterType.targetIndustry) cInd=planet.currentMeterValue(fo.meterType.industry) cPop = planet.currentMeterValue(fo.meterType.population) - if (cPop < 23) or cPop < 0.7*tPop: #check even if not aggressive, etc, just in case acquired planet with a ConcCamp on it + if (cPop < 23) or cPop < 0.8*tPop: #check even if not aggressive, etc, just in case acquired planet with a ConcCamp on it for bldg in planet.buildingIDs: if universe.getObject(bldg).buildingTypeName == bldName: res=fo.issueScrapOrder( bldg) print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) elif foAI.foAIstate.aggression>fo.aggression.typical and empire.buildingTypeAvailable(bldName) and (tPop >= 32) : + if (planet.focus== EnumsAI.AIFocusType.FOCUS_GROWTH) or ("COMPUTRONIUM_SPECIAL" in planet.specials): + continue queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] - if (cPop >=0.95*tPop) and cInd < 1.5* tInd: + if (cPop >=0.95*tPop):# and cInd < 1.5* tInd: if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building #if planet.focus not in [ EnumsAI.AIFocusType.FOCUS_INDUSTRY ]: # fo.issueChangeFocusOrder(pid, EnumsAI.AIFocusType.FOCUS_INDUSTRY) @@ -1156,6 +1153,7 @@ print "production summary: %s"%[elem.name for elem in productionQueue] queuedColonyShips={} queuedOutpostShips = 0 + queuedTroopShips=0 #TODO: blocked items might not need dequeuing, but rather for supply lines to be un-blockaded fo.updateProductionQueue() @@ -1173,6 +1171,8 @@ queuedColonyShips[thisSpec] = queuedColonyShips.get(thisSpec, 0) + element.remaining*element.blocksize if foAI.foAIstate.getShipRole(element.designID) == EnumsAI.AIShipRoleType.SHIP_ROLE_CIVILIAN_OUTPOST: queuedOutpostShips+= element.remaining*element.blocksize + if foAI.foAIstate.getShipRole(element.designID) == EnumsAI.AIShipRoleType.SHIP_ROLE_MILITARY_INVASION: + queuedTroopShips+= element.remaining*element.blocksize if queuedColonyShips: print "\nFound colony ships in build queue: %s"%queuedColonyShips if queuedOutpostShips: Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-23 18:25:51 UTC (rev 5900) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-24 07:23:22 UTC (rev 5901) @@ -137,6 +137,7 @@ def setPlanetResourceFoci(): #+ "set resource focus of planets " global __timerFile + newFoci = {} p... [truncated message content] |
From: <dil...@us...> - 2013-03-24 20:48:04
|
Revision: 5903 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5903&view=rev Author: dilvish-fo Date: 2013-03-24 20:47:54 +0000 (Sun, 24 Mar 2013) Log Message: ----------- AI update with improved troopship management & other misc changes Modified Paths: -------------- trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/EnumsAI.py trunk/FreeOrion/default/AI/FleetUtilsAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResourcesAI.py trunk/FreeOrion/default/AI/charting/charts.py Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -94,7 +94,7 @@ self.expInteriorSystemIDs= {} self.exploredSystemIDs = {} self.unexploredSystemIDs = {self.origHomeSystemID:1} - self.fleetStatus={} #keys: 'sysID', 'nships' + self.fleetStatus={} #keys: 'sysID', 'nships', 'rating' self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'myfleets', 'neighbors', 'name', 'myDefenses' self.needsEmergencyExploration=[] self.newlySplitFleets={} Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -743,21 +743,42 @@ potentialTargets = [ (pid, (score, specName) ) for (pid, (score, specName) ) in evaluatedPlanets if score > (0.8 * cost) ] print "colony/outpost ship matching -- fleets %s to planets %s"%( fleetPool, evaluatedPlanets) - #for planetID_value_pair in evaluatedPlanets: + + #adding a lot of checking here because have been getting mysterious exception, after too many recursions to get info fleetPool=set(fleetPool) universe=fo.getUniverse() + empireID=fo.empireID() + destroyedObjIDs = universe.destroyedObjectIDs(empireID) + for fid in fleetPool: + fleet = universe.getFleet(fid) + if not fleet or fleet.empty: + print "Error: bad fleet ( ID %d ) given to colonization routine; will be skipped"%fid + fleetPool.remove(fid) + continue + reportStr="Fleet ID (%d): %d ships; species: "%(fid, fleet.numShips) + for sid in fleet.shipIDs: + ship = universe.getShip(sid) + if not ship: + reportStr += "NoShip, " + else: + reportStr += "%s, "%ship.speciesName + print reportStr + print + #for planetID_value_pair in evaluatedPlanets: while (len(fleetPool) > 0 ) and ( len(potentialTargets) >0): thisTarget = potentialTargets.pop(0) thisScore=thisTarget[1][0] thisPlanetID=thisTarget[0] - thisSysID = universe.getPlanet(thisPlanetID).systemID + thisPlanet = universe.getPlanet(thisPlanetID) + print "checking pool %s against target %s current owner %s targetSpec %s"%(fleetPool, thisPlanet.name, thisPlanet.owner, thisTarget) + thisSysID = thisPlanet.systemID if (foAI.foAIstate.systemStatus.setdefault(thisSysID, {}).setdefault('monsterThreat', 0) > 2000) or (fo.currentTurn() <20 and foAI.foAIstate.systemStatus[thisSysID]['monsterThreat'] > 200): print "Skipping colonization of system %s due to Big Monster, threat %d"%(PlanetUtilsAI.sysNameIDs([thisSysID]), foAI.foAIstate.systemStatus[thisSysID]['monsterThreat']) continue thisSpec=thisTarget[1][1] foundFleets=[] thisFleetList = FleetUtilsAI.getFleetsForMission(nships=1, targetStats={}, minStats={}, curStats={}, species=thisSpec, systemsToCheck=[thisSysID], systemsChecked=[], - fleetPoolSet = fleetPool, fleetList=foundFleets, verbose=False) + fleetPoolSet = fleetPool, fleetList=foundFleets, triedFleets=set([]), verbose=False) if thisFleetList==[]: fleetPool.update(foundFleets)#just to be safe continue #must have no compatible colony/outpost ships Modified: trunk/FreeOrion/default/AI/EnumsAI.py =================================================================== --- trunk/FreeOrion/default/AI/EnumsAI.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/EnumsAI.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -200,7 +200,7 @@ explorationShip = {"SD_SCOUT":"A", "Scout":"B", "Tracker":"C"} colonyShip = {"SD_COLONY_SHIP":"A", "Seeder":"B", "Nest-Maker":"C", "Den-Maker":"D"} outpostShip = {"SD_OUTPOST_SHIP":"A", "Outposter":"B"} - troopShip = {"SD_TROOP_SHIP":"A", "Basic-Troopers":"B", "Medium-Troopers":"C", "Heavy-Troopers":"D", "Very-Heavy-Troopers":"D"} + troopShip = {"SD_TROOP_SHIP":"A", "Basic-Troopers":"B", "Medium-Troopers":"C", "Heavy-Troopers":"D", "Very-Heavy-Troopers":"E"} attackShip= {"SD_MARK":"A", "Lynx":"B","Griffon":"C", "Wyvern":"D", "Manticore":"E", "Devil":"F", "Reaver":"G", "Obliterator":"H"} colonyBase={"SD_COLONY_BASE":"A", "NestBase":"B"} outpostBase={"SD_OUTPOST_BASE":"A", "OutpostBase":"B"} Modified: trunk/FreeOrion/default/AI/FleetUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/FleetUtilsAI.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/FleetUtilsAI.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -42,7 +42,7 @@ return tally def getFleetsForMission(nships, targetStats, minStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList, - takeAny=False, extendSearch=True, verbose=False): #implements breadth-first search through systems + takeAny=False, extendSearch=True, triedFleets=set([]), verbose=False): #implements breadth-first search through systems if verbose: print "getFleetsForMission: (nships:%1d, targetStats:%s, minStats:%s, curStats:%s, species:%6s, systemsToCheck:%8s, systemsChecked:%8s, fleetPoolSet:%8s, fleetList:%8s) "%( nships, targetStats, minStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList) @@ -122,7 +122,7 @@ if not fleet.ownedBy(empireID): return [] if len(list(fleet.shipIDs)) <= 1: # fleet with only one ship cannot be split - return [fleetID] + return [] shipIDs = list( fleet.shipIDs ) for shipID in shipIDs[1:]: newFleetID = fo.issueNewFleetOrder("Fleet %d"%(shipID), shipID) @@ -140,7 +140,8 @@ print "Error - got no fleet ID back after trying to split a ship from fleet %d"%fleetID foAI.foAIstate.getFleetRole(fleetID, forceNew=True) # foAI.foAIstate.updateFleetRating(fleetID) # - foAI.foAIstate.ensureHaveFleetMissions(newfleets) + if newfleets !=[]: + foAI.foAIstate.ensureHaveFleetMissions(newfleets) return newfleets def mergeFleetAintoB(fleetA_ID, fleetB_ID, leaveRating=0, needRating=0, context=""): Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -179,16 +179,16 @@ ar3= "AR_NEUTRONIUM_PLATE" arL=[ar1, ar2, ar3] - for ari in [1, 2]: - nb, hull = designNameBases[ari+2]+"%1d-%1d", "SH_ORGANIC" - #newTroopDesigns += [ (nb%(2, ari+1), desc, hull, ["SR_WEAPON_2", arL[ari], tp, tp], "", model) ] - #newTroopDesigns += [ (nb%(3, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp], "", model) ] - nb, hull = designNameBases[ari+2]+"%1d-%1d", "SH_STATIC_MULTICELLULAR" - #newTroopDesigns += [ (nb%(4, ari+1), desc, hull, ["SR_WEAPON_2", arL[ari], tp, tp, tp], "", model) ] - #newTroopDesigns += [ (nb%(5, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp], "", model) ] - nb, hull = designNameBases[ari+2]+"%1d-%1d", "SH_ENDOMORPHIC" - newTroopDesigns += [ (nb%(6, ari+1), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp, tp], "", model) ] - newTroopDesigns += [ (nb%(7, ari+1), desc, hull, ["SR_WEAPON_8", arL[ari], tp, tp, tp, tp], "", model) ] + for ari in [1, 2]: #naming below only works because skipping Lead armor + nb, hull = designNameBases[ari+1]+"%1d-%1d", "SH_ORGANIC" + newTroopDesigns += [ (nb%(1, ari), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp], "", model) ] + newTroopDesigns += [ (nb%(2, ari), desc, hull, ["SR_WEAPON_8", arL[ari], tp, tp], "", model) ] + nb, hull = designNameBases[ari+1]+"%1d-%1d", "SH_STATIC_MULTICELLULAR" + newTroopDesigns += [ (nb%(3, ari), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp], "", model) ] + newTroopDesigns += [ (nb%(4, ari), desc, hull, ["SR_WEAPON_8", arL[ari], tp, tp, tp], "", model) ] + nb, hull = designNameBases[ari+1]+"%1d-%1d", "SH_ENDOMORPHIC" + newTroopDesigns += [ (nb%(5, ari), desc, hull, ["SR_WEAPON_5", arL[ari], tp, tp, tp, tp], "", model) ] + newTroopDesigns += [ (nb%(6, ari), desc, hull, ["SR_WEAPON_8", arL[ari], tp, tp, tp, tp], "", model) ] currentTurn=fo.currentTurn() needsAdding=[] @@ -542,8 +542,10 @@ capitolID = PlanetUtilsAI.getCapital() if capitolID == None: homeworld=None + capitolSysID=None else: homeworld = universe.getPlanet(capitolID) + capitolSysID = homeworld.systemID print "Production Queue Management:" empire = fo.getEmpire() productionQueue = empire.productionQueue @@ -1177,6 +1179,33 @@ print "\nFound colony ships in build queue: %s"%queuedColonyShips if queuedOutpostShips: print "\nFound colony ships in build queue: %s"%queuedOutpostShips + + allTroopFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(EnumsAI.AIFleetMissionType.FLEET_MISSION_INVASION ) + nTroopTot = sum( [ foAI.foAIstate.fleetStatus.get(fid, {}).get('nships', 0) for fid in allTroopFleetIDs ] ) + availTroopFleetIDs = list( FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allTroopFleetIDs)) + nAvailTroopTot = sum( [ foAI.foAIstate.fleetStatus.get(fid, {}).get('nships', 0) for fid in availTroopFleetIDs ] ) + print "Trooper Status: %d total, with %d unassigned. %d queued"%(nTroopTot, nAvailTroopTot, queuedTroopShips) + if ( capitolID!=None and currentTurn>=40 and foAI.foAIstate.systemStatus.get(capitolSysID, {}).get('fleetThreat', 0)==0 and + foAI.foAIstate.systemStatus.get(capitolSysID, {}).get('neighborThreat', 0)==0): + bestShip, bestDesign, buildChoices = getBestShipInfo( EnumsAI.AIPriorityType.PRIORITY_PRODUCTION_INVASION) + if buildChoices!=None and len(buildChoices)>0: + loc = random.choice(buildChoices) + prodTime = bestDesign.productionTime(empire.empireID, loc) + prodCost=bestDesign.productionCost(empire.empireID, loc) + troopersNeededForcing = max(0, int( 0.99+ (currentTurn/20 - nAvailTroopTot)/max(2, prodTime-1)) ) + numShips=troopersNeededForcing + perTurnCost = (float(prodCost) / prodTime) + if troopersNeededForcing>0 and totalPP > 3*perTurnCost*queuedTroopShips: + retval = fo.issueEnqueueShipProductionOrder(bestShip, loc) + if retval !=0: + print "forcing %d new ship(s) to production queue: %s; per turn production cost %.1f"%(numShips, bestDesign.name(True), numShips*perTurnCost) + print "" + if numShips>1: + fo.issueChangeProductionQuantityOrder(productionQueue.size -1, 1, numShips) + availPP -= numShips*perTurnCost + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + fo.updateProductionQueue() + print "" print "" # get the highest production priorities Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -205,20 +205,34 @@ if RFocus not in planet.availableFoci: continue newFoci[pid] = RFocus + result=0 if curFocus != RFocus: result = fo.issueChangeFocusOrder(pid, RFocus) if result == 1: universe.updateMeterEstimates(empirePlanetIDs) + if curFocus == RFocus or result==1: + if pid in empirePlanetIDs: + del empirePlanetIDs[ empirePlanetIDs.index( pid ) ] elif ( ("BLD_CONC_CAMP" in [bld.buildingTypeName for bld in map( universe.getObject, planet.buildingIDs)] ) or ( [ ccspec for ccspec in planet.specials if ccspec in [ "CONC_CAMP_MASTER_SPECIAL", "CONC_CAMP_SLAVE_SPECIAL" ] ] != [] )): if IFocus not in planet.availableFoci: continue curFocus = planet.focus newFoci[pid] = IFocus + result=0 if curFocus != IFocus: result = fo.issueChangeFocusOrder(pid, IFocus) if result == 1: + print ("Tried setting %s for Concentration Camp planet %s (%d) with species %s and current focus %s, got result %d and focus %s"% + ( newFoci[pid], planet.name, pid, planet.speciesName, curFocus, result, planetMap[pid].focus )) universe.updateMeterEstimates(empirePlanetIDs) + if (result != 1) or planetMap[pid].focus != IFocus: + newplanet=universe.getPlanet(pid) + print ("Error: Failed setting %s for Concentration Camp planet %s (%d) with species %s and current focus %s, but new planet copy shows %s"% + ( newFoci[pid], planetMap[pid].name, pid, planetMap[pid].speciesName, planetMap[pid].focus, newplanet.focus )) + if curFocus == IFocus or result==1: + if pid in empirePlanetIDs: + del empirePlanetIDs[ empirePlanetIDs.index( pid ) ] pp, rp = getResourceTargetTotals(empirePlanetIDs, planetMap) print "\n-----------------------------------------" @@ -239,7 +253,7 @@ curTargetRP += nRP continue else: - print "Error: new focus %s set early but not applied for planet %s (%d)"%( newFoci[pid], planetMap[pid].name, pid ) + print "Error: new focus %s set early but not applied for planet %s (%d) with species %s"%( newFoci[pid], planetMap[pid].name, pid, planetMap[pid].speciesName ) II, IR = newTargets[pid][IFocus] RI, RR = newTargets[pid][RFocus] CI, CR = currentOutput[pid][ IFocus], currentOutput[pid][ RFocus] Modified: trunk/FreeOrion/default/AI/charting/charts.py =================================================================== --- trunk/FreeOrion/default/AI/charting/charts.py 2013-03-24 14:00:38 UTC (rev 5902) +++ trunk/FreeOrion/default/AI/charting/charts.py 2013-03-24 20:47:54 UTC (rev 5903) @@ -24,8 +24,9 @@ else: return '' +doPlotTypes = ["PP"]#+ [ "RP"] +[ "ShipCount"] -for plotType in ["PP", "RP", "ShipCount"]: +for plotType in doPlotTypes: if plotType=="PP": caption="Production" @@ -69,8 +70,8 @@ data=PP elif plotType=="RP": data=RP - else: - data = shipCount + else: + data = shipCount if data != []: ymin = min(ymin, min(data)) ymax = max(ymax, max(data)) @@ -78,6 +79,13 @@ allData[playerName]=data logfiles=sorted(glob(dataDir+os.sep+"A*.log")) + A1log = glob(dataDir+os.sep+"AI_1.log") + if A1log and A1log[0] in logfiles: + A1Time = os.path.getmtime(A1log[0]) + for path in logfiles: + logtime = os.path.getmtime(path) + if logtime < A1Time - 300: + del logfiles[ logfiles.index(path)] empire=0 for lfile in logfiles: with open(lfile, 'r') as lf: @@ -159,9 +167,9 @@ x1,x2,y1,y2 = axis() newY2=y2 for yi in range(1, 10): - if 1.05*ymax < yi*y2/10: - newY2= yi*y2/10 - break + if 1.05*ymax < yi*y2/10: + newY2= yi*y2/10 + break print "y1: %.1f ; ymin: %.1f ; newY2/100: %.1f"%(y1, ymin, newY2/100) y1 = max(y1, 4, ymin, newY2/100) #axis( (x1,min(x2,200),y1,y2)) |
From: <dil...@us...> - 2013-03-24 23:05:02
|
Revision: 5904 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5904&view=rev Author: dilvish-fo Date: 2013-03-24 23:04:55 +0000 (Sun, 24 Mar 2013) Log Message: ----------- a couple additional tweaks to the charting script & to AI Modified Paths: -------------- trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/TechsListsAI.py trunk/FreeOrion/default/AI/charting/charts.py Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-03-24 20:47:54 UTC (rev 5903) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-03-24 23:04:55 UTC (rev 5904) @@ -109,6 +109,7 @@ if capitalPlanet: capitalSysID = capitalPlanet.systemID else: # should be rare, but so as to not break code below, pick a randomish mil-centroid system + capitalSysID=None #unless we can find one to use systemDict = {} for fleetID in allMilitaryFleetIDs: status = foAI.foAIstate.fleetStatus.get(fleetID, None) @@ -121,7 +122,10 @@ if rankedSystems: capitalSysID = rankedSystems[-1][-1] else: - capitalSysID = foAI.foAIstate.fleetStatus.items()[0]['sysID'] + try: + capitalSysID = foAI.foAIstate.fleetStatus.items()[0][1]['sysID'] + except: + pass if False: if fo.currentTurn() < 20: Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-24 20:47:54 UTC (rev 5903) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-24 23:04:55 UTC (rev 5904) @@ -262,10 +262,12 @@ "PRO_SOL_ORB_GEN", "DEF_DEFENSE_NET_2", "PRO_INDUSTRY_CENTER_I", + "DEF_GARRISON_2", "CON_METRO_INFRA", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_1", "PRO_INDUSTRY_CENTER_II", + "SPY_DETECT_3", "GRO_LIFECYCLE_MAN", "SHP_MULTICELL_CAST", "SHP_ENDOCRINE_SYSTEMS", @@ -280,10 +282,8 @@ "DEF_SYST_DEF_MINE_1", "DEF_PLAN_BARRIER_SHLD_3", "CON_ORBITAL_HAB", - "DEF_GARRISON_2", "DEF_GARRISON_3", "SHP_WEAPON_8", - "SPY_DETECT_3", "SHP_CONT_SYMB", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", Modified: trunk/FreeOrion/default/AI/charting/charts.py =================================================================== --- trunk/FreeOrion/default/AI/charting/charts.py 2013-03-24 20:47:54 UTC (rev 5903) +++ trunk/FreeOrion/default/AI/charting/charts.py 2013-03-24 23:04:55 UTC (rev 5904) @@ -82,10 +82,12 @@ A1log = glob(dataDir+os.sep+"AI_1.log") if A1log and A1log[0] in logfiles: A1Time = os.path.getmtime(A1log[0]) - for path in logfiles: + for path in logfiles[::-1]: logtime = os.path.getmtime(path) + print "path ", path, "logtime diff: %.1f"%(A1Time -logtime) if logtime < A1Time - 300: del logfiles[ logfiles.index(path)] + print "skipping stale logfile ", path empire=0 for lfile in logfiles: with open(lfile, 'r') as lf: |
From: <dil...@us...> - 2013-03-27 22:57:15
|
Revision: 5909 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5909&view=rev Author: dilvish-fo Date: 2013-03-27 22:57:06 +0000 (Wed, 27 Mar 2013) Log Message: ----------- misc AI updates, mostly combat/invasion Modified Paths: -------------- trunk/FreeOrion/default/AI/AIFleetMission.py trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/FleetUtilsAI.py trunk/FreeOrion/default/AI/InvasionAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIFleetMission.py =================================================================== --- trunk/FreeOrion/default/AI/AIFleetMission.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/AIFleetMission.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -9,6 +9,7 @@ import ProductionAI import AIAbstractMission import EnumsAI +import MilitaryAI AIFleetMissionTypeNames = EnumsAI.AIFleetMissionType() @@ -115,7 +116,7 @@ return # can't merge fleets in middle of starlane sysStatus = foAI.foAIstate.systemStatus[systemID] destroyedList = list( universe.destroyedObjectIDs(empireID) ) - otherFleetsHere= [fid for fid in sysStatus.get('myfleets', []) if ( (fid != fleetID) and (fid not in destroyedList) ) ] + otherFleetsHere= [fid for fid in sysStatus.get('myFleetsAccessible', []) if ( (fid != fleetID) and (fid not in destroyedList) ) ] if otherFleetsHere==[]: return #nothing of record to merge with mainMissionTargets = self.getAITargets(mainMissionType) @@ -315,8 +316,8 @@ if ordersCompleted: orders=self.getAIFleetOrders() lastOrder= orders and orders[-1] + universe=fo.getUniverse() if orders and lastOrder.getAIFleetOrderType() == EnumsAI.AIFleetOrderType.ORDER_COLONISE: - universe=fo.getUniverse() planet = universe.getPlanet(lastOrder.getTargetAITarget().getTargetID()) pop=planet.currentMeterValue(fo.meterType.population) if pop==0: @@ -341,6 +342,12 @@ AIstate.invasionTargetedSystemIDs + AIstate.blockadeTargetedSystemIDs))): #consider a secure mission print "Fleet %d has completed initial stage of its mission to secure system %d, may release a portion of ships"%(self.getAITargetID() , lastOrder.getTargetAITarget().getTargetID()) clearAll=False + fleetID=self.getAITargetID() + fleet=universe.getFleet(fleetID) + if fleet.systemID != -1: + loc = fleet.systemID + else: + loc=fleet.nextSystemID if clearAll: print "Fleet %d has completed its mission; clearing all orders and targets."%(self.getAITargetID() ) print "Full set of orders were:" @@ -348,9 +355,29 @@ print "\t\t %s"%aiFleetOrder2 self.clearAIFleetOrders() self.clearAITargets(([-1]+ self.getAIMissionTypes()[:1])[-1]) + if foAI.foAIstate.getFleetRole(fleetID) in [ EnumsAI.AIFleetMissionType.FLEET_MISSION_MILITARY, + EnumsAI.AIFleetMissionType.FLEET_MISSION_ATTACK, + EnumsAI.AIFleetMissionType.FLEET_MISSION_DEFEND, + EnumsAI.AIFleetMissionType.FLEET_MISSION_HIT_AND_RUN, + EnumsAI.AIFleetMissionType.FLEET_MISSION_SECURE ]: + allocations = MilitaryAI.getMilitaryFleets(milFleetIDs=[fleetID], tryReset=False, round="Fleet %d Reassignment"%fleetID) + if allocations: + MilitaryAI.assignMilitaryFleetsToSystems(useFleetIDList=[fleetID], allocations=allocations) else: #TODO: evaluate releasing a smaller portion or none of the ships - FleetUtilsAI.splitFleet(self.getAITargetID() ) #at least first stage of current task is done; release extra ships for potential other deployments + newFleets=FleetUtilsAI.splitFleet(self.getAITargetID() ) #at least first stage of current task is done; release extra ships for potential other deployments + newMilFleets = [] + for fleetID in newFleets: + if foAI.foAIstate.getFleetRole(fleetID) in [ EnumsAI.AIFleetMissionType.FLEET_MISSION_MILITARY, + EnumsAI.AIFleetMissionType.FLEET_MISSION_ATTACK, + EnumsAI.AIFleetMissionType.FLEET_MISSION_DEFEND, + EnumsAI.AIFleetMissionType.FLEET_MISSION_HIT_AND_RUN, + EnumsAI.AIFleetMissionType.FLEET_MISSION_SECURE ]: + newMilFleets.append(fleetID) + allocations = MilitaryAI.getMilitaryFleets(milFleetIDs=newMilFleets, tryReset=False, round="Fleet Reassignment %s"%newMilFleets) + if allocations: + MilitaryAI.assignMilitaryFleetsToSystems(useFleetIDList=newMilFleets, allocations=allocations) + def generateAIFleetOrders(self): "generates AIFleetOrders from fleets targets to accomplish" @@ -372,6 +399,7 @@ # for some targets fleet has to visit systems and therefore fleet visit them systemAITargets = self.__getRequiredToVisitSystemAITargets() aiFleetOrdersToVisitSystems = MoveUtilsAI.getAIFleetOrdersFromSystemAITargets(self.getAITarget(), systemAITargets) + #TODO: if fleet doesn't have enough fuel to get to final target, consider resetting Mission #print "----------------------------------------" #print "*+*+ fleet %d : has fleet action system targets: %s"%(fleetID, [str(obj) for obj in systemAITargets]) #print "----------" @@ -397,7 +425,7 @@ self.appendAIFleetOrder(aiFleetOrder) - # if fleet don't have any mission, then resupply if is current location not in supplyable system + # if fleet doesn't have any mission, then resupply if is current location not in supplyable system empire = fo.getEmpire() fleetSupplyableSystemIDs = empire.fleetSupplyableSystemIDs if (not self.hasAnyAIMissionTypes()) and not(self.getLocationAITarget().getTargetID() in fleetSupplyableSystemIDs): Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -95,7 +95,7 @@ self.exploredSystemIDs = {} self.unexploredSystemIDs = {self.origHomeSystemID:1} self.fleetStatus={} #keys: 'sysID', 'nships', 'rating' - self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'myfleets', 'neighbors', 'name', 'myDefenses' + self.systemStatus={} #keys: 'fleetThreat'. 'planetThreat', 'monsterThreat' (specifically, immobile nonplanet threat), 'myfleets', 'neighbors', 'name', 'myDefenses', 'myFleetsAccessible'(not just next desitination) self.needsEmergencyExploration=[] self.newlySplitFleets={} self.aggression=aggression @@ -238,6 +238,7 @@ enemyFleetIDs = [] enemiesBySystem = {} myFleetsBySystem={} + fleetSpotPosition={} sawEnemiesAtSystem={} currentTurn = fo.currentTurn() for fleetID in universe.fleetIDs: @@ -250,6 +251,7 @@ if fleet.ownedBy(empireID): if (fleetID not in destroyedObjIDs): myFleetsBySystem.setdefault( thisSysID, [] ).append( fleetID ) + fleetSpotPosition.setdefault( fleet.systemID, [] ).append( fleetID ) else: partialVisTurn = dictFromMap(universe.getVisibilityTurnsMap(fleetID, empireID)).get(fo.visibility.partial, -9999) if partialVisTurn >= currentTurn -1 : #only interested in immediately recent data @@ -264,6 +266,7 @@ system = universe.getSystem(sysID) #update fleets sysStatus['myfleets']=myFleetsBySystem.get(sysID, []) + sysStatus['myFleetsAccessible']=fleetSpotPosition.get(sysID, []) localEnemyFleetIDs=enemiesBySystem.get(sysID, []) if system: sysStatus['name']=system.name @@ -296,7 +299,7 @@ if (not system) or partialVisTurn==-9999: print "Have never had partial vis for system %d ( %s ) -- basing threat assessment on old info and lost ships"%(sysID, sysStatus.get('name', "name unknown")) sysStatus['planetThreat'] = 0 - sysStatus['fleetThreat'] = int( max(enemyRating, sysStatus.get('fleetThreat', 0) , 1.1*lostFleetRating) ) + sysStatus['fleetThreat'] = int( max(enemyRating, 0.98*sysStatus.get('fleetThreat', 0) , 1.1*lostFleetRating) ) sysStatus['monsterThreat']=0 sysStatus['mydefenses'] = {'overall':0, 'attack':0, 'health':0 } sysStatus['totalThreat'] = sysStatus['fleetThreat'] @@ -325,7 +328,7 @@ if not partialVisTurn == currentTurn: #(universe.getVisibility(sysID, self.empireID) >= fo.visibility.partial): print "Stale visibility for system %d ( %s ) -- last seen %d, current Turn %d -- basing threat assessment on old info and lost ships"%(sysID, sysStatus.get('name', "name unknown"), partialVisTurn, currentTurn) - sysStatus['fleetThreat'] = int( enemyRating + 1.1*lostFleetRating) + sysStatus['fleetThreat'] = int( max(enemyRating, 0.98*sysStatus.get('fleetThreat', 0), 1.1*lostFleetRating) ) sysStatus['totalThreat'] = (pattack + enemyAttack + sysStatus.get('monsterThreat', 0)**0.5) * (phealth + enemyHealth + sysStatus.get('monsterThreat', 0)**0.5) else: #system considered visible #TODO: reevaluate as visibility rules change enemyattack, enemyhealth, enemythreat=0, 0, 0 Modified: trunk/FreeOrion/default/AI/FleetUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/FleetUtilsAI.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/FleetUtilsAI.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -56,7 +56,7 @@ return [] thisSystemID = systemsToCheck.pop(0) #take the head of the line systemsChecked.append(thisSystemID) - fleetsHere = [ fid for fid in foAI.foAIstate.systemStatus.get(thisSystemID, {}).get('myfleets', []) if fid in fleetPoolSet] + fleetsHere = [ fid for fid in foAI.foAIstate.systemStatus.get(thisSystemID, {}).get('myFleetsAccessible', []) if fid in fleetPoolSet] if verbose: print "found fleetPool Fleets %s"%fleetsHere while fleetsHere !=[]: @@ -137,7 +137,10 @@ newfleets.append(newFleetID) foAI.foAIstate.newlySplitFleets[newFleetID]=True else: - print "Error - got no fleet ID back after trying to split a ship from fleet %d"%fleetID + if fleet.systemID==-1: + print "Error - tried to split ship id (%d) from fleet %d when fleet is in starlane"%(shipID, fleetID) + else: + print "Error - got no fleet ID back after trying to split ship id (%d) from fleet %d"%(shipID, fleetID) foAI.foAIstate.getFleetRole(fleetID, forceNew=True) # foAI.foAIstate.updateFleetRating(fleetID) # if newfleets !=[]: @@ -426,6 +429,7 @@ print " " + str(ODAIFleetMission) aiFleetMissions = foAI.foAIstate.getAllAIFleetMissions() + for aiFleetMission in aiFleetMissions: aiFleetMission.generateAIFleetOrders() @@ -433,15 +437,20 @@ "issues fleet orders" print "" - print "issuing fleet orders:" universe=fo.getUniverse() aiFleetMissions = foAI.foAIstate.getAllAIFleetMissions() - for aiFleetMission in aiFleetMissions: - fleetID = aiFleetMission.getAITargetID() - fleet = aiFleetMission.getAITarget().getTargetObj() - if (not fleet) or ( len(fleet.shipIDs)==0) or fleetID in universe.destroyedObjectIDs(fo.empireID()): # in case fleet was merged into another previously during this turn - continue - aiFleetMission.issueAIFleetOrders() + round = 0 + while (round <3): + round += 1 + print "issuing fleet orders Round %d:"%round + for aiFleetMission in aiFleetMissions: + fleetID = aiFleetMission.getAITargetID() + fleet = aiFleetMission.getAITarget().getTargetObj() + if (not fleet) or ( len(fleet.shipIDs)==0) or fleetID in universe.destroyedObjectIDs(fo.empireID()): # in case fleet was merged into another previously during this turn + continue + aiFleetMission.issueAIFleetOrders() + aiFleetMissions = foAI.foAIstate.misc.get('ReassignedFleetMissions', []) + foAI.foAIstate.misc['ReassignedFleetMissions']=[] print "" def printSystems(systemIDs): Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -78,7 +78,7 @@ numInvasionFleets = len(FleetUtilsAI.extractFleetIDsWithoutMissionTypes(invasionFleetIDs)) print "Invasion Fleets Without Missions: " + str(numInvasionFleets) - evaluatedPlanetIDs = list(set(invadablePlanetIDs) - set(invasionTargetedPlanetIDs)) + evaluatedPlanetIDs = list(set(invadablePlanetIDs) - set(invasionTargetedPlanetIDs)) #TODO: check if any invasionTargetedPlanetIDs need more troops assigned print "Evaluating potential invasions, PlanetIDs: " + str(evaluatedPlanetIDs) evaluatedPlanets = assignInvasionValues(evaluatedPlanetIDs, EnumsAI.AIFleetMissionType.FLEET_MISSION_INVASION, fleetSupplyablePlanetIDs, empire) Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -17,12 +17,12 @@ totMilRating=0 milShips=0 -def tryAgain(milFleetIDs, tryReset=False): +def tryAgain(milFleetIDs, tryReset=False, round=""): for fid in milFleetIDs: thisMission=foAI.foAIstate.getAIFleetMission(fid) thisMission.clearAIFleetOrders() thisMission.clearAITargets(-1) - getMilitaryFleets(tryReset=tryReset) + getMilitaryFleets(tryReset=tryReset, round=round) return def ratingNeeded(target, current=0): @@ -31,7 +31,7 @@ else: return target + current - (4*target*current)**0.5 -def getMilitaryFleets(tryReset=True): +def getMilitaryFleets(milFleetIDs=None, tryReset=True, round="Main"): "get armed military fleets" global MilitaryAllocations, totMilRating @@ -48,31 +48,39 @@ else: homeSystemID=-1 - allMilitaryFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_MILITARY ) - if tryReset and ((fo.currentTurn()+empireID) % 10 ==0): - tryAgain(allMilitaryFleetIDs) + if milFleetIDs !=None: + allMilitaryFleetIDs = milFleetIDs + else: + allMilitaryFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_MILITARY ) + if tryReset and ((fo.currentTurn()+empireID) % 10 ==0) and round=="Main": + tryAgain(allMilitaryFleetIDs, tryReset=False, round = round+" Reset") - totMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), allMilitaryFleetIDs ) ) milShips = 0 for fid in allMilitaryFleetIDs: milShips += foAI.foAIstate.fleetStatus.get(fid, {}).get('nships', 0) - print "==================================================" - print "Total Military Rating: %d"%totMilRating - print "---------------------------------" - foAI.foAIstate.militaryRating=totMilRating + thisTotMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), allMilitaryFleetIDs ) ) + if "Main" in round: + totMilRating = thisTotMilRating + print "==================================================" + print "%s Round Total Military Rating: %d"%(round, totMilRating) + print "---------------------------------" + foAI.foAIstate.militaryRating=totMilRating + milFleetIDs = list( FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allMilitaryFleetIDs)) availMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), milFleetIDs ) ) - print "==================================================" - print "Available Military Rating: %d"%availMilRating - print "---------------------------------" + if "Main" in round: + print "==================================================" + print "%s Round Available Military Rating: %d"%(round, availMilRating) + print "---------------------------------" remainingMilRating = availMilRating allocations = [] allocationGroups={} if milFleetIDs == []: - MilitaryAllocations = [] - return + if "Main" in round: + MilitaryAllocations = [] + return [] #for each system, get total rating of fleets assigned to it alreadyAssignedRating={} @@ -164,15 +172,18 @@ allocations.append( ( capitalSysID, newAlloc, True, 2*capitalThreat) ) allocationGroups.setdefault('capitol', []).append( ( capitalSysID, newAlloc, True, 2*capitalThreat) ) remainingMilRating -= newAlloc - print "Empire Capital System: (%d) %s -- threat : %d, military allocation: existing: %d ; new: %d"%(capitalSysID, universe.getSystem(capitalSysID).name , capitalThreat, alreadyAssignedRating[capitalSysID], newAlloc) - print "-----------------" + if "Main" in round or newAlloc >0: + print "Empire Capital System: (%d) %s -- threat : %d, military allocation: existing: %d ; new: %d"%(capitalSysID, universe.getSystem(capitalSysID).name , capitalThreat, alreadyAssignedRating[capitalSysID], newAlloc) + print "-----------------" #================================ #--------Empire Occupied Systems ---------- empirePlanetIDs = PlanetUtilsAI.getOwnedPlanetsByEmpire(universe.planetIDs, empireID) empireOccupiedSystemIDs = list( set(PlanetUtilsAI.getSystems(empirePlanetIDs)) - set([capitalSysID] ) ) - print "Empire-Occupied Systems: %s"%( [ "| %d %s |"%(eoSysID, universe.getSystem(eoSysID).name) for eoSysID in empireOccupiedSystemIDs ] ) - print "-----------------" + if "Main" in round: + print "Empire-Occupied Systems: %s"%( [ "| %d %s |"%(eoSysID, universe.getSystem(eoSysID).name) for eoSysID in empireOccupiedSystemIDs ] ) + print "-----------------" + newAlloc=0 if len( empireOccupiedSystemIDs ) > 0: ocSysTotThreat = [ ( oSID, threatBias +safetyFactor*sum( [ foAI.foAIstate.systemStatus.get(oSID, {}).get(thrtKey, 0) for thrtKey in ['totalThreat', 'neighborThreat']] )) for oSID in empireOccupiedSystemIDs ] @@ -181,27 +192,34 @@ allocationFactor = min( 1.5, remainingMilRating /max(0.01, ( totocSysThreat -totCurAlloc) )) ocSysAlloc = 0 for sid, thrt in ocSysTotThreat: - neededRating = ratingNeeded( 1.2*thrt, alreadyAssignedRating[sid]) + curAlloc=alreadyAssignedRating[sid] + neededRating = ratingNeeded( 1.4*thrt, curAlloc) if (neededRating > 0.8*(remainingMilRating )) and tryReset: tryAgain(allMilitaryFleetIDs) return thisAlloc=0 if ( neededRating>0 ) and remainingMilRating > 0: thisAlloc = max(0, min( neededRating, 0.5*availMilRating, remainingMilRating)) + newAlloc+=thisAlloc allocations.append( (sid, thisAlloc, True, 2*thrt) ) allocationGroups.setdefault('occupied', []).append( (sid, thisAlloc, True, 2*thrt) ) remainingMilRating -= thisAlloc ocSysAlloc += thisAlloc - print "Provincial Empire-Occupied Sytems under total threat: %d -- total mil allocation: existing %d ; new: %d"%(totocSysThreat, totCurAlloc, ocSysAlloc ) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Provincial Occupied system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "Provincial Empire-Occupied Sytems under total threat: %d -- total mil allocation: existing %d ; new: %d"%(totocSysThreat, totCurAlloc, ocSysAlloc ) + print "-----------------" #================================ #--------Top Targeted Systems ---------- #TODO: do native invasions highest priority otherTargetedSystemIDs = topTargetSystems - print "Top Colony and Invasion Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) - print "-----------------" + if "Main" in round: + print "Top Colony and Invasion Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) + print "-----------------" # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety + newAlloc=0 if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neightborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] @@ -216,22 +234,27 @@ if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) maxAlloc = safetyFactor*3*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) + newAlloc+=thisAlloc allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('topTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) - print "-----------------" - print "Top Colony and Invasion Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Top Colony and Invasion Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" #================================ #--------Targeted Systems ---------- #TODO: do native invasions highest priority otherTargetedSystemIDs = [sysID for sysID in set( PlanetUtilsAI.getSystems(AIstate.opponentPlanetIDs)) if sysID not in topTargetSystems] - print "Other Invasion Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) - print "-----------------" + if "Main" in round: + print "Other Invasion Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) + print "-----------------" # for these, calc local threat only, no neighbor threat, but use a multiplier for fleet safety + newAlloc=0 if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neighborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] @@ -245,24 +268,29 @@ takeAny= alreadyAssignedRating[sid] > 0 if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) + newAlloc+=thisAlloc maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) - print "-----------------" - print "Invasion Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Invasion Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" otherTargetedSystemIDs = [sysID for sysID in list(set(AIstate.colonyTargetedSystemIDs + AIstate.outpostTargetedSystemIDs)) if sysID not in topTargetSystems] - print "Other Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) - print "-----------------" + if "Main" in round: + print "Other Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) + print "-----------------" if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, safetyFactor*(threatBias +foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neighborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + newAlloc=0 for sid, thrt in otSysThreat: curAlloc=alreadyAssignedRating[sid] neededRating = ratingNeeded( 1.2*thrt, curAlloc) @@ -271,15 +299,18 @@ takeAny= alreadyAssignedRating[sid] > 0 if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) + newAlloc+=thisAlloc maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) - print "-----------------" - print "Other Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Other Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" otherTargetedSystemIDs = [] targetableIDs = ColonisationAI.annexableSystemIDs.union( empire.fleetSupplyableSystemIDs ) @@ -292,13 +323,15 @@ otherTargetedSystemIDs.append(sysID) break - print "Blockade Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) - print "-----------------" + if "Main" in round: + print "Blockade Targeted Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in otherTargetedSystemIDs ] ) + print "-----------------" if len( otherTargetedSystemIDs ) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)+ 0.5*foAI.foAIstate.systemStatus.get(oSID, {}).get('neighborThreat', 0) ) ) for oSID in otherTargetedSystemIDs ] tototSysThreat = sum( [thrt for sid, thrt in otSysThreat] ) totCurAlloc = sum( [alreadyAssignedRating[sid] for sid, thrt in otSysThreat] ) + newAlloc=0 for sid, thrt in otSysThreat: curAlloc=alreadyAssignedRating[sid] neededRating = ratingNeeded( 1.2*thrt, curAlloc) @@ -307,24 +340,29 @@ takeAny= alreadyAssignedRating[sid] > 0 if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) + newAlloc+=thisAlloc maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Blockade Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) - print "-----------------" - print "Blockade Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Blockade Targeted system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Blockade Targeted Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" currentMilSystems = [sid for sid, alloc, takeAny, mm in allocations ] interiorIDs = list( foAI.foAIstate.expInteriorSystemIDs) interiorTargets1 = (targetableIDs.union(interiorIDs)).difference( currentMilSystems ) interiorTargets = [sid for sid in interiorTargets1 if ( (threatBias + foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0) >0.8*alreadyAssignedRating[sid] ) ) ] - print "" - print "Other Empire-Proximal Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in interiorTargets1 ] ) - print "-----------------" + if "Main" in round: + print "" + print "Other Empire-Proximal Systems : %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in interiorTargets1 ] ) + print "-----------------" # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety + newAlloc=0 if len(interiorTargets) >0: otSysAlloc = 0 otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('totalThreat', 0)) ) for oSID in interiorTargets ] @@ -338,17 +376,20 @@ takeAny= alreadyAssignedRating[sid] > 0 if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) + newAlloc+=thisAlloc maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('otherTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Other interior system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or thisAlloc >0: + print "Other interior system %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Other Interior Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" + elif "Main" in round: print "-----------------" - print "Other Interior Systems under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" - else: - print "-----------------" print "No Other Interior Systems with fleet threat " print "-----------------" @@ -356,10 +397,12 @@ #exploTargetIDs, _ = ExplorationAI.getCurrentExplorationInfo(verbose=False) exploTargetIDs=[] - print "" - print "Exploration-targeted Systems: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in exploTargetIDs ] ) - print "-----------------" + if "Main" in round: + print "" + print "Exploration-targeted Systems: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in exploTargetIDs ] ) + print "-----------------" # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety + newAlloc=0 if len(exploTargetIDs) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) )) for oSID in exploTargetIDs ] @@ -377,25 +420,30 @@ takeAny= False if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) + newAlloc+=thisAlloc maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('exploreTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Exploration-targeted %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) - print "-----------------" - print "Exploration-targeted s under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Exploration-targeted %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Exploration-targeted s under total threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" visibleSystemIDs = foAI.foAIstate.visInteriorSystemIDs.keys() + foAI.foAIstate. visBorderSystemIDs.keys() accessibleSystemIDs = [sysID for sysID in visibleSystemIDs if universe.systemsConnected(sysID, homeSystemID, empireID) ] currentMilSystems = [sid for sid, alloc, takeAny, multiplier in allocations if alloc > 0 ] borderTargets1 = [sid for sid in accessibleSystemIDs if ( ( sid not in currentMilSystems )) ] borderTargets = [sid for sid in borderTargets1 if ( ( threatBias +foAI.foAIstate.systemStatus.get(sid, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(sid, {}).get('planetThreat', 0) > 0.8*alreadyAssignedRating[sid] )) ] - print "" - print "Empire-Accessible Systems not yet allocated military: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID) and universe.getSystem(sysID).name) for sysID in borderTargets1 ] ) - print "-----------------" + if "Main" in round: + print "" + print "Empire-Accessible Systems not yet allocated military: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID) and universe.getSystem(sysID).name) for sysID in borderTargets1 ] ) + print "-----------------" # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety + newAlloc=0 if len(borderTargets) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, threatBias +safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0)+ foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0)) ) for oSID in borderTargets ] @@ -409,25 +457,30 @@ takeAny= False if ( neededRating>0 ) and (remainingMilRating > neededRating or takeAny): thisAlloc = max(0, min( neededRating, remainingMilRating)) + newAlloc+=thisAlloc maxAlloc = safetyFactor*2*max( foAI.foAIstate.systemStatus.get(sid, {}).get('totalThreat', 0), foAI.foAIstate.systemStatus.get(sid, {}).get('neightborThreat', 0)) allocations.append( (sid, thisAlloc, takeAny , maxAlloc) ) allocationGroups.setdefault('accessibleTargets', []).append( (sid, thisAlloc, takeAny , maxAlloc) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Other Empire-Accessible system %4d ( %10s ) has local biased threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or thisAlloc >0: + print "Other Empire-Accessible system %4d ( %10s ) has local biased threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" + print "Other Empire-Accessible Systems under total biased threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) + print "-----------------" + elif "Main" in round: print "-----------------" - print "Other Empire-Accessible Systems under total biased threat: %d -- total mil allocation-- existing: %d ; new: %d"%(tototSysThreat, totCurAlloc, otSysAlloc ) - print "-----------------" - else: - print "-----------------" print "No Other Empire-Accessible Systems with biased local threat " print "-----------------" #monster den treatment probably unnecessary now - print "" - print "Big-Monster Dens: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in monsterDens ] ) - print "-----------------" + if "Main" in round: + print "" + print "Big-Monster Dens: %s"%( [ "| %d %s |"%(sysID, universe.getSystem(sysID).name) for sysID in monsterDens ] ) + print "-----------------" # for these, calc fleet threat only, no neighbor threat, but use a multiplier for fleet safety + newAlloc=0 if len(monsterDens) > 0: otSysAlloc = 0 otSysThreat = [ ( oSID, safetyFactor*(foAI.foAIstate.systemStatus.get(oSID, {}).get('fleetThreat', 0)+foAI.foAIstate.systemStatus.get(oSID, {}).get('monsterThreat', 0) + foAI.foAIstate.systemStatus.get(oSID, {}).get('planetThreat', 0) ) ) for oSID in monsterDens ] @@ -438,11 +491,14 @@ thisAlloc=0 if (thrt > curAlloc) and remainingMilRating > 2* thrt: thisAlloc = int(0.99999 + (thrt-curAlloc)*1.5) + newAlloc+=thisAlloc allocations.append( (sid, thisAlloc, False, 5) ) remainingMilRating -= thisAlloc otSysAlloc += thisAlloc - print "Monster Den %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) - print "-----------------" + if "Main" in round or thisAlloc >0: + print "Monster Den %4d ( %10s ) has local threat %8d ; existing military allocation %d and new allocation %8d"%(sid, universe.getSystem(sid).name, thrt, curAlloc, thisAlloc) + if "Main" in round or newAlloc >0: + print "-----------------" if remainingMilRating <=6: @@ -455,7 +511,7 @@ print "error unpacking sid, alloc, takeAny, maxAlloc from ", allocations factor =(2.0* remainingMilRating ) / ( totAlloc + 0.1) #print "Remaining military strength allocation %d will be allocated as %.1f %% surplus allocation to top current priorities"%(remainingMilRating, 100*factor) - print "Remaining military strength allocation %d will be allocated as surplus allocation to top current priorities"%(remainingMilRating) + print "%s Round Remaining military strength allocation %d will be allocated as surplus allocation to top current priorities"%(round, remainingMilRating) newAllocations = [] for cat in ['capitol', 'topTargets', 'otherTargets', 'accessibleTargets', 'occupied', 'exploreTargets']: for sid, alloc, takeAny, maxAlloc in allocationGroups.get(cat, []): @@ -466,13 +522,18 @@ newAllocations.append( ( sid, newRating, alloc, takeAny ) ) remainingMilRating -= ( newRating - alloc ) - MilitaryAllocations = newAllocations + if "Main" in round: + MilitaryAllocations = newAllocations minMilAllocations = dict( [ (sid, alloc) for sid, alloc, takeAny, mm in allocations ] ) - print "------------------------------\nFinal Military Allocations: %s \n-----------------------"%dict( [ (sid, alloc) for sid, alloc, minalloc, takeAny in newAllocations ] ) + print "------------------------------\nFinal %s Round Military Allocations: %s \n-----------------------"%(round, dict( [ (sid, alloc) for sid, alloc, minalloc, takeAny in newAllocations ] ) ) # export military systems for other AI modules - AIstate.militarySystemIDs = [sid for sid, alloc, minalloc, takeAny in newAllocations] - + if "Main" in round: + AIstate.militarySystemIDs = list( set([sid for sid, alloc, minalloc, takeAny in newAllocations]).union( [sid for sid in alreadyAssignedRating if alreadyAssignedRating[sid]>0 ] )) + else: + AIstate.militarySystemIDs = list( set([sid for sid, alloc, minalloc, takeAny in newAllocations]).union( AIstate.militarySystemIDs) ) + return newAllocations + def getMilitaryTargetedSystemIDs(systemIDs, missionType, empireID): "return list of military targeted systems" @@ -530,91 +591,59 @@ else: return 1 + .25 * distanceFactor -def sendMilitaryFleets(militaryFleetIDs, evaluatedSystems, missionType): - "sends a list of military fleets to a list of system_value_pairs" - - if len(militaryFleetIDs)==0: return - - allMilitaryFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_MILITARY) - AIstate.militaryFleetIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allMilitaryFleetIDs) - - targets=[] - for systemID_value_pair in evaluatedSystems: # evaluatedSystems is a dictionary - targets.extend( int(systemID_value_pair[1]) *[ systemID_value_pair[0] ] ) - #currentFleetSizes= dict ( [ (fleetID, len( universe.getFleet(fleetID).shipIDs) ) for fleetID in allMilitaryFleetIDs ] ) - #newFleetSizes= dict ( [ (fleetID, len( universe.getFleet(fleetID).shipIDs) ) for fleetID in AIstate.militaryFleetIDs ] ) - - if len(targets)==0: return - - if True: - for fleetID in militaryFleetIDs: - systemID = choice( targets ) - aiTarget = AITarget.AITarget(AITargetType.TARGET_SYSTEM, systemID) - aiFleetMission = foAI.foAIstate.getAIFleetMission(fleetID) - aiFleetMission.addAITarget(missionType, aiTarget) - return - else: - - i = 0 - for systemID_value_pair in evaluatedSystems: # evaluatedSystems is a dictionary - if i >= len(militaryFleetIDs): return - - fleetID = militaryFleetIDs[i] - systemID = systemID_value_pair[0] - - aiTarget = AITarget.AITarget(AITargetType.TARGET_SYSTEM, systemID) - aiFleetMission = foAI.foAIstate.getAIFleetMission(fleetID) - aiFleetMission.addAITarget(missionType, aiTarget) - i = i + 1 - - return - -def assignMilitaryFleetsToSystems(): +def assignMilitaryFleetsToSystems(useFleetIDList=None, allocations=[]): # assign military fleets to military theater systems global MilitaryAllocations universe = fo.getUniverse() - baseDefenseIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE) - unassignedBaseDefenseIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(baseDefenseIDs) - for fleetID in unassignedBaseDefenseIDs: - fleet = universe.getFleet(fleetID) - if not fleet: - continue - sysID = fleet.systemID - aiTarget = AITarget.AITarget(AITargetType.TARGET_SYSTEM, sysID) - aiFleetMission = foAI.foAIstate.getAIFleetMission(fleetID) - aiFleetMission.clearAIFleetOrders() - aiFleetMission.clearAITargets( (aiFleetMission.getAIMissionTypes() + [-1])[0] ) - missionType = AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE - aiFleetMission.addAITarget( missionType , aiTarget) + doingMain = (useFleetIDList==None) + if doingMain: + baseDefenseIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE) + unassignedBaseDefenseIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(baseDefenseIDs) + for fleetID in unassignedBaseDefenseIDs: + fleet = universe.getFleet(fleetID) + if not fleet: + continue + sysID = fleet.systemID + aiTarget = AITarget.AITarget(AITargetType.TARGET_SYSTEM, sysID) + aiFleetMission = foAI.foAIstate.getAIFleetMission(fleetID) + aiFleetMission.clearAIFleetOrders() + aiFleetMission.clearAITargets( (aiFleetMission.getAIMissionTypes() + [-1])[0] ) + missionType = AIFleetMissionType.FLEET_MISSION_ORBITAL_DEFENSE + aiFleetMission.addAITarget( missionType , aiTarget) - allMilitaryFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_MILITARY) - if allMilitaryFleetIDs == []: - MilitaryAllocations = [] - return - #TODO: keep some continuity of missions - AIstate.militaryFleetIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allMilitaryFleetIDs) - availMilFleetIDs = list( AIstate.militaryFleetIDs ) - - #availMilFleetIDs = list( allMilitaryFleetIDs) - totMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), allMilitaryFleetIDs ) ) - availMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), availMilFleetIDs ) ) - print "==================================================" - print "assigning military fleets" - print "---------------------------------" + allMilitaryFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_MILITARY) + if allMilitaryFleetIDs == []: + MilitaryAllocations = [] + return + #TODO: keep some continuity of missions + AIstate.militaryFleetIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allMilitaryFleetIDs) + availMilFleetIDs = list( AIstate.militaryFleetIDs ) + availMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), availMilFleetIDs ) ) + theseAllocations = MilitaryAllocations + print "==================================================" + print "assigning military fleets" + print "---------------------------------" + else: + availMilFleetIDs = list( useFleetIDList ) + availMilRating = sum( map(lambda x: foAI.foAIstate.getRating(x).get('overall', 0), availMilFleetIDs ) ) + theseAllocations = allocations remainingMilRating = availMilRating # get systems to defend availMilFleetIDs = set(availMilFleetIDs) - for sysID, alloc, minalloc, takeAny in MilitaryAllocations: + for sysID, alloc, minalloc, takeAny in theseAllocations: + if not doingMain and len(availMilFleetIDs)==0: + break foundFleets = [] foundStats={} theseFleets = FleetUtilsAI.getFleetsForMission(1, {'rating':alloc}, {'rating':minalloc}, foundStats, "", systemsToCheck=[sysID], systemsChecked=[], fleetPoolSet=availMilFleetIDs, fleetList=foundFleets, verbose=False) if theseFleets == []: if foundFleets==[] or not ( FleetUtilsAI.statsMeetReqs( foundStats, {'rating':minalloc}) or takeAny): - print "NO available/suitable military allocation for system %d ( %s ) -- requested allocation %8d, found available rating %8d in fleets %s"%(sysID, universe.getSystem(sysID).name, minalloc, foundStats.get('rating', 0), foundFleets) + if doingMain: + print "NO available/suitable military allocation for system %d ( %s ) -- requested allocation %8d, found available rating %8d in fleets %s"%(sysID, universe.getSystem(sysID).name, minalloc, foundStats.get('rating', 0), foundFleets) availMilFleetIDs.update(foundFleets) continue else: @@ -622,11 +651,12 @@ #rating = sum( map(lambda x: foAI.foAIstate.rateFleet(x), foundFleets ) ) ratings = map(lambda x: foAI.foAIstate.rateFleet(x), foundFleets ) rating = sum([fr.get('attack', 0) for fr in ratings]) * sum([fr.get('health', 0) for fr in ratings]) - if rating < minMilAllocations.get(sysID, 0): - print "PARTIAL military allocation for system %d ( %s ) -- requested allocation %8d -- got %8d with fleets %s"%(sysID, universe.getSystem(sysID).name, minalloc, rating, theseFleets) - else: - print "FULL MIN military allocation for system %d ( %s ) -- requested allocation %8d -- got %8d with fleets %s "%(sysID, universe.getSystem(sysID).name, minMilAllocations.get(sysID, 0) , rating, theseFleets) - else: + if doingMain: + if rating < minMilAllocations.get(sysID, 0): + print "PARTIAL military allocation for system %d ( %s ) -- requested allocation %8d -- got %8d with fleets %s"%(sysID, universe.getSystem(sysID).name, minalloc, rating, theseFleets) + else: + print "FULL MIN military allocation for system %d ( %s ) -- requested allocation %8d -- got %8d with fleets %s "%(sysID, universe.getSystem(sysID).name, minMilAllocations.get(sysID, 0) , rating, theseFleets) + elif doingMain: print "FULL+ military allocation for system %d ( %s ) -- requested allocation %8d, got %8d with fleets %s"%(sysID, universe.getSystem(sysID).name, alloc, foundStats.get('rating', 0), theseFleets) aiTarget = AITarget.AITarget(AITargetType.TARGET_SYSTEM, sysID) for fleetID in theseFleets: @@ -640,9 +670,9 @@ else: missionType = AIFleetMissionType.FLEET_MISSION_MILITARY aiFleetMission.addAITarget( missionType , aiTarget) - print "---------------------------------" + aiFleetMission.generateAIFleetOrders() + if not doingMain: + foAI.foAIstate.misc.setdefault('ReassignedFleetMissions', []).append(aiFleetMission) -def assignMilitaryFleetsToSystems_Old(): - # assign military fleets to military theater systems - - sendMilitaryFleets(AIstate.militaryFleetIDs, AIstate.militarySystemIDs, AIFleetMissionType.FLEET_MISSION_MILITARY) + if doingMain: + print "---------------------------------" Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -1111,7 +1111,8 @@ print "Tried scrapping %s at planet %s, got result %d"%(bldName, planet.name, res) elif foAI.foAIstate.aggression>fo.aggression.typical and empire.buildingTypeAvailable(bldName) and (tPop >= 32) : if (planet.focus== EnumsAI.AIFocusType.FOCUS_GROWTH) or ("COMPUTRONIUM_SPECIAL" in planet.specials): - continue + #continue + pass # now that focus setting takes these into account, probably works ok to have conc camp queuedBldLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] if (cPop >=0.95*tPop):# and cInd < 1.5* tInd: if pid not in queuedBldLocs and bldType.canBeProduced(empire.empireID, pid):#TODO: verify that canBeProduced() checks for prexistence of a barring building Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-27 18:23:55 UTC (rev 5908) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-03-27 22:57:06 UTC (rev 5909) @@ -345,14 +345,14 @@ "SHP_WEAPON_3", "SHP_DOMESTIC_MONSTER", "SHP_ORG_HULL", - "LRN_ALGO_ELEGANCE", "GRO_SUBTER_HAB", "SHP_WEAPON_5", + "LRN_ALGO_ELEGANCE", "LRN_ARTIF_MINDS", + "SHP_WEAPON_6", "LRN_FORCE_FIELD", "PRO_ROBOTIC_PROD", "GRO_SYMBIOTIC_BIO", - "SHP_WEAPON_6", "PRO_FUSION_GEN", "DEF_DEFENSE_NET_1", "CON_ENV_ENCAPSUL", @@ -360,17 +360,19 @@ "CON_ORBITAL_CON", "PRO_ORBITAL_GEN", "GRO_GENETIC_ENG", - "GRO_XENO_GENETICS", "SPY_DETECT_2", + "PRO_INDUSTRY_CENTER_I", "SHP_WEAPON_7", + "DEF_DEFENSE_NET_2", + "GRO_XENO_GENETICS", "SHP_WEAPON_8", "PRO_SOL_ORB_GEN", - "DEF_DEFENSE_NET_2", - "PRO_INDUSTRY_CENTER_I", + "DEF_GARRISON_2", "CON_METRO_INFRA", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_1", "PRO_INDUSTRY_CENTER_II", + "SPY_DETECT_3", "GRO_LIFECYCLE_MAN", "SHP_MULTICELL_CAST", "SHP_ENDOCRINE_SYSTEMS", @@ -385,10 +387,8 @@ "DEF_SYST_DEF_MINE_1", "DEF_PLAN_BARRIER_SHLD_3", "CON_ORBITAL_HAB", - "DEF_GARRISON_2", "DEF_GARRISON_3", "SHP_WEAPON_8", - "SPY_DETECT_3", "SHP_CONT_SYMB", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", |
From: <dil...@us...> - 2013-03-29 23:07:50
|
Revision: 5911 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5911&view=rev Author: dilvish-fo Date: 2013-03-29 23:07:43 +0000 (Fri, 29 Mar 2013) Log Message: ----------- AI tweaks Modified Paths: -------------- trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ResourcesAI.py Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-29 20:58:45 UTC (rev 5910) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-03-29 23:07:43 UTC (rev 5911) @@ -23,12 +23,14 @@ def calculatePriorities(): "calculates the priorities of the AI player" print("calculating priorities") + foAI.foAIstate.setPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_PRODUCTION, 50) # let this one stay fixed & just adjust Research foAI.foAIstate.setPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_RESEARCH, calculateResearchPriority()) ColonisationAI.getColonyFleets() # sets foAI.foAIstate.colonisablePlanetIDs and foAI.foAIstate.outpostPlanetIDs and many other values used by other modules InvasionAI.getInvasionFleets() # sets AIstate.invasionFleetIDs, AIstate.opponentPlanetIDs, and AIstate.invasionTargetedPlanetIDs MilitaryAI.getMilitaryFleets() # sets AIstate.militaryFleetIDs and AIstate.militaryTargetedSystemIDs + + calculateIndustryPriority()#purely for reporting purposes - foAI.foAIstate.setPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_PRODUCTION, calculateIndustryPriority()) foAI.foAIstate.setPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_TRADE, 0) foAI.foAIstate.setPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_CONSTRUCTION, 0) @@ -75,7 +77,7 @@ return foodPriority -def calculateIndustryPriority(): +def calculateIndustryPriority(): #currently only used to print status "calculates the demand for industry" universe = fo.getUniverse() @@ -87,24 +89,8 @@ planets = map(universe.getPlanet, ownedPlanetIDs) targetPP = sum( map( lambda x: x.currentMeterValue(fo.meterType.targetIndustry), planets) ) - if fo.currentTurn() < 30: - industryPriority = 20 # mid industry , high research at beginning of game to get easy gro tech - elif fo.currentTurn() < 45: - industryPriority = 25 # mid industry , mid research - elif fo.currentTurn() < 60: - industryPriority = 30 # high industry , mid research - elif fo.currentTurn() < 100: - industryPriority = 50 # high industry , mid research - else: - industryPriority = 60 # high industry , low-mid research + industryPriority = foAI.foAIstate.getPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_PRODUCTION) - - industryPriority = 50 # try a flat number, adjust research - - - # increase demand for industry industry production is low - #industryPriority = 380 / (industryProduction + 0.001) - print "" print "Industry Production (current/target) : ( %.1f / %.1f ) at turn %s"%(industryProduction, targetPP, fo.currentTurn()) print "Priority for Industry: " + str(industryPriority) @@ -117,6 +103,9 @@ universe = fo.getUniverse() empire = fo.getEmpire() empireID = empire.empireID + + industryPriority = foAI.foAIstate.getPriority(EnumsAI.AIPriorityType.PRIORITY_RESOURCE_PRODUCTION) + gotAlgo = empire.getTechStatus("LRN_ALGO_ELEGANCE") == fo.techStatus.complete researchQueueList = ResearchAI.getResearchQueueTechs() orbGenTech = "PRO_ORBITAL_GEN" @@ -130,34 +119,32 @@ targetRP = sum( map( lambda x: x.currentMeterValue(fo.meterType.targetResearch), planets) ) styleIndex = empireID%2 - styleAdjustmentMap = {0:0, 1:0}#TODO: decide if I want to do anything with this - styleAdjustment = styleAdjustmentMap.get( styleIndex, 0 ) cutoffSets = [ [25, 45, 70 ], [35, 50, 70 ] ] cutoffs = cutoffSets[styleIndex ] - settings = [ [100, 40, 35, 30 ], [70, 40, 30, 25 ] ][styleIndex ] + settings = [ [2, .6, .4, .35 ], [1.4, .7, .4, .35 ] ][styleIndex ] if industrySurge and True: - researchPriority = 15+styleAdjustment + researchPriority = 0.2 * industryPriority else: if (fo.currentTurn() < cutoffs[0]) or not gotAlgo: - researchPriority = settings[0] # mid industry , high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance + researchPriority = settings[0] * industryPriority # high research at beginning of game to get easy gro tech and to get research booster Algotrithmic Elegance elif fo.currentTurn() < cutoffs[1]: - researchPriority = settings[1] +styleAdjustment# mid industry , mid research + researchPriority = settings[1] * industryPriority# med-high research elif fo.currentTurn() < cutoffs[2]: - researchPriority = settings[2]+styleAdjustment # high industry , low research + researchPriority = settings[2] * industryPriority # med-high industry else: researchQueue = list(empire.researchQueue) - researchPriority = settings[3]+styleAdjustment # high industry , low research + researchPriority = settings[3] * industryPriority # high industry , low research if len(researchQueue) == 0 : researchPriority = 0 # done with research elif len(researchQueue) <5 and researchQueue[-1].allocation > 0 : researchPriority = len(researchQueue) # barely not done with research elif len(researchQueue) <10 and researchQueue[-1].allocation > 0 : - researchPriority = 2 # almost done with research + researchPriority = 4+ len(researchQueue) # almost done with research elif len(researchQueue) <20 and researchQueue[int(len(researchQueue)/2)].allocation > 0 : - researchPriority = 5 # closing in on end of research + researchPriority = 0.5 * researchPriority # closing in on end of research elif len(researchQueue) <20: - researchPriority = 10 # high industry , low research + researchPriority = 0.7*researchPriority # high industry , low research print "" print "Research Production (current/target) : ( %.1f / %.1f )"%(totalRP, targetRP) Modified: trunk/FreeOrion/default/AI/ResourcesAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-29 20:58:45 UTC (rev 5910) +++ trunk/FreeOrion/default/AI/ResourcesAI.py 2013-03-29 23:07:43 UTC (rev 5911) @@ -257,9 +257,9 @@ II, IR = newTargets[pid][IFocus] RI, RR = newTargets[pid][RFocus] CI, CR = currentOutput[pid][ IFocus], currentOutput[pid][ RFocus] - #consider straddling balance range within which 1RP costs 1PP + #if AI is aggressive+, and this planet in range where temporary Research focus can get an additional RP at cost of 1 PP, and still need some RP, then do it if True and (foAI.foAIstate.aggression >= fo.aggression.aggressive): - if (CR<RR) and ( (CR-IR) >= (II-CI) ) and (priorityRatio > ( (curTargetRP+CR+1)/ max(0.001, curTargetPP +CI -1))): + if (CR<RR) and ( (CR-IR) >= (II-CI) ) and (priorityRatio > 0.8* ( (CR+1)/ max(0.001, CI -1))): curTargetPP += CI -1 # curTargetRP += CR+1 newFoci[pid] = RFocus @@ -274,9 +274,6 @@ # RR += min( 2, RR/4.0 ) #calculate factor F at which II + F * RI == RI + F * RR =====> F = ( II-RI ) / (RR-IR) thisFactor = ( II-RI ) / max( 0.01, RR-IR) # don't let denominator be zero for planets where focus doesn't change RP - if foAI.foAIstate.aggression >fo.aggression.aggressive: - if currentOutput[pid][ IFocus] > II +RI - RR: - thisFactor = min(thisFactor, 1.0 + thisFactor/10.0 ) ratios.append( (thisFactor, pid ) ) ctPP0 = curTargetPP |
From: <dil...@us...> - 2013-03-31 16:48:46
|
Revision: 5928 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5928&view=rev Author: dilvish-fo Date: 2013-03-31 16:48:36 +0000 (Sun, 31 Mar 2013) Log Message: ----------- adjustments to AI colonization, outpost and invasion planning Modified Paths: -------------- trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/InvasionAI.py Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-31 15:32:29 UTC (rev 5927) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-03-31 16:48:36 UTC (rev 5928) @@ -293,7 +293,6 @@ # print "Evaluated Outpost PlanetIDs: " + str(evaluatedOutpostPlanetIDs) evaluatedColonyPlanets = assignColonisationValues(evaluatedColonyPlanetIDs, AIFleetMissionType.FLEET_MISSION_COLONISATION, fleetSupplyablePlanetIDs, species, empire) - #removeLowValuePlanets(evaluatedColonyPlanets) sortedPlanets = evaluatedColonyPlanets.items() sortedPlanets.sort(lambda x, y: cmp(x[1], y[1]), reverse=True) @@ -304,15 +303,16 @@ print " %15s | %5s | %s | %s "%(score, ID, universe.getPlanet(ID).name , list(universe.getPlanet(ID).specials)) print "" + sortedPlanets = [(ID, score) for ID, score in sortedPlanets if score[0] > 0] # export planets for other AI modules - foAI.foAIstate.colonisablePlanetIDs = sortedPlanets#TODO: should include species designation corresponding to rating + foAI.foAIstate.colonisablePlanetIDs = sortedPlanets # get outpost fleets allOutpostFleetIDs = FleetUtilsAI.getEmpireFleetIDsByRole(AIFleetMissionType.FLEET_MISSION_OUTPOST) AIstate.outpostFleetIDs = FleetUtilsAI.extractFleetIDsWithoutMissionTypes(allOutpostFleetIDs) evaluatedOutpostPlanets = assignColonisationValues(evaluatedOutpostPlanetIDs, AIFleetMissionType.FLEET_MISSION_OUTPOST, fleetSupplyablePlanetIDs, species, empire) - removeLowValuePlanets(evaluatedOutpostPlanets) #bad! lol, was preventing all mining outposts + #removeLowValuePlanets(evaluatedOutpostPlanets) sortedOutposts = evaluatedOutpostPlanets.items() sortedOutposts.sort(lambda x, y: cmp(x[1], y[1]), reverse=True) @@ -322,6 +322,7 @@ print " %5s | %5s | %s | %s "%(score, ID, universe.getPlanet(ID).name , list(universe.getPlanet(ID).specials)) print "" + sortedOutposts = [(ID, score) for ID, score in sortedOutposts if score[0] > 0] # export outposts for other AI modules foAI.foAIstate.colonisableOutpostIDs = sortedOutposts @@ -686,15 +687,17 @@ researchBonus += discountMultiplier*2*10 #TODO: do actual calc detail.append("COMPUTRONIUM_SPECIAL") - retval=0.0 - if popSize > 0: - retval = starBonus+max(indVal+asteroidBonus+gasGiantBonus, researchBonus, growthVal)+fixedInd + fixedRes - if planet.systemID in annexableRing1: - retval += 10 - elif planet.systemID in annexableRing2: - retval += 20 - elif planet.systemID in annexableRing3: - retval += 10 + if popSize <= 0: + detail.append("Non-positive population projection for species '%s', so no colonization value"%(species and species.name)) + return 0 + + retval += max(indVal+asteroidBonus+gasGiantBonus, researchBonus, growthVal)+fixedInd + fixedRes + if planet.systemID in annexableRing1: + retval += 10 + elif planet.systemID in annexableRing2: + retval += 20 + elif planet.systemID in annexableRing3: + retval += 10 retval *= priorityScaling thrtRatio = (foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('fleetThreat', 0)+foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('monsterThreat', 0)+0.2*foAI.foAIstate.systemStatus.get(planet.systemID, {}).get('neighborThreat', 0)) / float(curBestMilShipRating) Modified: trunk/FreeOrion/default/AI/InvasionAI.py =================================================================== --- trunk/FreeOrion/default/AI/InvasionAI.py 2013-03-31 15:32:29 UTC (rev 5927) +++ trunk/FreeOrion/default/AI/InvasionAI.py 2013-03-31 16:48:36 UTC (rev 5928) @@ -9,7 +9,11 @@ import math import ProductionAI import ColonisationAI +import MilitaryAI +def dictFromMap(map): + return dict( [ (el.key(), el.data() ) for el in map ] ) + def getInvasionFleets(): "get invasion fleets" @@ -99,6 +103,7 @@ else: print "No Invadable planets identified" + sortedPlanets = [(pid, pscore, ptroops) for (pid, pscore, ptroops) in sortedPlanets if pscore > 0] # export opponent planets for other AI modules AIstate.opponentPlanetIDs = [pid for pid, pscore, trp in sortedPlanets] AIstate.invasionTargets = sortedPlanets @@ -168,10 +173,16 @@ print "invasion AI couldn't get current info on planet %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: + 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:#TODO: probably stealth makes planet inacccesible & should abort - return 0, 0 + if not species: + popVal = ColonisationAI.evaluatePlanet(planetID, EnumsAI.AIFleetMissionType.FLEET_MISSION_OUTPOST, [planetID], species, empire, detail) #evaluatePlanet is imported from ColonisationAI else: popVal = ColonisationAI.evaluatePlanet(planetID, EnumsAI.AIFleetMissionType.FLEET_MISSION_COLONISATION, [planetID], species, empire, detail) #evaluatePlanet is imported from ColonisationAI @@ -200,6 +211,8 @@ pmaxShield = planet.currentMeterValue(fo.meterType.maxShield) sysFThrt = foAI.foAIstate.systemStatus.get(pSysID, {}).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 print "invasion eval of %s %d --- maxShields %.1f -- sysFleetThreat %.1f -- sysMonsterThreat %.1f"%(planet.name, planetID, pmaxShield, sysFThrt, sysMThrt) supplyVal=0 enemyVal=0 @@ -216,13 +229,14 @@ supplyVal = 20 else: supplyVal *= int( min(1, ProductionAI.curBestMilShipRating() / sysFThrt ) ) + threatFactor = min(1, 0.2*MilitaryAI.totMilRating/(sysTotThrt+0.001))**2 #devalue invasions that would require too much military force buildTime=4 plannedTroops = min(troops+maxJumps+buildTime, maxTroops) if ( empire.getTechStatus("SHP_ORG_HULL") != fo.techStatus.complete ): troopCost = math.ceil( plannedTroops/6.0) * ( 40*( 1+foAI.foAIstate.shipCount * AIDependencies.shipUpkeep ) ) else: troopCost = math.ceil( plannedTroops/6.0) * ( 20*( 1+foAI.foAIstate.shipCount * AIDependencies.shipUpkeep ) ) - invscore = max(0, popVal+supplyVal+bldTally+enemyVal-0.8*troopCost), plannedTroops + invscore = threatFactor*max(0, popVal+supplyVal+bldTally+enemyVal-0.8*troopCost), plannedTroops print invscore, "projected Troop Cost:", troopCost, "planet detail ", detail, popVal, supplyVal, bldTally, enemyVal return invscore |
From: <dil...@us...> - 2013-04-10 04:59:08
|
Revision: 5973 http://freeorion.svn.sourceforge.net/freeorion/revision/?rev=5973&view=rev Author: dilvish-fo Date: 2013-04-10 04:59:00 +0000 (Wed, 10 Apr 2013) Log Message: ----------- misc AI adjustments, including use of Scanning Facilities Modified Paths: -------------- trunk/FreeOrion/default/AI/AIstate.py trunk/FreeOrion/default/AI/ColonisationAI.py trunk/FreeOrion/default/AI/FleetUtilsAI.py trunk/FreeOrion/default/AI/MilitaryAI.py trunk/FreeOrion/default/AI/PriorityAI.py trunk/FreeOrion/default/AI/ProductionAI.py trunk/FreeOrion/default/AI/ResearchAI.py trunk/FreeOrion/default/AI/TechsListsAI.py Modified: trunk/FreeOrion/default/AI/AIstate.py =================================================================== --- trunk/FreeOrion/default/AI/AIstate.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/AIstate.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -13,8 +13,9 @@ ##moving ALL or NEARLY ALL 'global' variables into AIState object rather than module +##in general, leaving items as a module attribute if they are recalculated each turn without reference to prior values # global variables -foodStockpileSize = 1 # food stored per population +#foodStockpileSize = 1 # food stored per population minimalColoniseValue = 3 # minimal value for a planet to be colonised #colonisablePlanetIDs = [] # moved into AIstate colonyTargetedSystemIDs = [] @@ -53,24 +54,11 @@ def __init__(self, aggression=fo.aggression.typical): "constructor" # 'global' (?) variables - self.foodStockpileSize = 1 # food stored per population + #self.foodStockpileSize = 1 # food stored per population self.minimalColoniseValue = 3 # minimal value for a planet to be colonised self.colonisablePlanetIDs = [] - self.colonyTargetedSystemIDs = [] self.colonisableOutpostIDs = [] # - self.outpostTargetedSystemIDs = [] - self.opponentPlanetIDs = [] - self.opponentSystemIDs=[] - self.invasionTargetedSystemIDs = [] - self.militarySystemIDs = [] - self.militaryTargetedSystemIDs = [] - self.colonyFleetIDs = [] - self.outpostFleetIDs = [] - self.invasionFleetIDs = [] - self.militaryFleetIDs = [] - self.untaskedFleets=[] self.__aiMissionsByFleetID = {} - self.__shipRoleByDesignID = {} self.__fleetRoleByID = {} self.__designStats={} @@ -108,21 +96,9 @@ del self.__shipRoleByDesignID del self.__fleetRoleByID del self.__priorityByType - #del self.__explorableSystemByType del self.__aiMissionsByFleetID del self.colonisablePlanetIDs - del self.colonyTargetedSystemIDs del self.colonisableOutpostIDs - del self.outpostTargetedSystemIDs - del self.opponentPlanetIDs - del self.opponentSystemIDs - del self.invasionTargetedSystemIDs - del self.militarySystemIDs - del self.militaryTargetedSystemIDs - del self.colonyFleetIDs - del self.outpostFleetIDs - del self.invasionFleetIDs - del self.militaryFleetIDs del self.needsEmergencyExploration del self.newlySplitFleets del self.misc @@ -133,7 +109,7 @@ fleetsLostBySystem.clear() fleetsLostByID.clear() - invasionTargets=[] + invasionTargets[:]=[] ExplorationAI.graphFlags.clear() print "-------------------------------------------------" @@ -220,9 +196,10 @@ tDefense = planet.currentMeterValue(fo.meterType.maxDefense) shields = min(tShields, cShields+2*sightingAge)#TODO: base off regen tech defense = min(tDefense, cDefense+2*sightingAge)#TODO: base off regen tech - cInfra = planet.currentMeterValue(fo.meterType.construction) - tInfra = planet.currentMeterValue(fo.meterType.targetConstruction) - infra = min(tInfra, cInfra+sightingAge) + #cInfra = planet.currentMeterValue(fo.meterType.construction) + #tInfra = planet.currentMeterValue(fo.meterType.targetConstruction) + #infra = min(tInfra, cInfra+sightingAge) + infra=0 #doesn't really contribute to combat since damage to shields & 'defense' done first return {'overall': defense*(defense + shields + infra ), 'attack':defense , 'health':(defense + shields + infra ) } def updateSystemStatus(self, sysIDList=None): Modified: trunk/FreeOrion/default/AI/ColonisationAI.py =================================================================== --- trunk/FreeOrion/default/AI/ColonisationAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/ColonisationAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -780,8 +780,11 @@ continue thisSpec=thisTarget[1][1] foundFleets=[] - thisFleetList = FleetUtilsAI.getFleetsForMission(nships=1, targetStats={}, minStats={}, curStats={}, species=thisSpec, systemsToCheck=[thisSysID], systemsChecked=[], - fleetPoolSet = fleetPool, fleetList=foundFleets, triedFleets=set([]), verbose=False) + try: + thisFleetList = FleetUtilsAI.getFleetsForMission(nships=1, targetStats={}, minStats={}, curStats={}, species=thisSpec, systemsToCheck=[thisSysID], systemsChecked=[], + fleetPoolSet = fleetPool, fleetList=foundFleets, triedFleets=set([]), verbose=False) + except: + continue if thisFleetList==[]: fleetPool.update(foundFleets)#just to be safe continue #must have no compatible colony/outpost ships Modified: trunk/FreeOrion/default/AI/FleetUtilsAI.py =================================================================== --- trunk/FreeOrion/default/AI/FleetUtilsAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/FleetUtilsAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -42,7 +42,7 @@ return tally def getFleetsForMission(nships, targetStats, minStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList, - takeAny=False, extendSearch=True, triedFleets=set([]), verbose=False): #implements breadth-first search through systems + takeAny=False, extendSearch=True, triedFleets=set([]), verbose=False, depth=0): #implements breadth-first search through systems if verbose: print "getFleetsForMission: (nships:%1d, targetStats:%s, minStats:%s, curStats:%s, species:%6s, systemsToCheck:%8s, systemsChecked:%8s, fleetPoolSet:%8s, fleetList:%8s) "%( nships, targetStats, minStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList) @@ -105,9 +105,20 @@ if extendSearch: thisSys = universe.getSystem(thisSystemID) for neighborID in [el.key() for el in universe.getSystemNeighborsMap(thisSystemID, foAI.foAIstate.empireID) ]: - if neighborID not in systemsChecked and neighborID in foAI.foAIstate.exploredSystemIDs: + if neighborID not in systemsChecked and neighborID not in systemsToCheck and neighborID in foAI.foAIstate.exploredSystemIDs: systemsToCheck.append(neighborID) - return getFleetsForMission(nships, targetStats, minStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList, takeAny, extendSearch, verbose) + try: + resList = getFleetsForMission(nships, targetStats, minStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList, takeAny, extendSearch, verbose, depth=depth+1) + return resList + except: + s1=len(systemsToCheck) + s2=len(systemsChecked) + s3=len(set( systemsToCheck + systemsChecked ) ) + print "Error: exception triggered in 'getFleetsForMissions' and caught at depth %d w/s1/s2/s3 (%d/%d/%d): "%(depth+2, s1, s2, s3), traceback.format_exc() + #print ("Error: call parameters were targetStats: %s, curStats: %s, species: '%s', systemsToCheck: %s, systemsChecked: %s, fleetPoolSet: %s, fleetList: %s"%( + # targetStats, curStats, species, systemsToCheck, systemsChecked, fleetPoolSet, fleetList)) + return [] +import traceback def splitFleet(fleetID): "splits a fleet into its ships" Modified: trunk/FreeOrion/default/AI/MilitaryAI.py =================================================================== --- trunk/FreeOrion/default/AI/MilitaryAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/MilitaryAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -638,8 +638,11 @@ break foundFleets = [] foundStats={} - theseFleets = FleetUtilsAI.getFleetsForMission(1, {'rating':alloc}, {'rating':minalloc}, foundStats, "", systemsToCheck=[sysID], systemsChecked=[], - fleetPoolSet=availMilFleetIDs, fleetList=foundFleets, verbose=False) + try: + theseFleets = FleetUtilsAI.getFleetsForMission(1, {'rating':alloc}, {'rating':minalloc}, foundStats, "", systemsToCheck=[sysID], systemsChecked=[], + fleetPoolSet=availMilFleetIDs, fleetList=foundFleets, verbose=False) + except: + continue if theseFleets == []: if foundFleets==[] or not ( FleetUtilsAI.statsMeetReqs( foundStats, {'rating':minalloc}) or takeAny): if doingMain: Modified: trunk/FreeOrion/default/AI/PriorityAI.py =================================================================== --- trunk/FreeOrion/default/AI/PriorityAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/PriorityAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -59,7 +59,8 @@ empire = fo.getEmpire() foodProduction = empire.resourceProduction(fo.resourceType.food) foodStockpile = empire.resourceStockpile(fo.resourceType.food) - foodTarget = 10 * empire.population() * AIstate.foodStockpileSize + #foodTarget = 10 * empire.population() * AIstate.foodStockpileSize + foodTarget=0 if (foodTarget == 0): return 0 Modified: trunk/FreeOrion/default/AI/ProductionAI.py =================================================================== --- trunk/FreeOrion/default/AI/ProductionAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/ProductionAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -28,6 +28,8 @@ } +doDoubleShields=False + #get key routines declared for import by others before completing present imports, to avoid circularity problems def curBestMilShipRating(): if (fo.currentTurn()+1) in bestMilRatingsHistory: @@ -327,28 +329,36 @@ ar1 = "AR_LEAD_PLATE" ar2= "AR_ZORTRIUM_PLATE" ar3= "AR_NEUTRONIUM_PLATE" + + if foAI.foAIstate.aggression in [fo.aggression.beginner, fo.aggression.turtle]: + maxEM= 8 + elif foAI.foAIstate.aggression ==fo.aggression.cautious: + maxEM= 12 + else: + maxEM= 10 + nb, hull = designNameBases[1]+"-%1d", "SH_BASIC_MEDIUM" newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, ""], "", model) for iw in range(1, 8) ] #newMarkDesigns += [ ((nb%iw)+'N', desc, hull, [ srb%iw, ar3, ""], "", model) for iw in range(1, 8) ] nb, hull = designNameBases[2]+"-1-%1d", "SH_ORGANIC" - newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is1], "", model) for iw in range(2, 9) ] - nb, hull = designNameBases[2]+"-2-%1d", "SH_STATIC_MULTICELLULAR" + newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is1], "", model) for iw in range(3, 9) ] + nb, hull = designNameBases[2]+"-3-%1d", "SH_STATIC_MULTICELLULAR" newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is1, is2], "", model) for iw in range(6, 9) ] + + if doDoubleShields or (empire.empireID%2 == 0) : + nb, hull = designNameBases[2]+"-2-%1x", "SH_ORGANIC" + newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, is2, is2], "", model) for iw in range(5, maxEM+1) ] + nb, hull = designNameBases[2]+"-4-%1d", "SH_STATIC_MULTICELLULAR" + newMarkDesigns += [ (nb%iw, desc, hull, [ srb%iw, srb%iw, srb%iw, is2, is2], "", model) for iw in range(6, maxEM+1) ] + - if foAI.foAIstate.aggression in [fo.aggression.beginner, fo.aggression.turtle]: - maxEM= 8 - elif foAI.foAIstate.aggression ==fo.aggression.cautious: - maxEM= 12 - else: - maxEM= 10 - nb, hull = designNameBases[3]+"-1-%1x", "SH_ENDOMORPHIC" newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + 2*[ is1], "", model) for iw in [5, 6, 7 ] ] nb = designNameBases[3]+"-2-%1x" - newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + [ is2, is2], "", model) for iw in range(6, maxEM+1) ] + newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw] + [ is2, is2, is2], "", model) for iw in range(6, maxEM+1) ] nb = designNameBases[3]+"3-%1x" #newMarkDesigns += [ (nb%iw, desc, hull, 2*[srb%iw]+[ar1] + [ is1, is1], "", model) for iw in [5, 6, 7, 8, 10, 11, 12 ] ] @@ -366,7 +376,7 @@ newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw] +[ar3]+ 2*[ is2], "", model) for iw in range(8, maxEM+1) ] nb = designNameBases[3]+"-7-%1x" - newMarkDesigns += [ (nb%iw, desc, hull, 4*[srb%iw] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] + newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw] + [ is3, is3, is3], "", model) for iw in range(8, maxEM+1) ] nb = designNameBases[3]+"-8-%1x" newMarkDesigns += [ (nb%iw, desc, hull, 3*[srb%iw]+[ar2] + [ is3, is3], "", model) for iw in range(8, maxEM+1) ] @@ -376,8 +386,8 @@ if foAI.foAIstate.aggression >=fo.aggression.typical: nb, hull = designNameBases[4]+"-%1x-%1x", "SH_ENDOSYMBIOTIC" - newMarkDesigns += [ (nb%(1, iw), desc, hull, 4*[srb%iw] + 3*[ is2], "", model) for iw in range(7, 14) ] - newMarkDesigns += [ (nb%(2, iw), desc, hull, 4*[srb%iw] + 3*[ is3], "", model) for iw in range(7, 14) ] + newMarkDesigns += [ (nb%(1, iw), desc, hull, 4*[srb%iw] + 3*[ is2], "", model) for iw in range(7, 15) ] + newMarkDesigns += [ (nb%(2, iw), desc, hull, 4*[srb%iw] + 3*[ is3], "", model) for iw in range(7, 15) ] newMarkDesigns += [ (nb%(3, iw), desc, hull, 3*[srb%iw]+[ar2] + 3*[ is2], "", model) for iw in range(7, 14) ] newMarkDesigns += [ (nb%(4, iw), desc, hull, 3*[srb%iw]+[ar3] + 3*[ is2], "", model) for iw in range(8, 14) ] @@ -704,7 +714,12 @@ print "Orbital Defense Check -- target Defense Orbitals: ", targetOrbitals for element in productionQueue: if ( element.buildType == EnumsAI.AIEmpireProductionTypes.BT_SHIP) and (foAI.foAIstate.getShipRole(element.designID) == EnumsAI.AIShipRoleType.SHIP_ROLE_BASE_DEFENSE): - queuedDefenses[element.locationID] = queuedDefenses.get( element.locationID, 0) + element.blocksize*element.remaining + bldPlanet = universe.getPlanet(element.locationID) + if not bldPlanet: + print "Error: Problem getting Planet for build loc %s"%element.locationID + continue + sysID = bldPlanet.systemID + queuedDefenses[sysID] = queuedDefenses.get( sysID, 0) + element.blocksize*element.remaining defenseAllocation += element.allocation print "Queued Defenses:", [( PlanetUtilsAI.sysNameIDs([sysID]), num) for sysID, num in queuedDefenses.items()] for sysID in ColonisationAI.empireSpeciesSystems: @@ -1124,6 +1139,45 @@ queuedBldLocs.append(pid) res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + bldName = "BLD_SCANNING_FACILITY" + if empire.buildingTypeAvailable(bldName): + bldType = fo.getBuildingType(bldName) + queuedLocs = [element.locationID for element in productionQueue if (element.name==bldName) ] + scannerLocs={} + for pid in list(AIstate.popCtrIDs) + list(AIstate.outpostIDs): + planet=universe.getPlanet(pid) + if planet: + if ( pid in queuedLocs ) or ( bldName in [bld.buildingTypeName for bld in map( universe.getObject, planet.buildingIDs)] ): + scannerLocs[planet.systemID] = True + maxScannerBuilds = max(1, int(empire.productionPoints/30)) + for sysID in AIstate.colonizedSystems: + if len(queuedLocs)>= maxScannerBuilds: + break + if sysID in scannerLocs: + continue + needScanner=False + for nSys in AIstate.dictFromMap( universe.getSystemNeighborsMap(sysID, empire.empireID) ): + if (universe.getVisibility(nSys, empire.empireID) < fo.visibility.partial): + needScanner=True + break + if not needScanner: + continue + buildLocs=[] + for pid in AIstate.colonizedSystems[sysID]: + planet=universe.getPlanet(pid) + if not planet: continue + buildLocs.append( (planet.currentMeterValue(fo.meterType.maxTroops), pid) ) + if not buildLocs: continue + for troops, loc in sorted( buildLocs ): + planet = universe.getPlanet(loc) + res=fo.issueEnqueueBuildingProductionOrder(bldName, loc) + print "Enqueueing %s at planet %d (%s) , with result %d"%(bldName, loc, planet.name, res) + if res: + res=fo.issueRequeueProductionOrder(productionQueue.size -1, 0) # move to front + print "Requeueing %s to front of build queue, with result %d"%(bldName, res) + queuedLocs.append( planet.systemID ) + break + bldName = "BLD_EVACUATION" bldType = fo.getBuildingType(bldName) for pid in AIstate.popCtrIDs: Modified: trunk/FreeOrion/default/AI/ResearchAI.py =================================================================== --- trunk/FreeOrion/default/AI/ResearchAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/ResearchAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -12,6 +12,7 @@ def generateResearchOrders(): global inProgressTechs "generate research orders" + universe=fo.getUniverse() empire = fo.getEmpire() empireID = empire.empireID @@ -102,7 +103,7 @@ else: print " %25s allocated %6.2f RP -- missing preReqs: %s -- unlockable items: %s "%(element.tech, element.allocation, missingPrereqs, unlockedItems) print "" - if fo.currentTurn()==1: + if (fo.currentTurn()==1) or ((fo.currentTurn()<5) and (len(researchQueueList)==0) ): if foAI.foAIstate.aggression <=fo.aggression.typical: newtech = TechsListsAI.primaryMetaTechsList( index=empireID%2 ) else: @@ -172,7 +173,7 @@ generateDefaultResearchOrders() #researchQueueList = getResearchQueueTechs() - if len (AIstate.empireStars.get(fo.starType.blackHole, []))!=0 and foAI.foAIstate.aggression > fo.aggression.cautious: + if fo.currentTurn() >50 and len (AIstate.empireStars.get(fo.starType.blackHole, []))!=0 and foAI.foAIstate.aggression > fo.aggression.cautious: for singTech in [ "CON_ARCH_PSYCH", "CON_CONC_CAMP", "LRN_GRAVITONICS" , "PRO_SINGULAR_GEN"]: if (empire.getTechStatus(singTech) != fo.techStatus.complete) and ( singTech not in researchQueueList[:4]) : res=fo.issueEnqueueTechOrder(singTech,0) Modified: trunk/FreeOrion/default/AI/TechsListsAI.py =================================================================== --- trunk/FreeOrion/default/AI/TechsListsAI.py 2013-04-09 07:58:26 UTC (rev 5972) +++ trunk/FreeOrion/default/AI/TechsListsAI.py 2013-04-10 04:59:00 UTC (rev 5973) @@ -232,7 +232,7 @@ def primaryMetaTechsList(index=0): "primary techs for all categories" #index=1-index - index=0 + #index=0 if index == 0: primaryMetaTechs = [ "SHP_WEAPON_2", @@ -244,26 +244,27 @@ "SHP_WEAPON_5", "LRN_ALGO_ELEGANCE", "LRN_ARTIF_MINDS", - "SHP_WEAPON_6", - "LRN_FORCE_FIELD", "PRO_ROBOTIC_PROD", - "GRO_SYMBIOTIC_BIO", - "PRO_FUSION_GEN", + "SHP_WEAPON_6", "DEF_DEFENSE_NET_1", + "PRO_FUSION_GEN", "CON_ENV_ENCAPSUL", - "DEF_GARRISON_1", + "LRN_FORCE_FIELD", "CON_ORBITAL_CON", "PRO_ORBITAL_GEN", + "GRO_SYMBIOTIC_BIO", + "DEF_GARRISON_1", "GRO_GENETIC_ENG", "GRO_XENO_GENETICS", "SPY_DETECT_2", "SHP_WEAPON_7", - "PRO_SOL_ORB_GEN", - "DEF_DEFENSE_NET_2", "PRO_INDUSTRY_CENTER_I", + "DEF_DEFENSE_NET_2", + "PRO_SOL_ORB_GEN", "SHP_WEAPON_9", "DEF_GARRISON_2", "CON_METRO_INFRA", + "LRN_QUANT_NET", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_1", "SHP_WEAPON_10", @@ -293,7 +294,6 @@ "PRO_MICROGRAV_MAN", "SHP_LEAD_PLATE", "GRO_XENO_HYBRIDS", - "LRN_QUANT_NET", "SHP_ZORTRIUM_PLATE", "SHP_WEAPON_13", "LRN_TIME_MECH", @@ -347,30 +347,32 @@ "SHP_WEAPON_5", "LRN_ALGO_ELEGANCE", "LRN_ARTIF_MINDS", + "PRO_ROBOTIC_PROD", "SHP_WEAPON_6", "LRN_FORCE_FIELD", - "PRO_ROBOTIC_PROD", - "GRO_SYMBIOTIC_BIO", "PRO_FUSION_GEN", "DEF_DEFENSE_NET_1", "CON_ENV_ENCAPSUL", - "DEF_GARRISON_1", "CON_ORBITAL_CON", "PRO_ORBITAL_GEN", + "GRO_SYMBIOTIC_BIO", + "DEF_GARRISON_1", "GRO_GENETIC_ENG", + "GRO_XENO_GENETICS", "SPY_DETECT_2", - "PRO_INDUSTRY_CENTER_I", "SHP_WEAPON_7", - "DEF_DEFENSE_NET_2", - "GRO_XENO_GENETICS", - "SHP_WEAPON_8", "PRO_SOL_ORB_GEN", + "DEF_DEFENSE_NET_2", + "PRO_INDUSTRY_CENTER_I", + "SHP_WEAPON_9", "DEF_GARRISON_2", "CON_METRO_INFRA", "DEF_DEFENSE_NET_REGEN_1", "DEF_PLAN_BARRIER_SHLD_1", + "SHP_WEAPON_10", "PRO_INDUSTRY_CENTER_II", "SPY_DETECT_3", + "SHP_WEAPON_11", "GRO_LIFECYCLE_MAN", "SHP_MULTICELL_CAST", "SHP_ENDOCRINE_SYSTEMS", @@ -386,18 +388,21 @@ "DEF_PLAN_BARRIER_SHLD_3", "CON_ORBITAL_HAB", "DEF_GARRISON_3", - "SHP_WEAPON_8", "SHP_CONT_SYMB", "SHP_MONOCELL_EXP", "SHP_ENDOSYMB_HULL", "PRO_SINGULAR_GEN", "LRN_XENOARCH", - "SHP_WEAPON_9", "PRO_MICROGRAV_MAN", + "SHP_LEAD_PLATE", "GRO_XENO_HYBRIDS", "LRN_QUANT_NET", + "SHP_ZORTRIUM_PLATE", + "SHP_WEAPON_13", "LRN_TIME_MECH", "LRN_STELLAR_TOMOGRAPHY", + "SHP_WEAPON_14", + "SPY_DETECT_4", "PRO_NEUTRONIUM_EXTRACTION", "LRN_ENCLAVE_VOID", "LRN_PSY_DOM", @@ -405,20 +410,18 @@ "SHP_ASTEROID_HULLS", "GRO_TERRAFORM", "GRO_GENETIC_MED", - "SHP_LEAD_PLATE", "SHP_BIOADAPTIVE_SPEC", "SHP_INTSTEL_LOG", "SHP_REINFORCED_HULL", - "SHP_WEAPON_10", "SHP_CONT_BIOADAPT", "SHP_SENT_HULL", - "SHP_ZORTRIUM_PLATE", "DEF_SYST_DEF_MINE_2", "GRO_CYBORG", "SHP_BASIC_DAM_CONT", "CON_CONC_CAMP", "SHP_ADV_DAM_CONT", "PRO_INDUSTRY_CENTER_III", + "SHP_WEAPON_15", "DEF_GARRISON_4", "SPY_STEALTH_1", "DEF_DEFENSE_NET_REGEN_2", @@ -430,14 +433,9 @@ "GRO_ENERGY_META", "DEF_SYST_DEF_MINE_3", "DEF_PLAN_BARRIER_SHLD_4", - "SHP_WEAPON_13", - "SPY_DETECT_4", - "SHP_WEAPON_11", - "SHP_WEAPON_12", "DEF_PLAN_BARRIER_SHLD_5", "SHP_SOLAR_CONT", - "SHP_WEAPON_14", - "SHP_WEAPON_15", + "SPY_DETECT_5", "SHP_WEAPON_16", "SHP_WEAPON_17", ] |