Difference between revisions of "LuaAPI/ai"

From The Battle for Wesnoth Wiki
(Document the ai module)
 
(Move Maps: More info on the output format)
Line 109: Line 109:
 
* '''ai.get_enemy_src_dst'''() → ''move map''
 
* '''ai.get_enemy_src_dst'''() → ''move map''
  
These functions return move maps – tables that relate the current positions of units with the hexes they can move to.
+
These functions return move maps – tables that relate the current positions of units with the hexes they can move to. A move map is a location set, similar to the advancements map, which can be converted to a standard location set with the following code:
 +
 
 +
<syntaxhighlight lang=lua>
 +
local location_set = wesnoth.require "location_set"
 +
local ls = location_set.create()
 +
ls.values = ai.get_dst_src()
 +
-- Now you can use it as a regular location set
 +
print(ls[{1,4}]) -- prints out something like {{5,4},{5,3}} or the like
 +
</syntaxhighlight>
  
 
These functions are defined in ''ai/lua/stdlib.lua'', which is loaded by default if you allow the game to implicitly define a Lua [engine] tag. However, if you require a custom Lua [engine] tag, it must load this file manually with the following code in order to use these functions:
 
These functions are defined in ''ai/lua/stdlib.lua'', which is loaded by default if you allow the game to implicitly define a Lua [engine] tag. However, if you require a custom Lua [engine] tag, it must load this file manually with the following code in order to use these functions:

Revision as of 13:32, 1 July 2021

Code executed by Wesnoth AI components has access to the ai module, which contains functions for controlling the AI and querying AI information. Thus, all functions on this page are only available to AI code.

  • ai.read_onlyboolean

The AI module operates in two modes: read-only, and read-write. Read-write mode is used in the execution function for stages and candidate actions, while read-only mode is used in goals and aspects and in the evaluation function for candidate actions. The read_only key allows you to distinguish these cases at runtime, if necessary. Functions that are only available in read-write mode will be tagged (mutable) in the descriptions on this page.

  • ai.sidenumber

The side number that the AI module is bound to.

Game State Queries

ai.aspects

  • ai.aspects.aspectvalue

Provides access to the aspects of the AI engine. This fetches the result of the aspect evaluation given the game state when it was last refreshed (see aspect invalidation rules), not its definition. So, for example, ai.aspects.avoid returns the list of avoided hexes, not the Standard Location Filter that produced them, and a dynamic Lua aspect will return the result of calling the function, not the function itself.

The following aspects return scalar values (numbers, strings, or booleans):

  • aggression
  • caution
  • grouping
  • leader_aggression
  • leader_ignores_keep
  • leader_value
  • passive_leader
  • passive_leader_shares_keep
  • recruitment_diversity
  • recruitment_randomness
  • retreat_enemy_weight
  • retreat_factor
  • scout_village_targeting
  • simple_targeting
  • support_villages
  • village_value
  • villages_per_scout

For more details, see the definition of each aspect on AiWML.

The following aspects return tables:

  • advancements – a location set mapping locations to a list of possible advancements for the unit on that hex. To convert this to a location set:
    local location_set = wesnoth.require "location_set"
    local ls = location_set.create()
    ls.values = ai.aspects.advancements
    -- Now you can use it as a regular location set
    
  • attacks – a table with keys own containing all units that can attack and enemy containing all units that can be attacked.
  • avoid – an array of locations.
  • leader_goal – the WML content of the leader_goal aspect
  • recruitment_instructions – the WML content of the recruitment_instructions aspect
  • recruitment_more – an array of strings where each string is a usage, a unit type ID, or an integer
  • recruitment_pattern – an array of usage strings (see UnitTypeWML for an explanation of usage)
  • recruitment_save_gold – the WML content of the recruitment_save_gold aspect

ai.get_attacks

  • ai.get_attacks() → array of attack analyses

Get all possible attacks the AI could perform, and an analysis of each. Each attack analysis table has the following keys:

  • analysis.rating() → numeric rating
  • analysis.movementsarray of location pairs
    • move.srclocation
    • move.dstlocation
  • analysis.targetlocation
  • analysis.target_valuenumber
  • analysis.avg_lossesnumber
  • analysis.'chance_to_killprobability
  • analysis.avg_damage_inflictednumber
  • analysis.target_starting_damageinteger
  • analysis.avg_damage_takennumber
  • analysis.resources_usednumber
  • analysis.terrain_qualitynumber
  • analysis.alternative_terrain_qualitynumber
  • analysis.vulnerabilitynumber
  • analysis.supportnumber
  • analysis.leader_threatboolean
  • analysis.uses_leaderboolean
  • analysis.is_surroundedboolean

ai.get_targets

  • ai.get_targets() → array of targets

Get a list of all the current AI targets. Each target has the following keys:

  • loc: The coordinates of the target, as a 2-element array.
  • type: The type of target, as a string.
  • value: The value of the target, as a real number.

The possible target types are 'village', 'leader', 'explicit', 'threat', 'battle aid', 'mass', 'support'. More information on the meaning of each type can be found in the LuaAI documentation.

ai.suitable_keep

  • ai.suitable_keep(unit) → x, y

This returns the location of the closest keep to the unit passed as argument.

Move Maps

  • ai.get_dst_src() → move map
  • ai.get_src_dst() → move map
  • ai.get_enemy_dst_src() → move map
  • ai.get_enemy_src_dst() → move map

These functions return move maps – tables that relate the current positions of units with the hexes they can move to. A move map is a location set, similar to the advancements map, which can be converted to a standard location set with the following code:

local location_set = wesnoth.require "location_set"
local ls = location_set.create()
ls.values = ai.get_dst_src()
-- Now you can use it as a regular location set
print(ls[{1,4}]) -- prints out something like {{5,4},{5,3}} or the like

These functions are defined in ai/lua/stdlib.lua, which is loaded by default if you allow the game to implicitly define a Lua [engine] tag. However, if you require a custom Lua [engine] tag, it must load this file manually with the following code in order to use these functions:

local ai_stdlib = wesnoth.require('ai/lua/stdlib.lua')
ai_stdlib.init(ai)

AI Actions

All these functions instruct the AI to check or perform a specific action, and return a result table indicating the success of the action. The table has the following keys:

  • gamestate_changed: a boolean indicating whether anything actually changed as a result of the action
  • ok: a boolean indicating the success of the action
  • status: a numeric status code indicating why the action failed
  • result: a string error code indicating why the action failed

ai.attack

  • (mutable) ai.check_attack(attacker, defender, weapon, aggression) → result

Execute attack by attacker against defender. If weapon is provided, it is the number of the weapon to be used (count starts at 1, not 0, as always in Lua), otherwise the choice of the weapon is left to the AI engine. If aggression is provided, it is used to influence the choice of the best weapon. Obviously, this only makes sense if this choice is left to the engine, that is, if weapon is set to either 'nil' or '-1'.

ai.check_attack

  • ai.check_attack(attacker, defender, weapon, aggression) → result

Similar to ai.attack, but does not execute the attack – it merely checks if it would succeed.

ai.move

  • (mutable) ai.move(unit, to) → result

Execute a "partial" move of unit to hex (to.x, to.y). A "partial" move means that the unit keeps whatever movement points it has left after the move.

ai.move_full

  • (mutable) ai.move_full(unit, to) → result

Execute a "full" move of unit to hex (to.x, to.y). A "full" move means that the unit's movement points are set to zero at the end of the move.

ai.check_move

  • ai.check_move(unit, to) → result

Similar to ai.move or ai.move_full, but does not execute the move – it merely checks if it would succeed.

ai.recall

  • (mutable) ai.recall(unit_id, location) → result

Recall the unit with id unit_id. An optional recruit location can be given. If the location is omitted, a suitable hex is automatically chosen by the AI engine.

Note: The location must be specified as separate x and y parameters in 1.16.x.

ai.check_recall

  • ai.check_recall(unit_id, location) → result

Similar to ai.recall, but does not execute the recall – it merely checks if it would succeed.

ai.recruit

  • (mutable) ai.recruit(unit_type, location) → result

Recruit a unit of type unit_type. An optional recruit location can be given. If the location is omitted, a suitable hex is automatically chosen by the AI engine.

Note: The location must be specified as separate x and y parameters in 1.16.x.

ai.check_recruit

  • ai.check_recruit(unit_type, location) → result

Similar to ai.recruit, but does not execute the recruit – it merely checks if it would succeed.

ai.stopunit_attacks

  • (mutable) ai.stopunit_attacks(unit) → result

Remove remaining attacks from unit. This is equivalent to setting attacks_left=0.

ai.stopunit_moves

  • (mutable) ai.stopunit_moves(unit) → result

Remove remaining movement points from unit. This is equivalent to setting moves=0.

ai.stopunit_all

  • (mutable) ai.stopunit_all(unit) →

Remove both remaining attacks and remaining movement points from unit.

ai.check_stopunit

  • ai.check_stopunit(unit) → result

Similar to ai.stopunit_attacks, ai.stopunit_moves, or ai.stopunit_all, but does not execute the stop – it merely checks if it would succeed.

ai.fallback_human

  • (mutable) ai.fallback_human()

Hands over control of this side to the local human player until the end of the current turn. This action does not return a result; it always succeeds.