コード例 #1
0
 def handle_midgame_chat(self, sender_player_id, message_txt):
     debug("Midgame chat received from player %d, message: %s" %
           (sender_player_id, message_txt))
     if fo.playerIsAI(sender_player_id) or not self.be_chatty:
         return
     if "BE QUIET" in message_txt.upper():
         possible_acknowledgments = UserStringList(
             "AI_BE_QUIET_ACKNOWLEDGEMENTS__LIST")
         acknowledgement = random.choice(possible_acknowledgments)
         debug(
             "Acknowledging 'Be Quiet' chat request with initial message (from %d choices): '%s'"
             % (len(possible_acknowledgments), acknowledgement))
         fo.sendChatMessage(sender_player_id, acknowledgement)
         self.be_chatty = False
         return
     if random.random() > 0.25:
         return
     possible_acknowledgments = UserStringList(
         "AI_MIDGAME_ACKNOWLEDGEMENTS__LIST")
     acknowledgement = random.choice(possible_acknowledgments)
     debug(
         "Acknowledging midgame chat with initial message (from %d choices): '%s'"
         % (len(possible_acknowledgments), acknowledgement))
     fo.sendChatMessage(sender_player_id, acknowledgement)
     self.be_chatty = False
コード例 #2
0
ファイル: DiplomaticCorp.py プロジェクト: zeners/freeorion
 def handle_diplomatic_message(self, message):
     """Handle a diplomatic message update from the server,
     such as if another player declares war, accepts peace, or cancels a proposed peace treaty.
     :param message: message.recipient and message.sender are respective empire IDs
     :return:
     """
     debug("Received diplomatic %s message from %s to %s." %
           (message.type, fo.getEmpire(
               message.sender), 'me' if message.recipient == fo.empireID()
            else fo.getEmpire(message.recipient)))
     # TODO: remove the following early return once proper support for third party diplomatic history is added
     if message.recipient != fo.empireID():
         return
     aistate = get_aistate()
     if message.type == fo.diplomaticMessageType.peaceProposal:
         aistate.log_peace_request(message.sender, message.recipient)
         proposal_sender_player = fo.empirePlayerID(message.sender)
         attitude = aistate.character.attitude_to_empire(
             message.sender, aistate.diplomatic_logs)
         possible_acknowledgments = []
         aggression = aistate.character.get_trait(Aggression)
         if aggression.key <= fo.aggression.typical:
             possible_acknowledgments = UserStringList(
                 "AI_PEACE_PROPOSAL_ACKNOWLEDGEMENTS_MILD_LIST")
             if attitude > 0:
                 possible_replies = UserStringList(
                     "AI_PEACE_PROPOSAL_RESPONSES_YES_MILD_LIST")
             else:
                 possible_replies = UserStringList(
                     "AI_PEACE_PROPOSAL_RESPONSES_NO_MILD_LIST")
         else:
             possible_acknowledgments = UserStringList(
                 "AI_PEACE_PROPOSAL_ACKNOWLEDGEMENTS_HARSH_LIST")
             if attitude > 0:
                 possible_replies = UserStringList(
                     "AI_PEACE_PROPOSAL_RESPONSES_YES_HARSH_LIST")
             else:
                 possible_replies = UserStringList(
                     "AI_PEACE_PROPOSAL_RESPONSES_NO_HARSH_LIST")
         acknowledgement = random.choice(possible_acknowledgments)
         reply_text = random.choice(possible_replies)
         debug(
             "Acknowledging proposal with initial message (from %d choices): '%s'"
             % (len(possible_acknowledgments), acknowledgement))
         fo.sendChatMessage(proposal_sender_player, acknowledgement)
         if attitude > 0:
             diplo_reply = fo.diplomaticMessage(
                 message.recipient, message.sender,
                 fo.diplomaticMessageType.acceptPeaceProposal)
             debug("Sending diplomatic message to empire %s of type %s" %
                   (message.sender, diplo_reply.type))
             fo.sendDiplomaticMessage(diplo_reply)
         debug(
             "sending chat to player %d of empire %d, message body: '%s'" %
             (proposal_sender_player, message.sender, reply_text))
         fo.sendChatMessage(proposal_sender_player, reply_text)
     elif message.type == fo.diplomaticMessageType.warDeclaration:
         # note: apparently this is currently (normally?) sent not as a warDeclaration,
         # but as a simple diplomatic_status_update to war
         aistate.log_war_declaration(message.sender, message.recipient)
コード例 #3
0
def chat_human(message):
    """
    Send chat message to human and print it to log.
    Log message cleared form tags.
    """
    human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    fo.sendChatMessage(human_id, message)
    print "\nChat Message to human: %s" % remove_tags(message)
コード例 #4
0
def chat_human(message):
    """
    Send chat message to human and print it to log.
    Log message cleared form tags.
    """
    human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    fo.sendChatMessage(human_id, message)
    print "\n%s\n" % remove_tags(message)
コード例 #5
0
ファイル: DiplomaticCorp.py プロジェクト: matthoppe/freeorion
def handle_pregame_chat(sender_player_id, message_txt):
    if fo.playerIsAI(sender_player_id):
        return
    possible_acknowledgments = UserStringList("AI_PREGAME_ACKNOWLEDGEMENTS__LIST")
    acknowledgement = random.choice(possible_acknowledgments)
    print "Acknowledging pregame chat with initial message (from %d choices): '%s'" % (
        len(possible_acknowledgments), acknowledgement)
    fo.sendChatMessage(sender_player_id, acknowledgement)
コード例 #6
0
def greet_on_first_turn(diplomatic_corp):
    if fo.currentTurn() != 1:
        return

    human_player = fo.empirePlayerID(1)
    greet = diplomatic_corp.get_first_turn_greet_message()
    trait_name = get_trait_name_aggression(get_aistate().character)
    fo.sendChatMessage(human_player,
                       f"{fo.getEmpire().name} ({trait_name}): [[{greet}]]")
コード例 #7
0
 def handle_midgame_chat(self, sender_player_id, message_txt):
     print "Midgame chat received from player %d, message: %s" % (sender_player_id, message_txt)
     if fo.playerIsAI(sender_player_id):
         return
     possible_acknowledgments = UserStringList("AI_MIDGAME_ACKNOWLEDGEMENTS__LIST")
     acknowledgement = random.choice(possible_acknowledgments)
     print "Acknowledging midgame chat with initial message (from %d choices): '%s'" % (
           len(possible_acknowledgments), acknowledgement)
     fo.sendChatMessage(sender_player_id, acknowledgement)
コード例 #8
0
def chat_human(message):
    """
    Send chat message to human and print it to log.
    Log message cleared form tags.
    """
    human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    message = str(message)
    fo.sendChatMessage(human_id, message)
    debug("Chat Message to human: %s", remove_tags(message))
コード例 #9
0
ファイル: _freeorion_tools.py プロジェクト: Ouaz/freeorion
def chat_human(message, send_to_logs=True):
    """
    Send chat message to human and print it to log.
    Log message cleared form tags.
    """
    human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    message = str(message)
    fo.sendChatMessage(human_id, message)
    if send_to_logs:
        debug("Chat Message to human: %s", remove_tags(message))
コード例 #10
0
def handle_debug_chat(sender, message):
    global debug_mode
    human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    ais = [x for x in fo.allPlayerIDs() if not fo.playerIsHost(x)]
    is_debug_chat = False
    if message == ENTERING_DEBUG_MESSAGE:
        is_debug_chat = True
    if sender != human_id:
        return is_debug_chat  # don't chat with bots
    elif message == 'stop':
        is_debug_chat = True
        if debug_mode:
            chat_human("exiting debug mode")
        debug_mode = False
    elif debug_mode:
        is_debug_chat = True
        out, err = shell(message)
        if out:
            chat_human(WHITE % out)
        if err:
            chat_human(RED % err)
    elif message.startswith('start'):
        is_debug_chat = True
        try:
            player_id = int(message[5:].strip())
        except ValueError as e:
            print e
            chat_human(str(e))
            return True
        if player_id == fo.playerID():
            debug_mode = True
            # add some variables to scope
            lines = ['import FreeOrionAI as foAI',
                     'ai = foAI.foAIstate',
                     'u = fo.getUniverse()',
                     'e = fo.getEmpire()'
                     ]
            shell(';'.join(lines))
            # Notify all players this AI entering debug mode
            fo.sendChatMessage(-1, WHITE % ENTERING_DEBUG_MESSAGE)
            chat_human(WHITE % "Print 'stop' to exit.")
            chat_human(WHITE % " Local vars: <u>u</u>(universe), <u>e</u>(empire), <u>ai</u>(aistate)")

    elif message == 'help':
        is_debug_chat = True
        if ais[0] == fo.playerID():
            chat_human(WHITE % "Chat commands:")
            chat_human(WHITE % "  <u><rgba 0 255 255 255>start id</rgba></u>: start debug for selected empire")
            chat_human(WHITE % "  <u><rgba 0 255 255 255>stop</rgba></u>: stop debug")
            chat_human(WHITE % "Empire ids:")
            for player in fo.allPlayerIDs():
                if not fo.playerIsHost(player):
                    chat_human('  <rgba {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}>id={0.empireID} empire_name={0.name}</rgba> player_name={1}'.format(fo.getEmpire(fo.playerEmpireID(player)), fo.playerName(player)))
    return is_debug_chat
コード例 #11
0
 def handle_diplomatic_message(self, message):
     """Handle a diplomatic message update from the server,
     such as if another player declares war, accepts peace, or cancels a proposed peace treaty.
     :param message: message.recipient and message.sender are respective empire IDs
     :return:
     """
     debug("Received diplomatic %s message from %s to %s." % (
         message.type, fo.getEmpire(message.sender),
         'me' if message.recipient == fo.empireID() else fo.getEmpire(message.recipient)))
     # TODO: remove the following early return once proper support for third party diplomatic history is added
     if message.recipient != fo.empireID():
         return
     aistate = get_aistate()
     if message.type == fo.diplomaticMessageType.peaceProposal:
         aistate.log_peace_request(message.sender, message.recipient)
         proposal_sender_player = fo.empirePlayerID(message.sender)
         attitude = aistate.character.attitude_to_empire(message.sender, aistate.diplomatic_logs)
         possible_acknowledgments = []
         aggression = aistate.character.get_trait(Aggression)
         if aggression.key <= fo.aggression.typical:
             possible_acknowledgments = UserStringList("AI_PEACE_PROPOSAL_ACKNOWLEDGEMENTS_MILD_LIST")
             if attitude > 0:
                 possible_replies = UserStringList("AI_PEACE_PROPOSAL_RESPONSES_YES_MILD_LIST")
             else:
                 possible_replies = UserStringList("AI_PEACE_PROPOSAL_RESPONSES_NO_MILD_LIST")
         else:
             possible_acknowledgments = UserStringList("AI_PEACE_PROPOSAL_ACKNOWLEDGEMENTS_HARSH_LIST")
             if attitude > 0:
                 possible_replies = UserStringList("AI_PEACE_PROPOSAL_RESPONSES_YES_HARSH_LIST")
             else:
                 possible_replies = UserStringList("AI_PEACE_PROPOSAL_RESPONSES_NO_HARSH_LIST")
         acknowledgement = random.choice(possible_acknowledgments)
         reply_text = random.choice(possible_replies)
         debug("Acknowledging proposal with initial message (from %d choices): '%s'" % (
             len(possible_acknowledgments), acknowledgement))
         fo.sendChatMessage(proposal_sender_player, acknowledgement)
         if attitude > 0:
             diplo_reply = fo.diplomaticMessage(message.recipient, message.sender,
                                                fo.diplomaticMessageType.acceptPeaceProposal)
             debug("Sending diplomatic message to empire %s of type %s" % (message.sender, diplo_reply.type))
             fo.sendDiplomaticMessage(diplo_reply)
         debug("sending chat to player %d of empire %d, message body: '%s'" % (
             proposal_sender_player, message.sender, reply_text))
         fo.sendChatMessage(proposal_sender_player, reply_text)
     elif message.type == fo.diplomaticMessageType.warDeclaration:
         # note: apparently this is currently (normally?) sent not as a warDeclaration,
         # but as a simple diplomatic_status_update to war
         aistate.log_war_declaration(message.sender, message.recipient)
コード例 #12
0
ファイル: debug_tools.py プロジェクト: J-d-H/freeorion
def print_error(msg, location=None, trace=True):
    """
    Sends error to host chat and print its to log.
    :param msg: message text
    :param location: text that describes error location
    :param trace: flag if print traceback
    """
    recipient_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    if location:
        message = '%s in "%s": "%s"' % (UserString('AI_ERROR_MSG', 'AI_Error: AI script error'), location, msg)
    else:
        message = '%s: "%s"' % (fo.userString('AI_ERROR_MSG'), msg)
    fo.sendChatMessage(recipient_id, message)
    print "\n%s\n" % message
    if trace:
        print format_exc()
コード例 #13
0
    def emit(self, record):
        """Emit a record.

        If a formatter is specified, it is used to format the record and then sent to human players. """
        try:
            human_ids = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)]
            if not human_ids:
                return
            msg = self.format(record)

            for human_id in human_ids:
                fo.sendChatMessage(human_id, msg)
        except (KeyboardInterrupt, SystemExit):
            raise
        # Hide errors from within the ConsoleLogHandler
        except:
            self.handleError(record)
コード例 #14
0
    def emit(self, record):
        """Emit a record.

        If a formatter is specified, it is used to format the record and then sent to human players. """
        try:
            human_ids = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)]
            if not human_ids:
                return
            msg = self.format(record)

            for human_id in human_ids:
                fo.sendChatMessage(human_id, msg)
        except (KeyboardInterrupt, SystemExit):
            raise
        # Hide errors from within the ConsoleLogHandler
        except:
            self.handleError(record)
コード例 #15
0
 def handle_midgame_chat(self, sender_player_id, message_txt):
     print "Midgame chat received from player %d, message: %s" % (sender_player_id, message_txt)
     if fo.playerIsAI(sender_player_id) or not self.be_chatty:
         return
     if "BE QUIET" in message_txt.upper():
         possible_acknowledgments = UserStringList("AI_BE_QUIET_ACKNOWLEDGEMENTS__LIST")
         acknowledgement = random.choice(possible_acknowledgments)
         print "Acknowledging 'Be Quiet' chat request with initial message (from %d choices): '%s'" % (
             len(possible_acknowledgments), acknowledgement)
         fo.sendChatMessage(sender_player_id, acknowledgement)
         self.be_chatty = False
         return
     if random.random() > 0.25:
         return
     possible_acknowledgments = UserStringList("AI_MIDGAME_ACKNOWLEDGEMENTS__LIST")
     acknowledgement = random.choice(possible_acknowledgments)
     print "Acknowledging midgame chat with initial message (from %d choices): '%s'" % (
         len(possible_acknowledgments), acknowledgement)
     fo.sendChatMessage(sender_player_id, acknowledgement)
     self.be_chatty = False
コード例 #16
0
ファイル: FreeOrionAI.py プロジェクト: magnate/freeorion
def handleDiplomaticMessage(message):  # pylint: disable=invalid-name
    """Called when this player receives a diplomatic message update from the server,
    such as if another player declares war, accepts peace, or cancels a proposed peace treaty."""
    print "Received diplomatic %s message from empire %s to empire %s" % (
        message.type, message.sender, message.recipient)
    print "my empire id: %s" % fo.empireID()
    if message.type == fo.diplomaticMessageType.peaceProposal and message.recipient == fo.empireID(
    ):
        reply_sender = message.recipient
        reply_recipient = message.sender
        proposal_sender_player = fo.empirePlayerID(message.sender)
        fo.sendChatMessage(
            proposal_sender_player,
            "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(proposal_sender_player,
                               "OK, Peace offer accepted.")
            reply = fo.diplomaticMessage(
                reply_sender, reply_recipient,
                fo.diplomaticMessageType.acceptProposal)
            print "Sending diplomatic message to empire %s of type %s" % (
                reply_recipient, reply.type)
            fo.sendDiplomaticMessage(reply)
        else:
            fo.sendChatMessage(
                proposal_sender_player,
                "Maybe later. We are currently getting busy with Experimental Test Subject yo-Ma-ma."
            )
コード例 #17
0
ファイル: DiplomaticCorp.py プロジェクト: matthoppe/freeorion
 def handle_diplomatic_message(self, message):
     """Handle a diplomatic message update from the server,
     such as if another player declares war, accepts peace, or cancels a proposed peace treaty.
     :param message: message.recipient and message.sender are respective empire IDs
     :return:
     """
     print "Received diplomatic %s message from %s to %s." % (
         message.type, fo.getEmpire(message.sender),
         'me' if message.recipient == fo.empireID() else fo.getEmpire(message.recipient))
     # TODO: remove the following early return once proper support for third party diplomatic history is added
     if message.recipient != fo.empireID():
         return
     if message.type == fo.diplomaticMessageType.peaceProposal:
         foAI.foAIstate.log_peace_request(message.sender, message.recipient)
         proposal_sender_player = fo.empirePlayerID(message.sender)
         suffix = "MILD" if foAI.foAIstate.aggression <= fo.aggression.typical else "HARSH"
         possible_acknowledgments = UserStringList("AI_PEACE_PROPOSAL_ACKNOWLEDGEMENTS_" + suffix + "_LIST")
         acknowledgement = random.choice(possible_acknowledgments)
         print "Acknowledging proposal with initial message (from %d choices): '%s'" % (
             len(possible_acknowledgments), acknowledgement)
         fo.sendChatMessage(proposal_sender_player, acknowledgement)
         attitude = self.evaluate_diplomatic_attitude(message.sender)
         if attitude > 0:
             reply_text = random.choice(UserStringList("AI_PEACE_PROPOSAL_RESPONSES_YES_" + suffix + "_LIST"))
             diplo_reply = fo.diplomaticMessage(message.recipient, message.sender,
                                                fo.diplomaticMessageType.acceptProposal)
             print "Sending diplomatic message to empire %s of type %s" % (message.sender, diplo_reply.type)
             fo.sendDiplomaticMessage(diplo_reply)
         else:
             reply_text = random.choice(UserStringList("AI_PEACE_PROPOSAL_RESPONSES_NO_" + suffix + "_LIST"))
         print "sending chat to player %d of empire %d, message body: '%s'" % (
             proposal_sender_player, message.sender, reply_text)
         fo.sendChatMessage(proposal_sender_player, reply_text)
     elif message.type == fo.diplomaticMessageType.warDeclaration:
         # note: apparently this is currently (normally?) sent not as a warDeclaration,
         # but as a simple diplomatic_status_update to war
         foAI.foAIstate.log_war_declaration(message.sender, message.recipient)
コード例 #18
0
ファイル: FreeOrionAI.py プロジェクト: Ablu/freeorion
def handleDiplomaticMessage(message):
    print "Received diplomatic " + str(message.type) + " message from empire " + str(message.sender) + " to empire " + str(message.recipient)
    print "my empire id: " + str(fo.empireID())
    if (message.type == fo.diplomaticMessageType.peaceProposal and message.recipient == fo.empireID()):
        replySender = message.recipient
        replyRecipient = message.sender
        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.")
コード例 #19
0
ファイル: FreeOrionAI.py プロジェクト: TeoTwawki/freeorion
def handleDiplomaticMessage(message):  # pylint: disable=invalid-name
    """Called when this player receives a diplomatic message update from the server,
    such as if another player declares war, accepts peace, or cancels a proposed peace treaty."""
    print "Received diplomatic %s message from empire %s to empire %s" % (message.type, message.sender, message.recipient)
    print "my empire id: %s" % fo.empireID()
    if message.type == fo.diplomaticMessageType.peaceProposal and message.recipient == fo.empireID():
        reply_sender = message.recipient
        reply_recipient = message.sender
        proposal_sender_player = fo.empirePlayerID(message.sender)
        fo.sendChatMessage(proposal_sender_player, "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(proposal_sender_player, "OK, Peace offer accepted.")
            reply = fo.diplomaticMessage(reply_sender, reply_recipient, fo.diplomaticMessageType.acceptProposal)
            print "Sending diplomatic message to empire %s of type %s" % (reply_recipient, reply.type)
            fo.sendDiplomaticMessage(reply)
        else:
            fo.sendChatMessage(proposal_sender_player, "Maybe later. We are currently getting busy with Experimental Test Subject yo-Ma-ma.")
コード例 #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."""

    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
コード例 #21
0
ファイル: FreeOrionAI.py プロジェクト: MatGB/freeorion
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
コード例 #22
0
ファイル: FreeOrionAI.py プロジェクト: Deepsloth/freeorion
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
コード例 #23
0
ファイル: FreeOrionAI.py プロジェクト: magnate/freeorion
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
コード例 #24
0
ファイル: FreeOrionAI.py プロジェクト: zeners/freeorion
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."""
    try:
        rules = fo.getGameRules()
        debug("Defined game rules:")
        for rule_name, rule_value in rules.getRulesAsStrings().items():
            debug("%s: %s", rule_name, rule_value)
        debug("Rule RULE_NUM_COMBAT_ROUNDS value: " + str(rules.getInt("RULE_NUM_COMBAT_ROUNDS")))
    except Exception as e:
        error("Exception %s when trying to get game rules" % e, exc_info=True)

    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,
                   ]

    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
コード例 #25
0
def generateOrders():  # pylint: disable=invalid-name
    """
    Called once per turn to tell the Python AI to generate
    and issue orders, i.e. to control its empire.

    After leaving this function, the AI's turn will be finished
    and its orders will be sent to the server.
    """
    try:
        rules = fo.getGameRules()
        debug("Defined game rules:")
        for rule_name, rule_value in rules.getRulesAsStrings().items():
            debug("%s: %s", rule_name, rule_value)
        debug("Rule RULE_NUM_COMBAT_ROUNDS value: " +
              str(rules.getInt("RULE_NUM_COMBAT_ROUNDS")))
    except Exception as e:
        error("Exception %s when trying to get game rules" % e, exc_info=True)

    # If nothing can be ordered anyway, exit early.
    # Note that there is no need to update meters etc. in this case.
    empire = fo.getEmpire()
    if empire is None:
        fatal("This client has no empire. Aborting order generation.")
        return

    if empire.eliminated:
        info("This empire has been eliminated. Aborting order generation.")
        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()
    debug("\n\n\n" + "=" * 20)
    debug(f"Starting turn {turn}")
    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)
    empire = fo.getEmpire()
    aggression_name = get_trait_name_aggression(aistate.character)
    debug(
        "***************************************************************************"
    )
    debug(
        "*******  Log info for AI progress chart script. Do not modify.   **********"
    )
    debug("Generating Orders")

    name_parts = (
        empire.name,
        empire.empireID,
        "pid",
        fo.playerID(),
        fo.playerName(),
        "RIdx",
        ResearchAI.get_research_index(),
        aggression_name.capitalize(),
    )
    empire_name = "_".join(str(part) for part in name_parts)

    debug(f"EmpireID: {empire.empireID} Name: {empire_name} Turn: {turn}")

    debug(f"EmpireColors: {empire.colour}")
    planet_id = PlanetUtilsAI.get_capital()
    if planet_id:
        planet = fo.getUniverse().getPlanet(planet_id)
        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."
            )
            return
        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()
    debug("Calling AI Modules")
    # call AI modules
    action_list = [
        ColonisationAI.survey_universe,
        ShipDesignAI.Cache.update_for_new_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:
            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()

    turn_timer.start("Server_Processing")

    aistate.last_turn_played = fo.currentTurn()
コード例 #26
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
コード例 #27
0
def handle_debug_chat(sender, message):
    global debug_mode
    human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0]
    ais = [x for x in fo.allPlayerIDs() if not fo.playerIsHost(x)]
    is_debug_chat = False
    if message == ENTERING_DEBUG_MESSAGE:
        is_debug_chat = True
    if sender != human_id:
        return is_debug_chat  # don't chat with bots
    elif message == 'stop':
        is_debug_chat = True
        if debug_mode:
            chat_human("exiting debug mode")
        debug_mode = False
    elif debug_mode:
        is_debug_chat = True
        out, err = shell(message)
        if out:
            chat_human(WHITE % out)
        if err:
            chat_human(RED % err)
    elif message.startswith('start'):
        is_debug_chat = True
        try:
            player_id = int(message[5:].strip())
        except ValueError as e:
            print e
            chat_human(str(e))
            return True
        if player_id == fo.playerID():
            debug_mode = True
            # add some variables to scope
            lines = [
                'import FreeOrionAI as foAI', 'ai = foAI.foAIstate',
                'u = fo.getUniverse()', 'e = fo.getEmpire()'
            ]
            shell(';'.join(lines))
            # Notify all players this AI entering debug mode
            fo.sendChatMessage(-1, WHITE % ENTERING_DEBUG_MESSAGE)
            chat_human(WHITE % "Print 'stop' to exit.")
            chat_human(
                WHITE %
                " Local vars: <u>u</u>(universe), <u>e</u>(empire), <u>ai</u>(aistate)"
            )

    elif message == 'help':
        is_debug_chat = True
        if ais[0] == fo.playerID():
            chat_human(WHITE % "Chat commands:")
            chat_human(
                WHITE %
                "  <u><rgba 0 255 255 255>start id</rgba></u>: start debug for selected empire"
            )
            chat_human(WHITE %
                       "  <u><rgba 0 255 255 255>stop</rgba></u>: stop debug")
            chat_human(WHITE % "Empire ids:")
            for player in fo.allPlayerIDs():
                if not fo.playerIsHost(player):
                    chat_human(
                        '  <rgba {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}>id={0.empireID} empire_name={0.name}</rgba> player_name={1}'
                        .format(fo.getEmpire(fo.playerEmpireID(player)),
                                fo.playerName(player)))
    return is_debug_chat