Difference between revisions of "AI Python API"

From FreeOrionWiki
Jump to: navigation, search
m (ResourceCenter)
m (PopCenter)
Line 247: Line 247:
 
SubClasses: [[#Planet|Planet]]<br>
 
SubClasses: [[#Planet|Planet]]<br>
 
SubClass Of:<br>
 
SubClass Of:<br>
* '''allocatedFood()''' - Returns the amount of food (double) that has been allocated to this PopCenter.
+
====Properties====
 +
* '''allocatedFood''' - Returns the amount of food (double) that has been allocated to this PopCenter.
  
 
===Planet===
 
===Planet===

Revision as of 23:14, 15 August 2010

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 if the planet can't be found or isn't owned by this player, or if the specified focus is not valid on the planet.
  • 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 if the indicated tech can't be found. Will return 1 (int) but do nothing if the indicated tech can't be enqueued by this player's empire.
  • 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 if the indicated tech can't be found. Will return 1 (int) but do nothing if the indicated tech isn't on this player's empire's tech queue.
  • 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 if there is no such building or it is not available to this player's empire, or if the building can't be produced at the specified location.
  • 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 there is no such ship design or it not available to this player's empire, or if the design can't be produced at the specified location.
  • 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 if the old and new queue indices are equal, if either queue index is less than 0 or greater than the largest indexed item on the queue.
  • 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 if the queue index is less than 0 or greater than the largest indexed item on the queue.
  • 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 if any of the name, description, hull or graphic are empty strings, if the design is invalid (due to not following number and type of slot requirements for the hull) or if creating the design fails for some reason.
  • 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.
  • fleetIDs - An IntVec containing ids of all Fleets in the universe.
  • systemIDs - An IntVec containing ids of all Systems in the universe.
  • planetIDs - An IntVec containing ids of all Planets in the universe.
  • shipIDs - An IntVec containing ids of all Ships in the universe.
  • buildingIDs - An IntVec containing ids of all Buildings in the universe.

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, empireID) - Returns true if the system with ID systemID (int) has at least one starlane to any other system that is known of by the empire with id empireID (int). Returns false otherwise.
  • systemsConnected(systemID1, SystemID2, empireID) - Returns true (bool) if the systems with ids systemID1 (int) and systemID2 (int) have a series of starlanes connecting them directly or indirectly via other systems, that is known of by the empire with id empireID (int). 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(systemID1, systemID2, empireID) - Returns a list of system IDs (IntVec) that is the series of starlane jumps between systems with ids systemID1 (int) and systemID2 (int) that takes the fewest jumps (but not necessarily the shortest travel distance / time), as far as the empire with ID empireID (int) knowns. Empires generally don't know what other systems are visible to other empires, so specifying any empireID other than this client's empire's ID probably won't return an accurate result. May return an empty list if no path between the systems exists.
  • shortestPath(systemID1, systemID2, empireID) -- Returns a list of system IDs (IntVec) that is the series of starlane jumps between systems with ids systemID1 (int) and systemID2 (int) that is the shortest route (not the same as fewest jumps) as far as the empire with ID empireID (int) knowns. Empires generally don't know what other systems are visible to other empires, so specifying any empireID other than this client's empire's ID probably won't return an accurate result. May return an empty list if no path between the systems exists.
  • dump() - Returns a text representation of the objects (string) contained in the Universe. Probably only useful for debugging purposes if output to the log file.

UniverseObject

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

Properties

  • id - An internal unique identification number (int) for each object.
  • name - The name of an object (string).
  • x - The x-coordinate of the object's location in the universe (double).
  • y - The y-coordinate of the object's location in the universe (double).
  • systemID - The id (int) of the system in which the object is located. May be -1 to indicate the object is not in a system.
  • unowned - True (bool) if the object has no owners, false (bool) otherwise.
  • owners - The list of empire IDs (IntSet) of empires that own this object. Generally will be only a single empire or no empires, except for systems that may contain multiple empires' planets.
  • creationTurn - The turn number (int) on which this object was created. If an object was created before the start of the game, this should be a large negative number.
  • ageInTurns - The age in turns (int) of this object. If an object was created before the start of the game, this should be a large negative number.
  • specials - A list of names (StringSet) of specials attached to this object.

Functions

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

Fleet

SubClasses:
SubClass Of: UniverseObject

  • fuel() - Returns current fuel (double) available to this fleet, which is the smallest of the fuels on ships in the fleet.
  • maxFuel() - Returns the maximum fuel (double) capacity of this fleet, which is the smallest of the fuel capacities of ships in the fleet.
  • finalDestinationID() - Returns the id (int) of the system to which this fleet has been ordered to move. May return -1 to indicate there is no destination.
  • previousSystemID() - Returns the id (int) of the system from which the fleet most recently departed. May return -1 to indicate there is no previous system.
  • nextSystemID() - Returns the id (int) of the system to which the fleet is moving next. May return -1 to indicate there is no next system.
  • speed() - Returns the speed (double) of movement along starlanes for this fleet, which is the smallest of the starlane movement speeds of ships in the fleet. This returns the same value regardless of whether the fleet is currently moving or is stationary.
  • canChangeDirectionEnRoute() - Returns true (bool) if this fleet can change directions while in the middle of a starlane, or false (bool) otherwise.
  • hasArmedShips() - Returns true (bool) if this fleet contains one or more ships with weapons, or false (bool) otherwise.
  • hasColonyShips() - Returns true (bool) if this fleet contains one or more ships with colonists on board that can colonize a planet, or false (bool) otherwise.
  • numShips() - Returns the number (int) of ships in this fleet.
  • empty() - Returns true (bool) if this fleet contains no ships, or false (bool) if the fleet contains at least one ship. This might happen in the middle of a turn after ordering a ship transfer between fleets.
  • shipIDs() - Returns the ids (IntVec) of ships in this fleet.

Ship

SubClasses:
SubClass Of: UniverseObject

  • designID() -
  • fleetID() -
  • 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

Properties

  • buildingType - Returns the building type object (BuildingType) of this building.
  • buildingTypeName - Returns the building type name (string) of this building.
  • planetID - Returns the id (int) of the planet on which this buidling is located.

BuildingType

SubClasses:
SubClass Of:

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

ResourceCenter

SubClasses: Planet
SubClass Of:

Properties

  • 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:

Properties

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

Planet

SubClasses:
SubClass Of: UniverseObject, ResourceCenter, PopCenter

Properties

  • size - Planet size (planetSize) of planet.
  • type - Planet type (planetType) of planet.
  • buildingIDs - Ids (IntVec) of IDs of buildings on planet.

System

SubClasses:
SubClass Of: UniverseObject

Properties

  • starType - Returns the star type (StarType) of this system.
  • numOrbits - Returns the number of orbits (int) in which planets could be located in the system.
  • numStarlanes - Returns the number (int) of known starlanes connected to this system.
  • numWormholes - Returns the number (int) of known wormholes connected to this system.
  • 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.

Functions

  • HasStarlaneToSystemID(systemID) - Returns true (bool) if this system has a known direct starlane connection to the system with the indicated ID, and false (bool) otherwise.
  • HasWormholeToSystemID(systemID) - Returns true (bool) if this system has a known direct wormhole connection to the system with the indicated ID, and false (bool) otherwise.

Note that Universe also has the SystemHasStarlane function, which indicates whether a particular system has any starlanes visible to a particular empire.

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()"