Exemplo n.º 1
0
    def _portion_of_fleet_needed_here(self):
        """Calculate the portion of the fleet needed in target system considering enemy forces."""
        # TODO check rating against planets
        if assertion_fails(self.type in COMBAT_MISSION_TYPES, msg=str(self)):
            return 0
        if assertion_fails(self.target and self.target.id != INVALID_ID, msg=str(self)):
            return 0
        system_id = self.target.id
        aistate = get_aistate()
        local_defenses = MilitaryAI.get_my_defense_rating_in_system(system_id)
        potential_threat = CombatRatingsAI.combine_ratings(
            MilitaryAI.get_system_local_threat(system_id),
            MilitaryAI.get_system_neighbor_threat(system_id)
        )
        universe = fo.getUniverse()
        system = universe.getSystem(system_id)

        # tally planetary defenses
        total_defense = total_shields = 0
        for planet_id in system.planetIDs:
            planet = universe.getPlanet(planet_id)
            total_defense += planet.currentMeterValue(fo.meterType.defense)
            total_shields += planet.currentMeterValue(fo.meterType.shield)
        planetary_ratings = total_defense * (total_shields + total_defense)
        potential_threat += planetary_ratings  # TODO: rewrite to return min rating vs planets as well

        # consider safety factor just once here rather than everywhere below
        safety_factor = aistate.character.military_safety_factor()
        potential_threat *= safety_factor

        fleet_rating = CombatRatingsAI.get_fleet_rating(self.fleet.id)
        return CombatRatingsAI.rating_needed(potential_threat, local_defenses) / float(fleet_rating)
Exemplo n.º 2
0
def test_logger_argument():
    import logging
    loggers = [logging.debug, logging.info, logging.warning, logging.error]
    for logger in loggers:
        assert assertion_fails(False, logger=logger)
        assert assertion_fails(False, "Some message", logger=logger)
        assert not assertion_fails(True, logger=logger)
def test_logger_argument():
    import logging
    loggers = [logging.debug, logging.info, logging.warn, logging.error]
    for logger in loggers:
        assert assertion_fails(False, logger=logger)
        assert assertion_fails(False, "Some message", logger=logger)
        assert not assertion_fails(True, logger=logger)
Exemplo n.º 4
0
 def _rate_policy(self, name: str) -> float:
     """Gives a rough value of a policy."""
     rating_function = self._rating_functions.get(name)
     if assertion_fails(rating_function,
                        f"_rate_policy({name}) not yet supported"):
         return 0.0
     return rating_function()
Exemplo n.º 5
0
def split_ship_from_fleet(fleet_id, ship_id) -> int:
    """Try to split a ship from the fleet, creating a new fleet.

    :return: ID of the newly created fleet or INVALID_ID if failed
    """
    universe = fo.getUniverse()
    fleet = universe.getFleet(fleet_id)
    if assertion_fails(fleet is not None):
        return INVALID_ID

    if assertion_fails(ship_id in fleet.shipIDs):
        return INVALID_ID

    if assertion_fails(fleet.numShips > 1, "Can't split last ship from fleet"):
        return INVALID_ID

    new_fleet_id = fo.issueNewFleetOrder("Fleet %4d" % ship_id, ship_id)
    if new_fleet_id != INVALID_ID:
        aistate = get_aistate()
        new_fleet = universe.getFleet(new_fleet_id)
        if not new_fleet:
            warning("Newly split fleet %d not available from universe" %
                    new_fleet_id)
        debug("Successfully split ship %d from fleet %d into new fleet %d",
              ship_id, fleet_id, new_fleet_id)
        fo.issueRenameOrder(new_fleet_id, "Fleet %4d" %
                            new_fleet_id)  # to ease review of debugging logs
        fo.issueAggressionOrder(new_fleet_id, True)
        aistate.update_fleet_rating(new_fleet_id)
        aistate.newlySplitFleets[new_fleet_id] = True
        # register the new fleets so AI logic is aware of them
        sys_status = aistate.systemStatus.setdefault(fleet.systemID, {})
        sys_status["myfleets"].append(new_fleet_id)
        sys_status["myFleetsAccessible"].append(new_fleet_id)
    else:
        if fleet.systemID == INVALID_ID:
            warning(
                "Tried to split ship id (%d) from fleet %d when fleet is in starlane"
                % (ship_id, fleet_id))
        else:
            warning(
                "Got no fleet ID back after trying to split ship id (%d) from fleet %d"
                % (ship_id, fleet_id))
    return new_fleet_id
Exemplo n.º 6
0
def split_ship_from_fleet(fleet_id, ship_id):
    universe = fo.getUniverse()
    fleet = universe.getFleet(fleet_id)
    if assertion_fails(fleet is not None):
        return

    if assertion_fails(ship_id in fleet.shipIDs):
        return

    if assertion_fails(fleet.numShips > 1, "Can't split last ship from fleet"):
        return

    new_fleet_id = fo.issueNewFleetOrder("Fleet %4d" % ship_id, ship_id)
    if new_fleet_id:
        aistate = get_aistate()
        new_fleet = universe.getFleet(new_fleet_id)
        if not new_fleet:
            warn("Newly split fleet %d not available from universe" %
                 new_fleet_id)
        debug("Successfully split ship %d from fleet %d into new fleet %d",
              ship_id, fleet_id, new_fleet_id)
        fo.issueRenameOrder(new_fleet_id, "Fleet %4d" %
                            new_fleet_id)  # to ease review of debugging logs
        fo.issueAggressionOrder(new_fleet_id, True)
        aistate.update_fleet_rating(new_fleet_id)
        aistate.newlySplitFleets[new_fleet_id] = True
    else:
        if fleet.systemID == INVALID_ID:
            warn(
                "Tried to split ship id (%d) from fleet %d when fleet is in starlane"
                % (ship_id, fleet_id))
        else:
            warn(
                "Got no fleet ID back after trying to split ship id (%d) from fleet %d"
                % (ship_id, fleet_id))
    return new_fleet_id
Exemplo n.º 7
0
    def _get_target_for_protection_mission(self):
        """Get a target for a PROTECT_REGION mission.

        1) If primary target (system target of this mission) is under attack, move to primary target.
        2) If neighbors of primary target have local enemy forces weaker than this fleet, may move to attack
        3) If no neighboring fleets or strongest enemy force is too strong, move to defend primary target
        """
        # TODO: Also check fleet rating vs planets in decision making below not only vs fleets
        universe = fo.getUniverse()
        primary_objective = self.target.id
        debug("Trying to find target for protection mission. Target: %s", self.target)
        immediate_threat = MilitaryAI.get_system_local_threat(primary_objective)
        if immediate_threat:
            debug("Immediate threat! Moving to primary mission target")
            return primary_objective
        else:
            debug("No immediate threats.")
            # Try to eliminate neighbouring fleets
            neighbors = universe.getImmediateNeighbors(primary_objective, fo.empireID())
            threat_list = sorted(map(
                lambda x: (MilitaryAI.get_system_local_threat(x), x),
                neighbors
            ), reverse=True)

            if not threat_list:
                debug("No neighbors (?!). Moving to primary mission target")
                return primary_objective

            debug("%s", threat_list)
            top_threat, candidate_system = threat_list[0]
            if not top_threat:
                # TODO: Move into second ring but needs more careful evaluation
                # For now, consider staying at the current location if enemy
                # owns a planet here which we can bombard.
                current_system_id = self.fleet.get_current_system_id()
                if current_system_id in neighbors:
                    system = universe.getSystem(current_system_id)
                    if assertion_fails(system is not None):
                        return primary_objective
                    empire_id = fo.empireID()
                    for planet_id in system.planetIDs:
                        planet = universe.getPlanet(planet_id)
                        if (planet and
                                not planet.ownedBy(empire_id) and
                                not planet.unowned):
                            debug("Currently no neighboring threats. "
                                  "Staying for bombardment of planet %s", planet)
                            self.clear_fleet_orders()
                            self.set_target(MissionType.MILITARY, TargetSystem(current_system_id))
                            self.generate_fleet_orders()
                            self.issue_fleet_orders()
                            return INVALID_ID

                # TODO consider attacking neighboring, non-military fleets
                # - needs more careful evaluation against neighboring threats
                # empire_id = fo.empireID()
                # for sys_id in neighbors:
                #     system = universe.getSystem(sys_id)
                #     if assertion_fails(system is not None):
                #         continue
                #     local_fleets = system.fleetIDs
                #     for fleet_id in local_fleets:
                #         fleet = universe.getFleet(fleet_id)
                #         if not fleet or fleet.ownedBy(empire_id):
                #             continue
                #         return sys_id

                debug("No neighboring threats. Moving to primary mission target")
                return primary_objective

            # TODO rate against threat in target system
            # TODO only engage if can reach in 1 turn or leaves sufficient defense behind
            fleet_rating = CombatRatingsAI.get_fleet_rating(self.fleet.id)
            debug("This fleet rating: %d. Enemy Rating: %d", fleet_rating, top_threat)
            safety_factor = get_aistate().character.military_safety_factor()
            if fleet_rating < safety_factor*top_threat:
                debug("Neighboring threat is too powerful. Moving to primary mission target")
                return primary_objective  # do not engage!

            debug("Engaging neighboring threat: %d", candidate_system)
            return candidate_system
Exemplo n.º 8
0
    def issue_fleet_orders(self):
        """issues AIFleetOrders which can be issued in system and moves to next one if is possible"""
        # TODO: priority
        order_completed = True

        debug("\nChecking orders for fleet %s (on turn %d), with mission type %s and target %s",
              self.fleet.get_object(), fo.currentTurn(), self.type or 'No mission', self.target or 'No Target')
        if MissionType.INVASION == self.type:
            self._check_retarget_invasion()
        just_issued_move_order = False
        last_move_target_id = INVALID_ID
        # Note: the following abort check somewhat assumes only one major mission type
        for fleet_order in self.orders:
            if (isinstance(fleet_order, (OrderColonize, OrderOutpost, OrderInvade)) and
                    self._check_abort_mission(fleet_order)):
                return
        aistate = get_aistate()
        for fleet_order in self.orders:
            if just_issued_move_order and self.fleet.get_object().systemID != last_move_target_id:
                # having just issued a move order, we will normally stop issuing orders this turn, except that if there
                # are consecutive move orders we will consider moving through the first destination rather than stopping
                # Without the below noinspection directive, PyCharm is concerned about the 2nd part of the test
                # noinspection PyTypeChecker
                if (not isinstance(fleet_order, OrderMove) or
                        self.need_to_pause_movement(last_move_target_id, fleet_order)):
                    break
            debug("Checking order: %s" % fleet_order)
            self.check_mergers(context=str(fleet_order))
            if fleet_order.can_issue_order(verbose=False):
                # only move if all other orders completed
                if isinstance(fleet_order, OrderMove) and order_completed:
                    debug("Issuing fleet order %s" % fleet_order)
                    fleet_order.issue_order()
                    just_issued_move_order = True
                    last_move_target_id = fleet_order.target.id
                elif not isinstance(fleet_order, OrderMove):
                    debug("Issuing fleet order %s" % fleet_order)
                    fleet_order.issue_order()
                else:
                    debug("NOT issuing (even though can_issue) fleet order %s" % fleet_order)
                status_words = tuple(["not", ""][_s] for _s in [fleet_order.order_issued, fleet_order.executed])
                debug("Order %s issued and %s fully executed." % status_words)
                if not fleet_order.executed:
                    order_completed = False
            else:  # check that we're not held up by a Big Monster
                if fleet_order.order_issued:
                    # A previously issued order that wasn't instantly executed must have had cirumstances change so that
                    # the order can't currently be reissued (or perhaps simply a savegame has been reloaded on the same
                    # turn the order was issued).
                    if not fleet_order.executed:
                        order_completed = False
                    # Go on to the next order.
                    continue
                debug("CAN'T issue fleet order %s because:" % fleet_order)
                fleet_order.can_issue_order(verbose=True)
                if isinstance(fleet_order, OrderMove):
                    this_system_id = fleet_order.target.id
                    this_status = aistate.systemStatus.setdefault(this_system_id, {})
                    threat_threshold = fo.currentTurn() * MilitaryAI.cur_best_mil_ship_rating() / 4.0
                    if this_status.get('monsterThreat', 0) > threat_threshold:
                        # if this move order is not this mil fleet's final destination, and blocked by Big Monster,
                        # release and hope for more effective reassignment
                        if (self.type not in (MissionType.MILITARY, MissionType.SECURE) or
                                fleet_order != self.orders[-1]):
                            debug("Aborting mission due to being blocked by Big Monster at system %d, threat %d" % (
                                this_system_id, aistate.systemStatus[this_system_id]['monsterThreat']))
                            debug("Full set of orders were:")
                            for this_order in self.orders:
                                debug(" - %s" % this_order)
                            self.clear_fleet_orders()
                            self.clear_target()
                            return
                break  # do not order the next order until this one is finished.
        else:  # went through entire order list
            if order_completed:
                debug("Final order is completed")
                orders = self.orders
                last_order = orders[-1] if orders else None
                universe = fo.getUniverse()

                if last_order and isinstance(last_order, OrderColonize):
                    planet = universe.getPlanet(last_order.target.id)
                    sys_partial_vis_turn = get_partial_visibility_turn(planet.systemID)
                    planet_partial_vis_turn = get_partial_visibility_turn(planet.id)
                    if (planet_partial_vis_turn == sys_partial_vis_turn and
                            not planet.initialMeterValue(fo.meterType.population)):
                        warn("Fleet %d has tentatively completed its "
                             "colonize mission but will wait to confirm population." % self.fleet.id)
                        debug("    Order details are %s" % last_order)
                        debug("    Order is valid: %s; issued: %s; executed: %s" % (
                            last_order.is_valid(), last_order.order_issued, last_order.executed))
                        if not last_order.is_valid():
                            source_target = last_order.fleet
                            target_target = last_order.target
                            debug("        source target validity: %s; target target validity: %s " % (
                                bool(source_target), bool(target_target)))
                        return  # colonize order must not have completed yet
                clear_all = True
                last_sys_target = INVALID_ID
                if last_order and isinstance(last_order, OrderMilitary):
                    last_sys_target = last_order.target.id
                    # not doing this until decide a way to release from a SECURE mission
                    # if (MissionType.SECURE == self.type) or
                    secure_targets = set(AIstate.colonyTargetedSystemIDs +
                                         AIstate.outpostTargetedSystemIDs +
                                         AIstate.invasionTargetedSystemIDs)
                    if last_sys_target in secure_targets:  # consider a secure mission
                        if last_sys_target in AIstate.colonyTargetedSystemIDs:
                            secure_type = "Colony"
                        elif last_sys_target in AIstate.outpostTargetedSystemIDs:
                            secure_type = "Outpost"
                        elif last_sys_target in AIstate.invasionTargetedSystemIDs:
                            secure_type = "Invasion"
                        else:
                            secure_type = "Unidentified"
                        debug("Fleet %d has completed initial stage of its mission "
                              "to secure system %d (targeted for %s), "
                              "may release a portion of ships" % (self.fleet.id, last_sys_target, secure_type))
                        clear_all = False

                # for PROTECT_REGION missions, only release fleet if no more threat
                if self.type == MissionType.PROTECT_REGION:
                    # use military logic code below to determine if can release
                    # any or even all of the ships.
                    clear_all = False
                    last_sys_target = self.target.id
                    debug("Check if PROTECT_REGION mission with target %d is finished.", last_sys_target)

                fleet_id = self.fleet.id
                if clear_all:
                    if orders:
                        debug("Fleet %d has completed its mission; clearing all orders and targets." % self.fleet.id)
                        debug("Full set of orders were:")
                        for this_order in orders:
                            debug("\t\t %s" % this_order)
                        self.clear_fleet_orders()
                        self.clear_target()
                        if aistate.get_fleet_role(fleet_id) in (MissionType.MILITARY, MissionType.SECURE):
                            allocations = MilitaryAI.get_military_fleets(mil_fleets_ids=[fleet_id],
                                                                         try_reset=False,
                                                                         thisround="Fleet %d Reassignment" % fleet_id)
                            if allocations:
                                MilitaryAI.assign_military_fleets_to_systems(use_fleet_id_list=[fleet_id],
                                                                             allocations=allocations)
                    else:  # no orders
                        debug("No Current Orders")
                else:
                    potential_threat = CombatRatingsAI.combine_ratings(
                        MilitaryAI.get_system_local_threat(last_sys_target),
                        MilitaryAI.get_system_neighbor_threat(last_sys_target)
                    )
                    threat_present = potential_threat > 0
                    debug("Fleet threat present? %s", threat_present)
                    target_system = universe.getSystem(last_sys_target)
                    if not threat_present and target_system:
                        for pid in target_system.planetIDs:
                            planet = universe.getPlanet(pid)
                            if (planet and
                                    planet.owner != fo.empireID() and
                                    planet.currentMeterValue(fo.meterType.maxDefense) > 0):
                                debug("Found local planetary threat: %s", planet)
                                threat_present = True
                                break
                    if not threat_present:
                        debug("No current threat in target system; releasing a portion of ships.")
                        # at least first stage of current task is done;
                        # release extra ships for potential other deployments
                        new_fleets = FleetUtilsAI.split_fleet(self.fleet.id)
                        if self.type == MissionType.PROTECT_REGION:
                            self.clear_fleet_orders()
                            self.clear_target()
                            new_fleets.append(self.fleet.id)
                    else:
                        debug("Threat remains in target system; Considering to release some ships.")
                        new_fleets = []
                        fleet_portion_to_remain = self._portion_of_fleet_needed_here()
                        if fleet_portion_to_remain > 1:
                            debug("Can not release fleet yet due to large threat.")
                        elif fleet_portion_to_remain > 0:
                            debug("Not all ships are needed here - considering releasing a few")
                            fleet_remaining_rating = CombatRatingsAI.get_fleet_rating(fleet_id)
                            fleet_min_rating = fleet_portion_to_remain * fleet_remaining_rating
                            debug("Starting rating: %.1f, Target rating: %.1f",
                                  fleet_remaining_rating, fleet_min_rating)
                            allowance = CombatRatingsAI.rating_needed(fleet_remaining_rating, fleet_min_rating)
                            debug("May release ships with total rating of %.1f", allowance)
                            ship_ids = list(self.fleet.get_object().shipIDs)
                            for ship_id in ship_ids:
                                ship_rating = CombatRatingsAI.get_ship_rating(ship_id)
                                debug("Considering to release ship %d with rating %.1f", ship_id, ship_rating)
                                if ship_rating > allowance:
                                    debug("Remaining rating insufficient. Not released.")
                                    continue
                                debug("Splitting from fleet.")
                                new_fleet_id = FleetUtilsAI.split_ship_from_fleet(fleet_id, ship_id)
                                if assertion_fails(new_fleet_id and new_fleet_id != INVALID_ID):
                                    break
                                new_fleets.append(new_fleet_id)
                                fleet_remaining_rating = CombatRatingsAI.rating_difference(
                                    fleet_remaining_rating, ship_rating)
                                allowance = CombatRatingsAI.rating_difference(
                                    fleet_remaining_rating, fleet_min_rating)
                                debug("Remaining fleet rating: %.1f - Allowance: %.1f",
                                      fleet_remaining_rating, allowance)
                            if new_fleets:
                                aistate.get_fleet_role(fleet_id, force_new=True)
                                aistate.update_fleet_rating(fleet_id)
                                aistate.ensure_have_fleet_missions(new_fleets)
                        else:
                            debug("Planetary defenses are deemed sufficient. Release fleet.")
                            new_fleets = FleetUtilsAI.split_fleet(self.fleet.id)

                    new_military_fleets = []
                    for fleet_id in new_fleets:
                        if aistate.get_fleet_role(fleet_id) in COMBAT_MISSION_TYPES:
                            new_military_fleets.append(fleet_id)
                    allocations = []
                    if new_military_fleets:
                        allocations = MilitaryAI.get_military_fleets(
                            mil_fleets_ids=new_military_fleets,
                            try_reset=False,
                            thisround="Fleet Reassignment %s" % new_military_fleets
                        )
                    if allocations:
                        MilitaryAI.assign_military_fleets_to_systems(use_fleet_id_list=new_military_fleets,
                                                                     allocations=allocations)
Exemplo n.º 9
0
def test_does_not_fail():
    assert not assertion_fails(True)
Exemplo n.º 10
0
def test_does_fail():
    assert assertion_fails(False)
Exemplo n.º 11
0
def test_message_argument():
    assert assertion_fails(False, "")
    assert assertion_fails(False, "Some message")
    assert not assertion_fails(True, "")
    assert not assertion_fails(True, "Some message")
Exemplo n.º 12
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()
    debug("Defined game rules:")
    for rule in rules.getRulesAsStrings:
        debug("Name: " + rule.name + "  value: " + str(rule.value))
    debug("Rule RULE_NUM_COMBAT_ROUNDS value: " + str(rules.getInt("RULE_NUM_COMBAT_ROUNDS")))

    empire = fo.getEmpire()
    if empire is None:
        fatal("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:
            error("Exception %s in doneTurn() on non-existent empire" % e, exc_info=True)
        return

    if empire.eliminated:
        debug("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:
            error("Exception %s while trying doneTurn() on eliminated empire" % e, exc_info=True)
        return

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

    turn = fo.currentTurn()
    aistate = get_aistate()
    turn_uid = aistate.set_turn_uid()
    debug("\n\n\n" + "=" * 20)
    debug("Starting turn %s (%s) of game: %s" % (turn, turn_uid, aistate.uid))
    debug("=" * 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(aistate.character)
    debug("***************************************************************************")
    debug("*******  Log info for AI progress chart script. Do not modify.   **********")
    debug("Generating Orders")
    debug("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()))
    debug("EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(empire))
    if planet:
        debug("CapitalID: " + str(planet_id) + " Name: " + planet.name + " Species: " + planet.speciesName)
    else:
        debug("CapitalID: None Currently Name: None Species: None ")
    debug("***************************************************************************")
    debug("***************************************************************************")

    # When loading a savegame, the AI will already have issued orders for this turn.
    # To avoid duplicate orders, generally try not to replay turns. However, for debugging
    # purposes it is often useful to replay the turn and observe varying results after
    # code changes. Set the replay_after_load flag in the AI config to let the AI issue
    # new orders after a game load. Note that the orders from the original savegame are
    # still being issued and the AIstate was saved after those orders were issued.
    # TODO: Consider adding an option to clear AI orders after load (must save AIstate at turn start then)
    if fo.currentTurn() == aistate.last_turn_played:
        info("The AIstate indicates that this turn was already played.")
        if not check_bool(get_option_dict().get('replay_turn_after_load', 'False')):
            info("Aborting new order generation. Orders from savegame will still be issued.")
            try:
                fo.doneTurn()
            except Exception as e:
                error("Exception %s while trying doneTurn()" % e, exc_info=True)
            return
        else:
            info("Issuing new orders anyway.")

    if turn == 1:
        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(aistate.character), greet))

    aistate.prepare_for_new_turn()
    turn_state.state.update()
    debug("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,
                   ]

    from freeorion_tools import assertion_fails
    print assertion_fails(False)
    print assertion_fails(True)
    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            error("Exception %s while trying to %s" % (e, action.__name__), exc_info=True)
    main_timer.stop_print_and_clear()
    turn_timer.stop_print_and_clear()

    debug('Size of issued orders: ' + str(fo.getOrders().size))

    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        error("Exception %s while trying doneTurn()" % e, exc_info=True)  # TODO move it to cycle above
    finally:
        aistate.last_turn_played = fo.currentTurn()

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
Exemplo n.º 13
0
def test_does_not_fail():
    assert not assertion_fails(True)
Exemplo n.º 14
0
def test_does_fail():
    assert assertion_fails(False)
Exemplo n.º 15
0
def test_message_argument():
    assert assertion_fails(False, "")
    assert assertion_fails(False, "Some message")
    assert not assertion_fails(True, "")
    assert not assertion_fails(True, "Some message")