def test_tech_integrity():
    """Check the TechGroups for integrity.

    Try to get all tech lists by querying all the TechGroups.
    Any error is displayed in chat window.
    Also checks if all techs exist and displays error if invalid tech name encountered.
    """
    tech_groups = [
        TechGroup, TechGroup1, TechGroup1a, TechGroup1b, TechGroup1SparseA,
        TechGroup1SparseB, TechGroup2, TechGroup2A, TechGroup2B,
        TechGroup2SparseA, TechGroup2SparseB, TechGroup3, TechGroup3A,
        TechGroup3B, TechGroup3Sparse, TechGroup4, TechGroup5
    ]
    print "Checking TechGroup integrity..."
    for group in tech_groups:
        print "Checking %s: " % group.__name__,
        error_occured = False
        this_group = group()
        techs = this_group.get_techs()
        for tech in techs:
            if not fo.getTech(tech):
                print_error("In %s: Tech %s seems not to exist!" %
                            (group.__name__, tech))
                error_occured = True
        for err in this_group.get_errors():
            print_error(err, location=group.__name__)
            error_occured = True
        if not error_occured:
            print "Seems to be OK!"
Exemple #2
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    if fo.getEmpire() is None:
        print "This client has no empire. Doing nothing to resume loaded game."
        return    
    
    if fo.getEmpire().eliminated:
        print "This empire has been eliminated. Ignoring resume loaded game."
        return
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    if not saved_state_string:
        print_error("AI given empty state-string to resume from; this is expected if the AI is assigned to an empire "
                    "previously run by a human, but is otherwise an error. AI will be set to Aggressive.")
        foAIstate = AIstate.AIstate(fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
    else:
        try:
            # loading saved state
            # pre load code
            foAIstate = pickle.loads(saved_state_string)
        except Exception as e:
            # assigning new state
            foAIstate = AIstate.AIstate(fo.aggression.aggressive)
            foAIstate.session_start_cleanup()
            print_error("Fail to load aiState from saved game: %s" % e)

    aggression_trait = foAIstate.character.get_trait(Aggression)
    diplomatic_corp_configs = {fo.aggression.beginner: DiplomaticCorp.BeginnerDiplomaticCorp,
                               fo.aggression.maniacal: DiplomaticCorp.ManiacalDiplomaticCorp}
    global diplomatic_corp
    diplomatic_corp = diplomatic_corp_configs.get(aggression_trait.key, DiplomaticCorp.DiplomaticCorp)()
    TechsListsAI.test_tech_integrity()
Exemple #3
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    if fo.getEmpire().eliminated:
        print "This empire has been eliminated. Ignoring resume loaded game."
        return
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    try:
        # loading saved state
        # pre load code
        foAIstate = pickle.loads(saved_state_string)
    except Exception as e:
        # assigning new state
        foAIstate = AIstate.AIstate(fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
        print_error("Fail to load aiState form saved game: %s" % e)

    aggression_trait = foAIstate.character.get_trait(Aggression)
    diplomatic_corp_configs = {fo.aggression.beginner: DiplomaticCorp.BeginnerDiplomaticCorp,
                               fo.aggression.maniacal: DiplomaticCorp.ManiacalDiplomaticCorp}
    global diplomatic_corp
    diplomatic_corp = diplomatic_corp_configs.get(aggression_trait.key, DiplomaticCorp.DiplomaticCorp)()
    TechsListsAI.test_tech_integrity()
Exemple #4
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    try:
        # loading saved state
        foAIstate = pickle.loads(saved_state_string)
        foAIstate.session_start_cleanup()
    except:
        print "failed to parse saved state string"
        # assigning new state
        foAIstate = AIstate.AIstate(aggression=fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
        print_error("Fail to load aiState form saved game")
Exemple #5
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    try:
        # loading saved state
        foAIstate = pickle.loads(saved_state_string)
        foAIstate.session_start_cleanup()
    except:
        print "failed to parse saved state string"
        # assigning new state
        foAIstate = AIstate.AIstate(aggression=fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
        print_error("Fail to load aiState form saved game")
Exemple #6
0
    def __init__(self, fleet, target):
        """
        :param fleet: fleet to execute order
        :type fleet: universe_object.Fleet
        :param target: fleet target, depends of order type
        :type target: universe_object.UniverseObject
        """
        if not isinstance(fleet, Fleet):
            print_error("Order required fleet got %s" % type(fleet))

        if not isinstance(target, self.TARGET_TYPE):
            print_error("Target is not allowed, got %s expect %s" % (type(target), self.TARGET_TYPE))

        self.fleet = fleet
        self.target = target
        self.executed = False
        self.order_issued = False
Exemple #7
0
def get_capital():
    """
    Return current empire capital id.
    If no current capital returns planet with biggest population in first not empty group.
    First check all planets with coloniser species, after that with ship builders and at last all inhabited planets.
    :return: id
    """
    universe = fo.getUniverse()
    empire = fo.getEmpire()
    if empire is None:
        print >> sys.stderr, "Danger Danger! FO can't find an empire for me!!!!"
        return -1
    empire_id = empire.empireID
    capital_id = empire.capitalID
    homeworld = universe.getPlanet(capital_id)
    if homeworld:
        if homeworld.owner == empire_id:
            return capital_id
        else:
            print "Nominal Capitol %s does not appear to be owned by empire %d %s" % (
                homeworld.name, empire_id, empire.name)
    empire_owned_planet_ids = get_owned_planets_by_empire(universe.planetIDs)
    peopled_planets = get_populated_planet_ids(empire_owned_planet_ids)
    if not peopled_planets:
        if empire_owned_planet_ids:
            return empire_owned_planet_ids[0]
        else:
            return -1
    try:
        for spec_list in [
                ColonisationAI.empire_colonizers,
                ColonisationAI.empire_ship_builders, None
        ]:
            population_id_pairs = []
            for planet_id in peopled_planets:
                planet = universe.getPlanet(planet_id)
                if spec_list is None or planet.speciesName in spec_list:
                    population_id_pairs.append(
                        (planet.currentMeterValue(fo.meterType.population),
                         planet_id))
            if population_id_pairs:
                return max(population_id_pairs)[-1]
    except Exception as e:
        print_error(e)
    return -1  # shouldn't ever reach here
Exemple #8
0
def prepareForSave():  # pylint: disable=invalid-name
    """Called by client when the game is about to be saved, to let the Python AI know it should save any AI state
    information, such as plans or knowledge about the game from previous turns,
    in the state string so that they can be restored if the game is loaded."""
    empire = fo.getEmpire()
    if empire.eliminated:
        print "This empire has been eliminated. Save info request"
        return

    print "Preparing for game save by serializing state"

    # serialize (convert to string) global state dictionary and send to AI client to be stored in save file
    try:
        dump_string = pickle.dumps(foAIstate)
        print "foAIstate pickled to string, about to send to server"
        fo.setSaveStateString(dump_string)
    except:
        print_error("foAIstate unable to pickle save-state string; the save file should be playable but the AI may have a different aggression.", trace=True)
def get_capital():
    """
    Return current empire capital id.
    If no current capital returns planet with biggest population in first not empty group.
    First check all planets with coloniser species, after that with ship builders and at last all inhabited planets.
    :return: id
    """
    universe = fo.getUniverse()
    empire = fo.getEmpire()
    if empire is None:
        print >> sys.stderr, "Danger Danger! FO can't find an empire for me!!!!"
        return INVALID_ID
    empire_id = empire.empireID
    capital_id = empire.capitalID
    homeworld = universe.getPlanet(capital_id)
    if homeworld:
        if homeworld.owner == empire_id:
            return capital_id
        else:
            print "Nominal Capitol %s does not appear to be owned by empire %d %s" % (
                homeworld.name,
                empire_id,
                empire.name,
            )
    empire_owned_planet_ids = get_owned_planets_by_empire(universe.planetIDs)
    peopled_planets = get_populated_planet_ids(empire_owned_planet_ids)
    if not peopled_planets:
        if empire_owned_planet_ids:
            return empire_owned_planet_ids[0]
        else:
            return INVALID_ID
    try:
        for spec_list in [ColonisationAI.empire_colonizers, ColonisationAI.empire_ship_builders, None]:
            population_id_pairs = []
            for planet_id in peopled_planets:
                planet = universe.getPlanet(planet_id)
                if spec_list is None or planet.speciesName in spec_list:
                    population_id_pairs.append((planet.currentMeterValue(fo.meterType.population), planet_id))
            if population_id_pairs:
                return max(population_id_pairs)[-1]
    except Exception as e:
        print_error(e)
    return INVALID_ID  # shouldn't ever reach here
Exemple #10
0
def test_tech_integrity():
    """Check the TechGroups for integrity.

    Try to get all tech lists by querying all the TechGroups.
    Any error is displayed in chat window.
    Also checks if all techs exist and displays error if invalid tech name encountered.
    """
    tech_groups = [
        TechGroup,
        TechGroup1,
        TechGroup1a,
        TechGroup1b,
        TechGroup1SparseA,
        TechGroup1SparseB,
        TechGroup1SparseC,
        TechGroup2,
        TechGroup2A,
        TechGroup2B,
        TechGroup2SparseA,
        TechGroup2SparseB,
        TechGroup3,
        TechGroup3A,
        TechGroup3B,
        TechGroup3Sparse,
        TechGroup4,
        TechGroup5
    ]
    print "Checking TechGroup integrity..."
    for group in tech_groups:
        print "Checking %s: " % group.__name__,
        error_occured = False
        this_group = group()
        techs = this_group.get_techs()
        for tech in techs:
            if not fo.getTech(tech):
                print_error("In %s: Tech %s seems not to exist!" % (group.__name__, tech))
                error_occured = True
        for err in this_group.get_errors():
            print_error(err, location=group.__name__)
            error_occured = True
        if not error_occured:
            print "Seems to be OK!"
Exemple #11
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    try:
        # loading saved state
        # pre load code
        foAIstate = pickle.loads(saved_state_string)
    except Exception as e:
        # assigning new state
        foAIstate = AIstate.AIstate(aggression=fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
        print_error("Fail to load aiState form saved game: %s" % e)

    diplomatic_corp_configs = {fo.aggression.beginner: DiplomaticCorp.BeginnerDiplomaticCorp,
                               fo.aggression.maniacal: DiplomaticCorp.ManiacalDiplomaticCorp}
    global diplomatic_corp
    diplomatic_corp = diplomatic_corp_configs.get(foAIstate.aggression, DiplomaticCorp.DiplomaticCorp)()
Exemple #12
0
def prepareForSave():  # pylint: disable=invalid-name
    """Called by client when the game is about to be saved, to let the Python AI know it should save any AI state
    information, such as plans or knowledge about the game from previous turns,
    in the state string so that they can be restored if the game is loaded."""
    empire = fo.getEmpire()
    if empire.eliminated:
        print "This empire has been eliminated. Save info request"
        return

    print "Preparing for game save by serializing state"

    # serialize (convert to string) global state dictionary and send to AI client to be stored in save file
    try:
        dump_string = pickle.dumps(foAIstate)
        print "foAIstate pickled to string, about to send to server"
        fo.setSaveStateString(dump_string)
    except:
        print_error(
            "foAIstate unable to pickle save-state string; the save file should be playable but the AI may have a different aggression.",
            trace=True)
Exemple #13
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    if fo.getEmpire() is None:
        print "This client has no empire. Doing nothing to resume loaded game."
        return

    if fo.getEmpire().eliminated:
        print "This empire has been eliminated. Ignoring resume loaded game."
        return
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    if not saved_state_string:
        print_error(
            "AI given empty state-string to resume from; this is expected if the AI is assigned to an empire "
            "previously run by a human, but is otherwise an error. AI will be set to Aggressive."
        )
        foAIstate = AIstate.AIstate(fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
    else:
        try:
            # loading saved state
            # pre load code
            foAIstate = pickle.loads(saved_state_string)
        except Exception as e:
            # assigning new state
            foAIstate = AIstate.AIstate(fo.aggression.aggressive)
            foAIstate.session_start_cleanup()
            print_error("Fail to load aiState from saved game: %s" % e)

    aggression_trait = foAIstate.character.get_trait(Aggression)
    diplomatic_corp_configs = {
        fo.aggression.beginner: DiplomaticCorp.BeginnerDiplomaticCorp,
        fo.aggression.maniacal: DiplomaticCorp.ManiacalDiplomaticCorp
    }
    global diplomatic_corp
    diplomatic_corp = diplomatic_corp_configs.get(
        aggression_trait.key, DiplomaticCorp.DiplomaticCorp)()
    TechsListsAI.test_tech_integrity()
Exemple #14
0
def resumeLoadedGame(saved_state_string):  # pylint: disable=invalid-name
    """Called by client to when resume a loaded game."""
    turn_timer.start("Server Processing")

    global foAIstate
    print "Resuming loaded game"
    try:
        # loading saved state
        # pre load code
        import imp
        import sys

        ai_target_name = 'AITarget'
        ai_target = imp.new_module(ai_target_name)
        sys.modules[ai_target_name] = ai_target

        class AITarget(object):
            pass
        ai_target.AITarget = AITarget

        ai_order_name = 'AIFleetOrder'
        ai_order = imp.new_module(ai_order_name)
        sys.modules[ai_order_name] = ai_order

        class AIFleetOrder(object):
            pass
        ai_order.AIFleetOrder = AIFleetOrder
        foAIstate = pickle.loads(saved_state_string)
    except Exception as e:
        # assigning new state
        foAIstate = AIstate.AIstate(aggression=fo.aggression.aggressive)
        foAIstate.session_start_cleanup()
        print_error("Fail to load aiState form saved game: e")

    diplomatic_corp_configs = {fo.aggression.beginner: DiplomaticCorp.BeginnerDiplomaticCorp,
                               fo.aggression.maniacal: DiplomaticCorp.ManiacalDiplomaticCorp}
    global diplomatic_corp
    diplomatic_corp = diplomatic_corp_configs.get(foAIstate.aggression, DiplomaticCorp.DiplomaticCorp)()
Exemple #15
0
def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""
    empire = fo.getEmpire()
    if empire.eliminated:
        print "This empire has been eliminated. Aborting order generation"
        try:
            # early abort if already eliminated. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            fo.doneTurn()
        except Exception as e:
            print_error(e)
        return

    # This code block is required for correct AI work.
    print "Meter / Resource Pool updating..."
    fo.initMeterEstimatesDiscrepancies()
    fo.updateMeterEstimates(0)
    fo.updateResourcePools()

    turn = fo.currentTurn()
    turn_uid = foAIstate.set_turn_uid()
    print "Start turn %s (%s) of game: %s" % (turn, turn_uid, foAIstate.uid)

    turn_timer.start("AI planning")
    # set the random seed (based on galaxy seed, empire name and current turn)
    # for game-reload consistency.
    random_seed = str(fo.getGalaxySetupData().seed) + "%05d%s" % (turn, fo.getEmpire().name)
    random.seed(random_seed)
    aggression_name = fo.aggression.values[foAIstate.aggression].name
    if turn == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        fo.sendChatMessage(human_player,  '%s Empire (%s):\n"Ave, Human, morituri te salutant!"' % (empire.name, aggression_name))

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    foAIstate.split_new_fleets()

    foAIstate.refresh()  # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
    foAIstate.report_system_threats()
    print("Calling AI Modules")
    # call AI modules
    action_list = [ColonisationAI.survey_universe,
                   ProductionAI.find_best_designs_this_turn,
                   PriorityAI.calculate_priorities,
                   ExplorationAI.assign_scouts_to_explore_systems,
                   ColonisationAI.assign_colony_fleets_to_colonise,
                   InvasionAI.assign_invasion_fleets_to_invade,
                   MilitaryAI.assign_military_fleets_to_systems,
                   FleetUtilsAI.generate_fleet_orders_for_fleet_missions,
                   FleetUtilsAI.issue_fleet_orders_for_fleet_missions,
                   ResearchAI.generate_research_orders,
                   ProductionAI.generateProductionOrders,
                   ResourcesAI.generate_resources_orders,
                   foAIstate.after_turn_cleanup,
                   ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            print_error(e, location=action.__name__)
    main_timer.end()
    turn_timer.end()
    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        print_error(e)  # TODO move it to cycle above

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
Exemple #16
0
def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""

    rules = fo.getGameRules()
    print "Defined game rules:"
    for rule in rules.getRulesAsStrings:
        print "Name: " + rule.name + "  value: " + str(rule.value)
    print "Rule RULE_NUM_COMBAT_ROUNDS value: " + str(
        rules.getInt("RULE_NUM_COMBAT_ROUNDS"))

    empire = fo.getEmpire()
    if empire is None:
        print "This client has no empire. Doing nothing to generate orders."
        try:
            # early abort if no empire. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            #
            # note that doneTurn() is issued on behalf of the client network
            # id, not the empire id, so not having a correct empire id does
            # not invalidate doneTurn()
            fo.doneTurn()
        except Exception as e:
            print_error(e)
        return

    if empire.eliminated:
        print "This empire has been eliminated. Aborting order generation"
        try:
            # early abort if already eliminated. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            fo.doneTurn()
        except Exception as e:
            print_error(e)
        return

    # This code block is required for correct AI work.
    print "Meter / Resource Pool updating..."
    fo.initMeterEstimatesDiscrepancies()
    fo.updateMeterEstimates(False)
    fo.updateResourcePools()

    turn = fo.currentTurn()
    turn_uid = foAIstate.set_turn_uid()
    print "\n\n\n", "=" * 20,
    print "Starting turn %s (%s) of game: %s" % (turn, turn_uid,
                                                 foAIstate.uid),
    print "=" * 20, "\n"

    turn_timer.start("AI planning")
    # set the random seed (based on galaxy seed, empire name and current turn)
    # for game-reload consistency.
    random_seed = str(
        fo.getGalaxySetupData().seed) + "%05d%s" % (turn, fo.getEmpire().name)
    random.seed(random_seed)

    universe = fo.getUniverse()
    empire = fo.getEmpire()
    planet_id = PlanetUtilsAI.get_capital()
    planet = None
    if planet_id is not None:
        planet = universe.getPlanet(planet_id)
    aggression_name = get_trait_name_aggression(foAIstate.character)
    print "***************************************************************************"
    print "*******  Log info for AI progress chart script. Do not modify.   **********"
    print("Generating Orders")
    print(
        "EmpireID: {empire.empireID}"
        " Name: {empire.name}_{empire.empireID}_pid:{p_id}_{p_name}RIdx_{res_idx}_{aggression}"
        " Turn: {turn}").format(empire=empire,
                                p_id=fo.playerID(),
                                p_name=fo.playerName(),
                                res_idx=ResearchAI.get_research_index(),
                                turn=turn,
                                aggression=aggression_name.capitalize())
    print "EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(
        empire)
    if planet:
        print "CapitalID: " + str(
            planet_id
        ) + " Name: " + planet.name + " Species: " + planet.speciesName
    else:
        print "CapitalID: None Currently Name: None Species: None "
    print "***************************************************************************"
    print "***************************************************************************"

    if turn == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        greet = diplomatic_corp.get_first_turn_greet_message()
        fo.sendChatMessage(
            human_player, '%s (%s): [[%s]]' %
            (empire.name, get_trait_name_aggression(
                foAIstate.character), greet))

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    foAIstate.split_new_fleets()

    foAIstate.refresh(
    )  # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
    foAIstate.report_system_threats()
    print("Calling AI Modules")
    # call AI modules
    action_list = [
        ColonisationAI.survey_universe,
        ProductionAI.find_best_designs_this_turn,
        PriorityAI.calculate_priorities,
        ExplorationAI.assign_scouts_to_explore_systems,
        ColonisationAI.assign_colony_fleets_to_colonise,
        InvasionAI.assign_invasion_fleets_to_invade,
        MilitaryAI.assign_military_fleets_to_systems,
        FleetUtilsAI.generate_fleet_orders_for_fleet_missions,
        FleetUtilsAI.issue_fleet_orders_for_fleet_missions,
        ResearchAI.generate_research_orders,
        ProductionAI.generate_production_orders,
        ResourcesAI.generate_resources_orders,
    ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            print_error(e, location=action.__name__)
    main_timer.stop_print_and_clear()
    turn_timer.stop_print_and_clear()
    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        print_error(e)  # TODO move it to cycle above

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
Exemple #17
0
def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""
    turn_timer.start("AI planning")
    universe = fo.getUniverse()
    empire = fo.getEmpire()
    planet_id = PlanetUtilsAI.get_capital()
    # set the random seed (based on galaxy seed, empire ID and current turn)
    # for game-reload consistency
    random_seed = str(fo.getGalaxySetupData().seed) + "%03d%05d" % (
        fo.empireID(), fo.currentTurn())
    random.seed(random_seed)
    planet = None
    if planet_id is not None:
        planet = universe.getPlanet(planet_id)
    aggression_name = fo.aggression.values[foAIstate.aggression].name
    print "***************************************************************************"
    print "**********   String for chart. Do not modify.   ***************************"
    print("Generating Orders")
    print(
        "EmpireID: {empire.empireID}"
        " Name: {empire.name}_{empire.empireID}_pid:{p_id}_{p_name}RIdx_{res_idx}_{aggression}"
        " Turn: {turn}").format(empire=empire,
                                p_id=fo.playerID(),
                                p_name=fo.playerName(),
                                res_idx=ResearchAI.get_research_index(),
                                turn=fo.currentTurn(),
                                aggression=aggression_name.capitalize())
    print "EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(
        empire)
    if planet:
        print "CapitalID: " + str(
            planet_id
        ) + " Name: " + planet.name + " Species: " + planet.speciesName
    else:
        print "CapitalID: None Currently Name: None Species: None "
    print "***************************************************************************"
    print "***************************************************************************"

    if fo.currentTurn() == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        fo.sendChatMessage(
            human_player,
            '%s Empire (%s):\n"Ave, Human, morituri te salutant!"' %
            (empire.name, aggression_name))

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    foAIstate.split_new_fleets()

    foAIstate.refresh(
    )  # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
    foAIstate.report_system_threats()
    # ...missions
    # ...demands/priorities
    print("Calling AI Modules")
    # call AI modules
    action_list = [
        PriorityAI.calculate_priorities,
        ExplorationAI.assign_scouts_to_explore_systems,
        ColonisationAI.assign_colony_fleets_to_colonise,
        InvasionAI.assign_invasion_fleets_to_invade,
        MilitaryAI.assign_military_fleets_to_systems,
        FleetUtilsAI.generate_fleet_orders_for_fleet_missions,
        FleetUtilsAI.issue_fleet_orders_for_fleet_missions,
        ResearchAI.generate_research_orders,
        ProductionAI.generateProductionOrders,
        ResourcesAI.generate_resources_orders,
        foAIstate.after_turn_cleanup,
    ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            print_error(e, location=action.__name__)
    main_timer.end()
    turn_timer.end()
    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        print_error(e)  # TODO move it to cycle above

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
Exemple #18
0
def assign_scouts_to_explore_systems():
    # TODO: use Graph Theory to explore closest systems
    universe = fo.getUniverse()
    capital_sys_id = PlanetUtilsAI.get_capital_sys_id()
    # order fleets to explore
    if not border_unexplored_system_ids or (capital_sys_id == INVALID_ID):
        return
    exp_systems_by_dist = sorted((universe.linearDistance(capital_sys_id, x), x) for x in border_unexplored_system_ids)
    print "Exploration system considering following system-distance pairs:\n  %s" % ("\n  ".join("%3d: %5.1f" % info for info in exp_systems_by_dist))
    explore_list = [sys_id for dist, sys_id in exp_systems_by_dist]

    already_covered, available_scouts = get_current_exploration_info()

    print "Explorable system IDs: %s" % explore_list
    print "Already targeted: %s" % already_covered
    needs_vis = foAI.foAIstate.misc.setdefault('needs_vis', [])
    check_list = foAI.foAIstate.needsEmergencyExploration + needs_vis + explore_list
    if INVALID_ID in check_list:  # shouldn't normally happen, unless due to bug elsewhere
        for sys_list, name in [(foAI.foAIstate.needsEmergencyExploration, "foAI.foAIstate.needsEmergencyExploration"), (needs_vis, "needs_vis"), (explore_list, "explore_list")]:
            if INVALID_ID in sys_list:
                print_error("INVALID_ID found in " + name)
    needs_coverage = [sys_id for sys_id in check_list if sys_id not in already_covered and sys_id != INVALID_ID]  # emergency coverage can be due to invasion detection trouble, etc.
    print "Needs coverage: %s" % needs_coverage

    print "Available scouts & AIstate locs: %s" % [(x, foAI.foAIstate.fleetStatus.get(x, {}).get('sysID', INVALID_ID)) for x in available_scouts]
    print "Available scouts & universe locs: %s" % [(x, universe.getFleet(x).systemID) for x in available_scouts]
    if not needs_coverage or not available_scouts:
        return

    available_scouts = set(available_scouts)
    sent_list = []
    while available_scouts and needs_coverage:
        this_sys_id = needs_coverage.pop(0)
        sys_status = foAI.foAIstate.systemStatus.setdefault(this_sys_id, {})
        if this_sys_id not in explore_list:  # doesn't necessarily need direct visit
            if universe.getVisibility(this_sys_id, fo.empireID()) >= fo.visibility.partial:
                # already got visibility; remove from visit lists and skip
                if this_sys_id in needs_vis:
                    del needs_vis[needs_vis.index(this_sys_id)]
                if this_sys_id in foAI.foAIstate.needsEmergencyExploration:
                    del foAI.foAIstate.needsEmergencyExploration[
                        foAI.foAIstate.needsEmergencyExploration.index(this_sys_id)]
                print "system id %d already currently visible; skipping exploration" % this_sys_id
                continue
        # TODO: if blocked byu monster, try to find nearby system from which to see this system
        if not foAI.foAIstate.character.may_explore_system(sys_status.setdefault('monsterThreat', 0)) or (fo.currentTurn() < 20 and foAI.foAIstate.systemStatus[this_sys_id]['monsterThreat'] > 200):
            print "Skipping exploration of system %d due to Big Monster, threat %d" % (this_sys_id, foAI.foAIstate.systemStatus[this_sys_id]['monsterThreat'])
            continue
        this_fleet_list = FleetUtilsAI.get_fleets_for_mission(target_stats={}, min_stats={}, cur_stats={},
                                                              starting_system=this_sys_id, fleet_pool_set=available_scouts,
                                                              fleet_list=[])
        if not this_fleet_list:
            print "Seem to have run out of scouts while trying to cover sys_id %d" % this_sys_id
            break  # must have ran out of scouts
        fleet_id = this_fleet_list[0]
        fleet_mission = foAI.foAIstate.get_fleet_mission(fleet_id)
        target = universe_object.System(this_sys_id)
        if len(MoveUtilsAI.can_travel_to_system_and_return_to_resupply(fleet_id, fleet_mission.get_location_target(), target)) > 0:
            fleet_mission.set_target(MissionType.EXPLORATION, target)
            sent_list.append(this_sys_id)
        else:  # system too far out, skip it, but can add scout back to available pool
            print "sys_id %d too far out for fleet ( ID %d ) to reach" % (this_sys_id, fleet_id)
            available_scouts.update(this_fleet_list)
    print "Sent scouting fleets to sysIDs : %s" % sent_list
    return
    # pylint: disable=pointless-string-statement
    """
Exemple #19
0
 def __init__(self, msg=""):
     print_error(msg)
Exemple #20
0
def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""
    empire = fo.getEmpire()
    if empire is None:
        print "This client has no empire. Doing nothing to generate orders."
        try:
            # early abort if no empire. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            #
            # note that doneTurn() is issued on behalf of the client network
            # id, not the empire id, so not having a correct empire id does
            # not invalidate doneTurn()            
            fo.doneTurn()
        except Exception as e:
            print_error(e)
        return
    
    if empire.eliminated:
        print "This empire has been eliminated. Aborting order generation"
        try:
            # early abort if already eliminated. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            fo.doneTurn()
        except Exception as e:
            print_error(e)
        return

    # This code block is required for correct AI work.
    print "Meter / Resource Pool updating..."
    fo.initMeterEstimatesDiscrepancies()
    fo.updateMeterEstimates(False)
    fo.updateResourcePools()

    turn = fo.currentTurn()
    turn_uid = foAIstate.set_turn_uid()
    print "\n\n\n", "=" * 20,
    print "Starting turn %s (%s) of game: %s" % (turn, turn_uid, foAIstate.uid),
    print "=" * 20, "\n"

    turn_timer.start("AI planning")
    # set the random seed (based on galaxy seed, empire name and current turn)
    # for game-reload consistency.
    random_seed = str(fo.getGalaxySetupData().seed) + "%05d%s" % (turn, fo.getEmpire().name)
    random.seed(random_seed)

    universe = fo.getUniverse()
    empire = fo.getEmpire()
    planet_id = PlanetUtilsAI.get_capital()
    planet = None
    if planet_id is not None:
        planet = universe.getPlanet(planet_id)
    aggression_name = get_trait_name_aggression(foAIstate.character)
    print "***************************************************************************"
    print "*******  Log info for AI progress chart script. Do not modify.   **********"
    print ("Generating Orders")
    print ("EmpireID: {empire.empireID}"
           " Name: {empire.name}_{empire.empireID}_pid:{p_id}_{p_name}RIdx_{res_idx}_{aggression}"
           " Turn: {turn}").format(empire=empire,  p_id=fo.playerID(), p_name=fo.playerName(),
                                   res_idx=ResearchAI.get_research_index(), turn=turn,
                                   aggression=aggression_name.capitalize())
    print "EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(empire)
    if planet:
        print "CapitalID: " + str(planet_id) + " Name: " + planet.name + " Species: " + planet.speciesName
    else:
        print "CapitalID: None Currently Name: None Species: None "
    print "***************************************************************************"
    print "***************************************************************************"

    if turn == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        greet = diplomatic_corp.get_first_turn_greet_message()
        fo.sendChatMessage(human_player, '%s (%s): [[%s]]' % (empire.name, get_trait_name_aggression(foAIstate.character), greet))

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    foAIstate.split_new_fleets()

    foAIstate.refresh()  # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
    foAIstate.report_system_threats()
    print("Calling AI Modules")
    # call AI modules
    action_list = [ColonisationAI.survey_universe,
                   ProductionAI.find_best_designs_this_turn,
                   PriorityAI.calculate_priorities,
                   ExplorationAI.assign_scouts_to_explore_systems,
                   ColonisationAI.assign_colony_fleets_to_colonise,
                   InvasionAI.assign_invasion_fleets_to_invade,
                   MilitaryAI.assign_military_fleets_to_systems,
                   FleetUtilsAI.generate_fleet_orders_for_fleet_missions,
                   FleetUtilsAI.issue_fleet_orders_for_fleet_missions,
                   ResearchAI.generate_research_orders,
                   ProductionAI.generate_production_orders,
                   ResourcesAI.generate_resources_orders,
                   ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            print_error(e, location=action.__name__)
    main_timer.stop_print_and_clear()
    turn_timer.stop_print_and_clear()
    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        print_error(e)  # TODO move it to cycle above

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
Exemple #21
0
def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""
    turn = fo.currentTurn()
    turn_uid = foAIstate.set_turn_uid()
    print "Start turn %s (%s) of game: %s" % (turn, turn_uid, foAIstate.uid)

    turn_timer.start("AI planning")
    universe = fo.getUniverse()
    empire = fo.getEmpire()
    planet_id = PlanetUtilsAI.get_capital()
    # set the random seed (based on galaxy seed, empire ID and current turn)
    # for game-reload consistency 
    random_seed = str(fo.getGalaxySetupData().seed) + "%03d%05d" % (fo.empireID(), turn)
    random.seed(random_seed)
    planet = None
    if planet_id is not None:
        planet = universe.getPlanet(planet_id)
    aggression_name = fo.aggression.values[foAIstate.aggression].name
    print "***************************************************************************"
    print "**********   String for chart. Do not modify.   ***************************"
    print ("Generating Orders")
    print ("EmpireID: {empire.empireID}"
           " Name: {empire.name}_{empire.empireID}_pid:{p_id}_{p_name}RIdx_{res_idx}_{aggression}"
           " Turn: {turn}").format(empire=empire,  p_id=fo.playerID(), p_name=fo.playerName(),
                                   res_idx=ResearchAI.get_research_index(), turn=turn,
                                   aggression=aggression_name.capitalize())
    print "EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(empire)
    if planet:
        print "CapitalID: " + str(planet_id) + " Name: " + planet.name + " Species: " + planet.speciesName
    else:
        print "CapitalID: None Currently Name: None Species: None "
    print "***************************************************************************"
    print "***************************************************************************"

    if turn == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        fo.sendChatMessage(human_player,  '%s Empire (%s):\n"Ave, Human, morituri te salutant!"' % (empire.name, aggression_name))

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    foAIstate.split_new_fleets()

    foAIstate.refresh()  # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
    foAIstate.report_system_threats()
    # ...missions
    # ...demands/priorities
    print("Calling AI Modules")
    # call AI modules
    action_list = [ColonisationAI.survey_universe,
                   ProductionAI.find_best_designs_this_turn,
                   PriorityAI.calculate_priorities,
                   ExplorationAI.assign_scouts_to_explore_systems,
                   ColonisationAI.assign_colony_fleets_to_colonise,
                   InvasionAI.assign_invasion_fleets_to_invade,
                   MilitaryAI.assign_military_fleets_to_systems,
                   FleetUtilsAI.generate_fleet_orders_for_fleet_missions,
                   FleetUtilsAI.issue_fleet_orders_for_fleet_missions,
                   ResearchAI.generate_research_orders,
                   ProductionAI.generateProductionOrders,
                   ResourcesAI.generate_resources_orders,
                   foAIstate.after_turn_cleanup,
                   ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            print_error(e, location=action.__name__)
    main_timer.end()
    turn_timer.end()
    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        print_error(e)  # TODO move it to cycle above

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass