AI Python API

From FreeOrionWiki
Revision as of 19:32, 15 August 2010 by Geoff the Medio (Talk | contribs) (Functions)

Jump to: navigation, search

FreeOrion provides an embedded Python interface for writing AI scripts to determine AI behaviours. Python scripts can be easily modified and used without need to recompile the AI executable. This page provides (or will provide) an overview of FreeOrion AI Python scripting and a reference for the FreeOrion AI Python interface.

FreeOrion AI scripts work by acting like a player: examining the gamestate, deciding on strategies, and issuing orders... essentially playing the game just like a player, except without a GUI. The AI script can't directly modify the game universe by creating buildings or planets or ships from nothing, as these are not powers available to any player. If the AI wants a new ship, it needs to order its production and wait for it to complete, just like a player. Similarly, the AI client is given the same information that any player, human or AI, receives about the gamestate, based on what ships, planets, system, etc. that the player's empire knows about. AIs play by the same rules as human players.

The FreeOrion AI interface provides functions and classes to access the known game Universe and its contents, Empires and player information, as well as functions to issue orders and for logging or debug purposes. (Essentially) all these functions and classes are exposed to Python in the freeOrionAIInterface module, which can be imported into Python scripts executed by the FreeOrion AI executable.

Scripting Structure

The FreeOrion AI executable looks for an AI script file:

/default/AI/FreeOrionAI.py

This main AI script file must contain the following Python functions for the FreeOrion AI client to execute properly:

  • initFreeOrionAI() - Called when the AI client is first started. Doesn't need to do anything.
  • startNewGame() - Called when a new game is started (but not when a game is loaded). Should clear any pre-existing AI state and set up whatever the AI script needs to generate orders.
  • resumeLoadedGame(savedStateString) - Called when a saved game is loaded. The savedStateString (string) parameter will contain AI state information from when the game was saved, and this information should be extracted now so that the AI script can resume from where it was when the game was saved. If a script does not need to restore state information, resumeLoadedGame() can do nothing.
  • prepareForSave() - Called when the game is about to be saved. The AI script should compact any state information it wishes to retain when a game is later loaded into a single string (This can be done using Python's pickle library). The setSaveStateString() function is used to set the save state string, and should be called within prepareForSave(). If a script does not need to save state information, prepareForSave() can do nothing.
  • handleChatMessage(senderID, messageText) - Called when this player receives a text message. The AI script can reply using the sendChatMessage() function, or can ignore the message. senderID (int) is the player ID of the player who send the message, and messageText (string) is the text of the sent message.
  • generateOrders() - Called once per turn to tell the AI script that it should generate and issue orders for the current turn. Within this function the doneTurn() function should be called to indicate that the script is done issuing orders for this turn. Not calling doneTurn() within generateOrders() or within another function called by generateOrders() will cause the FreeOrion server to wait indefinitely for the AI's turn to complete.

freeOrionAIInterface

Within FreeOrionAI.py and within any other script files called by it, the freeOrionAIInterface module should be imported:

import freeOrionAIInterface as fo

This module provides all the functions and classes used to access the gamestate that the AI player knows about and all the functions used to issue orders, interact with other players, save game state or to end the AI player's turn. The following functions and classes are all contained within freeOrionAIInterface.

Logging

FreeOrion AI Python scripts are run by the AI executable, which does not have any display or user interface. In order to see error messages or debug output from scripts, the AI executable redirects standard output and error to the AI log file. Any error output that is produced during execution of a script will appear in the FreeOrion AI log file automatically. To generate debug output, simply use the built-in python print command:

print "this will generate debug output"

The printed text will appear int he FreeOrion AI log file.

Free Functions

The following functions are exposed to Python in the freeOrionAIInterface module:

  • playerName() - Returns the name (string) of this AI player.
  • playerName(playerID) - Returns the name (string) of the player with the indicated playerID (int).
  • playerID() - Returns the integer id of this AI player.
  • empirePlayerID(empireID) - Returns the player ID (int) of the player who is controlling the empire with the indicated empireID (int).
  • allPlayerIDs() - Returns an object (intVec) that contains the player IDs of all players in the game.
  • playerIsAI(playerID) - Returns true (boolean) if the player with the indicated playerID (int) is controlled by an AI and false (boolean) otherwise.
  • playerIsHost(playerID) - Returns true (booean) if the player with the indicated playerID (int) is the host player for the game and false (boolean) otherwise.
  • empireID() - Returns the empire ID (int) of this AI player's empire.
  • playerEmpireID(playerID) - Returns the empire ID (int) of the player with the specified player ID (int).
  • allEmpireIDs() - Returns an object (intVec) that contains the empire IDs of all empires in the game.
  • getEmpire() - Returns the empire object (Empire) of this AI player
  • getEmpire(empireID) - Returns the empire object (Empire) with the specified empire ID (int)
  • getUniverse() - Returns the universe object (Universe)
  • validShipDesign(hull, parts) - Returns true (boolean) if the passed hull (string) and parts (StringVec) make up a valid ship design, and false (boolean) otherwise. Valid ship designs don't have any parts in slots that can't accept that type of part, and contain only hulls and parts that exist (and may also need to contain the correct number of parts - this needs to be verified).
  • validShipDesign(shipDesign) - Returns true (boolean) if the passed ship design (ShipDesign) is valid, and false otherwise.
  • getShipDesign(id) - Returns the ship design (ShipDesign) with the indicated id number (int).
  • getPartType(name) - Returns the ship part (PartType) with the indicated name (string).
  • getHullType(name) - Returns the ship hull (HullType) with the indicated name (string).
  • getBuildingType(name) - Returns the building type (BuildingType) with the indicated name (string).
  • getSpecial(name) - Returns the special (Special) with the indicated name (string).
  • getTech(name) - Returns the tech (Tech) with the indicated name (string).
  • getTechCategories() - Returns the names of all tech categories (StringVec).
  • techs() - Returns the names of all techs (StringVec).
  • techsInCategory(name) - Returns the names of all techs (StringVec) in the indicated tech category name (string).
  • currentTurn() - Returns the current game turn (int).
  • issueFleetMoveOrder(fleetID, destinationID) - Orders the fleet with indicated fleetID (int) to move to the system with the indicated destinationID (int). Returns 1 (int) on success or 0 (int) on failure due to not finding the indicated fleet or system.
  • issueRenameOrder(objectID, name) - Orders the renaming of the object with indicated objectID (int) to the new indicated name (string). Returns 1 (int) on success or 0 (int) on failure due to this AI player not being able to rename the indicated object (which this player must fully own, and which must be a fleet, ship or planet).
  • issueScrapOrder(objectID) - Orders the ship or building with the indicated objectID (int) to be scrapped. Returns 1 (int) on success or 0 (int) on failure due to not finding a ship or building with the indicated ID, or if the indicated ship or building is not owned by this AI client's empire.
  • issueNewFleetOrder(name, shipIDs) - Orders a new fleet to be created with the indicated name (string) and containing the indicated shipIDs (IntVec). The ships must be located in the same system and must all be owned by this player. Returns 1 (int) on success or 0 (int) on failure due to one of the noted conditions not being met.
  • issueFleetTransferOrder(shipID, newFleetID) - Orders the ship with ID shipID (int) to be transferred to the fleet with ID newFleetID. Returns 1 (int) on success, or 0 (int) on failure due to not finding the fleet or ship, or the client's empire not owning either, or the two not being in the same system (or either not being in a system) or the ship already being in the fleet.
  • issueColonizeOrder(shipID, planetID) - Orders the ship with ID shipID (int) to colonize the planet with ID planetID (int). Returns 1 (int) on success or 0 (int) on failure due to not finding the indicated ship or planet, this client's player not owning the indicated ship, the planet already being colonized, or the planet and ship not being in the same system.
  • issueChangeFocusOrder(planetID, focus) - Orders the planet with ID planetID (int) to use focus setting focus (string). Returns 1 (int) on success or 0 (int) on failure.
  • issueEnqueueTechOrder(techName, position) - Orders the tech with name techName (string) to be added to the tech queue at position (int) on the queue. Returns 1 (int) on success or 0 (int) on failure.
  • issueDequeueTechOrder(techName) - Orders the tech with name techName (string) to be removed from the queue. Returns 1 (int) on success or 0 (int) on failure.
  • issueEnqueueBuildingProductionOrder(buildingName, locationID) - Orders the building with name (string) to be added to the production queue at the location of the planet with id locationID. Returns 1 (int) on success or 0 (int) on failure.
  • issueEnqueueShipProductionOrder(designID, locationID) - Orders the ship design with ID designID (int) to be added to the production queue at the location of the planet with id locationID (int). Returns 1 (int) on success or 0 (int) on failure.
  • issueRequeueProductionOrder(oldQueueIndex, newQueueIndex) - Orders the item on the production queue at index oldQueueIndex (int) to be moved to index newQueueIndex (int). Returns 1 (int) on success or 0 (int) on failure.
  • issueDequeueProductionOrder(queueIndex) - Orders the item on the production queue at index queueIndex (int) to be removed form the production queue. Returns 1 (int) on success or 0 (int) on failure.
  • IssueCreateShipDesignOrder(name, description, hull, partsVec, graphic, model) - Orders the creation of a new ship design with the name (string), description (string), hull (string), parts vector partsVec (StringVec), graphic (string) and model (string). model should be left as an empty string as of this writing. There is currently no easy way to find the id of the new design, though the client's empire should have the new design after this order is issued successfully. Returns 1 (int) on success or 0 (int) on failure.
  • sendChatMessage(recipientID, message) - Sends the indicated message (string) to the player with the indicated recieipientID (int) or to all players if recipientID is -1.
  • setSaveStateString(saveStateString) - Sets the save state string (string). This is a persistant storage space for the AI script to retain state information when the game is saved and reloaded. Any AI state information to be saved should be stored in a single string (likely using Python's pickle module) and stored using this function when the prepareForSave() Python function is called.
  • getSaveStateString() - Returns the previously-saved state string (string). Can be used to retreive the last-set save state string at any time, although this string is also passed to the resumeLoadedGame(savedStateString) Python function when a game is loaded, so this function isn't necessary to use if resumeLoadedGame stores the passed string.
  • doneTurn() - Ends the AI player's turn, indicating to the server that all orders have been issued and turn processing may commence.

Classes

Universe

SubClasses:
SubClass Of:

The Universe class contains the majority of FreeOrion gamestate: All the UniverseObjects in the game, and all ShipDesigns in the game. (Other gamestate is contained in the Empire class.) The Universe class provides functions with which to access objects in it and information about connections and paths between systems.

Properties

  • allObjectIDs - An IntVec containing ids of all objects in the universe.
  • systemIDs - An IntVec containing ids of all Systems in the universe.
  • fleetIDs - An IntVec containing ids of all Fleets in the universe.
  • invalidObjectID - A special object id (int) used to indicate no object or an invalid object when an object id (int) is required.
  • invalidObjectAge - A special value (int) used to indicate an invalid object age, which might be the age (ageInTurns property) of a UniverseObject if an object has no valid age.

Functions

  • getObject(id) - Returns the UniverseObject in the universe with the indicated id (int), or None if no object exists with that id.
  • getFleet(id) - Returns the Fleet in the universe with the indicated id (int), or None if no fleet exists with that id.
  • getShip(id) - Returns the Ship in the universe with the indicated id (int), or None if no ship exists with that id.
  • getPlanet(id) - Returns the Planet in the universe with the indicated id (int), or None if no planet exists with that id.
  • getSystem(id) - Returns the System in the universe with the indicated id (int), or None if no system exists with that id.
  • getBuilding(id) - Returns the Building in the universe with the indicated id (int), or None if no building exists with that id.
  • systemHasStarlane(systemID) - Returns true if the system with ID systemID (int) has at least one (known) starlane to any other system. Returns false otherwise.
  • systemsConnected(systemID1, SystemID2) - Returns true (bool) if the systems with ids systemID1 (int) and systemID2 (int) have a (known) series of starlanes connecting them directly or indirectly via other systems. Returns false (bool) otherwise.
  • updateMeterEstimates() - Recalculates the estimated next-turn meter values of all objects in the universe, taking into account any orders that this player has issued since the start of the current turn. To have object meters updated, this function must be called after issuing any meter-altering orders, including issueChangeFocusOrder.
  • leastJumpsPath() -
  • shortestPath() -

UniverseObject

SubClasses: Fleet, Ship, Building, Planet, System
SubClass Of:

Properties

  • id -
  • name -
  • x -
  • y -
  • systemID -
  • unowned -
  • owners -
  • creationTurn -
  • ageInTurns -
  • specials -

Functions

  • ownedBy() -
  • whollyOwnedBy() -
  • Contains() -
  • ContainedBy() -
  • MeterPoints() -
  • ProjectedMeterPoints() -
  • CurrentMeter() -
  • ProjectedCurrentMeter() -
  • MaxMeter() -
  • ProjectedMaxMeter() -

Fleet

SubClasses:
SubClass Of: UniverseObject

  • fuel() -
  • maxFuel() -
  • finalDestinationID() -
  • previousSystemID() -
  • nextSystemID() -
  • speed() -
  • canChangeDirectionEnRoute() -
  • hasArmedShips() -
  • hasColonyShips() -
  • numShips() -
  • empty() -
  • shipIDs() -

Ship

SubClasses:
SubClass Of: UniverseObject

  • designID() -
  • fleetID() -
  • getFleet() -
  • isArmed() -
  • canColonize() -
  • speed() -

ShipDesign

SubClasses:
SubClass Of:

  • id() -
  • name() -
  • description() -
  • designedByEmpireID() -
  • designedOnTurn() -
  • starlaneSpeed() -
  • battleSpeed() -
  • defense() -
  • speed() -
  • attack() -
  • canColonize() -
  • cost() -
  • buildTime() -
  • hull() -
  • parts() -
  • partsInSlotType() -
  • graphic() -
  • model() -
  • productionLocationForEmpire() -

PartType

SubClasses:
SubClass Of:

  • name() -
  • canMountInSlotType() -

HullType

SubClasses:
SubClass Of:

  • name() -
  • numSlots() -
  • numSlotsOfSlotType() -
  • slots() -

Building

SubClasses:
SubClass Of: UniverseObject

  • getBuildingType() -
  • operating() -
  • getPlanet() -

BuildingType

SubClasses:
SubClass Of:

  • name() -
  • description() -
  • buildCost() -
  • buildTime() -
  • maintenanceCost() -
  • captureResult() -

ResourceCenter

SubClasses: Planet
SubClass Of:

  • Focus() - Returns the focus setting (string) to which the resource center is set.
  • AvailableFoci() - Returns a list (StringVec) of names of focus settings that are available for this resource center.

PopCenter

SubClasses: Planet
SubClass Of:

  • allocatedFood() - Returns the amount of food (double) that has been allocated to this PopCenter.

Planet

SubClasses:
SubClass Of: UniverseObject, ResourceCenter, PopCenter

System

SubClasses:
SubClass Of: UniverseObject

  • starType() -
  • numOrbits() -
  • numStarlanes() -
  • numWormholes() -
  • HasStarlaneToSystemID() -
  • HasWormholeToSystemID() -
  • allObjectIDs() - IntVec of IDs of objects in this system.
  • planetIDs() - IntVec of IDs of planets in this system.
  • fleetIDs() - IntVec of IDs fleets in this system.

Special

SubClasses:
SubClass Of:

  • name() - Name (string) of this special.
  • description() - Description (string) of this special.

Empire

Subclasses:
Subclass Of:

  • name() -
  • playerName() -
  • empireID() -
  • capitolID() -
  • buildingTypeAvailable() -
  • availableBuildingTypes() -
  • shipDesignAvailable() -
  • availableShipDesigns() -
  • productionQueue() -
  • techResearched() -
  • availableTechs() -
  • getTechStatus() -
  • researchStatus() -
  • researchQueue() -
  • canBuild() -
  • canBuild() -
  • hasExploredSystem() -
  • exploredSystemIDs() -
  • productionPoints() -
  • resourceStockpile() -
  • resourceProduction() -
  • resourceAvailable() -
  • population() -
  • fleetSupplyableSystemIDs() -
  • supplyUnobstructedSystems() -

ResearchQueue

Subclasses:
Subclass Of:

  • researchQueue() -
  • __iter__() -
  • __getitem__() -
  • __len__() -
  • size() -
  • empty() -
  • inQueue() -
  • inQueue() -
  • __contains__() -
  • totalSpent() -

ResearchQueueElement

Subclasses:
Subclass Of:

  • tech() -
  • spending() -
  • turnsLeft() -

ProductionQueue

Subclasses:
Subclass Of:

  • productionQueue() -
  • __iter__() -
  • __getitem__() -
  • __len__() -
  • size() -
  • empty() -
  • totalSpent() -

ProductionQueueElement

Subclasses:
Subclass Of:

  • name() -
  • designID() -
  • buildType() - buildType of iten on queue.
  • locationID() -
  • spending() -
  • turnsLeft() -

Tech

Subclasses:
Subclass Of:

  • tech() -
  • name() -
  • description() -
  • shortDescription() -
  • type() -
  • category() -
  • researchCost() -
  • researchTurns() -
  • prerequisites() -
  • unlockedTechs() -

Enumerations

starType

  • blue -
  • white -
  • yellow -
  • orange -
  • red -
  • neutron -
  • blackHole -

planetSize

  • tiny -
  • small -
  • medium -
  • large -
  • huge -
  • asteroids -
  • gasGiant -

planetType

  • swamp -
  • radiated -
  • toxic -
  • inferno -
  • barren -
  • tundra -
  • desert -
  • terran -
  • ocean -
  • asteroids -
  • gasGiant -

planetEnvironment

  • uninhabitable -
  • hostile -
  • poor -
  • adequate -
  • good -

techType

  • theory -
  • application -
  • refinement -

techStatus

  • unresearchable -
  • researchable -
  • complete -

buildType

  • building -
  • ship -

resourceType

  • food -
  • minerals -
  • industry -
  • trade -
  • research -

meterType

  • population - Population of a planet. Usually used to influence resource output.
  • targetPopulation - Stable population of a planet. When less, population will generally increase towards target population. When more, population will generally decrease.
  • health - Health of a planet. Generally determines the rate of increase or decrease of population. When below 20, population will always decrease.
  • targetHealth - Stable health of a planet. Like population and target population, health moves towards target health.
  • farming - Food output per turn of a planet.
  • targetFarming - Value towards which food meter moves each turn.
  • industry - Industry output per turn of a planet.
  • targetIndustry - Industry moves towards this value.
  • research - Research output per turn of a planet.
  • targetResearch - Research moves towards this value.
  • trade - Trade output per turn of a planet.
  • targetTrade - Trade moves towards this value.
  • mining - Minerals output of a planet.
  • targetMining - Mining moves towards this value.
  • construction - Determines distance away planets can share / pool resource output of minearals, food and insdustry.
  • targetConstruction - Construction moves towards this value.
  • fuel - Number of starlane jumps a ship can make. Always refilled each turn when within fleet supply distance of a planet.
  • maxFuel - Maximum value fuel meter can have.
  • shield - Used in combat to absorb damage.
  • maxShield - Maximum value of shield meter.
  • structure - Tracks damage to ships. Structure of 0 destroys a ship.
  • maxStructure - Max value structure meter can have.
  • defense - Used to determine planets' combat strength.
  • maxDefense - Max value of defense meter.
  • foodConsumption - Determines how much food a planet needs each turn to maintain its population.
  • supply - How many starlane jumps away a planet can resupply ships' fuel and ammunition.
  • stealth - Reduces the distance away that detection of an object is possible. Interacts with detection meter.
  • detection - The distance away that another object of stealth (just above) 0 can be detected by an object owned by an empire. Stealth 0 objects can always be seen, but anything with nonzero stealth needs to be within the detection range of an object to be seen by an empire that does not own the detected object.
  • battleSpeed - How fast per combat turn a ship moves.
  • starlaneSpeed - How far per game turn a ship moves along starlanes.

captureResult

  • capture -
  • destroy -
  • retain -
  • share -

shipSlotType

  • external -
  • internal -

shipPartClass

  • shortrange -
  • missiles -
  • fighters -
  • pointdefense -
  • shields -
  • armour -
  • detection -
  • stealth -
  • fuel -
  • colony -
  • battlespeed -
  • starlanespeed -

STL Containers

Two types of C++ Standard Template Library (STL) containers are returned by FreeOrion Python AI interface functions: set and vector. Both set and vector may be returned containing integers or strings. All four combinations (integer set, integer vector, string set, string vector) are treated as separate classes in Python. All have been exposed to Python, and may be iterated over and treated like normal Python containers: C++ sets act similarly to Python frozenset and C++ vectors act similarly to Python lists.

IntSet and StringSet

Both specializations of C++ set act similarly to a Python frozenset containing a single type of object (int or string, respectively). The following functions are defined:

  • __str__() - Returns a string representation of the set. Usage: "str(setObject)"
  • __len__() - Returns the length (int) of the set. Usage: "len(setObject)"
  • size() - Returns the length (int) of the set. Usage: "setObject.size()"
  • empty() - Returns true (boolean) if the set is empty, or false (boolean) if the set contains at least one int or string. Usage: "setObject.empty()"
  • __contains__(item) - Returns true (boolean) if the set contains item (int or string). Usage: "item in SetObject"
  • count(item) - Returns the number (int) of item (int or string) held in the set.
  • __iter__ - Returns a Python iterator object for the set, pointing to the first element in the set. Allows iteration over the contents of the set in Python: "for item in setObject: ..."

IntVec and StringVec

Both specializations of C++ vector act similarly to a Python list containing a single type of object (int or string, respectively). The following functions are defined:

  • __len__() - Returns the length (int) of the vector. Usage: "len(vectorObject)"
  • __getitem__(key) - Returns the item (int or string) with index key (int) in the vector. Indices range from 0 to len(vectorObject) - 1. Indices can also be specified as a negative integer, which counts backwards from the end of the vector. Usage: "vectorObject[5]" or "vectorObject[-8:-2]"
  • __iter__() - Returns a Python iterator object for the vector, pointing to the first element in the vector. Allows iteration over the contents of the vector in Python: "for item in vectorObject: ..."
  • __contains__(item) - Returns true if the indicated item (int or string) is contained in the vector, and false otherwise. Usage: "23 in intVecObject"
  • __setitem__(key, item) - Sets the item with indicated key (int) equal to the indicated item (int or string). Usage: "intVecObject[23] = 52" or "stringVecObject[2] = 'example string'" or "intVecObject[:] = [1, 2, 4, 10, 8]"
  • __delitem__(key) - Removes the item with indicated key (int) from the vector, shifting higher-keyed items back to compensate. Usage: "del intVecObject[2]" or "del intVecObject[-4:-1]"
  • IntVec and StringVec may also be created as new objects in Python, which is useful when a function requires one as input. Usage: "vecObject = IntVec()"