from empire.ship_builders import get_ship_builder_locations, set_ship_builders from empire.survey_lock import survey_universe_lock from EnumsAI import FocusType from freeorion_tools import get_partial_visibility_turn, get_species_tag_grade from freeorion_tools.timers import AITimer from turn_state import ( get_empire_planets_by_species, get_owned_planets, set_have_asteroids, set_have_gas_giant, set_have_nest, ) register_pre_handler("generateOrders", survey_universe_lock.lock) survey_timer = AITimer("empire.surver_universe()") def survey_universe(): survey_timer.start("Categorizing Visible Planets") universe = fo.getUniverse() empire_id = fo.empireID() current_turn = fo.currentTurn() # set up / reset various variables; the 'if' is purely for code folding convenience if True: AIstate.empireStars.clear() empire_metabolisms.clear() active_growth_specials.clear() # var setup done
get_species_tag_grade, tech_is_complete, ) from freeorion_tools.caching import cache_for_current_turn from freeorion_tools.timers import AITimer from target import TargetPlanet, TargetSystem from turn_state import get_colonized_planets_in_system from turn_state.design import get_best_ship_info from universe.system_network import systems_connected MAX_BASE_TROOPERS_GOOD_INVADERS = 20 MAX_BASE_TROOPERS_POOR_INVADERS = 10 _TROOPS_SAFETY_MARGIN = 1 # try to send this amount of additional troops to account for uncertainties in calculation MIN_INVASION_SCORE = 20 invasion_timer = AITimer("get_invasion_fleets()", write_log=False) def get_invasion_fleets(): invasion_timer.start("gathering initial info") universe = fo.getUniverse() empire = fo.getEmpire() empire_id = fo.empireID() home_system_id = PlanetUtilsAI.get_capital_sys_id() aistate = get_aistate() visible_system_ids = list(aistate.visInteriorSystemIDs) + list( aistate.visBorderSystemIDs) if home_system_id != INVALID_ID: accessible_system_ids = [
) from common.handlers import init_handlers from common.listeners import listener from empire.survey_universe import survey_universe from freeorion_tools.timers import AITimer from generate_orders import ( empire_is_ok, greet_on_first_turn, print_existing_rules, print_starting_intro, replay_turn_after_load, set_game_turn_seed, update_resource_pool, ) turn_timer = AITimer("full turn") user_dir = fo.getUserDataDir() debug("Path to folder for user specific data: %s" % user_dir) debug("Python paths %s" % sys.path) diplomatic_corp = None def error_handler(func): """Decorator that logs any exception in decorated function, then re-raises""" @wraps(func) def _error_handler(*args, **kwargs): try: res = func(*args, **kwargs) return res
from freeorion_tools.timers import AITimer from target import TargetPlanet from turn_state import ( get_colonized_planets_in_system, get_empire_outposts, get_empire_planets_by_species, get_number_of_colonies, get_owned_planets, get_unowned_empty_planets, set_have_asteroids, set_have_gas_giant, set_have_nest, ) from turn_state.design import get_best_ship_info colonization_timer = AITimer("getColonyFleets()") _all_colony_opportunities = {} @cache_for_current_turn def colony_pod_cost_turns(): empire = fo.getEmpire() empire_id = empire.empireID loc = INVALID_ID pid = INVALID_ID parts = [get_ship_part(part) for part in list(empire.availableShipParts)] colo_parts = [ part for part in parts if part.partClass in frozenset({fo.shipPartClass.colony}) and part.capacity > 0 ] if colo_parts:
get_species_tag_value, tech_is_complete, ) from freeorion_tools.caching import cache_for_current_turn from freeorion_tools.timers import AITimer from target import TargetPlanet, TargetSystem from turn_state import get_colonized_planets_in_system from turn_state.design import get_best_ship_info from universe.system_network import systems_connected MAX_BASE_TROOPERS_GOOD_INVADERS = 20 MAX_BASE_TROOPERS_POOR_INVADERS = 10 _TROOPS_SAFETY_MARGIN = 1 # try to send this amount of additional troops to account for uncertainties in calculation MIN_INVASION_SCORE = 20 invasion_timer = AITimer("get_invasion_fleets()") def get_invasion_fleets(): invasion_timer.start("gathering initial info") universe = fo.getUniverse() empire = fo.getEmpire() empire_id = fo.empireID() home_system_id = PlanetUtilsAI.get_capital_sys_id() aistate = get_aistate() visible_system_ids = list(aistate.visInteriorSystemIDs) + list( aistate.visBorderSystemIDs) if home_system_id != INVALID_ID: accessible_system_ids = [
from logging import debug, info, warning from operator import itemgetter import AIDependencies import PlanetUtilsAI from aistate_interface import get_aistate from colonization.calculate_planet_colonization_rating import empire_metabolisms from common.print_utils import Table, Text from empire.growth_specials import get_growth_specials from EnumsAI import FocusType, PriorityType, get_priority_resource_types from freeorion_tools import combine_ratings, policy_is_adopted, tech_is_complete from freeorion_tools.statistics import stats from freeorion_tools.timers import AITimer from PolicyAI import algo_research, bureaucracy resource_timer = AITimer("timer_bucket") # Local Constants INDUSTRY = FocusType.FOCUS_INDUSTRY RESEARCH = FocusType.FOCUS_RESEARCH GROWTH = FocusType.FOCUS_GROWTH PROTECTION = FocusType.FOCUS_PROTECTION INFLUENCE = FocusType.FOCUS_INFLUENCE def _focus_name(focus: str) -> str: _known_names = { INDUSTRY: "Industry", RESEARCH: "Research", GROWTH: "Growth", PROTECTION: "Defense",
import ResearchAI import ResourcesAI import ShipDesignAI import TechsListsAI from AIDependencies import INVALID_ID from aistate_interface import create_new_aistate, get_aistate, load_aistate from character.character_module import Aggression from character.character_strings_module import ( get_trait_name_aggression, possible_capitals, ) from common.handlers import init_handlers from common.listeners import listener from freeorion_tools.timers import AITimer main_timer = AITimer("timer", write_log=True) turn_timer = AITimer("bucket", write_log=True) user_dir = fo.getUserDataDir() debug("Path to folder for user specific data: %s" % user_dir) debug("Python paths %s" % sys.path) diplomatic_corp = None def error_handler(func): """Decorator that logs any exception in decorated function, then re-raises""" @wraps(func) def _error_handler(*args, **kwargs): try: res = func(*args, **kwargs)
def get_design_repository( ) -> Dict[PriorityType, Tuple[float, int, int, float]]: """Calculate the best designs for each ship class available at this turn.""" design_repository = { } # dict of tuples (rating,pid,designID,cost) sorted by rating and indexed by priority type design_timer = AITimer("ShipDesigner") design_timer.start("Updating cache for new turn") # TODO Don't use PriorityType but introduce more reasonable Enum designers = [ ("Orbital Invasion", PriorityType.PRODUCTION_ORBITAL_INVASION, ShipDesignAI.OrbitalTroopShipDesigner), ("Invasion", PriorityType.PRODUCTION_INVASION, ShipDesignAI.StandardTroopShipDesigner), ( "Orbital Colonization", PriorityType.PRODUCTION_ORBITAL_COLONISATION, ShipDesignAI.OrbitalColonisationShipDesigner, ), ("Colonization", PriorityType.PRODUCTION_COLONISATION, ShipDesignAI.StandardColonisationShipDesigner), ("Orbital Outposter", PriorityType.PRODUCTION_ORBITAL_OUTPOST, ShipDesignAI.OrbitalOutpostShipDesigner), ("Outposter", PriorityType.PRODUCTION_OUTPOST, ShipDesignAI.StandardOutpostShipDesigner), ("Orbital Defense", PriorityType.PRODUCTION_ORBITAL_DEFENSE, ShipDesignAI.OrbitalDefenseShipDesigner), ("Scouts", PriorityType.PRODUCTION_EXPLORATION, ShipDesignAI.ScoutShipDesigner), ] for timer_name, priority_type, designer in designers: design_timer.start(timer_name) design_repository[priority_type] = designer().optimize_design() best_military_stats = ShipDesignAI.WarShipDesigner().optimize_design() best_carrier_stats = ShipDesignAI.CarrierShipDesigner().optimize_design() best_stats = best_military_stats + best_carrier_stats if random.random( ) < 0.8 else best_military_stats best_stats.sort(reverse=True) design_repository[PriorityType.PRODUCTION_MILITARY] = best_stats design_timer.start("Krill Spawner") ShipDesignAI.KrillSpawnerShipDesigner().optimize_design( ) # just designing it, building+mission not supported yet if fo.currentTurn() % 10 == 0: design_timer.start("Printing") ShipDesignAI.Cache.print_best_designs() design_timer.stop_print_and_clear() return design_repository
MissionType, PriorityType, ShipRoleType, get_priority_production_types, ) from freeorion_tools import tech_is_complete from freeorion_tools.timers import AITimer from turn_state import ( get_number_of_colonies, get_owned_planets, have_asteroids, have_gas_giant, ) from turn_state.design import cur_best_military_design_rating, get_best_ship_info prioritiees_timer = AITimer("calculate_priorities()") allottedColonyTargets = 0 allotted_outpost_targets = 0 unmetThreat = 0 def calculate_priorities(): """Calculates the priorities of the AI player.""" debug("\n=== Preparing to Calculate Priorities ===") prioritiees_timer.start("setting Production Priority") aistate = get_aistate() # let this one stay fixed & just adjust Research and Influence aistate.set_priority(PriorityType.RESOURCE_PRODUCTION, 50) # RESOURCE_INFLUENCE priority is calculated in PolicyAI