Difference between revisions of "Micro AIs"

From The Battle for Wesnoth Wiki
(Patrol specific keys for the [micro_ai] tag:)
(Note how [micro_ai] side= can take a list of sides as of 1.17.0)
 
(383 intermediate revisions by 11 users not shown)
Line 1: Line 1:
Mirco AIs allow Wesnoth campaign and scenario authors to add new AI functionality without the need for any AI programming.  A Micro AI is activated and configured (or deleted) via the [micro_ai] tag, requiring only a few lines of WML code.  Note that this is a new functionality and theat '''we are very much looking for feedback''' on bugs, new feature requests for the existing AIs or ideas for new Micro AIs.
+
== A Few General Words about Micro AIs ==
  
Micro AIs are available in mainline Wesnoth '''starting from Version 1.11.2'''.  Additional AIs that are still in an experimental stage are available in the ''AI Modification Demos'' add-on, which also might contain more advanced (development) versions of the mainline Micro AIs.
+
* Micro AIs allow Wesnoth campaign and scenario authors to add new AI functionality without the need for any AI programming. They bring new specialized behavior to Wesnoth that cannot be achieved, at least not easily, by adjusting default AI parameters (such as those described at [[AiWML]]) or with WML code.
  
== A Few General Words about Micro AIs ==
+
* A Micro AI is activated and configured (or deleted) via the [micro_ai] tag placed in an event, requiring only a few lines of WML code. {{DevFeature1.15|?}} Starting in 1.16 the [micro_ai] tag may also be used in [side][ai] or [unit][ai]. These are both shorthands for placing it in the prestart event with "action=add", side set to the side, and in the case of [unit][ai], a [filter] tag set to limit the Micro AI to that one unit.
 +
 
 +
* '''Before Wesnoth 1.13.6''', the Micro AI behavior was inconsistent when it came to '''hidden enemies and petrified units'''.  Some Micro AIs ignored those, while others did not.  In some case there was even a potential for AI errors when an AI unit ran into hidden or petrified enemies.  As of 1.13.6, this has all been fixed.  The Micro AIs now correctly and consistently ignore hidden units and treat petrified units as blocking the hex they are on but having no effect otherwise, in the same way as the default AI does.  '''Important notes:'''
 +
** It is not possible to re-include hidden/petrified units via the Standard Unit Filters (SUFs) used by some of the Micro AIs. In fact, if this is attempted, the filters will generally not match any unit.
 +
*** This only applies to SUFs which go directly into the [micro_ai] tag. Any SUF that is a sub-tag of another filter (for example, of a Standard Location Filter) is taken literally and returns all units matching the filter. If hidden or petrified units are to be excluded from such a sub-filter, that needs to be specified directly in that filter.
 +
** We also note that, because all the Micro AIs are written in Lua, it is possible to [[Micro_AIs#Using_Development_.281.13.29_Version_Micro_AIs_in_your_Stable_.281.12.29_Version_Add-on|move a Micro AI's code into one's add-on]] and modify it to whatever scenario-specific behavior is desired (this does not only apply to hidden/petrified units, but to all behavior). Setting up general Micro AI behavior that works in every possible setting is not feasible, but adapting it to work (only) in the specific setting of a given scenario is often quite simple. If you do not know how to do this, please post a message on the Wesnoth forums and we will be happy to help you with it.
 +
 
 +
* The '''[[AiWML#List_of_AI_Aspects|default AI aspects]] are, for the most part, not taken into account by the Micro AIs'''.  For example, unless noted otherwise, specifying a value for ''aggression'' does not change the MAI behavior.  The exception is the ''[avoid]'' tag which is taken into account by many Micro AIs (except those for which it would interfere with the Micro AI behavior or those that already use a a [[StandardLocationFilter|Standard Location Filter]] that can be used for the same purpose).  This is a feature of the Micro AIs, not a bug.  If you feel that a certain default AI aspect should also apply to a Micro AI, please let us know in the [http://forums.wesnoth.org/viewtopic.php?f=10&t=39456 Micro AIs Feedback thread].
  
* Micro AIs are meant to bring new specialized behavior to Wesnoth that cannot be achieved, at least not easily, by adjusting default AI parameters (such as those described at [[AiWML]]) or with WML code.
+
* '''Before Wesnoth 1.13.7''', the Micro AIs did not all work reliably when the '''AI side is under shroud''' and it may have been necessary to turn shroud off for the side when using a Micro AI. {{DevFeature1.13|7}} The Micro AIs now all work for sides under shroud. They do this by disregarding shroud for terrain purposes when path finding, consistent with default Wesnoth AI behavior, while still ignoring hidden units (including those hidden under shroud) correctly.
  
 
* Most Micro AIs in their default setting apply to all units of a side, although many of them provide parameters for filtering the units that should be affected by the new behavior.  If the Micro AI is applied only to part of the units of a side, the other units follow the default Wesnoth AI behavior.
 
* Most Micro AIs in their default setting apply to all units of a side, although many of them provide parameters for filtering the units that should be affected by the new behavior.  If the Micro AI is applied only to part of the units of a side, the other units follow the default Wesnoth AI behavior.
  
* By contrast, a few Micro AIs attach directly to a unit and only affect that unit's behavior.  These are so-called [[Lua_AI_Howto#Behavior_.28Sticky.29_Candidate_Actions|Behavior Candidate Actions]] (BCAs). This type of Micro AI has an [[Micro_AIs#2._Activating_and_configuring_.28or_deleting.29_a_Micro_AI|ai_type=]] value ending in ''_unit'', in order to distinguish it from the side-wide Micro AIs.
+
* Micro AIs are available in mainline since Wesnoth 1.11/1.12.
 +
 
 +
== Micro AI Test and Demo Scenarios ==
  
=== Micro AI Test and Demo Scenarios ===
+
All Micro AIs described here can be checked out in a number of test and demo scenarios.  The easiest way to access the test scenarios is by assigning a hotkey to "Start Test Scenario" in the preferences (as of Wesnoth 1.13.8). Then, simply press the hotkey in the titlescreen and select the desired scenario from the list (e.g. 'micro_ai_test' for the overall "switchboard scenario").
  
All Micro AIs described here can be checked out in a number of test and demo scenarios.  Test scenarios can be accessed from the command line by typing
+
Test scenarios can also be accessed from the command line by typing
 
  path/wesnoth-executable -t micro_ai_test
 
  path/wesnoth-executable -t micro_ai_test
 +
or (depending on your system and Wesnoth version)
 +
path/wesnoth-executable -tmicro_ai_test
 
This starts up a "switchboard scenario" in which you can select the Micro AI demonstration scenario you want to check out.  Here, ''path/wesnoth-executable'' needs to be replaced by whatever the path and filename of the Wesnoth executable is on your system.
 
This starts up a "switchboard scenario" in which you can select the Micro AI demonstration scenario you want to check out.  Here, ''path/wesnoth-executable'' needs to be replaced by whatever the path and filename of the Wesnoth executable is on your system.
 
Another way to test the Micro AIs (as well as some other AIs still under development) is to download the ''AI Modification Demos'' add-on.  All the test/demo scenarios are also available there.
 
  
 
== Setting up a Micro AI ==
 
== Setting up a Micro AI ==
  
Setting up a Micro AI is done in two simple steps:
+
Setting up a Micro AI requires only one simple step:
 
+
==== Activating and configuring (or deleting) a Micro AI ====
==== 1. Enabling the Micro AI functionality in the [side] tag ====
 
 
 
The desired AI functionality needs to be enabled for a side before it can be used.  This is done by including a single macro line inside the [side] tag, such as:
 
    {MICRO_AI_HEALER_SUPPORT}
 
The exact macro name depends on the specific Micro AI and is given below for each AI.  This macro must be put '''directly into the [side] tag''', it does not go inside an [ai] tag.  This step does not yet activate the Micro AI, it simply sets up the desired functionality.
 
 
 
==== 2. Activating and configuring (or deleting) a Micro AI ====
 
  
 
Micro AIs are activated, deleted and configured using the [micro_ai] tag.  This tag needs to be placed in [[ActionWML]], that is, in an event, a menu option or the like.  As an example, the following code activates the healer_support Micro AI in its default configuration for Side 2 from the beginning of the scenario:
 
Micro AIs are activated, deleted and configured using the [micro_ai] tag.  This tag needs to be placed in [[ActionWML]], that is, in an event, a menu option or the like.  As an example, the following code activates the healer_support Micro AI in its default configuration for Side 2 from the beginning of the scenario:
Line 42: Line 44:
 
         [/micro_ai]
 
         [/micro_ai]
 
     [/event]
 
     [/event]
All [micro_ai] tags must contain the following three (or four) required keys:
+
'''Keys required for all Micro AIs:'''
* '''side''': The side for which the Micro AI is to be added, changed or deleted
+
All [micro_ai] tags must contain the following three required keys:
 +
* '''side''': The side for which the Micro AI is to be added, changed or deleted. {{DevFeature1.17|0}} this can be a list of sides.
 
* '''ai_type''': The type of Micro AI to be added, changed or deleted.  See the following sections for allowed values.
 
* '''ai_type''': The type of Micro AI to be added, changed or deleted.  See the following sections for allowed values.
 
* '''action''' (string): The action to take concerning the Micro AI.  The following values are allowed:  
 
* '''action''' (string): The action to take concerning the Micro AI.  The following values are allowed:  
Line 49: Line 52:
 
** ''change'': Change the configuration of an existing Micro AI.  Note that this does not only change the specific parameters provided in the tag, but it replaces the entire existing Micro AI by a new version with the new (and only the new) configuration.  It is therefore equivalent to using first the ''delete'' and then the ''add'' action.
 
** ''change'': Change the configuration of an existing Micro AI.  Note that this does not only change the specific parameters provided in the tag, but it replaces the entire existing Micro AI by a new version with the new (and only the new) configuration.  It is therefore equivalent to using first the ''delete'' and then the ''add'' action.
 
** ''delete'': Delete an existing Micro AI from a side.
 
** ''delete'': Delete an existing Micro AI from a side.
* '''id''': If the Micro AI attaches directly to a unit, rather than being side-wide, the id of the unit is also a required parameter.
 
  
Other keys may also be required depending on the Micro AI.  In additional, a number of optional keys may be available to configure the AI behavior.  See the following sections on the individual Micro AIs for details.
+
'''Keys required under certain circumstances:'''
 +
* '''ca_id''': (string) If several MAIs of the same type are used for the same side and one or several of these are to be changed or deleted during a scenario, this key needs to be included so that the [micro_ai] tag knows which of them needs to be changed/deleted.  The same is also true if a Micro AI is changed more than once during a scenario.  We therefore '''strongly recommend always setting ''ca_id''''' for MAIs which are, or might be, changed or deleted during a scenario.
 +
** '''Note:''' The id(s)/name(s) actually assigned to the CA(s) of the MAI by the engine might be different from the parameter passed here.  It is, however, sufficient to use this ca_id with the [micro_ai] tag add/delete/change actions to identify the MAI uniquely.  (In other words: you don't have to worry about this if you always use the [micro_ai] tag, but might have to figure out the actual name(s) of the CA(s) if you want to delete or change them manually.)
 +
* Other keys may also be required depending on the Micro AI.  In additional, a number of optional keys may be available to configure the AI behavior.  See the sections on the individual Micro AIs for details.
 +
 
 +
'''Required keys for deleting a Micro AI:'''
 +
 
 +
Only a subset of the keys required for setting up a Micro AI are needed when deleting it.  '''side''', '''ai_type''' and '''action'''=delete always need to be provided.  '''ca_id''' needs to be given if it was provided when adding the Micro AI (see above for when this is needed).
  
 
'''Notes:'''  
 
'''Notes:'''  
* The ''add'' and ''change'' actions ignore all keys that do not apply to the respective Micro AI type.  The ''delete'' action ignores all keys other than the three (or four) required keys listed here.
+
* The ''add'' and ''change'' actions ignore all keys that do not apply to the respective Micro AI type.  The ''delete'' action ignores all keys other than the required keys listed above.
  
 
* Some of the Micro AIs use and/or modify default AI components (candidate actions or aspects) when they are added, or reset these components to their default values when they are deleted.  Thus, if you have modified the AI yourself using the default CAs or aspects, some of these modifications might be affected, or might be interfering with the Micro AI.  The sections below indicate whether a Micro AI modifies any default AI components.
 
* Some of the Micro AIs use and/or modify default AI components (candidate actions or aspects) when they are added, or reset these components to their default values when they are deleted.  Thus, if you have modified the AI yourself using the default CAs or aspects, some of these modifications might be affected, or might be interfering with the Micro AI.  The sections below indicate whether a Micro AI modifies any default AI components.
  
* It is currently not possible to combine different Micro AI types (AIs using different values of ai_type=) on the same side.  In other words, you can use several guardians (and even different guardian types) on the same side (as they are all handled by the Guardian Micro AI), but it is not possible to put, for example, guardians and patrollers on the same sideThis restriction will be lifted in an upcoming releaseIn the meantime, you will have to use different (allied) sides to accomplish this.
+
===Combining Different Micro AI Types for the Same Side===
 +
 
 +
No extra steps need to be taken when combining different Micro AIs on the same side.  Simply set up the [micro_ai] tags for all AIs you want to use.
 +
 
 +
'''Notes:'''
 +
* While it is ''technically'' possible to combine any number of Micro AIs, this does not mean that all Micro AIs work together in practice.  Some are not compatible because they control units in contradictory ways. 
 +
* Not all combinations that ''should'' work have been tested yet.  If you find a combination that you believe should work but doesn't, [http://forums.wesnoth.org/viewtopic.php?f=10&t=39456 please let us know] and we will see if that can be fixed.
 +
* The candidate action score almost certainly has to be set (using the ca_score= key) for one or several of the MAIs if several of them are used on the same side.
 +
 
 +
== Animals Micro AIs ==
 +
=== General Comments on the Animal Micro AIs ===
 +
 
 +
The Animals Micro AIs are meant to simulate the behaviors of certain types of animalsThey are, however, set up so that they can be used with arbitrary unit types and might be applicable in quite diverse situations.  The AIs nevertheless remain named after the animals for which they were written originally, so that they are (to some extent) descriptive of their behavior.
 +
 
 +
Brief descriptions of the AI behaviors are given in the following subsections.  To get a better feeling for their behavior, check out the "Animals", "Swarm", "Wolves" and "Dragon" scenarios from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].  Note that some of the animal AIs are designed for animal types that do not exist in mainline.  In the test scenario, other animal types are therefore substituted for them.
 +
 
 +
=== Animals AI: Wolves (ai_type=wolves) ===
 +
 
 +
The Wolves Micro AI organizes all "wolf" units (predators) of the side to hunt in a single pack.  They actively chase after the closest prey and try to corner it (not always super successfully), but are easily distracted by other enemy units coming into attack range, to the point where the pack might split up.  The wolves can, however, be told to attack only prey units as well as to try to avoid other types of units (such as larger predators).  When no prey is left, the wolves wander randomly.
 +
 
 +
This AI works best for a small number of predators (2 - 5) and sparse preyAlso, the predators should be put on the map in a pack, that is, reasonably close to each otherFor a demonstration of the Wolves AI behavior, check out the "Animals" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Note that another wolves AI exists, called [[Micro_AIs#Animals_AI:_Multi-pack_Wolves_.28ai_type.3Dwolves_multipacks.29|Multipack Wolves]], which distributes the wolves of a side into several packs, rather than all of them into one single pack as it is done here.
 +
 
 +
Enable the Wolves Micro AI by using
 +
ai_type=wolves
 +
in the [micro_ai] tag together with the following keys:
 +
 
 +
'''Required keys:'''
  
== Animals Micro AI (ai_type=animals) ==
+
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the predator units.  The filter automatically includes the side= key set to the AI side.
 +
* '''[filter_second]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the prey units.  The filter automatically includes a [[StandardSideFilter|Standard Side Filter]] set to all enemies of the AI side.
  
The Animals Micro AI defines a number of a animal AIs. Different animal AIs behave differently. For details, see below.
+
'''Optional keys:'''
  
For a demonstration, check out scenario "Dragon" of the AI-Demos campaign.
+
* '''attack_only_prey'''=no: In the default configuration, the wolves attack all enemy units in attack range.  If this key is set to 'yes', they only attack prey units.
 +
* '''avoid_type''': Comma-separated list of unit types (on enemy sides) which the wolves try to avoid.  They try to stay out of these units' way as much as possible when moving around (except when they are moving in to attack another enemy unit) and never attack them.
 +
* '''ca_score'''=90000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 90,000, which is lower than the default combat CA, but higher than most other default CAs which move units.  It can be changed by setting this parameter but in most cases this will not make sense.  Note that the Wolves AI consists of 2 CAs with scores ranging from <tt>ca_score-1</tt> to <tt>ca_score</tt>.
  
Enable the Animals Micro AI by putting
+
'''Notes on default (RCA) AI aspects:'''
{MICRO_AI_ANIMALS}
+
* If ''attack_only_prey'' or ''avoid_type'' are set, the Wolves Micro AI modifies the [[AiWML#Filtering_Combat_with_the_attacks_Aspect|attacks aspect]].
into the [side] tag and configure it by using
+
* Attacks by the wolves are left to the default (RCA) AI, meaning that the value of ''aggression'' has an influence on the behavior.
ai_type=animals
+
*'''[avoid]''': The standard RCA AI aspect used to define locations that should be avoided by the AI is taken into account. Note: as attacks by the wolves are left to the default AI, there is no separate ''[avoid]'' tag for this Micro AI in order to prevent inconsistencies.
in the [micro_ai] tag. The animal_type tag is used to choose from different animal AIs.
 
  
An example of the tag's usage:
+
Here's an example of a wolves [micro_ai] tag usage from the "Animals" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
# Set up the hunter_unit micro AI
+
        [micro_ai]
  [micro_ai]
+
            side=6
    # Required keys of [micro_ai] tag
+
            ai_type=wolves
    side=1
+
            action=add
    ai_type=animals
+
    animal_type=hunter_unit
+
            [filter]
    action=add
+
                type=Wolf
    # Required keys of hunter_unit micro AI
+
            [/filter]
    id=Rowck
+
            [filter_second]
     hunt_x,hunt_y="9-38","4-19"
+
                type=Vampire Bat
     home_x,home_y=4,3
+
            [/filter_second]
    rest_turns=2
+
            avoid_type=Yeti,Giant Spider,Ghast,Footpad
  [/micro_ai]
+
        [/micro_ai]
 +
 
 +
=== Animals AI: Multi-pack Wolves (ai_type=wolves_multipacks) ===
 +
 
 +
The Multi-pack Wolves Micro AI is different from the [[Micro_AIs#Animals_AI:_Wolves_.28ai_type.3Dwolves.29|Wolves Micro AI]] in that there can be an arbitrary number of wolf packs, with the pack size being a free parameter.  At the beginning of the scenario, close wolves are grouped into packs in a semi-methodical way.  If the wolves are put on the map in distinct groups of close wolves of the correct number, they will be joined into packs matching these groups.  If, on the other hand, they are spread out all over the map, the method of assigning them to packs is semi-random.
 +
 
 +
Wolves of the same pack begin by joining each other on the map.  After that, they stay together until only one wolf is left, which then tries to join up with an incomplete pack or with other single wolves.  Individual wolves entering the map during the scenario behave in that way as well.
 +
 
 +
A second difference to the other Wolves AI is that wolves do not actively hunt here.  For the most part they just wander (often long distance).  However, the pack ferociously (and without regard for its own health) attacks any enemy units that come into range, as long as that does not mean separating the pack by more than a few hexes.  Staying together, or joining with a new wolf assigned to the pack, is the only thing that takes priority over satisfying the wolves' thirst for blood.
 +
 
 +
For a demonstration of the Multi-pack Wolves AI behavior, check out the "Wolves" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Multi-pack Wolves Micro AI by using
 +
ai_type=wolves_multipacks
 +
in the [micro_ai] tag together with the following keys:
 +
 
 +
'''Required keys:'''
 +
 
 +
There are no required keys
 +
 
 +
'''Optional keys:'''
 +
 
 +
* '''[avoid]''':  {{DevFeature1.15|0}} A [[StandardLocationFilter|Standard Location Filter]] for the locations which the AI units should avoid.  If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.  Note that the Multi-pack Wolves AI consists of 2 CAs with scores ranging from <tt>ca_score-1</tt> to <tt>ca_score</tt>.
 +
* '''pack_size'''=3: (integer) The size of the packs.
 +
* '''show_pack_number'''=no: If set to "yes", the wolves' pack numbers will be shown below them.  Note that this means that the pack number of a wolf killed in an attack will remain as a label on the map.  This behavior is intentional to help UMC authors note where units might have made suicidal mistakes.
 +
* '''type'''=Wolf: Comma-separated list of the unit types which the AI controls. The default value is "Wolf".
 +
 
 +
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''[avoid]''':  {{DevFeature1.15|0}} The standard RCA AI aspect used to define locations that should be avoided by the AI.  See above (under 'optional keys') for details.
 +
 
 +
Here's an example of a wolves_multipacks [micro_ai] tag usage from the "Wolves" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=wolves_multipacks
 +
            action=add
 +
 +
            show_pack_number=yes
 +
            pack_size=4
 +
        [/micro_ai]
 +
 
 +
=== Animals AI: Big Animals (ai_type=big_animals) ===
 +
 
 +
The Big Animals Micro AI is a simulation of large predators that wander and hunt alone, such as Bears, Giant Spiders or Yetis.  For the most part, these just wander on the terrain that's been defined for them, but they attack enemy units if those happen to come into range.  The AI can be set up so that the Big Animals stay out of the way of other units (such as other large predators), in which case they only attack those if cornered or if they run into them accidentally (such as ambushers).
 +
 
 +
For a demonstration of the Big Animals AI behavior, check out the "Animals" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Big Animals Micro AI by using
 +
  ai_type=big_animals
 +
in the [micro_ai] tag together with the following keys:
 +
 
 +
'''Required keys:'''
 +
 
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the animals to which this AI is applied.  The filter automatically includes the side= key set to the AI side.
 +
 
 +
'''Optional keys:'''
 +
 
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''[filter_location]''': The big animals often go for long distance (multi-turn) journeys.  This tag is a [[StandardLocationFilter|Standard Location Filter]] describing the terrain from which the next goal is chosen.  The default is all terrain on the map.
 +
* '''[filter_location_wander]''': The terrain on which the big animals will end their moves. This is a [[StandardLocationFilter|Standard Location Filter]].  The default is all terrain on the map.
 +
* '''[avoid_unit]''': A [[StandardUnitFilter|Standard Unit Filter]] describing all enemy units that the big animals will avoid.  The filter automatically includes a [[StandardSideFilter|Standard Side Filter]] set to all enemies of the AI side.
 +
 
 +
Here's an example of big_animals [micro_ai] tag usage from the "Animals" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=3
 +
            ai_type=big_animals
 +
            action=add
 +
 +
            [filter]
 +
                type=Ghast
 +
            [/filter]
 +
            [avoid_unit]
 +
                type=Yeti,Giant Spider,Ghast,Footpad
 +
            [/avoid_unit]
 +
            [filter_location]
 +
                x,y=1-40,1-18
 +
            [/filter_location]
 +
        [/micro_ai]
 +
 
 +
=== Animals AI: Forest Animals (ai_type=forest_animals) ===
 +
 
 +
The Forest Animals Micro AI simulates a number of different animal behaviors that one might find in a forest, namely animals behaving like deer, rabbits and families of tuskers.  In the following, we will refer to those animals by these types, even though the actual unit types can be selected freely.  They behave as follows:
 +
* Each deer wanders randomly on (selectable) terrain, except when enemies get in its (the deer's) maximum movement range, in which case it flees to the farthest point it can reach.
 +
* Tuskers exhibit the same behavior as deer, except when an enemy is next to one of the tusklets.  This enemy is attacked unconditionally by the tuskers trying to protect their young.
 +
* Tusklets blindly follow the closest adult tusker, except when there is no tusker left, in which case they behave the same as deer.
 +
* Rabbits also wander randomly, but in addition disappear into their holes (if any are within reach) when enemies are close.  They reappear out of their holes at the beginning of the turn, if it is safe.
 +
 
 +
For a demonstration of the Forest Animals AI behavior, check out the "Animals" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Forest Animals Micro AI by using
 +
ai_type=forest_animals
 +
in the [micro_ai] tag together with the following keys:
 +
 
 +
'''Required keys:'''
 +
 
 +
There are no required keys
 +
 
 +
'''Optional keys:'''
 +
 
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.  Note that the Forest Animals AI consists of 4 CAs with scores ranging from <tt>ca_score-3</tt> to <tt>ca_score</tt>.
 +
* '''rabbit_type, tusker_type, tusklet_type, deer_type''': Comma-separated lists of the unit types behaving as the respective animals.  If any of these parameters are not set, those types of animal behavior are skipped by the AI.
 +
* '''[filter_location]''': A [[StandardLocationFilter|Standard Location Filter]] describing the terrain on which the forest animals wander when they are not threatened by enemies.
 +
* '''rabbit_number'''=6: (integer)  The number of rabbits for the AI to have on the map simultaneously.  The AI puts the missing number of rabbits onto the map at the beginning of the AI's turn (when the rabbits come out of their holes).
 +
* '''rabbit_enemy_distance'''=3: (number)  Rabbits won't spawn in holes that aren't more than this distance away from all enemies.
 +
* '''rabbit_hole_img''': Rabbit holes are marked by items on the map.  If this parameter is set, it must be the file name of the item image.  If it is not set, all items on the map are treated as rabbit holes.
 +
** {{DevFeature1.14|10}} Items used for rabbit holes on the map border used to produce an error. Placing them on the map border therefore needed to be avoided on the scenario setup side. They are now automatically excluded from consideration by the AI code.
 +
 
 +
Here's an example of forest_animals [micro_ai] tag usage from the "Animals" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=forest_animals
 +
            action=add
 +
 +
            deer_type=Vampire Bat
 +
            rabbit_type=Giant Rat
 +
            tusker_type=Ogre
 +
            tusklet_type=Young Ogre
 +
            [filter_location]
 +
                terrain=*^F*
 +
            [/filter_location]
 +
        [/micro_ai]
 +
 
 +
=== Animals AI: Herd and Herders (ai_type=herding) ===
 +
 
 +
The Herding Micro AI sets up an area on the map where a number of herder units (such as sheep dog) control and protect a herd (such as sheep).  For convenience, we simply refer to them as sheep dogs and sheep in the following, even though arbitrary unit types can be selected for either.
 +
 
 +
Sheep dogs try to keep their sheep safe.  This involves keeping them inside the herding area, positioning themselves in between the sheep and approaching enemies, and attacking the enemies if those get too close.  If no active herding or protecting move is needed, the dogs go to a random location on the perimeter of the herding area.
 +
 
 +
Sheep wander aimlessly except when a sheep dog is next to them, in which case they run away from the dog.  The dogs exploit this by positioning themselves on the outside of the sheep, if possible.  Sheep also run away from approaching enemies.
 +
 
 +
For a demonstration of the Herding AI behavior, check out the "Animals" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Herding Micro AI by using
 +
ai_type=herding
 +
in the [micro_ai] tag together with the following keys:
 +
 
 +
'''Required keys:'''
 +
 
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] describing the herder units (e.g. dogs).  The filter automatically includes the side= key set to the AI side.
 +
* '''[filter_second]''': A [[StandardUnitFilter|Standard Unit Filter]] describing the herd units (e.g. sheep).  The filter automatically includes the side= key set to the AI side.
 +
* '''[filter_location]''': A [[StandardLocationFilter|Standard Location Filter]] describing the terrain forming the perimeter of the herding area.  In other words, this is the path the herders (dogs) use to patrol around the outside of the herding area.  This must be a set of coordinates ''completely enclosing'' the herding area.  Here's an example of setting up a rectangular perimeter:
 +
     [filter_location]
 +
        x=10-20,10-20,10,  ,20
 +
        y=11,  21,  11-21,11-21
 +
    [/filter_location]
 +
Another possibility is by defining the path by certain terrain on the map (as it is done in the "Animals" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]), in which case the filter can simply look like this:
 +
     [filter_location]
 +
        terrain=Rb
 +
    [/filter_location]
 +
* '''herd_x,herd_y''': The coordinate of one hex (''any'' one hex) inside the herding area.  This is needed to define which part of the map is on the ''inside'' of the herding area perimeter defined by [herding_perimeter], and which is the ''outside''. {{DevFeature1.15|0}} '''herd_loc''' can be used instead with a named/special location.
 +
 
 +
'''Optional keys:'''
 +
* '''attention_distance'''=8: (integer)  If an enemy is within this distance of a herd unit, but not as close as ''attack_distance'', the herders try to position themselves in between the enemy and the herd unit.
 +
* '''attack_distance'''=4: (integer)  If an enemy is within this distance of a herd animal, the herders attack this enemy.
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.  Note that the Herding AI consists of 6 CAs with scores ranging from <tt>ca_score-5</tt> to <tt>ca_score</tt>.
 +
 
 +
Here's an example of a Herding [micro_ai] tag usage from the "Animals" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=7
 +
            ai_type=herding
 +
            action=add
 +
   
 +
            [filter]
 +
                type=Footpad
 +
            [/filter]
 +
            [filter_second]
 +
                type=Troll Whelp
 +
            [/filter_second]
 +
            herd_x,herd_y=32,28
 +
            [filter_location]
 +
                terrain=Rb
 +
            [/filter_location]
 +
        [/micro_ai]
 +
 
 +
=== Animals AI: Hunter (ai_type=hunter) ===
 +
 
 +
The Hunter Micro AI leads a unit (or units) through hunt-and-rest cycles.  The units wander in a prescribed area of the map, their hunting ground, until an enemy unit comes within range.  Note that the units do not actively chase down enemies, but wander randomly through the hunting ground until an enemy is encountered.
 +
 
 +
If enemies are within range of a hunter unit, the hunter attacks the weakest of them.  If a kill is made, it then retreats to its rest location, where it stays for a certain number of turns and until fully healed (whatever happens later).
 +
 
 +
A few more details:
 +
* If the hunter's way home is entirely blocked on the return (so that there is no possible path), the normal RCA AI takes over its behavior.
 +
* However, if the way is blocked by an enemy unit occupying the rest hex, that enemy will be attacked unconditionally.
 +
* A kill only makes the hunter go home when it is the attacker, not as defender.
 +
 
 +
For a demonstration of the Hunter AI behavior, check out the "Dragon" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Hunter Micro AI by using
 +
ai_type=hunter
 +
in the [micro_ai] tag together with the following keys:
  
'''Animal types:'''
+
'''Required keys:'''
  
* '''hunter_unit''': hunts in a specific area, then stays home for a specified time/until fully healed.  This AI attaches to a unit, rather than controlling all units of a side.
+
* '''id''' or '''[filter]''': The ID of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
* '''wolves''': they hunt in a pack of arbitrary number of predators.  '''Note:''' The Wolves Micro AI modifies the [[AiWML#Filtering_Combat_with_the_.27attacks.27_Aspect|attacks aspect]].
+
** One or the other is required
* '''wolves_multipacks''': same as above but this AI supports an arbitrary number of units and this can't avoid specific types of enemies.
+
** If both are given, [filter] takes priority over id=
* '''big_animals''': these just go to random places, avoid other big animals and stay at their preferred types of terrain.
+
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
* '''swarm''': the animals in the side with this AI will try to stay together and avoid enemies.
+
** If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
* '''herding''': this AI controls both the sheep and the dogs of a side. The dogs keep the sheep in a herd. This AI only requires the animal_type key in addition to the needed [micro_ai] keys.
+
* '''home_x,home_y''': The coordinates of the hex to which the hunter returns and rests at after a kill. {{DevFeature1.15|0}} '''home_loc''' can be used instead with a named/special location.
* '''forest_animals''': This AI controls a set of animals: tuskers, tusklets, rabbits.
 
  
====Keys for the hunter_unit AI:====
+
'''Optional keys:'''
  
Required keys:
+
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]]. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
* '''id''': The ID of the unit to which this AI should be applied.
+
* '''[filter_location]''': A [[StandardLocationFilter|Standard Location Filter]] describing the unit's hunting ground.  If this tag is not provided, the hunter uses all of the map.
* '''animal_type''': This has to be "hunter_unit" (without quotation marks) if you want a hunter_unit AI.
+
* '''rest_turns'''=3: (integer)  The number of turns the AI stays at home_x,home_y after a kill.  It will not leave its home until this number of turns have passed ''and'' it is fully healed.
* '''hunt_x''': The x range of the area where the AI will wander.
+
* '''show_messages'''=no: (boolean) If set to yes, the hunter announces whenever its behavior changes to the next phase.  Note that this is meant as debug output for the scenario author. The messages are not translated and are not included in replays (and are only visible to the host in an MP game).
* '''hunt_y''': The y range of the area where the AI will wander.
 
* '''home_x''': The x coordinate of the place where the AI will return.
 
* '''home_y''': The y coordinate of the place where the AI will return.
 
* '''rest_turns''': The number of turns the AI will stay at "home".
 
  
Optional keys:
+
Here's an example of a hunter [micro_ai] tag usage from the "Dragon" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
* '''show_messages'''=no: (boolean) If set to yes, the hunter announces whenever its behavior changes to the next phase
+
        [micro_ai]
 +
            side=1
 +
            ai_type=hunter
 +
            action=add
  
====Keys of the wolves AI:====
+
            [filter]
 +
                id=Rowck
 +
            [/filter]
 +
            [filter_location]
 +
                x,y=5-30,1-15
 +
            [/filter_location]
 +
            home_x,home_y=3,15
 +
            rest_turns=2
 +
 +
            show_messages=yes
 +
        [/micro_ai]
  
* '''animal_type''': You have to set this to "wolves".
+
=== Animals AI: Swarm (ai_type=swarm) ===
* '''avoid_type''': The wolves will try to avoid creatures with these types. '''Optional.'''
 
* '''[predators]''': A SUF WML tag. '''Required.'''
 
* '''[prey]''': A SUF WML tag. '''Required.'''
 
  
====Keys of the wolves_multipacks AI:====
+
The Swarm Micro AI uses some very simply algorithms to simulate animal swarm behavior.  Without adjacent enemies, they simply do a random move, trying to stay together and at a certain distance from enemies.  However, if an enemy unit is close to any bat, the swarm scatters.  This is particular fun to watch when one places an enemy unit in the middle of the swarm.  After being scattered, the swarm members slowly rejoin, but not in a very organized way.  Sub-swarms or individual bats might roam around for quite some time before they find their way back.  It is also possible that individual bats (or small groups) split off from the larger swarm at times.
  
* '''animal_type''': You have to set this to "wolves_multipacks". '''Required.'''
+
For a demonstration of the Swarm AI behavior, check out the "Swarm" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
* '''type''': the type of units the AI controls. The default value is "Wolf".
 
* '''pack_size''': the size of the packs the units will hunt in. (default: 3)
 
* '''show_pack_number''': if "yes", the wolves' pack numbers will be shown below them.
 
  
====Keys of the big_animals AI:====
+
Enable the Swarm Micro AI by using
 +
ai_type=swarm
 +
in the [micro_ai] tag together with the following keys:
  
 
'''Required keys:'''
 
'''Required keys:'''
* '''animal_type''': You have to set this to "big_animals" if you want a big_animals AI.
 
* '''[big_animals]''': SUF describing the animals of the side to which this AI is applied.
 
* '''[goal_terrain]''': The terrain which the big animal will aim for. This is a [[StandardLocationFilter|Standard Location Filter]].
 
* '''[wander_terrain]''': The terrain which the big animal will wander on. This is a [[StandardLocationFilter|Standard Location Filter]].
 
* '''[avoid_unit]''': The units which the big animals will avoid. This is a [[StandardUnitFilter|Standard Unit Filter]].
 
  
====Optional keys of the swarm AI:====
+
There are no required keys
 +
 
 +
'''Optional keys:'''
  
* '''scatter_distance'''=3: (int) Enemies within "scatter_distance" hexes of any swarm unit will cause the swarm to scatter.
+
* '''[avoid]''':  {{DevFeature1.15|0}} A [[StandardLocationFilter|Standard Location Filter]] for the locations which the AI units should avoid.  If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.  Note that the Swarm AI consists of 2 CAs with scores ranging from <tt>ca_score-1</tt> to <tt>ca_score</tt>.
 
* '''enemy_distance'''=5: (int) The minimum distance kept between units of the swarm and enemies when the swarm moves as a whole.
 
* '''enemy_distance'''=5: (int) The minimum distance kept between units of the swarm and enemies when the swarm moves as a whole.
* '''vision_distance'''=12: (int) Only units within this distance follow the overall swarm motion (either away from an enemy or of the swarm as a whole).  The smaller this value is set, the less likely the swarm is to stay together or rejoin.  Its meaning is that if the swarm is more than this distance away, it is "out of sight" and the unit will therefore not be able to follow it.
+
* '''[filter]''': {{DevFeature1.15|12}} A [[StandardUnitFilter|Standard Unit Filter]] selecting the units.  Only AI units matching this filter participate in the swarm.  The filter automatically includes the side= key set to the AI side.
 +
* '''scatter_distance'''=3: (int) Enemies within "scatter_distance" hexes of any swarm unit cause the swarm to scatter, by each unit trying to maximize its individual distance from the enemy.
 +
* '''vision_distance'''=12: (int) Only units within this distance follow the overall swarm motion (either away from an enemy or of the swarm as a whole).  The smaller this value is set, the less likely the swarm is to stay together or rejoin.  This parameter is meant to simulate how far an individual member of the swarm can see, meaning that the swarm is "out of sight" (and the unit will not be able to follow it) if it is more than this distance away.
 +
 
 +
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''[avoid]''':  {{DevFeature1.15|0}} The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.
 +
 
 +
Here's an example of a Swarm [micro_ai] tag usage from the "Swarm" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=swarm
 +
            action=add
 +
        [/micro_ai]
  
====Required keys of the herding AI:====
+
== Assassin Squad Micro AI (ai_type=assassin) ==
  
* '''[herd]''': The units that are being herded. This is a [[StandardUnitFilter|Standard Unit Filter]].
+
{{DevFeature1.13|6}}
* '''[herders]''': The units that are herding. This is a [[StandardLocationFilter|Standard Location Filter]].
+
 
* '''herd_x,herd_y''': The coordinate of the (approximate) herding area center.
+
This Micro AI controls one or several assassin units which try to circle around enemy units with the goal of hitting a target unit without being distracted or impeded by other enemies.  The units will always attack the target if such attacks are possible, otherwise they will follow the path of least resistance toward it. Notes:
* '''[herder_area]''': The terrain of which the herders prefer. This is a [[StandardLocationFilter|Standard Location Filter]].
+
 
 +
* The main priority for the AI is to find paths that avoid enemy units. However, if no such path can be found, the assassins will still advance toward the target, taking the path exposing the units to the least potential damage from enemies.
 +
 
 +
* The units will not necessarily follow the same path. The best path is chosen individually for each unit.
 +
 
 +
* While it is not a requirement for the AI to work, using ambusher or skirmisher units, or units with the quick trait, makes this AI more lethal in many cases.
 +
 
 +
* The CA evaluation scores of this AI are hard-coded, it does not work otherwise. That means that '''ca_score''' is not a valid key for the [micro_ai] tag.
 +
 
 +
Enable the Assassin Squad Micro AI by using
 +
ai_type=assassin
 +
in the [micro_ai] tag.
 +
 
 +
===Assassin Squad specific keys for the [micro_ai] tag:===
 +
 
 +
'''Required keys:'''
 +
 
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] defining the assassin units. The filter automatically includes the side= key set to the AI side.
 +
* '''[filter_second]''': A [[StandardUnitFilter|Standard Unit Filter]] defining the target unit.
 +
** It is important to realize that the AI currently only works correctly with a single target unit. It is thus the responsibility of the scenario designer to make sure that this filter matches an individual enemy unit. If several enemy units are to be targeted in the same scenario, several instances of the Assassin Micro AI can be used.
 +
** The filter automatically includes a [[StandardSideFilter|Standard Side Filter]] set to all enemies of the AI side.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
* '''attention_distance'''=8: (integer)  The radius within which enemies must be to attract the attention of the herders.
 
* '''attack_distance'''=4: (integer)  The radius within which enemies must be to be attacked by the herders.
 
  
====Optional keys of the forest_animals AI:====
+
* '''[prefer]''': A [[StandardLocationFilter|Standard Location Filter]] selecting locations on the map for the assassins to prefer when making their way toward the target unit. This could be used, for example, to make units with the ambush ability move (mostly) through forest or to have the assassins circle around the, say, northern part of the map rather than the south if that is desirable for scenario design purposes.
 +
** As with avoiding enemies, the units will still move across non-preferred terrain if that is either the only option or ''much'' shorter than preferred terrain
 +
** Attacking, once the target unit is in range, is not influenced by the [prefer] SLF.
  
* '''rabbits_number''': The number of rabbits to be on the map.
+
Here is an example of an Assassin Squad [micro_ai] tag usage:
* '''radius''': Rabbits won't spawn in holes that aren't more than radius hexes away from enemies.
+
        [micro_ai]
* '''rabbit_hole''': The image/halo of the rabbit hole item.
+
            side=2
* '''[move_filter]''': The terrain the animals prefer to move on. This is a [[StandardLocationFilter|Standard Location Filter]].
+
            ai_type=assassin
* '''rabbit_type''': The unit types that should behave as rabbits.
+
            action=add
* '''tusker_type''': The unit types that should behave as tuskers.
+
* '''tusklet_type''': The unit types that should behave as tusklets.
+
            [filter]
* '''other_types''': The unit types that should behave as deers.
+
                type=Assassin,Master at Arms,Duelist
 +
            [/filter]
 +
            [filter_second]
 +
                id=Konrad
 +
            [/filter_second]
 +
            [prefer] # Circle around northern part of map
 +
                x=1-9, 10-99
 +
                y=1-37, 1-17
 +
            [/prefer]
 +
        [/micro_ai]
  
 
== Bottleneck Defense Micro AI (ai_type=bottleneck_defense) ==
 
== Bottleneck Defense Micro AI (ai_type=bottleneck_defense) ==
Line 166: Line 437:
 
The Bottleneck Defense Micro AI lets you define a location on the map where the AI can take a defensive stance behind a narrow passage (bottleneck).  Units on the front line are backed up by healers and/or units with the leadership ability.  Injured units are moved to the back and replaced by uninjured (or less injured) units.  The units on the front line only attack when it is safe (no retaliation) or when there is a high chance that they will make a kill or level up.  Using this Micro AI only makes sense if there is no way for the enemy sides to move around the bottleneck and attack the AI's units from behind.
 
The Bottleneck Defense Micro AI lets you define a location on the map where the AI can take a defensive stance behind a narrow passage (bottleneck).  Units on the front line are backed up by healers and/or units with the leadership ability.  Injured units are moved to the back and replaced by uninjured (or less injured) units.  The units on the front line only attack when it is safe (no retaliation) or when there is a high chance that they will make a kill or level up.  Using this Micro AI only makes sense if there is no way for the enemy sides to move around the bottleneck and attack the AI's units from behind.
  
For a demonstration, check out the "Bottleneck" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.
+
For a demonstration, check out the "Bottleneck" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
  
Enable the Bottleneck Defense Micro AI by putting
+
Enable the Bottleneck Defense Micro AI by using
{MICRO_AI_BOTTLENECK_DEFENSE}
 
into the [side] tag and configure it by using
 
 
  ai_type=bottleneck_defense
 
  ai_type=bottleneck_defense
 
in the [micro_ai] tag.
 
in the [micro_ai] tag.
Line 180: Line 449:
 
The Bottleneck Defense AI requires two sets of coordinates that define where it should be taking up its defensive stance, and from which side the enemy attacks at that location.
 
The Bottleneck Defense AI requires two sets of coordinates that define where it should be taking up its defensive stance, and from which side the enemy attacks at that location.
  
* '''x,y''': Comma separated lists of the hexes on the front line, where strong units are placed.  All hexes on which the AI makes contact with (can be attacked by) the enemy need to be included here.  Units are placed on them in the order in which they are listed here.
+
* '''x,y''': Comma separated lists of the hexes on the front line, where strong units are placed.  All hexes on which the AI makes contact with (can be attacked by) the enemy need to be included here.  Units are placed on them in the order in which they are listed here. {{DevFeature1.15|0}} '''location_id''' can be used instead with named/special locations.
* '''enemy_x,enemy_y''': Comma separated list of the hexes from which the enemy can attack the AI front line units.  This is needed for the AI to know on which side of the front line support units (healers etc.) need to be placed.  In many cases, it is sufficient to provide only one of the enemy front line hexes, but there are geometries for which that does not work.  It is therefore safer to list all enemy front line hexes here.
+
* '''enemy_x,enemy_y''': Comma separated list of the hexes from which the enemy can attack the AI front line units.  This is needed for the AI to know on which side of the front line support units (healers etc.) need to be placed.  In many cases, it is sufficient to provide only one of the enemy front line hexes, but there are geometries for which that does not work.  It is therefore safer to list all enemy front line hexes here. {{DevFeature1.15|0}} '''enemy_loc''' can be used instead with named/special locations.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
Line 187: Line 456:
 
By default, the AI places healers and units with the leadership ability both on the front line itself (if they are the strongest units available) and on hexes adjacent to and behind the line.  If different placement is desired, these locations can be overridden with the following keys.
 
By default, the AI places healers and units with the leadership ability both on the front line itself (if they are the strongest units available) and on hexes adjacent to and behind the line.  If different placement is desired, these locations can be overridden with the following keys.
  
* '''healer_x,healer_y''': Comma separated list of hexes where healers are placed.  This can be used to keep healers from the front line (or to take up only certain positions on the front line), and/or to override the default healing positions behind the line.  Healers are placed on them in the order in which the hexes are listed, with the exception that hexes on the line always take priority over hexes behind the line.
 
* '''leadership_x,leadership_y''': Same as ''healer_x,healer_y'', but for units with the leadership ability.
 
 
* '''active_side_leader'''=no: (boolean)  If set to 'yes', the side leader participates in the bottleneck defense action after the side's gold has been spent.  If set to 'no' (default), the leader follows default AI behavior (sitting on the keep and recruiting, for the most part).
 
* '''active_side_leader'''=no: (boolean)  If set to 'yes', the side leader participates in the bottleneck defense action after the side's gold has been spent.  If set to 'no' (default), the leader follows default AI behavior (sitting on the keep and recruiting, for the most part).
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.  Note that the Bottleneck Defense AI consists of 2 CAs with scores ranging from <tt>ca_score-1</tt> to <tt>ca_score</tt>.
 +
* '''[filter]''': {{DevFeature1.15|3}} A [[StandardUnitFilter|Standard Unit Filter]] selecting the units.  Only AI units matching this filter participate in the bottleneck defense.  The filter automatically includes the side= key set to the AI side.
 +
* '''healer_x,healer_y''': Comma separated list of hexes where healers are placed.  This can be used to keep healers from the front line (or to take up only certain positions on the front line), and/or to override the default healing positions behind the line.  Healers are placed on them in the order in which the hexes are listed, with the exception that hexes on the line always take priority over hexes behind the line. {{DevFeature1.15|0}} '''healer_loc''' can be used instead with named/special locations.
 +
* '''leadership_x,leadership_y''': Same as ''healer_x,healer_y'', but for units with the leadership ability. {{DevFeature1.15|0}} '''leadership_loc''' can be used instead with named/special locations.
  
As an example, in the "Bottleneck" scenario of the test scenario, there are three front line hexes, two of which are on hill terrain, while the third is a road with a lower defense rating.  The healer and side leader are supposed to participate in combat because they are strong units, but only from the hill hexes to keep them safer.  This is accomplished by using the following keys settings (check out the scenario to see which hex is which):
+
As an example, in the "Bottleneck" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]], there are three front line hexes, two of which are on hill terrain, while the third is a road with a lower defense rating.  The healer and side leader are supposed to participate in combat because they are strong units, but only from the hill hexes to keep them safer.  This is accomplished by using the following keys settings (check out the scenario to see which hex is which):
 
  [micro_ai]
 
  [micro_ai]
    # Required keys of [micro_ai] tag
 
 
     side=1
 
     side=1
 
     ai_type=bottleneck_defense
 
     ai_type=bottleneck_defense
 
     action=add
 
     action=add
 
   
 
   
    # Required keys of Bottleneck Defense Micro AI
 
 
     x=14,14,14
 
     x=14,14,14
 
     y= 7, 9, 8
 
     y= 7, 9, 8
Line 204: Line 473:
 
     enemy_y= 8, 9
 
     enemy_y= 8, 9
 
   
 
   
    # Optional keys of Bottleneck Defense Micro AI
 
 
     healer_x=14,14,15,15
 
     healer_x=14,14,15,15
 
     healer_y= 7, 9, 8, 9
 
     healer_y= 7, 9, 8, 9
Line 212: Line 480:
 
  [/micro_ai]
 
  [/micro_ai]
  
== Guardian Micro AI (ai_type=guardian_unit) ==
+
== Fast Micro AI (ai_type=fast_ai) ==
The Guardian Micro AI attaches to an individual unit and can be used to set up different kind of guardian behaviorsThree different types of guardians are available and are described below.
+
 
 +
{{DevFeature1.13|0}}
 +
 
 +
This AI is meant as a fall-back AI for scenarios where there are so many units that attacks and moves done by the default AI are slow with long delays before each move.  It replaces the default castle-switch, retreat-injured, spread-poison, high-xp-attack, combat, place-healers, move-to-targets, villages and retreat candidate actions (CAs).  It should be obvious that in order to achieve the faster speed, compromises concerning the quality of the moves have to be made.
 +
 
 +
Enable the Fast Micro AI by using
 +
ai_type=fast_ai
 +
in the [micro_ai] tag.
 +
 
 +
'''Combat candidate action:'''
 +
* Attackers are considered individually one at a time.  The best attack found for a unit is executed without checking whether a better attack by another unit might be possible.
 +
* The default order in which attackers are considered is by decreasing hitpoints, starting with the strongest unit (in terms of HP).  This can be modified with the optional keys below.
 +
* By default, if weaker units block attack hexes for a stronger unit, they do not move out of the way (this is the same as for the default AI).  If a hex becomes available after an attack (e.g. due to a weaker unit dying in the attack), all attacks that were possible ''before'' this happened are finished first.  Only after that are attacks by the stronger unit reconsidered.
 +
* If include_occupied_attack_hexes=yes is set, weaker units move out of the way for stronger units if possibleThis can, however slow down the AI depending on the situation on the map.  Use with caution.
 +
* {{DevFeature1.13|2}} Previous to this version, attacks by the leader were bunched in with the attacks by the other units.  Now leader attacks are treated separately and contain an extra layer of analysis to determine whether the attack position is "safe" (in an approximate way).  Currently, this is done with two simple considerations:
 +
** Count all enemy units that can reach the leader's attack position.  If there are more than given by optional parameter 'leader_attack_max_units' (default value 3), do not attack.
 +
** Add up the hitpoints of all enemies that can reach the leader's attack position.  If this value, multiplied by optional parameter 'leader_weight'(default value 2), is larger than the leaders hitpoints, do not attack.
 +
** Two optional parameters, 'threatened_leader_fights' and 'leader_additional_threat', can also be used to let the leader attack when the threat at the attack hex is comparable to that at the leader's current position.
 +
** In order to keep this AI as fast as possible, leader attacks are done by a separate candidate action that is only evaluated when all other CAs are done.
  
Multiple guardian units can be used on the same side, by setting up a separate [micro_ai] tag for each unit.
+
'''Move-to-targets, villages and retreat candidate actions:'''
 +
* The move-to-targets, villages and retreat candidate actions of the default AI are removed.  Move-to-targets and villages are taken over by the Fast Micro AI, whereas retreat is simply not done.
 +
* This CA moves units toward goals after attacks are done.  Goals are unowned (if the AI side has a leader only) and enemy-owned villages and enemy leaders.
 +
* For each goal, units are pre-sorted in order of the fewest moves needed to cover the ''distance'' toward the goal (that is, as if move cost on each hex toward the goal were 1).  Units are then considered sequentially and if a unit can get there "efficiently", its move is executed without considering other units.
 +
** A move is considered efficient if the move cost to get to the hex is not more than 'move_cost_factor' larger than the distance to the hex.  'move_cost_factor' is an optional key that defaults to 2.  It can be set to values of 1.1 or larger (see below).
 +
** If the move for the current unit is not found to be efficient, the AI considers the next unit instead.  If no unit can do an efficient move toward the goal, the best (fastest) of the inefficient moves is selected instead.
  
For a demonstration of several different guardian behaviors, check out the "Guardians" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.
+
* Village goals:
 +
** Village goals are considered before enemy leader goals so that the AI preferentially chooses scouts (or otherwise fast units) for them.
 +
** The number of units sent toward villages depends on the value of the default AI aspect village_value.  It is set to village_value/4 times the number of units the AI has left to move.  Thus, by default (village_value=1.0) the AI sends a quarter of its units toward villages, and the rest toward enemy leaders.  This means that the meaningful range of values for village_value is 0..4.
 +
** Only one unit is moved toward each village.  This consideration also overrides the number of units to move toward villages defined by village_value, topping it at the number of unowned/enemy-owned villages on the map.
 +
** Setting village_value=0 disables moving units toward villages altogether.  That is, not only are no units chosen, but the village targeting phase of the AI is entirely disabled with no evaluation time used for it.  Note that, unlike with the default AI, this also means that no villages within range of an AI unit are grabbed.
 +
** The order in which villages are chosen as goals is some combination of them being close to the AI side's leader and being spread out over the map.
  
Enable the Guardians Micro AI by putting
+
* Enemy leader goals:
{MICRO_AI_GUARDIAN}
+
** The order of enemy leaders goals is set according to their distance from the AI leader with the closest enemy leader being targeted first (if the AI has a leader, otherwise their order is random). One unit is sent toward each enemy leader in this order, after which the AI starts with the first enemy leader againThis is repeated until all units have moved.
into the [side] tag and configure it by using
 
  ai_type=guardian_unit
 
in the [micro_ai] tagThe ''guardian_type='' key also needs to be set, as shown in the following.
 
  
=== Return Guardian (guardian_type=return_guardian) ===
+
* Guardians (units with ai_special=guardian set) are ignored by the fast move-to-targets CA.
 +
 
 +
'''Tips for speeding up/modifying the Fast Micro AI in specific scenarios:'''
 +
 
 +
A number of optional keys and default AI aspects can be used to modify the behavior of the Fast Micro AI.  The MAI is set up so that it is a reasonable compromise between speed and quality of the moves in most situations.  However, this might not be ideal for all scenarios here are some things that can be done to speed up the AI (or to get better behavior in some situations by doing the opposite):
 +
* Use large values for the default AI aspect aggression.  The largest delays before attacks happen (in some circumstances) when the Fast MAI has to consider lots of units with attacks left but decides not to attack with them.  See below for a description of how aggression is used by the fast AI.
 +
* Use large values of move_cost_factor (see above for description of what this does).  If you want to emphasize units that can move across terrain easily (e.g. bats) to be chosen for village grabbing, you might want to use low values of move_cost_factor, but this might slow down the AI.  The default value should work reasonably well in most standard situations, but modifying the value might work better on specific maps.
 +
* Don't use dungeon_mode=yes unless absolutely necessary, even in most dungeon crawls.  Test the AI without this setting first and only use it if it is the only way to solve the problem.  Often, a minor tweak to the map will have the same effect, without the speed penalty.
 +
* Use include_occupied_attack_hexes=yes with caution.  It might (or might not) slow down the attack CA significantly, depending on the scenario.
 +
* Set village_value=0, which makes the AI not consider villages as goals.  This has not been found to make a large difference on the maps tested so far, but it might have an effect on maps with a very large number of villages.
 +
* Use attack_hidden_enemies=yes on maps where there are no hidden enemies. Excluding hidden enemies from the attack calculation requires an additional filter to be evaluated that takes extra time. In most cases this will not result in a large computation time saving.
 +
 
 +
'''Required keys:'''
 +
 
 +
There are no required keys.
 +
 
 +
'''Optional keys:'''
 +
 
 +
* '''attack_hidden_enemies'''=no: (boolean)  By default, hidden enemies are excluded from the attack calculation.  Setting this to 'yes' makes the AI also consider those enemies as attack targets.
 +
* '''[avoid]''':  {{DevFeature1.13|2}} A [[StandardLocationFilter|Standard Location Filter]] for the terrain which the AI units should avoid.  If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).  As with the default AI, units will not step on hexes defined by the [avoid] tag.  In addition, no goals will be chosen that lie on those hexes.  The one minor exception is that a unit stepping out of the way for another unit might temporarily enter the avoided zone.
 +
* '''dungeon_mode'''=no: (boolean)  As much as possible, the Fast Micro AI works with distances between hexes rather than path finding.  This works pretty well on open maps and even most dungeon crawls (and similar scenarios), but it might result in some units getting temporarily (and in rare cases permanently) stuck on maps with convoluted labyrinths.  If that is the case, setting dungeon_mode=yes triggers more path finding that avoids such situations (but as a result is somewhat slower).
 +
* '''include_occupied_attack_hexes'''=no: (boolean) If set to 'yes', the AI moves weaker units out of the way for a stronger attacker.  This might lead to better attacks but is slower, so don't use if speed is essential.
 +
* '''[filter]''': {{DevFeature1.13|2}} A [[StandardUnitFilter|Standard Unit Filter]] selecting the attackers.  Only AI units matching this filter will attack, analog to filtering units using [filter_own] with the [[AiWML#Filtering_Combat_with_the_attacks_Aspect|attacks aspect]] for the default AI.  The filter automatically includes the side= key set to the AI side.  It does not affect the move-to-targets CA.
 +
* '''[filter_second]''': {{DevFeature1.13|2}} A [[StandardUnitFilter|Standard Unit Filter]] selecting the enemies.  Only enemy units matching this filter will be attacked, analog to filtering units using [filter_own] with the [[AiWML#Filtering_Combat_with_the_attacks_Aspect|attacks aspect]] for the default AI.  The filter automatically includes a [[StandardSideFilter|Standard Side Filter]] set to all enemies of the AI side.  It does not affect the move-to-targets CA.
 +
* '''leader_weight'''=2: (number >= 0) {{DevFeature1.13|2}} A factor specifying how much more valuable the AI considers side leaders than non-leader units in the attack evaluation. This is also used to determine whether an attack by the leader is safe (see description of the combat candidate action above).
 +
* '''leader_additional_threat'''=1: (number > 0) {{DevFeature1.13|2}} If threatened_leader_fights=yes, the threat at the attack position may be larger by this factor for the leader to leave the keep for an attack.
 +
* '''leader_attack_max_units'''=3: (number >= 0) {{DevFeature1.13|2}} A number specifying how many enemy units within reach are acceptable when determining whether an attack by the leader is safe (see description of the combat candidate action above).
 +
* '''move_cost_factor'''=2: (number >= 1.1)  The factor by which the move cost to a goal hex may be larger than the distance to the goal hex for a move to be considered "efficient".  See description above.  1.1 is used if this is set to values smaller than 1.1.  Smaller values might lead to better behavior, while larger values might speed up the AI.
 +
* '''weak_units_first'''=no: (boolean) If set to 'yes', inverts the order in which units are considered by the combat CA.  Attacks are then done in order of increasing hitpoints of the attackers.
 +
* '''skip_combat_ca'''=no: (boolean) If set to 'yes', the fast combat CA is not used.  The default AI's high_xp_attack and combat CAs remains in place in this case.
 +
* '''skip_move_ca'''=no: (boolean) If set to 'yes', the fast move-to-targets CA is not used.  The default AI's retreat, villages and move-to-targets CAs remains in place in this case.
 +
* '''threatened_leader_fights'''=no: (boolean) {{DevFeature1.13|2}} By default, the AI leader will not attack if the threat at the attack position is too high.  If this key is set to 'yes', the leader will attack if the threat there is not larger than the threat at his current position multiplied by the value of 'leader_additional_threat'. This is meant as an option for the endgame: when the AI leader is under attack, he might as well go down fighting.
 +
 
 +
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''aggression''': The [[AiWML#List_of_AI_Aspects|default RCA AI aspect]] used to set how aggressive the AI should attack.  It works in roughly the same way as the default AI aspect:
 +
** The value of (1 - aggression) determines how much the AI values its own units compared to the enemy's units.  Thus, aggression=0 means that attacks are only done if the AI expects to deal (roughly) the same amount of damage as it will receive.  aggression=1 means that expected damage to the AI's units is not considered, only the expected damage to enemy units matters.
 +
** Damage is calculated as a combination of hitpoints and chance to die, in "gold equivalent units".
 +
** Unlike the default AI, aggression is set to 1 for values larger than 1.  Allowed values are thus anything from -infinity to +infinity, although only -infinity to +1.0 make sense.
 +
*'''[avoid]''':  {{DevFeature1.13|2}} The standard RCA AI aspect used to define locations that should be avoided by the AI.  See above (under 'optional keys') for details.
 +
*'''attacks aspect''':  {{DevFeature1.13|2}} The standard RCA AI [[AiWML#Filtering_Combat_with_the_attacks_Aspect|attacks aspect]] used to filter own and enemy units for attacks is now also taken into account as long as neither [filter] nor [filter_second] (see above under 'optional keys') are defined in the [micro_ai] tag.
 +
*'''village_value=1''': (number ranging from 0 to 4) The [[AiWML#List_of_AI_Aspects|default RCA AI aspect]] used to define how much villages should be targeted by the move-to-targets CA.  In the Fast MAI, this defines which fraction of the AI units are moved toward village goals (see above for details).  If set to 0, villages are ignored as goals.
 +
 
 +
'''Notes:'''
 +
* The CA evaluation scores of this AI are hard-coded to the same values as those of the respective [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|default candidate actions]].  ca_score is therefore not a valid optional key.
 +
* The fast Micro AI modifies (removes) the default castle-switch, retreat-injured, spread-poison, high-xp-attack, combat, place-healers, move-to-targets, villages and retreat candidate actions.
 +
 
 +
Enabling the Fast Micro AI in its default configuration is as simple as this usage example from the "Fast AI" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=1
 +
            ai_type=fast_ai
 +
            action=add
 +
        [/micro_ai]
 +
 
 +
== Generalized Goto Micro AI (ai_type=goto) ==
 +
 
 +
The Goto Micro AI provides a highly configurable method of sending a unit (or units) to a location or set of locations.  The units to be moved are defined using a [[StandardUnitFilter|Standard Unit Filter]] (SUF) [alternatively, all side units are used if the SUF is not provided), while the goto locations are given in a [[StandardLocationFilter|Standard Location Filter]] (SLF).
 +
 
 +
By default, each unit matching the SUF will move toward the closest goal (in terms of turns needed to get there) matching the SLF via the fastest route given the current situation on the map (locations of enemy units etc.), but this behavior can be influenced by the optional keys listed below.  Note that this means that a unit's goal might change from one turn to the next depending on the situation on the map.
 +
 
 +
The behavior of the unit(s) once they reach their goal location(s) is configurable as well.  By default, they will stay there until the Goto Micro AI is deleted or changed.
 +
 
 +
For demonstrations of several Goto Micro AI usages, check out the "Goto" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Goto Micro AI by using
 +
ai_type=goto
 +
in the [micro_ai] tag.
 +
 
 +
===Goto specific keys for the [micro_ai] tag:===
 +
 
 +
'''Required keys:'''
 +
 
 +
* '''[filter_location]''': A [[StandardLocationFilter|Standard Location Filter]] describing the possible goal locations for the move.
 +
 
 +
'''Optional keys:'''
 +
 
 +
* '''[avoid]''':  {{DevFeature1.15|0}} A [[StandardLocationFilter|Standard Location Filter]] for the locations which the AI units should avoid.  If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists). Note that the area defined by [avoid] is not entered at all, even if the end point of the move would lie outside the area again.
 +
* '''avoid_enemies''': (number>0) By default, units controlled by the Goto Micro AI will not take enemy units into account for route finding, other than the enemies' ZoCs.  By contrast, if this key is set, they will try to avoid traversing hexes on which they can be attacked by enemies.  The larger the value of ''avoid_enemies'', the more the units will try to stay out of the enemies' way.  Notes:
 +
** Units are willing to take a path that is 'avoid_enemies' movement points longer for each enemy unit that can be avoided by doing so for each hex along the path.  As an example, if avoid_enemies=1 and the shortest path crosses 2 hexes that can be reached by 3 enemies each, the unit is willing to take a path that is up to 6 hexes longer instead.  If avoid_enemies=10 in the same situation, the unit will take a path up to 60 hexes longer.
 +
** Hexes adjacent to enemy units are always strongly avoided, independent of the value of avoid_enemies.
 +
** avoid_enemies is ignored if 'use_straight_line=true' is set.
 +
** Due to an issue with the path finding code, '''tunnels and teleports are ignored in Wesnoth 1.14 and before''' if 'avoid_enemies' is used. This has been fixed in Wesnoth 1.15.
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the units to be moved.  Defaults to all units of the side if not defined.  The filter automatically includes the side= key set to the AI side.
 +
* '''ignore_enemy_at_goal'''=no and '''ignore_units'''=no: (boolean)  In the default configuration, the Goto MAI does not move units if the path to all goal hexes is blocked by enemies.  It is therefore possible to disable the Goto MAI by putting enemy units on all the goal hexes.  That can be changed if either of these two keys is set to 'yes'.
 +
** 'ignore_enemy_at_goal=yes' makes the AI choose its goals while disregarding any enemy units at the goal hexes.  Even so, a stiff rating penalty is applied to goal hexes occupied by enemies, thus that unoccupied goal hexes are chosen unless all possible goals are occupied by enemies.  Note that this setting ''only'' ignores enemy units at the goal hexes themselves.  It is still possible to disable the AI by putting enemies all around the goals.
 +
** 'ignore_units=yes' let's the AI ignore ''all'' enemy units when deciding which goal hex(es) to move toward.
 +
** In both cases, enemies are only ignored for deciding which unit to move toward which goal hex.  For the actual move itself, all enemies and their ZoCs are considered as usual.
 +
** Both options only take effect if neither avoid_enemies is used, nor use_straight_line is set to 'yes', as neither of these consider enemies as blockers. Or in other words, if avoid_enemies is used, or use_straight_line=yes, it is unnecessary to set ignore_enemy_at_goal or ignore_units to yes.
 +
* '''release_unit_at_goal'''=no: (boolean) By default, a unit that reaches a goal location will stay there until the Goto Micro AI is deleted or changed (or until the conditions specified in the [goto_goals] SLF change).  If this parameter is set, a unit that has reached its goal will not be controlled by this Micro AI any more starting from the next turn.
 +
* '''release_all_units_at_goal'''=no: (boolean) Same as ''release_unit_at_goal'', but this will deactivate the Goto Micro AI for all units once the first unit reaches a goal.
 +
* '''remove_movement'''=yes: (boolean):  {{DevFeature1.15|11}}  By default, when the Goto MAI cannot move a unit (for example, because the path is blocked by enemies), its movement points are still removed. If this option is set to 'no', this step does not happen, so that other AI candidate actions (or even another Goto MAI with different parameters) can take over instead.
 +
* '''unique_goals'''=no: (boolean)  If set to 'yes', each unit will be sent to a different goal location.  Note that the best goals are recalculated each turn, so a unit might choose a different goal this turn from what it was heading for during the previous turn if the situation on the map has changed.  Also note that if there are more units than goal locations, the left over units will not be handled by the Goto MAI but follow default behavior instead.
 +
* '''use_straight_line'''=no: (boolean)  By default, units choose the route by which they will get to their goal locations in the smallest number of turns.  If this parameter is set to 'yes', a straight line route (or something pretty close to it at least) will be chosen instead, irrespective of whether this leads into a dead end, whether it is blocked by enemies, etc.
 +
 
 +
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''[avoid]''':  {{DevFeature1.15|0}} The standard RCA AI aspect used to define locations that should be avoided by the AI.  See above (under 'optional keys') for details.
 +
 
 +
'''Notes:'''
 +
* Depending on the parameters used, the Goto Micro AI might require a lot of path finding to be done.  Thus, while it is possible to set up this AI to move many units to many different locations, a usage like that might require quite a long calculation time.
 +
 
 +
===Goto Micro AI example usages:===
 +
 
 +
Here are several examples of goto [micro_ai] tag usages from the "Goto" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
* Send a unit toward a castle (similar to the RCA AI's Goto Candidate Action, but avoiding dead ends and areas ZoCed by enemies)
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=goto
 +
            action=add
 +
            ca_id=messenger1
 +
 +
            [filter]
 +
                id=messenger1
 +
            [/filter]
 +
            [filter_location]
 +
                x,y=6-7,2-4
 +
                terrain=C*
 +
            [/filter_location]
 +
            ca_score=210001
 +
        [/micro_ai]
 +
* Send all units of the side toward the southern border of the map
 +
        [micro_ai]
 +
            side=8
 +
            ai_type=goto
 +
            action=add
 +
 +
            [filter_location]
 +
                  y=33
 +
            [/filter_location]
 +
            avoid_enemies=1
 +
        [/micro_ai]
 +
* Send units to the four corners of the map (with each unit going to a different corner).
 +
        [micro_ai]
 +
            side=7
 +
            ai_type=goto
 +
            action=add
 +
 +
            [filter_location]
 +
                x=1,1,44,44
 +
                y=1,33,1,33
 +
            [/filter_location]
 +
            unique_goals=yes
 +
        [/micro_ai]
 +
* Set up a guardian unit that doesn't move while no enemy unit is within 8 hexes (ironically, the Goto Micro AI can be used to keep units in place, although using one of the Guardian Micro AIs might often be a better idea)
 +
        [micro_ai]
 +
            side=3
 +
            ai_type=goto
 +
            action=add
 +
 +
            [filter]
 +
                id=guard1
 +
            [/filter]
 +
            [filter_location]
 +
                [filter]
 +
                    id=guard1
 +
                [/filter]
 +
                [not]
 +
                    [filter]
 +
                        side=1
 +
                    [/filter]
 +
                    radius=8
 +
                [/not]
 +
            [/filter_location]
 +
        [/micro_ai]
 +
 
 +
== Guardian Micro AIs ==
 +
=== General Comments on the Guardian Micro AIs ===
 +
 
 +
The Guardian Micro AIs can be used to set up different kind of guardian behaviors for a unit or a set of units.  Four different types of guardians are available and are described below.
 +
 
 +
For a demonstration of several different guardian behaviors, check out the "Guardians" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
=== Return Guardian (ai_type=return_guardian)===
  
 
A 'return guardian' is a variation of the standard Wesnoth guardian. It has an assigned guard position (GP) to which it returns after attacks on approaching enemies:
 
A 'return guardian' is a variation of the standard Wesnoth guardian. It has an assigned guard position (GP) to which it returns after attacks on approaching enemies:
 
* If at GP with no enemy in reach, do nothing.
 
* If at GP with no enemy in reach, do nothing.
* If at GP with an enemy in reach, attack (note that the attack is done by default AI, which might result in the guardian not attacking if the enemy is deemed too strong).
+
* If at GP with an enemy in reach, attack. Note that the attack is done by the default AI, which might result in the guardian not attacking if the enemy is deemed too strong (this can be influenced by setting the default ''aggression'' value to a different value).
 
* If not at GP, return there, no matter whether an enemy is in reach or not.
 
* If not at GP, return there, no matter whether an enemy is in reach or not.
 
* If enemies are blocking the way back to GP, do your best to move around them.
 
* If enemies are blocking the way back to GP, do your best to move around them.
 
* If the guardian ends up next to an enemy on the way back, attack that enemy after the move.
 
* If the guardian ends up next to an enemy on the way back, attack that enemy after the move.
  
You can configure each return guardian using the following keys in the [micro_ai] tag:
+
Enable the Return Guardian Micro AI by using
 +
ai_type=return_guardian
 +
in the [micro_ai] tag together with the following keys:
  
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''guardian_type''': Must be set to "return_guardian"
+
* '''id''' or '''[filter]''': The ID of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
* '''id''': The ID of the unit to which this AI should be attached
+
** One or the other is required
* '''return_x,return_y''': The coordinate of the hex the unit returns to after each attack
+
** If both are given, [filter] takes priority over id=
 +
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
 +
** If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
 +
* '''return_x,return_y''': The coordinate of the hex the unit returns to after each attack.  {{DevFeature1.15|0}} '''return_loc''' can be used instead with a named/special location.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
There are no optional keys.
+
* '''ca_score'''=100010: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  This AI consist of 2 CAs, one with score <tt>ca_score</tt> the other with <tt>ca_score-20</tt>.  The default value is set so that the first CA gets executed right before the default combat CA, and the other right after.  It usually will not make sense to change this value, but it is possible to do so for custom applications.  {{DevFeature1.13|6}}: This is now changed to 100100 and 99900 in order to avoid conflicts with the new high_XP_attacks candidate action.
  
Here's an example of a return guardian [micro_ai] tag usage from the "Guardians" test scenario:
+
Here's an example of a return guardian [micro_ai] tag usage from the "Guardians" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
 
             side=2
 
             side=2
             ai_type=guardian_unit
+
             ai_type=return_guardian
 
             action=add
 
             action=add
            id=return1
 
 
   
 
   
             guardian_type=return_guardian
+
             [filter]
 +
                id=return1
 +
            [/filter]
 
             return_x,return_y=20,2
 
             return_x,return_y=20,2
 
         [/micro_ai]
 
         [/micro_ai]
  
===Stationed Guardian (guardian_type=stationed_guardian) ===
+
===Stationed Guardian (ai_type=stationed_guardian) ===
  
 
A 'stationed guardian' is another variation of the standard Wesnoth guardian with a somewhat more complex behavior than that of the 'return guardian'. Two positions are defined for it, a 'station' and a 'guarded location', as well as a distance. The behavior is as follows:
 
A 'stationed guardian' is another variation of the standard Wesnoth guardian with a somewhat more complex behavior than that of the 'return guardian'. Two positions are defined for it, a 'station' and a 'guarded location', as well as a distance. The behavior is as follows:
 
* If no enemy is within 'distance' of the guard's current position, do nothing.  This is independent of the guardian being at its station or not.
 
* If no enemy is within 'distance' of the guard's current position, do nothing.  This is independent of the guardian being at its station or not.
* Otherwise: If an enemy is within 'distance' of the guard, but not also within the same distance of the guarded location and the station (all of this simultaneously), move the guard in the direction of the station.
+
* Otherwise: If an enemy is within 'distance' of the guard, but not also within the same distance of the guarded location and the station (all of this simultaneously), move the guard in the direction of the station (or keep the guard in place if the station is unreachable).
 
* Otherwise:
 
* Otherwise:
 
** Pick the enemy unit that is closest to the guarded location.
 
** Pick the enemy unit that is closest to the guarded location.
Line 267: Line 737:
 
** If not in reach, move toward this unit.
 
** If not in reach, move toward this unit.
  
You can configure each stationed guardian using the following keys in the [micro_ai] tag:
+
Enable the Stationed Guardian Micro AI by using
 +
ai_type=stationed_guardian
 +
in the [micro_ai] tag together with the following keys:
  
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''guardian_type''': Must be "stationed_guardian"
+
* '''id''' or '''[filter]''': The ID of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
* '''id''': The ID of the unit to which this AI should be attached
+
** One or the other is required
 +
** If both are given, [filter] takes priority over id=
 +
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
 +
** If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
 
* '''distance''': The distance parameter as explained above
 
* '''distance''': The distance parameter as explained above
* '''station_x,station_y''': The x and y position of the hex that serves as the guardians station.
+
* '''station_x,station_y''': The x and y position of the hex that serves as the guardians station. {{DevFeature1.15|0}} '''station_loc''' can be used instead with a named/special location.
* '''guard_x, guard_y''': The x and y position of the guarded location.
+
* '''guard_x, guard_y''': The x and y position of the guarded location.  {{DevFeature1.13|0}}  These are now optional keys, defaulting to station_x,station_y if not provided. {{DevFeature1.15|0}} '''guard_loc''' can be used instead with a named/special location.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
There are no optional keys.
+
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  
Here's an example of a stationed guardian [micro_ai] tag usage from the "Guardians" test scenario:
+
Here's an example of a stationed guardian [micro_ai] tag usage from the "Guardians" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
 
             side=2
 
             side=2
             ai_type=guardian_unit
+
             ai_type=stationed_guardian
 
             action=add
 
             action=add
 
   
 
   
             guardian_type=stationed_guardian
+
             [filter]
            id=stationed1
+
                id=stationed1
 +
            [/filter]
 
             distance=4
 
             distance=4
 
             station_x,station_y=2,14
 
             station_x,station_y=2,14
Line 294: Line 770:
 
         [/micro_ai]
 
         [/micro_ai]
  
=== Coward (guardian_type=coward) ===
+
=== Coward (ai_type=coward) ===
  
 
Cowards are units that, like guardians, sit around doing nothing until an enemy comes into range.  Unlike guardians, however, they run away once enemies approach. Applications might be wild animals, unarmed civilians getting in the way of a battle, etc.  The coward macro can be called with two optional locations, 'seek' and 'avoid':
 
Cowards are units that, like guardians, sit around doing nothing until an enemy comes into range.  Unlike guardians, however, they run away once enemies approach. Applications might be wild animals, unarmed civilians getting in the way of a battle, etc.  The coward macro can be called with two optional locations, 'seek' and 'avoid':
Line 302: Line 778:
 
* Both 'seek' and 'avoid' may consist of only one coordinate ('x' or 'y'), in which case not a single hex, but a line of hexes is sought or avoided.
 
* Both 'seek' and 'avoid' may consist of only one coordinate ('x' or 'y'), in which case not a single hex, but a line of hexes is sought or avoided.
  
You can configure each coward using the following keys in the [micro_ai] tag:
+
Enable the Coward Micro AI by using
 +
ai_type=coward
 +
in the [micro_ai] tag together with the following keys:
  
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''guardian_type''': Must be "coward"
+
* '''id''' or '''[filter]''': The ID of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
* '''id''': The ID of the unit to which this AI should be attached
+
** One or the other is required
 +
** If both are given, [filter] takes priority over id=
 +
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
 +
** If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
 
* '''distance''': The distance within which an enemy must be to "scare" the unit
 
* '''distance''': The distance within which an enemy must be to "scare" the unit
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
* '''seek_x, seek_y''': The x and y coordinate of the hex to seek
+
* '''attack_if_trapped'''='no':  {{DevFeature1.13|0}}  With the default settings, a coward never attacks.  If this key is set to 'yes', the coward attacks the weakest (lowest hitpoints) enemy next to which it ends up after moving (such as a cornered animal would do, blindly lashing out without regards for its own safety).
* '''avoid_x, avoid_y''': The x and y coordinate of the hex to avoid
+
* '''avoid_x, avoid_y''': The x and y coordinate of the hex to avoid. {{DevFeature1.15|0}} '''avoid_loc''' can be used instead with a named/special location.
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''[filter_second]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the units from which the cowards flee.  If not set, this defaults to all enemy units.  Note, however, that no "enemy of AI side" condition is added if [filter_second] is specified, meaning that it can include allied and/or enemy units as desired (and even units on the same side as the coward).
 +
* '''seek_x, seek_y''': The x and y coordinate of the hex to seek. {{DevFeature1.15|0}} '''seek_loc''' can be used instead with a named/special location.
  
Here's an example of a coward [micro_ai] tag usage from the "Guardians" test scenario:  
+
Here's an example of a coward [micro_ai] tag usage from the "Guardians" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:  
 
         [micro_ai]
 
         [micro_ai]
 
             side=2
 
             side=2
             ai_type=guardian_unit
+
             ai_type=coward
 
             action=add
 
             action=add
            id=coward3
 
 
   
 
   
             guardian_type=coward
+
             [filter]
 +
                id=coward3
 +
            [/filter]
 
             distance=5
 
             distance=5
 
             seek_x,seek_y=24,5
 
             seek_x,seek_y=24,5
 
             avoid_x,avoid_y=24,15
 
             avoid_x,avoid_y=24,15
 +
        [/micro_ai]
 +
 +
=== Zone guardian (ai_type=zone_guardian) ===
 +
 +
A zone guardian is a unit that, as the name says, guards a zone. It moves randomly inside this zone until an enemy enters it (or a separately defined enemy zone, see below). Applications might be the defense of a castle, a nesting area or for protecting an unit.  The zone macro can be called with an optional SLF, [filter_location_enemy]:
 +
* If not specified, the zone guard attacks any enemy coming inside its guard zone.
 +
* If [filter_location_enemy] is given, it attacks any enemy entering this zone and once there are no more enemies, it goes back to patrol in its basic zone.
 +
 +
Enable the Zone Guardian Micro AI by using
 +
ai_type=zone_guardian
 +
in the [micro_ai] tag together with the following keys:
 +
 +
'''Required keys:'''
 +
 +
* '''id''' or '''[filter]''': The ID of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
 +
** One or the other is required
 +
** If both are given, [filter] takes priority over id=
 +
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
 +
** If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
 +
* '''[filter_location]''': A [[StandardLocationFilter|Standard Location Filter]] designating the zone to guard.
 +
 +
'''Optional keys:'''
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''[filter_location_enemy]''': A [[StandardLocationFilter|Standard Location Filter]] designating the zone where enemies have to be attacked.  If not given, it defaults to [filter_location].
 +
* '''station_x,station_y''': By default, the zone guardian moves randomly within the zone if there is no enemy to attack.  However, if station_x/y is given, it moves to this position instead during turns when it does not have an enemy to attack.  This position does not need to be inside the zone defined above.  Note: obviously it does not make sense to define [filter_location], [filter_location_enemy] and station_x/y all at the same time.  Only [filter_location] and either one of the latter two (or none of them) should be provided for any zone guardian. {{DevFeature1.15|0}} '''station_loc''' can be used instead with a named/special location.
 +
 +
Here's an example of a zone guardian [micro_ai] tag usage from the "Guardians" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=zone_guardian
 +
            action=add
 +
 +
            [filter]
 +
                id=zone3
 +
            [/filter]
 +
            [filter_location]
 +
                x,y=22-31,4-11  # This is intentionally chosen to extend past the lake
 +
                terrain=W*
 +
            [/filter_location]
 +
            station_x,station_y=32,8
 +
        [/micro_ai]
 +
 +
== Hang Out Micro AI (ai_type=hang_out) ==
 +
 +
The Hang Out Micro AI instructs units of the AI side to "hang out" around a certain location, or locations, until a condition for mobilizing the side is met.  If none of the optional keys are given, the AI controls all units of the side to hang around the leader while moving off castle tiles to make room for recruiting.
 +
 +
The AI works by moving each unit to its best hex first using the minimum amount of movement points required for this move.  Once all AI units are in position, movement points are set to zero for all of them simultaneously such that they cannot be used by other AI candidate actions.  This is done because the mobilizing condition might be met as result of one of the moves of the Hang Out AI, after which we want units to be able to continue with other AI actions.
 +
 +
For a demonstration, check out the "Hang Out and Messenger" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 +
Enable the Hang Out Micro AI by using
 +
ai_type=hang_out
 +
in the [micro_ai] tag.
 +
 +
===Hang Out specific keys for the [micro_ai] tag:===
 +
 +
'''Required keys:'''
 +
 +
There are no required keys.  In its default configuration, the Hang Out MAI controls all units of a side, keeping them as close to the side leader(s) as possible while moving off castle tiles to make room for recruiting.  For this purpose, the candidate action score defaults to 170,000, which is just below the score of the default recruiting CA.
 +
 +
'''Optional keys:'''
 +
 +
* '''[avoid]''': A [[StandardLocationFilter|Standard Location Filter]] for the terrain which the AI units should avoid.  If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).  If neither of these two exists, this parameter is set to default to all castle terrain (<tt>terrain=C*,C*^*,*^C*</tt>) so that units move off the castle to make room for recruiting.  Note that this does not include keep terrain, otherwise the leader would be moved off the keep as well.
 +
* '''ca_score'''=170000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 170,000, which means that it is executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the units of the AI side participating in the Hang Out action (<tt>side=</tt> is always set and does not need to be provided).  It defaults to all units of the side.  The filter automatically includes the side= key set to the AI side.
 +
* '''[filter_location]''': A [[StandardLocationFilter|Standard Location Filter]] describing the locations ''near'' which the AI units should hang out.  This does not mean that the units only move onto terrain specified here, but that they minimize the distance to such terrain.  It defaults to the position of the side leader(s).
 +
* '''[mobilize_condition]''':  Contains ([[ConditionalActionsWML#Condition_Tags|WML Condition Tags]])  Once the condition set up here has been met, the Hang Out MAI is disabled and the side goes over to other AI activity.  The Hang Out MAI remains disabled after this, even if the condition is not met any more later in the scenario.
 +
* '''mobilize_on_gold_less_than''': (integer) Since side gold cannot be checked in a WML condition tag without storing it in a variable first, this key is provided separately.  It disables the Hang Out Micro AI once the side gold goes below the value specified here for the first time.
 +
 +
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''[avoid]''': The standard RCA AI aspect used to define locations that should be avoided by the AI.  See above (under 'optional keys') for details.
 +
 +
'''Notes:'''
 +
 +
* The Hang Out AI still takes effect if no locations to hang out at are found or if all map locations are to be avoided.  In that case, it simply keeps all units at their current locations.
 +
 +
This is an example of a Hang Out Micro AI configuration from the "Hang Out and Messenger" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=1
 +
            ai_type=hang_out
 +
            action=add
 +
 +
            [avoid]
 +
                terrain=C*,H*,M*,A*,S*,*^F*
 +
            [/avoid]
 +
            [mobilize_condition]
 +
                [have_unit]
 +
                    side=1
 +
                    count=7-99
 +
                [/have_unit]
 +
            [/mobilize_condition]
 
         [/micro_ai]
 
         [/micro_ai]
  
 
== Healer Support Micro AI (ai_type=healer_support) ==
 
== Healer Support Micro AI (ai_type=healer_support) ==
  
The Healer Support Micro AI configures the healers of a side to stay behind the battle lines and heal injured and/or threatened units rather than participate in combat under all circumstances.  You can set different levels of aggressiveness for the healers.  Note that it is not always better to use this Micro AI than the default AI, as it takes healers (which can be strong units) away from the pool of units to choose for attacks.
+
The Healer Support Micro AI configures the healers of a side to stay behind the battle lines and heal injured and/or threatened units rather than participate in combat under all circumstances.  You can set different levels of aggressiveness for the healers.   
  
For a demonstration, check out the "Healers" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.
+
'''Notes'''
 +
* By default, ''all'' healers of the AI side are controlled by this AI.  This includes in particular also the side leader, if the leader is a healer.  If you do not want the leader to be included (and possibly be moved away from the keep etc.) use the [filter] tag with canrecruit=no (see below).
 +
* It is not always better to use this Micro AI than the default AI, as it takes healers (which can be strong units) away from the pool of units to choose for attacks.
 +
* {{DevFeature1.15|3}} This Micro AI now takes unit guardian status and the passive_leader aspect into account.
  
Enable the Healer Support Micro AI by putting
+
For a demonstration, check out the "Healers" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
{MICRO_AI_HEALER_SUPPORT}
+
 
into the [side] tag and configure it by using
+
Enable the Healer Support Micro AI by using
 
  ai_type=healer_support
 
  ai_type=healer_support
 
in the [micro_ai] tag.
 
in the [micro_ai] tag.
Line 348: Line 927:
 
'''Optional keys:'''
 
'''Optional keys:'''
  
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the healer units.  If set, only units on the AI side passing this filter ''and'' having the healing ability are considered by this Micro AI.
 +
*'''[filter_second]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting units to receive healing. If set, only units on the AI side passing this filter ''and'' the other healee selection criteria will be selected for healing by this Micro AI.
 
* '''aggression'''=1.0: (float) Sets the aggressiveness of the AI.  This parameter is set up as a float to accommodate future functionality, but it currently acts as a boolean: if set to zero, the AI will never let its healers participate in combat, for all other values it allows them to attack after all other units have attacked and if the healers cannot find any more units to support.  The former behavior might be appropriate in scenarios with only one or few valuable healers, while the latter might work better in scenarios with many healers.
 
* '''aggression'''=1.0: (float) Sets the aggressiveness of the AI.  This parameter is set up as a float to accommodate future functionality, but it currently acts as a boolean: if set to zero, the AI will never let its healers participate in combat, for all other values it allows them to attack after all other units have attacked and if the healers cannot find any more units to support.  The former behavior might be appropriate in scenarios with only one or few valuable healers, while the latter might work better in scenarios with many healers.
 
* '''injured_units_only'''=no: (boolean) If set to 'yes', the AI will only move healers next to units that are already injured and skip units that currently have full hitpoints, but might get injured during the next enemy turn.
 
* '''injured_units_only'''=no: (boolean) If set to 'yes', the AI will only move healers next to units that are already injured and skip units that currently have full hitpoints, but might get injured during the next enemy turn.
 
* '''max_threats'''=9999: (integer) The maximum allowable number of enemies that can attack a hex in order for it to be considered for a healer.  As an example, setting 'max_threats=0' means that the AI only moves healers to locations that are entirely safe from the enemy (assuming that none of the units currently on the map dies).  Note that the value of this key is checked against the number of enemies that can make it to the hex, not the number of adjacent hexes from which the healer could be attacked.
 
* '''max_threats'''=9999: (integer) The maximum allowable number of enemies that can attack a hex in order for it to be considered for a healer.  As an example, setting 'max_threats=0' means that the AI only moves healers to locations that are entirely safe from the enemy (assuming that none of the units currently on the map dies).  Note that the value of this key is checked against the number of enemies that can make it to the hex, not the number of adjacent hexes from which the healer could be attacked.
  
'''Note:''' The Healer Support Micro AI modifies the [[AiWML#Filtering_Combat_with_the_.27attacks.27_Aspect|attacks aspect]].
+
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''[avoid]''': The standard RCA AI aspect used to define locations that should be avoided by the AI. Note: as attacks by the healers are left to the default AI, there is no separate ''[avoid]'' tag for this Micro AI in order to prevent inconsistencies.
  
This is an example of a Healer Support Micro AI configuration:
+
'''Notes:'''
 +
* The Healer Support Micro AI modifies the [[AiWML#Filtering_Combat_with_the_attacks_Aspect|attacks aspect]].
 +
* The CA evaluation scores of this AI are hard-coded.  It does not work otherwise.
 +
 
 +
This is an example of a Healer Support Micro AI configuration from the "Healers" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
 
             side=2
 
             side=2
 
             ai_type=healer_support
 
             ai_type=healer_support
 
             action=add
 
             action=add
 +
 
             aggression=0
 
             aggression=0
 
         [/micro_ai]
 
         [/micro_ai]
  
 
== Lurkers Micro AI (ai_type=lurkers) ==
 
== Lurkers Micro AI (ai_type=lurkers) ==
The Lurkers Micro AI defines a lurker battle AI. A lurker can move across most terrains but stop only on thoes that are explicitly defined.
 
They always attack the weakest enemy within their reach from only explicitly defined terrains. If no enemy is in reach, the lurker does a random move instead.
 
  
For a demonstration, check out scenario "Swamp Lurkers" of the AI-Demos campaign.
+
The Lurker Micro AI controls some or all units of a side in "lurker mode".  A lurker is a unit that is capable of moving across most terrains, but that only stops on and attacks from specific terrain.  It might also have the ability to hide on this terrain (which is the reason why it is called a lurker).
  
Enable the Lurkers Micro AI by putting
+
Lurkers move individually without strategy and always attack the weakest enemy within their reach.  If no enemy is in reach, the lurker does a random move instead - or it just sits and waits (lurks).
{MICRO_AI_LURKERS}
+
 
into the [side] tag and configure it by using
+
For a demonstration of different types of lurker behavior, check out the "Lurkers" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Lurkers Micro AI by using
 
  ai_type=lurkers
 
  ai_type=lurkers
 
in the [micro_ai] tag
 
in the [micro_ai] tag
Line 377: Line 964:
  
 
'''Required keys:'''
 
'''Required keys:'''
* '''[lurkers]''': Specifies which units of the side are to be controlled by the Lurker Micro AI.  This is a [[StandardUnitFilter|Standard Unit Filter]].
+
* '''[filter]''': Specifies which units of the side are controlled by the Lurker Micro AI.  This is a [[StandardUnitFilter|Standard Unit Filter]].  The filter automatically includes the side= key set to the AI side.
* '''[attack_terrain]''': Specifies terrains from which the lurkers attack. This is a [[StandardLocationFilter|Standard Location Filter]].
+
* '''[filter_location]''': Specifies the terrain from which the lurkers attack. This is a [[StandardLocationFilter|Standard Location Filter]].
  
 
'''Optional keys:'''
 
'''Optional keys:'''
* '''[wander_terrain]''': Specifies terrains on which lurkers end there moves if there is no enemy in reach. This is a [[StandardLocationFilter|Standard Location Filter]].  If [wander_terrain] is not given, it defaults to [attack_terrain].
+
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''[filter_location_wander]''': Specifies the terrain on which lurkers end their moves if there is no enemy in reach. This is a [[StandardLocationFilter|Standard Location Filter]].  If [filter_location_wander] is not given, it defaults to [filter_location].
 
* '''stationary'''=no: (boolean)  If set to yes, a lurker never moves if there is no enemy within attack range.
 
* '''stationary'''=no: (boolean)  If set to yes, a lurker never moves if there is no enemy within attack range.
 +
 +
Here's an example of [micro_ai] tag usage from the "Lurkers" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 +
        [micro_ai]
 +
            side=4
 +
            ai_type=lurkers
 +
            action=add
 +
 +
            [filter]
 +
                type=Naga Fighter
 +
            [/filter]
 +
            [filter_location]
 +
                terrain=W*,S*
 +
            [/filter_location]
 +
            [filter_location_wander]
 +
                terrain=W*
 +
            [/filter_location_wander]
 +
        [/micro_ai]
  
 
== Messenger Escort Micro AI (ai_type=messenger_escort) ==
 
== Messenger Escort Micro AI (ai_type=messenger_escort) ==
  
The Messenger Escort Micro AI lets you define a set of waypoints through which it tries to move one of its units, the messenger.  The other units escort the messenger, trying to protect it and attacking enemies that are in its way.  Note that the messenger might not strictly hit intermediate waypoints, but that getting close is good enough, especially if a waypoint is occupied by an enemy unit.  It does, however, always try to get to the last waypoint.  
+
The Messenger Escort Micro AI lets you define a set of waypoints through which it tries to move one or several of its units, the messenger(s).  The other units escort the messenger, trying to protect it and attacking enemies that are in its way.  Note that a messenger might not strictly hit intermediate waypoints, but that getting close is good enough, especially if a waypoint is occupied by an enemy unit.  It does, however, always try to get to the last waypoint.
  
For a demonstration, check out the "Messenger" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.
+
'''Notes on the use of several messengers:''' {{DevFeature1.13|0}} 
 +
* This Micro AI can control several messengers at the same time, which can but do not have to move in a group.  They can be put on the map altogether in one location, or be spread out on the map or across different turns.
 +
* The farther a messenger has moved through the chain of waypoints, the higher a priority it is for the AI, meaning that farther advanced (on the map) messengers are moved first, and that the escort units try to clear the way and stay with those messengers more so than with those further back on the map.  This order can be inverted using the invert_order= key.
 +
* If several messengers are on the map, escort units might move from one to the other, the AI making a judgement call where they are needed most.  Closeness to a messenger is generally the most important criterion, but not the only one.
 +
* If a messenger dies, the escort units previously staying with it now join one of the other messengers if there are any left (otherwise they follow default AI behavior).
 +
* If you want certain escort units to stay always with the same messenger, use several messenger [micro_ai] tags with different [filter]/[filter_second] combinations.
  
Enable the Messenger Escort Micro AI by putting
+
For a demonstration, check out the "Messenger" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
{MICRO_AI_MESSENGER_ESCORT}
+
 
into the [side] tag and configure it by using
+
Enable the Messenger Escort Micro AI by using
 
  ai_type=messenger_escort
 
  ai_type=messenger_escort
 
in the [micro_ai] tag.
 
in the [micro_ai] tag.
Line 400: Line 1,010:
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''id''': The id of the messenger. All other units of the side protect the messenger.
+
* '''id''' or '''[filter]''': {{DevFeature1.13|0}} (Previous to 1.13.0, only id= was allowed.) The id of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
* '''waypoint_x,waypoint_y''': Comma-separated list of waypoint coordinates through which the messenger will go in the given order to reach its goal, given by the last coordinate.  If you want the messenger to go directly to the goal, simply enter a single x,y coordinate here.  Note that the messenger does not have to hit each waypoint exactly (except for the final one), getting close to them is good enough.
+
** One or the other is required
 +
** If both are given, [filter] takes priority over id=
 +
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
 +
* '''waypoint_x,waypoint_y''': Comma-separated list of waypoint coordinates through which the messenger will go in the given order to reach its goal, given by the last coordinate.  If you want the messenger to go directly to the goal, simply enter a single x,y coordinate here.  Note that the messenger does not have to hit each waypoint exactly (except for the final one), getting close to them is good enough. {{DevFeature1.15|0}} '''waypoint_loc''' can be used instead with named/special locations.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
 +
* '''[avoid]''':  {{DevFeature1.15|11}} A [[StandardLocationFilter|Standard Location Filter]] for the locations which the AI units should avoid.  If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.  Note that the Messenger Escort AI consists of 3 CAs with scores ranging from <tt>ca_score-2</tt> to <tt>ca_score</tt>.
 
* '''enemy_death_chance'''=0.67 and '''messenger_death_chance'''=0.0: (both floats; ranging from 0 to 1)    If the messenger is adjacent to an enemy at the end of the move, it will only attack the enemy if the chance of death of the enemy is >= enemy_death_chance and if the messenger's chance of death is <= messenger_death_chance (or if it is an attack at a range for which the enemy does not have a weapon).
 
* '''enemy_death_chance'''=0.67 and '''messenger_death_chance'''=0.0: (both floats; ranging from 0 to 1)    If the messenger is adjacent to an enemy at the end of the move, it will only attack the enemy if the chance of death of the enemy is >= enemy_death_chance and if the messenger's chance of death is <= messenger_death_chance (or if it is an attack at a range for which the enemy does not have a weapon).
 +
* '''[filter_second]''': {{DevFeature1.13|0}} A [[StandardUnitFilter|Standard Unit Filter]] selecting the escort units.  If not set, this defaults to all enemy units. The filter automatically includes the side= key set to the AI side.
 +
* '''invert_order'''=no: {{DevFeature1.13|0}} If set to 'yes', the order of priority with which messenger units are considered is inverted, starting with the messenger unit that is the least advanced on the map (see description above).  In most cases, selecting this option results in worse performance of the AI, so use it with caution.  (And obviously it has no effect at all if there is only one messenger controlled by the AI.)
  
Here's an example of [micro_ai] tag usage from the "Messenger Escort" test scenario:
+
'''Standard RCA AI aspects respected by this Micro AI:'''
 +
*'''[avoid]''':  {{DevFeature1.15|11}} The standard RCA AI aspect used to define locations that should be avoided by the AI.  See above (under 'optional keys') for details.
 +
 
 +
Here's an example of [micro_ai] tag usage from the "Messenger Escort" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
 
             side=2
 
             side=2
Line 413: Line 1,033:
 
             action=add
 
             action=add
 
   
 
   
             id=messenger
+
             [filter]
 +
                id=messenger
 +
            [/filter]
 
             waypoint_x=31,24,27,28
 
             waypoint_x=31,24,27,28
 
             waypoint_y=20,14,7,1
 
             waypoint_y=20,14,7,1
 
         [/micro_ai]
 
         [/micro_ai]
  
== Patrol Micro AI (ai_type=patrol_unit) ==
+
== Patrol Micro AI (ai_type=patrol) ==
  
The Patrol Micro AI attaches to an individual unit and defines a number of waypoints for that unit to follow.  Options can be set whether the route should be followed in a loop, as an out-and back, only once, whether units encountered along the way should be attacked, etc.
+
The defines a number of waypoints for a unit (or units) to follow.  Options can be set whether the route should be followed in a loop, as an out-and back, only once, whether units encountered along the way should be attacked, etc.
  
No matter what options are chosen, getting to the next waypoint always takes priority over attacking for a patroller.  The AI thus prefers to move the patrol unit around enemies rather than straight for them.  Also, if a waypoint is occupied by a unit the AI is not instructed to attack, it will (eventually) abandon that waypoint once it gets close enough and move on to the next one.
+
With the default settings, getting to the next waypoint takes priority over attacking for a patroller, but this can be overridden (as of '''Wesnoth 1.15.12''', using the '''attack_range''' option)Unless instructed otherwise, the AI thus prefers to move the patrol unit around enemies rather than straight for them.  Also, if a waypoint is occupied by a unit the AI is not instructed to attack, it will (eventually) abandon that waypoint once it gets close enough and move on to the next one.
  
Multiple patrol units can be used on the same side, by setting up a separate [micro_ai] tag for each unit.
+
For a demonstration of several different patrol behaviors, check out the "Patrols" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
  
For a demonstration of several different patrol behaviors, check out the "Patrols" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.
+
Enable the Patrol Micro AI it by using
 
+
  ai_type=patrol
Enable the Patrol Micro AI by putting
 
{MICRO_AI_PATROL}
 
into the [side] tag and configure it by using
 
  ai_type=patrol_unit
 
 
in the [micro_ai] tag.
 
in the [micro_ai] tag.
 
'''NOTE: The [micro_ai] tag needs to be placed after the creation of the unit it controls in the scenario event.'''
 
  
 
===Patrol specific keys for the [micro_ai] tag:===
 
===Patrol specific keys for the [micro_ai] tag:===
Line 440: Line 1,056:
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''id''': The id of the patrol unit.
+
* '''id''' or '''[filter]''': The ID of a unit or a [[StandardUnitFilter|Standard Unit Filter]] selecting the units controlled by this Micro AI.
* '''waypoint_x,waypoint_y''': Comma-separated lists of the waypoint coordinates through which the patrol travels (in order).
+
** One or the other is required
 +
** If both are given, [filter] takes priority over id=
 +
** The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
 +
** If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
 +
* '''waypoint_x,waypoint_y''': Comma-separated lists of the waypoint coordinates through which the patrol travels (in order). {{DevFeature1.15|0}} '''waypoint_loc''' can be used instead with named/special locations.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
 +
* '''attack''': By default (if this key is not set), the patrol unit attacks any unit it ends up next to after a move, or that is within '''attack_range''' (see below).  Alternatively, this parameter can be set to a comma-separated list of unit ids. If that is done, the patrol only attacks these units when it ends up next to them or if it gets within attack_range.  It ignores any other unit.  This can in turn be used to have the patroller not attack at all, by setting ''attack='' to a non-existing id.  The exception to this is an enemy on the last waypoint with ''one_time_only=yes'', which will always be attacked.
 +
* '''attack_range'''=1: {{DevFeature1.15|12}} If the patrol comes within this many hexes of an enemy unit, it interrupts its patrol route and attacks that enemy (assuming it still has enough movement left to get to the enemy).  The '''attack=''' instructions are taken into account for this.  Note that the patrol generally tries to move around enemies, which means that for the default value of 1, enemies are usually not within attack range, except at the end of the move.
 +
* '''attack_invisible_enemies'''=no: {{DevFeature1.15|12}} If set to 'yes', the unit also attacks invisible enemies (according to the criteria set by '''attack''' and '''attack_range''').
 +
* '''ca_score'''=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 300,000, which is higher than any of the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|RCA AI candidate actions]].  By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
 +
* '''one_time_only'''=no: (boolean)  If set to 'yes', the unit goes through the patrol route only once and then hangs out at the last waypoint.  It also always attacks any enemy unit on the last waypoint, independent of what ''attack='' is set to.
 
* '''out_and_back'''=no: (boolean)  By default, a patrol unit returns to the first waypoint after reaching the last, doing the patrol route as a loop.  If this parameter is set to 'yes', the unit instead reverses its course and perpetually does out and backs of the route.
 
* '''out_and_back'''=no: (boolean)  By default, a patrol unit returns to the first waypoint after reaching the last, doing the patrol route as a loop.  If this parameter is set to 'yes', the unit instead reverses its course and perpetually does out and backs of the route.
* '''one_time_only'''=no: (boolean)  If set to 'yes', the unit goes through the patrol route only once and then hangs out at the last waypoint.  It also always attacks any enemy unit on the last waypoint, independent of what ''attack='' is set to.
 
* '''attack''': By default (if this key is not set), the patrol unit attacks any unit it ends up next to after a move.  Alternatively, this parameter can be set to a comma-separated list of unit ids. If that is done, the patrol only attacks these units when it ends up next to them and ignores any other unit.  This can in turn be used to have the patroller not attack at all, by setting ''attack='' to a non-existing id.
 
  
Here's an example of [micro_ai] tag usage from the "Patrols" test scenario:
+
Here's an example of [micro_ai] tag usage from the "Patrols" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
 
             side=2
 
             side=2
             ai_type=patrol_unit
+
             ai_type=patrol
 
             action=add
 
             action=add
 
   
 
   
             id=Konrad
+
             [filter]
 +
                id=Konrad
 +
            [/filter]
 
             waypoint_x=9,24,25
 
             waypoint_x=9,24,25
 
             waypoint_y=21,23,15
 
             waypoint_y=21,23,15
Line 464: Line 1,089:
 
== Protect Unit Micro AI (ai_type=protect_unit) ==
 
== Protect Unit Micro AI (ai_type=protect_unit) ==
  
The Protect Unit Micro AI tries to move one or several units to a given location while keeping them safe from enem attacks. It does so by keeping the protected units away from enemy units and close to friendly units. Other units on the AI side are controlled by the default Wesnoth AI.
+
The Protect Unit Micro AI tries to move one or several units to a given location while keeping them safe from enemy attacks. It does so by keeping the protected units away from enemy units and close to friendly units. Other units on the AI side are controlled by the default Wesnoth AI.
  
For a demonstration, check out the "Protect Unit" and "The Elves Besieged" scenarios from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.
+
For a demonstration, check out the "Protect Unit" and "The Elves Besieged" scenarios from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
  
Enable the Protect Unit Micro AI by putting
+
Enable the Protect Unit Micro AI by using
{MICRO_AI_PROTECT_UNIT}
 
into the [side] tag and configure it by using
 
 
  ai_type=protect_unit
 
  ai_type=protect_unit
 
in the [micro_ai] tag.
 
in the [micro_ai] tag.
Line 478: Line 1,101:
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''[unit]''': A separate [unit] tag is required for each protected unit(s).  Each tag has required keys id=, goal_x=, goal_y= for each unit, as shown in the example below.
+
* '''[unit]''': A separate [unit] tag is required for each protected unit(s).  Each tag has required keys '''id''', '''goal_x''', '''goal_y''' for each unit, as shown in the example below. {{DevFeature1.15|0}} '''goal_loc''' can be used instead with a named/special location.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
Line 484: Line 1,107:
 
* '''disable_move_leader_to_keep'''=no: (boolean) If set to 'yes', side leaders protected by this AI do not try to return to their keep.  This is necessary for this Micro AI to work with units that are side leaders and that are supposed to move to an off-keep location.
 
* '''disable_move_leader_to_keep'''=no: (boolean) If set to 'yes', side leaders protected by this AI do not try to return to their keep.  This is necessary for this Micro AI to work with units that are side leaders and that are supposed to move to an off-keep location.
  
'''Note:''' The Protect Unit Micro AI modifies the [[AiWML#Filtering_Combat_with_the_.27attacks.27_Aspect|attacks aspect]].  Depending on the parameters, it might also modify the [[AiWML#Evaluating_AI_Moves_--_Candidate_Actions_.28CAs.29|move leader to keep candidate action]].
+
'''Notes:'''
 +
*The Protect Unit Micro AI modifies the [[AiWML#Filtering_Combat_with_the_attacks_Aspect|attacks aspect]].  Depending on the parameters, it might also modify the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|move leader to keep candidate action]].
 +
* The CA evaluation scores of this AI are hard-coded. It does not work otherwise.
  
Here's an example of [micro_ai] tag usage from the "HttT: The Elves Besieged" test scenario:
+
Here's an example of [micro_ai] tag usage from the "HttT: The Elves Besieged" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
            # Required keys of [micro_ai] tag
 
 
             side=1
 
             side=1
 
             ai_type=protect_unit
 
             ai_type=protect_unit
Line 505: Line 1,129:
 
         [/micro_ai]
 
         [/micro_ai]
  
== Recruiting Micro AI (ai_type=recruiting) ==
+
== Recruiting Micro AI==
 +
=== General Comments on the Recruiting Micro AIs ===
  
 
The Recruiting Micro AI replaces the default recruitment AI by alternative recruiting patterns.  Currently there are two recruiting algorithms you can choose from, random recruiting and the rush recruiting used in the new (as of Version 1.11.1) Experimental AI (see below).
 
The Recruiting Micro AI replaces the default recruitment AI by alternative recruiting patterns.  Currently there are two recruiting algorithms you can choose from, random recruiting and the rush recruiting used in the new (as of Version 1.11.1) Experimental AI (see below).
  
For a demonstration of a different recruiting pattern, check out the "Recruiting" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]] or in the ''AI Modification Demos'' add-on.  You can also explore the unit choices by watching the Experimental AI in a multiplayer game.
+
For a demonstration of a different recruiting pattern, check out the "Recruiting" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].  You can also explore the unit choices by watching the Experimental AI in a multiplayer game.
  
Enable the Recruiting Micro AI by putting
+
'''Note:''' Obviously, the Recruitment Micro AI modifies the [[RCA_AI#The_Candidate_Actions_.28CAs.29_of_the_main_loop_Stage_in_the_RCA_AI|recruitment candidate action]].
{MICRO_AI_RECRUITING}
 
into the [side] tag and configure it by using
 
ai_type=recruiting
 
in the [micro_ai] tag.
 
  
=== Random Recruitment AI (recruiting_type=random) ===
+
=== Random Recruitment AI (ai_type=recruit_random) ===
  
 
This AI randomly selects a unit type from the recruitment list of the side.  The probability of choosing each type and the behavior in low-gold situations can be influenced with optional parameters.
 
This AI randomly selects a unit type from the recruitment list of the side.  The probability of choosing each type and the behavior in low-gold situations can be influenced with optional parameters.
 +
 +
Enable the Random Recruiting Micro AI by using
 +
ai_type=recruit_random
 +
in the [micro_ai] tag.
  
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''recruiting_type''': Must be "random"
+
There are no required keys.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
 +
* '''ca_score'''=180000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 180,000.  This is identical to the default Recruiting CA which it replaces.
 
* '''[probability]''': This tag sets the probability of selecting the given unit type.  It has two required sub-keys:
 
* '''[probability]''': This tag sets the probability of selecting the given unit type.  It has two required sub-keys:
 
** '''type''': comma-separated list of unit types to which this probability is to be applied
 
** '''type''': comma-separated list of unit types to which this probability is to be applied
 
** '''probability''': (non-negative float)  The probability with which these unit types is to be selected.  All unit types for which no [probability] tag is defined receive a default probability of 1.0, thus values should be chosen relative to that.  As an example, in the code below swordsmen and peasants are given a probability of 8, while no other units have assigned probabilities.  Thus, each of these two unit types is 8 times more likely to be selected than any other individual unit type.
 
** '''probability''': (non-negative float)  The probability with which these unit types is to be selected.  All unit types for which no [probability] tag is defined receive a default probability of 1.0, thus values should be chosen relative to that.  As an example, in the code below swordsmen and peasants are given a probability of 8, while no other units have assigned probabilities.  Thus, each of these two unit types is 8 times more likely to be selected than any other individual unit type.
* '''skip_low_gold_recruit'''=no: (boolean)  By default, the random recruitment AI chooses a unit to recruit only from those types for which it has sufficient gold.  If this parameter is set to 'yes', it will instead choose from all available unit types and end recruiting for the turn if there is not enough gold to recruit it this turn (even if other, affordable unit types exist).
+
* '''skip_low_gold_recruiting'''=no: (boolean)  By default, the random recruitment AI chooses a unit to recruit only from those types for which it has sufficient gold.  If this parameter is set to 'yes', it will instead choose from all available unit types and end recruiting for the turn if there is not enough gold to recruit it this turn (even if other, affordable unit types exist).
 
 
Here's an example of a random recruiting [micro_ai] tag usage from the "Recruiting" test scenario:
 
  
 +
Here's an example of a random recruiting [micro_ai] tag usage from the "Recruiting" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:
 
         [micro_ai]
 
         [micro_ai]
 
             side=1
 
             side=1
             ai_type=recruiting
+
             ai_type=recruit_random
            recruiting_type=random
 
 
             action=add
 
             action=add
 
   
 
   
Line 548: Line 1,172:
 
         [/micro_ai]
 
         [/micro_ai]
  
=== Rush Recruitment AI (recruiting_type=rushers) ===
+
=== Rush Recruitment AI (ai_type=recruit_rushers) ===
  
This AI replaces the default recruiting with the rush recruiting used in the new (as of Version 1.11.1) Experimental AI.
+
This AI replaces the default recruiting with the recruiting used in the Experimental AI [[Experimental_AI#Recruitment|as described here]].
 +
 
 +
Enable the Rush Recruiting Micro AI by using
 +
ai_type=recruit_rushers
 +
in the [micro_ai] tag.
  
 
'''Required keys:'''
 
'''Required keys:'''
  
* '''recruiting_type''': Must be "rushers"
+
There are no required keys.
  
 
'''Optional keys:'''
 
'''Optional keys:'''
  
There are no optional keys.
+
* '''ca_score'''=180000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 180,000.  This is identical to the default Recruiting CA which it replaces.
 +
* {{DevFeature1.15|2}} '''high_level_fraction'''=0: (non-negative number) The approximate fraction of units of level 2 or higher to be recruited. This is defined as fraction of units on the map, not of new units being recruited during a turn or over several turns (which makes a difference if there are already units on the map). The effect is also cumulative per level (starting from level 2), meaning that 1/3 of L2 units will be recruited in the example above, 1/3*1/3=1/9 L3s etc. The default value is zero, which leaves the high-level unit recruiting to the default Experimental AI algorithm resulting usually in very few such units being recruited.
 +
* '''randomness'''=0.1: (number)  A random number is applied to the rusher recruit engine's score to prevent the recruitment pattern from being too predictable. 0 causes no randomness to be applied, while larger numbers increase the random effect. A value of 1-2 generates results in which the random effect is approximately equal to the scored effect. Extremely high values are essentially entirely random.
 +
* {{DevFeature1.17|6}} '''reset_cache_each_turn'''=no: (bool) Many of the operations of the rush recruitment evaluation are expensive and are therefore cached. For the most part, this cache can be kept from turn to turn, but in case there are events that change, for example, the map or the recruit list, this parameter can be set to 'yes' to force a reset of the cache each turn.
  
Rush recruiting is set up like this:
+
Here's an example of a rush recruiting [micro_ai] tag usage from the "Recruiting" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]]:  
 
         [micro_ai]
 
         [micro_ai]
 
             side=1
 
             side=1
             ai_type=recruiting
+
             ai_type=recruit_rushers
 +
            action=add
 +
          [/micro_ai]
 +
 
 +
== Simple Attack Micro AI (ai_type=simple_attack) ==
 +
 
 +
The Simple Attack Micro AI is meant as an addition to the default combat candidate action for when one wants to force the AI to do attacks that it would otherwise not do (for example on units that are 1 XP from leveling) or to execute certain attacks before all others (for example, attack with all "expendable" units first).  It is not set up to be a replacement for the default attacks.  Some notes:
 +
 
 +
* The algorithm is different from and simpler than that of the default combat CA.  For example, no attack combinations are considered, only individual attacks.  As a result, the [[AiWML#List_of_AI_Aspects|default aspects]] (aggression, caution, [avoid], ...) are not taken into account.  Also, if lots of units are involved, evaluation of this Micro AI is potentially quite a bit slower than of the default attacks.
 +
 
 +
* If an attack matching the Standard Unit Filters described below is found, this attack will always be executed, no matter how bad the odds are.  Thus, this Micro AI can be used to force the AI to do attacks it would otherwise avoid.
 +
 
 +
* Other than selecting the attacker/defender units, this AI is currently not configurable.  Let us know if you would like to see certain options to be added.  (No guarantees that we will add them, but we will definitely consider them.)
 +
 
 +
For a demonstration, check out the "Simple Attack" scenario from the [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
Enable the Simple Attack Micro AI by using
 +
ai_type=simple_attack
 +
in the [micro_ai] tag.
 +
 
 +
===Simple Attack specific keys for the [micro_ai] tag===
 +
 
 +
'''Required keys:'''
 +
 
 +
There are no required keys.  It is, however, in general not desirable to use this AI without at least one of the optional Standard Unit Filters below, as this AI is not meant as a replacement of the default combat candidate action.
 +
 
 +
'''Optional keys:'''
 +
 
 +
* '''ca_score'''=110000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI.  By default, it is set to 110,000, which means that it is executed right before the default combat candidate action.
 +
* '''[filter]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the units of the AI side participating in the Simple Attack action.  It defaults to all units of the side.  The filter automatically includes the side= key set to the AI side.
 +
* '''[filter_second]''': A [[StandardUnitFilter|Standard Unit Filter]] selecting the units the AI should attack.  It defaults to all enemy units.  The filter automatically includes a [[StandardSideFilter|Standard Side Filter]] set to all enemies of the AI side.
 +
* '''weapon'''=-1: (integer) The number of the weapon that should be used for this attack.  Weapon numbers start at 1 (not 0).  -1 stands for "best weapon" (by whatever criterion the AI chooses to use).  '''Available from Wesnoth 1.11.8'''
 +
 
 +
Below are 2 examples of Simple Attack Micro AI configurations from the "Simple Attack" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].  The first one shows how to force the AI to attack with all Soulless and Walking Corpse units first:
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=simple_attack
 
             action=add
 
             action=add
             recruiting_type=rushers
+
 +
             ca_score=110000
 +
            [filter]
 +
                type=Soulless,Walking Corpse
 +
            [/filter]
 
         [/micro_ai]
 
         [/micro_ai]
  
== Other Potential Micro AIs ==
+
The second example executes attacks by Soulless on all enemy units that are 1 XP from leveling.  Note that the Lua code in the preload event is there simply in order to code the "1 XP from advancing" condition.  It is not needed for most other SUFs, as can be seen in the previous example.
 +
    [event]
 +
        name=preload
 +
        first_time_only=no
 +
        [lua]
 +
            code=<<
 +
                function close_to_advancing(unit)
 +
                    if (unit.experience >= unit.max_experience-1) then
 +
                        return true
 +
                    else
 +
                        return false
 +
                    end
 +
                end
 +
            >>
 +
        [/lua]
 +
    [/event]
 +
 +
    [event]
 +
        name=prestart
 +
        [micro_ai]
 +
            side=2
 +
            ai_type=simple_attack
 +
            action=add
 +
 +
            ca_score=110001
 +
            [filter]
 +
                type=Soulless  # No Walking Corpses; L0 units don't advance enemy
 +
            [/filter]
 +
            [filter_second]
 +
                lua_function = "close_to_advancing"
 +
            [/filter_second]
 +
        [/micro_ai]
 +
    [/event]
 +
Several Simple Attack Micro AIs can be combined for the same AI side.  The two examples above are both used (note the different values for ca_score) in the "Simple Attack" [[Micro_AIs#Micro_AI_Test_and_Demo_Scenarios|test scenario]].
 +
 
 +
== Custom Micro AIs ==
 +
 
 +
{{DevFeature1.13|5}}
 +
 
 +
From 1.13.5 onwards, adding a new Micro AI can be easily done without altering any core files or overriding the micro_ai tag. The [micro_ai] tag now looks up its ''ai_type'' parameter in the <code>wesnoth.micro_ais</code> table and uses the micro AI setup function found there to determine which keys are required and allowed and what candidate actions to add.
 +
 
 +
A micro AI setup function takes as its single parameter the contents of the [micro_ai] tag and returns three separate values:
 +
*'''required''': A list of required keys and tags, as strings. Tags are indicated by enclosing them within square brackets in the string. If a key or tag in this list is missing from the [micro_ai] tag, an error will be printed. {{DevFeature1.17|6}} In order to enable better error handling, the syntax of this table has been changed. It is now of format <syntaxhighlight lang='lua' inline>{ param1 = 'param1_type', ... }</syntaxhighlight>. The supported parameter types can be found at the link to examples below.
 +
*'''optional''': Similar to above, a list of optional keys and tags, as strings. No error will be printed if a key or tag in this list is missing, nor will an error be printed if it is present (as would be the case for unrecognized keys or tags). {{DevFeature1.17|6}} The format of this table has been changed in the same way as for 'required'. Also, a warning message is now issued if the '[micro_ai]' tag contains a key or tag that is not listed in either 'required' or 'optional'.
 +
*'''ca_params''': A table specifying the candidate actions that constitute the micro AI. It should contain an ''ai_id'' key (which specifies a base ID to be used for candidate actions of this micro AI) and a series of candidate action definitions. Each candidate action definition is a table containing the following keys:
 +
**'''ca_id''': The ID used for the candidate action. This will be combined with the ''ai_id'' to produce the final ID.
 +
**'''location''': Path to the Lua file that defines the candidate action.
 +
**'''score''': The maximum score for the candidate action. If the [micro_ai] tag specified a ''ca_score'' parameter, the score here should normally be based on that.
 +
 
 +
(The return statement would thus look like <syntaxhighlight lang='lua' inline>return required, optional, ca_params</syntaxhighlight>.)
 +
 
 +
'''Examples''' of micro AI setup functions can be found in the [https://github.com/wesnoth/wesnoth/tree/1.14/data/ai/micro_ais/mai-defs default MAI definitions directory].  See the [https://github.com/wesnoth/wesnoth/blob/1.14/data/ai/micro_ais/mai-defs/animals.lua#L4-L12 Big Animals MAI definition] for a simple example.  For custom micro AIs, the setup code should be put into a ''[lua]'' tag inside a preload event.
 +
 
 +
Since the function has full access to the contents of the [micro_ai] tag, it can conditionally add candidate actions to '''ca_params''' depending on the values of other keys within the [micro_ai] tag. It can also perform other actions such as adding facets to an aspect; if it does such things, it should pay attention to the ''action'' key to determine whether it's being added or removed.
 +
 
 +
There are two useful helper functions that can be used by Micro AI setup functions requiring aspect changes. They can be brought into scope by a line similar to the following:
 +
<syntaxhighlight lang='lua>local MAIH = wesnoth.require("ai/micro_ais/micro_ai_helper.lua")</syntaxhighlight>
 +
* MAIH.add_aspects(side, aspect_params)
 +
* MAIH.delete_aspects(side, aspect_params)
  
The following Micro AIs might be added at some point. Feel free to add to this list, if you have other ideas.
+
The ''aspect_params'' parameter is an array of tables, each of which contains the following keys:
 +
*'''aspect''': The aspect to change.
 +
*'''facet''': The WML defining the facet. This must include an ''id'' key in order for the aspect to be correctly deleted. For maximum compatibility, incorporate the ''ca_id'' key from the [micro_ai] tag.
  
* Leader support
 
* Targeted enemy poisoning
 
* Protect unit/location/area
 
* Annoying AI (grab targets and avoid fights as much as possible)
 
* Orderly retreat
 
  
 +
'''See also:''' [[Wesnoth AI]]
 
[[Category:AI]]
 
[[Category:AI]]

Latest revision as of 17:35, 16 August 2023

Contents

A Few General Words about Micro AIs

  • Micro AIs allow Wesnoth campaign and scenario authors to add new AI functionality without the need for any AI programming. They bring new specialized behavior to Wesnoth that cannot be achieved, at least not easily, by adjusting default AI parameters (such as those described at AiWML) or with WML code.
  • A Micro AI is activated and configured (or deleted) via the [micro_ai] tag placed in an event, requiring only a few lines of WML code. (Version 1.15.? and later only) Starting in 1.16 the [micro_ai] tag may also be used in [side][ai] or [unit][ai]. These are both shorthands for placing it in the prestart event with "action=add", side set to the side, and in the case of [unit][ai], a [filter] tag set to limit the Micro AI to that one unit.
  • Before Wesnoth 1.13.6, the Micro AI behavior was inconsistent when it came to hidden enemies and petrified units. Some Micro AIs ignored those, while others did not. In some case there was even a potential for AI errors when an AI unit ran into hidden or petrified enemies. As of 1.13.6, this has all been fixed. The Micro AIs now correctly and consistently ignore hidden units and treat petrified units as blocking the hex they are on but having no effect otherwise, in the same way as the default AI does. Important notes:
    • It is not possible to re-include hidden/petrified units via the Standard Unit Filters (SUFs) used by some of the Micro AIs. In fact, if this is attempted, the filters will generally not match any unit.
      • This only applies to SUFs which go directly into the [micro_ai] tag. Any SUF that is a sub-tag of another filter (for example, of a Standard Location Filter) is taken literally and returns all units matching the filter. If hidden or petrified units are to be excluded from such a sub-filter, that needs to be specified directly in that filter.
    • We also note that, because all the Micro AIs are written in Lua, it is possible to move a Micro AI's code into one's add-on and modify it to whatever scenario-specific behavior is desired (this does not only apply to hidden/petrified units, but to all behavior). Setting up general Micro AI behavior that works in every possible setting is not feasible, but adapting it to work (only) in the specific setting of a given scenario is often quite simple. If you do not know how to do this, please post a message on the Wesnoth forums and we will be happy to help you with it.
  • The default AI aspects are, for the most part, not taken into account by the Micro AIs. For example, unless noted otherwise, specifying a value for aggression does not change the MAI behavior. The exception is the [avoid] tag which is taken into account by many Micro AIs (except those for which it would interfere with the Micro AI behavior or those that already use a a Standard Location Filter that can be used for the same purpose). This is a feature of the Micro AIs, not a bug. If you feel that a certain default AI aspect should also apply to a Micro AI, please let us know in the Micro AIs Feedback thread.
  • Before Wesnoth 1.13.7, the Micro AIs did not all work reliably when the AI side is under shroud and it may have been necessary to turn shroud off for the side when using a Micro AI. (Version 1.13.7 and later only) The Micro AIs now all work for sides under shroud. They do this by disregarding shroud for terrain purposes when path finding, consistent with default Wesnoth AI behavior, while still ignoring hidden units (including those hidden under shroud) correctly.
  • Most Micro AIs in their default setting apply to all units of a side, although many of them provide parameters for filtering the units that should be affected by the new behavior. If the Micro AI is applied only to part of the units of a side, the other units follow the default Wesnoth AI behavior.
  • Micro AIs are available in mainline since Wesnoth 1.11/1.12.

Micro AI Test and Demo Scenarios

All Micro AIs described here can be checked out in a number of test and demo scenarios. The easiest way to access the test scenarios is by assigning a hotkey to "Start Test Scenario" in the preferences (as of Wesnoth 1.13.8). Then, simply press the hotkey in the titlescreen and select the desired scenario from the list (e.g. 'micro_ai_test' for the overall "switchboard scenario").

Test scenarios can also be accessed from the command line by typing

path/wesnoth-executable -t micro_ai_test

or (depending on your system and Wesnoth version)

path/wesnoth-executable -tmicro_ai_test

This starts up a "switchboard scenario" in which you can select the Micro AI demonstration scenario you want to check out. Here, path/wesnoth-executable needs to be replaced by whatever the path and filename of the Wesnoth executable is on your system.

Setting up a Micro AI

Setting up a Micro AI requires only one simple step:

Activating and configuring (or deleting) a Micro AI

Micro AIs are activated, deleted and configured using the [micro_ai] tag. This tag needs to be placed in ActionWML, that is, in an event, a menu option or the like. As an example, the following code activates the healer_support Micro AI in its default configuration for Side 2 from the beginning of the scenario:

    [event]
        name=prestart

        # Configure the healer support micro AI
        [micro_ai]
            side=2
            ai_type=healer_support
            action=add
        [/micro_ai]
    [/event]

Keys required for all Micro AIs: All [micro_ai] tags must contain the following three required keys:

  • side: The side for which the Micro AI is to be added, changed or deleted. (Version 1.17.0 and later only) this can be a list of sides.
  • ai_type: The type of Micro AI to be added, changed or deleted. See the following sections for allowed values.
  • action (string): The action to take concerning the Micro AI. The following values are allowed:
    • add: Add a Micro AI to a side.
    • change: Change the configuration of an existing Micro AI. Note that this does not only change the specific parameters provided in the tag, but it replaces the entire existing Micro AI by a new version with the new (and only the new) configuration. It is therefore equivalent to using first the delete and then the add action.
    • delete: Delete an existing Micro AI from a side.

Keys required under certain circumstances:

  • ca_id: (string) If several MAIs of the same type are used for the same side and one or several of these are to be changed or deleted during a scenario, this key needs to be included so that the [micro_ai] tag knows which of them needs to be changed/deleted. The same is also true if a Micro AI is changed more than once during a scenario. We therefore strongly recommend always setting ca_id for MAIs which are, or might be, changed or deleted during a scenario.
    • Note: The id(s)/name(s) actually assigned to the CA(s) of the MAI by the engine might be different from the parameter passed here. It is, however, sufficient to use this ca_id with the [micro_ai] tag add/delete/change actions to identify the MAI uniquely. (In other words: you don't have to worry about this if you always use the [micro_ai] tag, but might have to figure out the actual name(s) of the CA(s) if you want to delete or change them manually.)
  • Other keys may also be required depending on the Micro AI. In additional, a number of optional keys may be available to configure the AI behavior. See the sections on the individual Micro AIs for details.

Required keys for deleting a Micro AI:

Only a subset of the keys required for setting up a Micro AI are needed when deleting it. side, ai_type and action=delete always need to be provided. ca_id needs to be given if it was provided when adding the Micro AI (see above for when this is needed).

Notes:

  • The add and change actions ignore all keys that do not apply to the respective Micro AI type. The delete action ignores all keys other than the required keys listed above.
  • Some of the Micro AIs use and/or modify default AI components (candidate actions or aspects) when they are added, or reset these components to their default values when they are deleted. Thus, if you have modified the AI yourself using the default CAs or aspects, some of these modifications might be affected, or might be interfering with the Micro AI. The sections below indicate whether a Micro AI modifies any default AI components.

Combining Different Micro AI Types for the Same Side

No extra steps need to be taken when combining different Micro AIs on the same side. Simply set up the [micro_ai] tags for all AIs you want to use.

Notes:

  • While it is technically possible to combine any number of Micro AIs, this does not mean that all Micro AIs work together in practice. Some are not compatible because they control units in contradictory ways.
  • Not all combinations that should work have been tested yet. If you find a combination that you believe should work but doesn't, please let us know and we will see if that can be fixed.
  • The candidate action score almost certainly has to be set (using the ca_score= key) for one or several of the MAIs if several of them are used on the same side.

Animals Micro AIs

General Comments on the Animal Micro AIs

The Animals Micro AIs are meant to simulate the behaviors of certain types of animals. They are, however, set up so that they can be used with arbitrary unit types and might be applicable in quite diverse situations. The AIs nevertheless remain named after the animals for which they were written originally, so that they are (to some extent) descriptive of their behavior.

Brief descriptions of the AI behaviors are given in the following subsections. To get a better feeling for their behavior, check out the "Animals", "Swarm", "Wolves" and "Dragon" scenarios from the test scenario. Note that some of the animal AIs are designed for animal types that do not exist in mainline. In the test scenario, other animal types are therefore substituted for them.

Animals AI: Wolves (ai_type=wolves)

The Wolves Micro AI organizes all "wolf" units (predators) of the side to hunt in a single pack. They actively chase after the closest prey and try to corner it (not always super successfully), but are easily distracted by other enemy units coming into attack range, to the point where the pack might split up. The wolves can, however, be told to attack only prey units as well as to try to avoid other types of units (such as larger predators). When no prey is left, the wolves wander randomly.

This AI works best for a small number of predators (2 - 5) and sparse prey. Also, the predators should be put on the map in a pack, that is, reasonably close to each other. For a demonstration of the Wolves AI behavior, check out the "Animals" scenario from the test scenario.

Note that another wolves AI exists, called Multipack Wolves, which distributes the wolves of a side into several packs, rather than all of them into one single pack as it is done here.

Enable the Wolves Micro AI by using

ai_type=wolves

in the [micro_ai] tag together with the following keys:

Required keys:

Optional keys:

  • attack_only_prey=no: In the default configuration, the wolves attack all enemy units in attack range. If this key is set to 'yes', they only attack prey units.
  • avoid_type: Comma-separated list of unit types (on enemy sides) which the wolves try to avoid. They try to stay out of these units' way as much as possible when moving around (except when they are moving in to attack another enemy unit) and never attack them.
  • ca_score=90000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 90,000, which is lower than the default combat CA, but higher than most other default CAs which move units. It can be changed by setting this parameter but in most cases this will not make sense. Note that the Wolves AI consists of 2 CAs with scores ranging from ca_score-1 to ca_score.

Notes on default (RCA) AI aspects:

  • If attack_only_prey or avoid_type are set, the Wolves Micro AI modifies the attacks aspect.
  • Attacks by the wolves are left to the default (RCA) AI, meaning that the value of aggression has an influence on the behavior.
  • [avoid]: The standard RCA AI aspect used to define locations that should be avoided by the AI is taken into account. Note: as attacks by the wolves are left to the default AI, there is no separate [avoid] tag for this Micro AI in order to prevent inconsistencies.

Here's an example of a wolves [micro_ai] tag usage from the "Animals" test scenario:

        [micro_ai]
            side=6
            ai_type=wolves
            action=add

            [filter]
                type=Wolf
            [/filter]
            [filter_second]
                type=Vampire Bat
            [/filter_second]
            avoid_type=Yeti,Giant Spider,Ghast,Footpad
        [/micro_ai]

Animals AI: Multi-pack Wolves (ai_type=wolves_multipacks)

The Multi-pack Wolves Micro AI is different from the Wolves Micro AI in that there can be an arbitrary number of wolf packs, with the pack size being a free parameter. At the beginning of the scenario, close wolves are grouped into packs in a semi-methodical way. If the wolves are put on the map in distinct groups of close wolves of the correct number, they will be joined into packs matching these groups. If, on the other hand, they are spread out all over the map, the method of assigning them to packs is semi-random.

Wolves of the same pack begin by joining each other on the map. After that, they stay together until only one wolf is left, which then tries to join up with an incomplete pack or with other single wolves. Individual wolves entering the map during the scenario behave in that way as well.

A second difference to the other Wolves AI is that wolves do not actively hunt here. For the most part they just wander (often long distance). However, the pack ferociously (and without regard for its own health) attacks any enemy units that come into range, as long as that does not mean separating the pack by more than a few hexes. Staying together, or joining with a new wolf assigned to the pack, is the only thing that takes priority over satisfying the wolves' thirst for blood.

For a demonstration of the Multi-pack Wolves AI behavior, check out the "Wolves" scenario from the test scenario.

Enable the Multi-pack Wolves Micro AI by using

ai_type=wolves_multipacks

in the [micro_ai] tag together with the following keys:

Required keys:

There are no required keys

Optional keys:

  • [avoid]: (Version 1.15.0 and later only) A Standard Location Filter for the locations which the AI units should avoid. If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs. Note that the Multi-pack Wolves AI consists of 2 CAs with scores ranging from ca_score-1 to ca_score.
  • pack_size=3: (integer) The size of the packs.
  • show_pack_number=no: If set to "yes", the wolves' pack numbers will be shown below them. Note that this means that the pack number of a wolf killed in an attack will remain as a label on the map. This behavior is intentional to help UMC authors note where units might have made suicidal mistakes.
  • type=Wolf: Comma-separated list of the unit types which the AI controls. The default value is "Wolf".

Standard RCA AI aspects respected by this Micro AI:

  • [avoid]: (Version 1.15.0 and later only) The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.

Here's an example of a wolves_multipacks [micro_ai] tag usage from the "Wolves" test scenario:

        [micro_ai]
            side=2
            ai_type=wolves_multipacks
            action=add

            show_pack_number=yes
            pack_size=4
        [/micro_ai]

Animals AI: Big Animals (ai_type=big_animals)

The Big Animals Micro AI is a simulation of large predators that wander and hunt alone, such as Bears, Giant Spiders or Yetis. For the most part, these just wander on the terrain that's been defined for them, but they attack enemy units if those happen to come into range. The AI can be set up so that the Big Animals stay out of the way of other units (such as other large predators), in which case they only attack those if cornered or if they run into them accidentally (such as ambushers).

For a demonstration of the Big Animals AI behavior, check out the "Animals" scenario from the test scenario.

Enable the Big Animals Micro AI by using

ai_type=big_animals

in the [micro_ai] tag together with the following keys:

Required keys:

  • [filter]: A Standard Unit Filter selecting the animals to which this AI is applied. The filter automatically includes the side= key set to the AI side.

Optional keys:

  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • [filter_location]: The big animals often go for long distance (multi-turn) journeys. This tag is a Standard Location Filter describing the terrain from which the next goal is chosen. The default is all terrain on the map.
  • [filter_location_wander]: The terrain on which the big animals will end their moves. This is a Standard Location Filter. The default is all terrain on the map.
  • [avoid_unit]: A Standard Unit Filter describing all enemy units that the big animals will avoid. The filter automatically includes a Standard Side Filter set to all enemies of the AI side.

Here's an example of big_animals [micro_ai] tag usage from the "Animals" test scenario:

        [micro_ai]
            side=3
            ai_type=big_animals
            action=add

            [filter]
                type=Ghast
            [/filter]
            [avoid_unit]
                type=Yeti,Giant Spider,Ghast,Footpad
            [/avoid_unit]
            [filter_location]
                x,y=1-40,1-18
            [/filter_location]
        [/micro_ai]

Animals AI: Forest Animals (ai_type=forest_animals)

The Forest Animals Micro AI simulates a number of different animal behaviors that one might find in a forest, namely animals behaving like deer, rabbits and families of tuskers. In the following, we will refer to those animals by these types, even though the actual unit types can be selected freely. They behave as follows:

  • Each deer wanders randomly on (selectable) terrain, except when enemies get in its (the deer's) maximum movement range, in which case it flees to the farthest point it can reach.
  • Tuskers exhibit the same behavior as deer, except when an enemy is next to one of the tusklets. This enemy is attacked unconditionally by the tuskers trying to protect their young.
  • Tusklets blindly follow the closest adult tusker, except when there is no tusker left, in which case they behave the same as deer.
  • Rabbits also wander randomly, but in addition disappear into their holes (if any are within reach) when enemies are close. They reappear out of their holes at the beginning of the turn, if it is safe.

For a demonstration of the Forest Animals AI behavior, check out the "Animals" scenario from the test scenario.

Enable the Forest Animals Micro AI by using

ai_type=forest_animals

in the [micro_ai] tag together with the following keys:

Required keys:

There are no required keys

Optional keys:

  • ca_score=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs. Note that the Forest Animals AI consists of 4 CAs with scores ranging from ca_score-3 to ca_score.
  • rabbit_type, tusker_type, tusklet_type, deer_type: Comma-separated lists of the unit types behaving as the respective animals. If any of these parameters are not set, those types of animal behavior are skipped by the AI.
  • [filter_location]: A Standard Location Filter describing the terrain on which the forest animals wander when they are not threatened by enemies.
  • rabbit_number=6: (integer) The number of rabbits for the AI to have on the map simultaneously. The AI puts the missing number of rabbits onto the map at the beginning of the AI's turn (when the rabbits come out of their holes).
  • rabbit_enemy_distance=3: (number) Rabbits won't spawn in holes that aren't more than this distance away from all enemies.
  • rabbit_hole_img: Rabbit holes are marked by items on the map. If this parameter is set, it must be the file name of the item image. If it is not set, all items on the map are treated as rabbit holes.
    • (Version 1.14.10 and later only) Items used for rabbit holes on the map border used to produce an error. Placing them on the map border therefore needed to be avoided on the scenario setup side. They are now automatically excluded from consideration by the AI code.

Here's an example of forest_animals [micro_ai] tag usage from the "Animals" test scenario:

        [micro_ai]
            side=2
            ai_type=forest_animals
            action=add

            deer_type=Vampire Bat
            rabbit_type=Giant Rat
            tusker_type=Ogre
            tusklet_type=Young Ogre
            [filter_location]
                terrain=*^F*
            [/filter_location]
        [/micro_ai]

Animals AI: Herd and Herders (ai_type=herding)

The Herding Micro AI sets up an area on the map where a number of herder units (such as sheep dog) control and protect a herd (such as sheep). For convenience, we simply refer to them as sheep dogs and sheep in the following, even though arbitrary unit types can be selected for either.

Sheep dogs try to keep their sheep safe. This involves keeping them inside the herding area, positioning themselves in between the sheep and approaching enemies, and attacking the enemies if those get too close. If no active herding or protecting move is needed, the dogs go to a random location on the perimeter of the herding area.

Sheep wander aimlessly except when a sheep dog is next to them, in which case they run away from the dog. The dogs exploit this by positioning themselves on the outside of the sheep, if possible. Sheep also run away from approaching enemies.

For a demonstration of the Herding AI behavior, check out the "Animals" scenario from the test scenario.

Enable the Herding Micro AI by using

ai_type=herding

in the [micro_ai] tag together with the following keys:

Required keys:

  • [filter]: A Standard Unit Filter describing the herder units (e.g. dogs). The filter automatically includes the side= key set to the AI side.
  • [filter_second]: A Standard Unit Filter describing the herd units (e.g. sheep). The filter automatically includes the side= key set to the AI side.
  • [filter_location]: A Standard Location Filter describing the terrain forming the perimeter of the herding area. In other words, this is the path the herders (dogs) use to patrol around the outside of the herding area. This must be a set of coordinates completely enclosing the herding area. Here's an example of setting up a rectangular perimeter:
    [filter_location]
        x=10-20,10-20,10,  ,20
        y=11,   21,   11-21,11-21
    [/filter_location]

Another possibility is by defining the path by certain terrain on the map (as it is done in the "Animals" test scenario), in which case the filter can simply look like this:

    [filter_location]
        terrain=Rb
    [/filter_location]
  • herd_x,herd_y: The coordinate of one hex (any one hex) inside the herding area. This is needed to define which part of the map is on the inside of the herding area perimeter defined by [herding_perimeter], and which is the outside. (Version 1.15.0 and later only) herd_loc can be used instead with a named/special location.

Optional keys:

  • attention_distance=8: (integer) If an enemy is within this distance of a herd unit, but not as close as attack_distance, the herders try to position themselves in between the enemy and the herd unit.
  • attack_distance=4: (integer) If an enemy is within this distance of a herd animal, the herders attack this enemy.
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs. Note that the Herding AI consists of 6 CAs with scores ranging from ca_score-5 to ca_score.

Here's an example of a Herding [micro_ai] tag usage from the "Animals" test scenario:

        [micro_ai]
            side=7
            ai_type=herding
            action=add

            [filter]
                type=Footpad
            [/filter]
            [filter_second]
                type=Troll Whelp
            [/filter_second]
            herd_x,herd_y=32,28
            [filter_location]
                terrain=Rb
            [/filter_location]
        [/micro_ai]

Animals AI: Hunter (ai_type=hunter)

The Hunter Micro AI leads a unit (or units) through hunt-and-rest cycles. The units wander in a prescribed area of the map, their hunting ground, until an enemy unit comes within range. Note that the units do not actively chase down enemies, but wander randomly through the hunting ground until an enemy is encountered.

If enemies are within range of a hunter unit, the hunter attacks the weakest of them. If a kill is made, it then retreats to its rest location, where it stays for a certain number of turns and until fully healed (whatever happens later).

A few more details:

  • If the hunter's way home is entirely blocked on the return (so that there is no possible path), the normal RCA AI takes over its behavior.
  • However, if the way is blocked by an enemy unit occupying the rest hex, that enemy will be attacked unconditionally.
  • A kill only makes the hunter go home when it is the attacker, not as defender.

For a demonstration of the Hunter AI behavior, check out the "Dragon" scenario from the test scenario.

Enable the Hunter Micro AI by using

ai_type=hunter

in the [micro_ai] tag together with the following keys:

Required keys:

  • id or [filter]: The ID of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
    • If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
  • home_x,home_y: The coordinates of the hex to which the hunter returns and rests at after a kill. (Version 1.15.0 and later only) home_loc can be used instead with a named/special location.

Optional keys:

  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • [filter_location]: A Standard Location Filter describing the unit's hunting ground. If this tag is not provided, the hunter uses all of the map.
  • rest_turns=3: (integer) The number of turns the AI stays at home_x,home_y after a kill. It will not leave its home until this number of turns have passed and it is fully healed.
  • show_messages=no: (boolean) If set to yes, the hunter announces whenever its behavior changes to the next phase. Note that this is meant as debug output for the scenario author. The messages are not translated and are not included in replays (and are only visible to the host in an MP game).

Here's an example of a hunter [micro_ai] tag usage from the "Dragon" test scenario:

        [micro_ai]
            side=1
            ai_type=hunter
            action=add
            [filter] 
                id=Rowck
            [/filter]
            [filter_location]
                x,y=5-30,1-15
            [/filter_location]
            home_x,home_y=3,15
            rest_turns=2

            show_messages=yes
        [/micro_ai]

Animals AI: Swarm (ai_type=swarm)

The Swarm Micro AI uses some very simply algorithms to simulate animal swarm behavior. Without adjacent enemies, they simply do a random move, trying to stay together and at a certain distance from enemies. However, if an enemy unit is close to any bat, the swarm scatters. This is particular fun to watch when one places an enemy unit in the middle of the swarm. After being scattered, the swarm members slowly rejoin, but not in a very organized way. Sub-swarms or individual bats might roam around for quite some time before they find their way back. It is also possible that individual bats (or small groups) split off from the larger swarm at times.

For a demonstration of the Swarm AI behavior, check out the "Swarm" scenario from the test scenario.

Enable the Swarm Micro AI by using

ai_type=swarm

in the [micro_ai] tag together with the following keys:

Required keys:

There are no required keys

Optional keys:

  • [avoid]: (Version 1.15.0 and later only) A Standard Location Filter for the locations which the AI units should avoid. If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs. Note that the Swarm AI consists of 2 CAs with scores ranging from ca_score-1 to ca_score.
  • enemy_distance=5: (int) The minimum distance kept between units of the swarm and enemies when the swarm moves as a whole.
  • [filter]: (Version 1.15.12 and later only) A Standard Unit Filter selecting the units. Only AI units matching this filter participate in the swarm. The filter automatically includes the side= key set to the AI side.
  • scatter_distance=3: (int) Enemies within "scatter_distance" hexes of any swarm unit cause the swarm to scatter, by each unit trying to maximize its individual distance from the enemy.
  • vision_distance=12: (int) Only units within this distance follow the overall swarm motion (either away from an enemy or of the swarm as a whole). The smaller this value is set, the less likely the swarm is to stay together or rejoin. This parameter is meant to simulate how far an individual member of the swarm can see, meaning that the swarm is "out of sight" (and the unit will not be able to follow it) if it is more than this distance away.

Standard RCA AI aspects respected by this Micro AI:

  • [avoid]: (Version 1.15.0 and later only) The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.

Here's an example of a Swarm [micro_ai] tag usage from the "Swarm" test scenario:

        [micro_ai]
            side=2
            ai_type=swarm
            action=add
        [/micro_ai]

Assassin Squad Micro AI (ai_type=assassin)

(Version 1.13.6 and later only)

This Micro AI controls one or several assassin units which try to circle around enemy units with the goal of hitting a target unit without being distracted or impeded by other enemies. The units will always attack the target if such attacks are possible, otherwise they will follow the path of least resistance toward it. Notes:

  • The main priority for the AI is to find paths that avoid enemy units. However, if no such path can be found, the assassins will still advance toward the target, taking the path exposing the units to the least potential damage from enemies.
  • The units will not necessarily follow the same path. The best path is chosen individually for each unit.
  • While it is not a requirement for the AI to work, using ambusher or skirmisher units, or units with the quick trait, makes this AI more lethal in many cases.
  • The CA evaluation scores of this AI are hard-coded, it does not work otherwise. That means that ca_score is not a valid key for the [micro_ai] tag.

Enable the Assassin Squad Micro AI by using

ai_type=assassin

in the [micro_ai] tag.

Assassin Squad specific keys for the [micro_ai] tag:

Required keys:

  • [filter]: A Standard Unit Filter defining the assassin units. The filter automatically includes the side= key set to the AI side.
  • [filter_second]: A Standard Unit Filter defining the target unit.
    • It is important to realize that the AI currently only works correctly with a single target unit. It is thus the responsibility of the scenario designer to make sure that this filter matches an individual enemy unit. If several enemy units are to be targeted in the same scenario, several instances of the Assassin Micro AI can be used.
    • The filter automatically includes a Standard Side Filter set to all enemies of the AI side.

Optional keys:

  • [prefer]: A Standard Location Filter selecting locations on the map for the assassins to prefer when making their way toward the target unit. This could be used, for example, to make units with the ambush ability move (mostly) through forest or to have the assassins circle around the, say, northern part of the map rather than the south if that is desirable for scenario design purposes.
    • As with avoiding enemies, the units will still move across non-preferred terrain if that is either the only option or much shorter than preferred terrain
    • Attacking, once the target unit is in range, is not influenced by the [prefer] SLF.

Here is an example of an Assassin Squad [micro_ai] tag usage:

        [micro_ai]
            side=2
            ai_type=assassin
            action=add

            [filter]
                type=Assassin,Master at Arms,Duelist
            [/filter]
            [filter_second]
                id=Konrad
            [/filter_second]
            [prefer] # Circle around northern part of map
                x=1-9, 10-99
                y=1-37, 1-17
            [/prefer]
        [/micro_ai]

Bottleneck Defense Micro AI (ai_type=bottleneck_defense)

The Bottleneck Defense Micro AI lets you define a location on the map where the AI can take a defensive stance behind a narrow passage (bottleneck). Units on the front line are backed up by healers and/or units with the leadership ability. Injured units are moved to the back and replaced by uninjured (or less injured) units. The units on the front line only attack when it is safe (no retaliation) or when there is a high chance that they will make a kill or level up. Using this Micro AI only makes sense if there is no way for the enemy sides to move around the bottleneck and attack the AI's units from behind.

For a demonstration, check out the "Bottleneck" scenario from the test scenario.

Enable the Bottleneck Defense Micro AI by using

ai_type=bottleneck_defense

in the [micro_ai] tag.

Bottleneck Defense specific keys for the [micro_ai] tag:

Required keys:

The Bottleneck Defense AI requires two sets of coordinates that define where it should be taking up its defensive stance, and from which side the enemy attacks at that location.

  • x,y: Comma separated lists of the hexes on the front line, where strong units are placed. All hexes on which the AI makes contact with (can be attacked by) the enemy need to be included here. Units are placed on them in the order in which they are listed here. (Version 1.15.0 and later only) location_id can be used instead with named/special locations.
  • enemy_x,enemy_y: Comma separated list of the hexes from which the enemy can attack the AI front line units. This is needed for the AI to know on which side of the front line support units (healers etc.) need to be placed. In many cases, it is sufficient to provide only one of the enemy front line hexes, but there are geometries for which that does not work. It is therefore safer to list all enemy front line hexes here. (Version 1.15.0 and later only) enemy_loc can be used instead with named/special locations.

Optional keys:

By default, the AI places healers and units with the leadership ability both on the front line itself (if they are the strongest units available) and on hexes adjacent to and behind the line. If different placement is desired, these locations can be overridden with the following keys.

  • active_side_leader=no: (boolean) If set to 'yes', the side leader participates in the bottleneck defense action after the side's gold has been spent. If set to 'no' (default), the leader follows default AI behavior (sitting on the keep and recruiting, for the most part).
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs. Note that the Bottleneck Defense AI consists of 2 CAs with scores ranging from ca_score-1 to ca_score.
  • [filter]: (Version 1.15.3 and later only) A Standard Unit Filter selecting the units. Only AI units matching this filter participate in the bottleneck defense. The filter automatically includes the side= key set to the AI side.
  • healer_x,healer_y: Comma separated list of hexes where healers are placed. This can be used to keep healers from the front line (or to take up only certain positions on the front line), and/or to override the default healing positions behind the line. Healers are placed on them in the order in which the hexes are listed, with the exception that hexes on the line always take priority over hexes behind the line. (Version 1.15.0 and later only) healer_loc can be used instead with named/special locations.
  • leadership_x,leadership_y: Same as healer_x,healer_y, but for units with the leadership ability. (Version 1.15.0 and later only) leadership_loc can be used instead with named/special locations.

As an example, in the "Bottleneck" test scenario, there are three front line hexes, two of which are on hill terrain, while the third is a road with a lower defense rating. The healer and side leader are supposed to participate in combat because they are strong units, but only from the hill hexes to keep them safer. This is accomplished by using the following keys settings (check out the scenario to see which hex is which):

[micro_ai]
    side=1
    ai_type=bottleneck_defense
    action=add

    x=14,14,14
    y= 7, 9, 8
    enemy_x=13,13
    enemy_y= 8, 9

    healer_x=14,14,15,15
    healer_y= 7, 9, 8, 9
    leadership_x=14,14,15,15
    leadership_y= 7, 9, 9 ,8
    active_side_leader=yes
[/micro_ai]

Fast Micro AI (ai_type=fast_ai)

(Version 1.13.0 and later only)

This AI is meant as a fall-back AI for scenarios where there are so many units that attacks and moves done by the default AI are slow with long delays before each move. It replaces the default castle-switch, retreat-injured, spread-poison, high-xp-attack, combat, place-healers, move-to-targets, villages and retreat candidate actions (CAs). It should be obvious that in order to achieve the faster speed, compromises concerning the quality of the moves have to be made.

Enable the Fast Micro AI by using

ai_type=fast_ai

in the [micro_ai] tag.

Combat candidate action:

  • Attackers are considered individually one at a time. The best attack found for a unit is executed without checking whether a better attack by another unit might be possible.
  • The default order in which attackers are considered is by decreasing hitpoints, starting with the strongest unit (in terms of HP). This can be modified with the optional keys below.
  • By default, if weaker units block attack hexes for a stronger unit, they do not move out of the way (this is the same as for the default AI). If a hex becomes available after an attack (e.g. due to a weaker unit dying in the attack), all attacks that were possible before this happened are finished first. Only after that are attacks by the stronger unit reconsidered.
  • If include_occupied_attack_hexes=yes is set, weaker units move out of the way for stronger units if possible. This can, however slow down the AI depending on the situation on the map. Use with caution.
  • (Version 1.13.2 and later only) Previous to this version, attacks by the leader were bunched in with the attacks by the other units. Now leader attacks are treated separately and contain an extra layer of analysis to determine whether the attack position is "safe" (in an approximate way). Currently, this is done with two simple considerations:
    • Count all enemy units that can reach the leader's attack position. If there are more than given by optional parameter 'leader_attack_max_units' (default value 3), do not attack.
    • Add up the hitpoints of all enemies that can reach the leader's attack position. If this value, multiplied by optional parameter 'leader_weight'(default value 2), is larger than the leaders hitpoints, do not attack.
    • Two optional parameters, 'threatened_leader_fights' and 'leader_additional_threat', can also be used to let the leader attack when the threat at the attack hex is comparable to that at the leader's current position.
    • In order to keep this AI as fast as possible, leader attacks are done by a separate candidate action that is only evaluated when all other CAs are done.

Move-to-targets, villages and retreat candidate actions:

  • The move-to-targets, villages and retreat candidate actions of the default AI are removed. Move-to-targets and villages are taken over by the Fast Micro AI, whereas retreat is simply not done.
  • This CA moves units toward goals after attacks are done. Goals are unowned (if the AI side has a leader only) and enemy-owned villages and enemy leaders.
  • For each goal, units are pre-sorted in order of the fewest moves needed to cover the distance toward the goal (that is, as if move cost on each hex toward the goal were 1). Units are then considered sequentially and if a unit can get there "efficiently", its move is executed without considering other units.
    • A move is considered efficient if the move cost to get to the hex is not more than 'move_cost_factor' larger than the distance to the hex. 'move_cost_factor' is an optional key that defaults to 2. It can be set to values of 1.1 or larger (see below).
    • If the move for the current unit is not found to be efficient, the AI considers the next unit instead. If no unit can do an efficient move toward the goal, the best (fastest) of the inefficient moves is selected instead.
  • Village goals:
    • Village goals are considered before enemy leader goals so that the AI preferentially chooses scouts (or otherwise fast units) for them.
    • The number of units sent toward villages depends on the value of the default AI aspect village_value. It is set to village_value/4 times the number of units the AI has left to move. Thus, by default (village_value=1.0) the AI sends a quarter of its units toward villages, and the rest toward enemy leaders. This means that the meaningful range of values for village_value is 0..4.
    • Only one unit is moved toward each village. This consideration also overrides the number of units to move toward villages defined by village_value, topping it at the number of unowned/enemy-owned villages on the map.
    • Setting village_value=0 disables moving units toward villages altogether. That is, not only are no units chosen, but the village targeting phase of the AI is entirely disabled with no evaluation time used for it. Note that, unlike with the default AI, this also means that no villages within range of an AI unit are grabbed.
    • The order in which villages are chosen as goals is some combination of them being close to the AI side's leader and being spread out over the map.
  • Enemy leader goals:
    • The order of enemy leaders goals is set according to their distance from the AI leader with the closest enemy leader being targeted first (if the AI has a leader, otherwise their order is random). One unit is sent toward each enemy leader in this order, after which the AI starts with the first enemy leader again. This is repeated until all units have moved.
  • Guardians (units with ai_special=guardian set) are ignored by the fast move-to-targets CA.

Tips for speeding up/modifying the Fast Micro AI in specific scenarios:

A number of optional keys and default AI aspects can be used to modify the behavior of the Fast Micro AI. The MAI is set up so that it is a reasonable compromise between speed and quality of the moves in most situations. However, this might not be ideal for all scenarios here are some things that can be done to speed up the AI (or to get better behavior in some situations by doing the opposite):

  • Use large values for the default AI aspect aggression. The largest delays before attacks happen (in some circumstances) when the Fast MAI has to consider lots of units with attacks left but decides not to attack with them. See below for a description of how aggression is used by the fast AI.
  • Use large values of move_cost_factor (see above for description of what this does). If you want to emphasize units that can move across terrain easily (e.g. bats) to be chosen for village grabbing, you might want to use low values of move_cost_factor, but this might slow down the AI. The default value should work reasonably well in most standard situations, but modifying the value might work better on specific maps.
  • Don't use dungeon_mode=yes unless absolutely necessary, even in most dungeon crawls. Test the AI without this setting first and only use it if it is the only way to solve the problem. Often, a minor tweak to the map will have the same effect, without the speed penalty.
  • Use include_occupied_attack_hexes=yes with caution. It might (or might not) slow down the attack CA significantly, depending on the scenario.
  • Set village_value=0, which makes the AI not consider villages as goals. This has not been found to make a large difference on the maps tested so far, but it might have an effect on maps with a very large number of villages.
  • Use attack_hidden_enemies=yes on maps where there are no hidden enemies. Excluding hidden enemies from the attack calculation requires an additional filter to be evaluated that takes extra time. In most cases this will not result in a large computation time saving.

Required keys:

There are no required keys.

Optional keys:

  • attack_hidden_enemies=no: (boolean) By default, hidden enemies are excluded from the attack calculation. Setting this to 'yes' makes the AI also consider those enemies as attack targets.
  • [avoid]: (Version 1.13.2 and later only) A Standard Location Filter for the terrain which the AI units should avoid. If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists). As with the default AI, units will not step on hexes defined by the [avoid] tag. In addition, no goals will be chosen that lie on those hexes. The one minor exception is that a unit stepping out of the way for another unit might temporarily enter the avoided zone.
  • dungeon_mode=no: (boolean) As much as possible, the Fast Micro AI works with distances between hexes rather than path finding. This works pretty well on open maps and even most dungeon crawls (and similar scenarios), but it might result in some units getting temporarily (and in rare cases permanently) stuck on maps with convoluted labyrinths. If that is the case, setting dungeon_mode=yes triggers more path finding that avoids such situations (but as a result is somewhat slower).
  • include_occupied_attack_hexes=no: (boolean) If set to 'yes', the AI moves weaker units out of the way for a stronger attacker. This might lead to better attacks but is slower, so don't use if speed is essential.
  • [filter]: (Version 1.13.2 and later only) A Standard Unit Filter selecting the attackers. Only AI units matching this filter will attack, analog to filtering units using [filter_own] with the attacks aspect for the default AI. The filter automatically includes the side= key set to the AI side. It does not affect the move-to-targets CA.
  • [filter_second]: (Version 1.13.2 and later only) A Standard Unit Filter selecting the enemies. Only enemy units matching this filter will be attacked, analog to filtering units using [filter_own] with the attacks aspect for the default AI. The filter automatically includes a Standard Side Filter set to all enemies of the AI side. It does not affect the move-to-targets CA.
  • leader_weight=2: (number >= 0) (Version 1.13.2 and later only) A factor specifying how much more valuable the AI considers side leaders than non-leader units in the attack evaluation. This is also used to determine whether an attack by the leader is safe (see description of the combat candidate action above).
  • leader_additional_threat=1: (number > 0) (Version 1.13.2 and later only) If threatened_leader_fights=yes, the threat at the attack position may be larger by this factor for the leader to leave the keep for an attack.
  • leader_attack_max_units=3: (number >= 0) (Version 1.13.2 and later only) A number specifying how many enemy units within reach are acceptable when determining whether an attack by the leader is safe (see description of the combat candidate action above).
  • move_cost_factor=2: (number >= 1.1) The factor by which the move cost to a goal hex may be larger than the distance to the goal hex for a move to be considered "efficient". See description above. 1.1 is used if this is set to values smaller than 1.1. Smaller values might lead to better behavior, while larger values might speed up the AI.
  • weak_units_first=no: (boolean) If set to 'yes', inverts the order in which units are considered by the combat CA. Attacks are then done in order of increasing hitpoints of the attackers.
  • skip_combat_ca=no: (boolean) If set to 'yes', the fast combat CA is not used. The default AI's high_xp_attack and combat CAs remains in place in this case.
  • skip_move_ca=no: (boolean) If set to 'yes', the fast move-to-targets CA is not used. The default AI's retreat, villages and move-to-targets CAs remains in place in this case.
  • threatened_leader_fights=no: (boolean) (Version 1.13.2 and later only) By default, the AI leader will not attack if the threat at the attack position is too high. If this key is set to 'yes', the leader will attack if the threat there is not larger than the threat at his current position multiplied by the value of 'leader_additional_threat'. This is meant as an option for the endgame: when the AI leader is under attack, he might as well go down fighting.

Standard RCA AI aspects respected by this Micro AI:

  • aggression: The default RCA AI aspect used to set how aggressive the AI should attack. It works in roughly the same way as the default AI aspect:
    • The value of (1 - aggression) determines how much the AI values its own units compared to the enemy's units. Thus, aggression=0 means that attacks are only done if the AI expects to deal (roughly) the same amount of damage as it will receive. aggression=1 means that expected damage to the AI's units is not considered, only the expected damage to enemy units matters.
    • Damage is calculated as a combination of hitpoints and chance to die, in "gold equivalent units".
    • Unlike the default AI, aggression is set to 1 for values larger than 1. Allowed values are thus anything from -infinity to +infinity, although only -infinity to +1.0 make sense.
  • [avoid]: (Version 1.13.2 and later only) The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.
  • attacks aspect: (Version 1.13.2 and later only) The standard RCA AI attacks aspect used to filter own and enemy units for attacks is now also taken into account as long as neither [filter] nor [filter_second] (see above under 'optional keys') are defined in the [micro_ai] tag.
  • village_value=1: (number ranging from 0 to 4) The default RCA AI aspect used to define how much villages should be targeted by the move-to-targets CA. In the Fast MAI, this defines which fraction of the AI units are moved toward village goals (see above for details). If set to 0, villages are ignored as goals.

Notes:

  • The CA evaluation scores of this AI are hard-coded to the same values as those of the respective default candidate actions. ca_score is therefore not a valid optional key.
  • The fast Micro AI modifies (removes) the default castle-switch, retreat-injured, spread-poison, high-xp-attack, combat, place-healers, move-to-targets, villages and retreat candidate actions.

Enabling the Fast Micro AI in its default configuration is as simple as this usage example from the "Fast AI" test scenario:

        [micro_ai]
            side=1
            ai_type=fast_ai
            action=add
        [/micro_ai]

Generalized Goto Micro AI (ai_type=goto)

The Goto Micro AI provides a highly configurable method of sending a unit (or units) to a location or set of locations. The units to be moved are defined using a Standard Unit Filter (SUF) [alternatively, all side units are used if the SUF is not provided), while the goto locations are given in a Standard Location Filter (SLF).

By default, each unit matching the SUF will move toward the closest goal (in terms of turns needed to get there) matching the SLF via the fastest route given the current situation on the map (locations of enemy units etc.), but this behavior can be influenced by the optional keys listed below. Note that this means that a unit's goal might change from one turn to the next depending on the situation on the map.

The behavior of the unit(s) once they reach their goal location(s) is configurable as well. By default, they will stay there until the Goto Micro AI is deleted or changed.

For demonstrations of several Goto Micro AI usages, check out the "Goto" scenario from the test scenario.

Enable the Goto Micro AI by using

ai_type=goto

in the [micro_ai] tag.

Goto specific keys for the [micro_ai] tag:

Required keys:

Optional keys:

  • [avoid]: (Version 1.15.0 and later only) A Standard Location Filter for the locations which the AI units should avoid. If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists). Note that the area defined by [avoid] is not entered at all, even if the end point of the move would lie outside the area again.
  • avoid_enemies: (number>0) By default, units controlled by the Goto Micro AI will not take enemy units into account for route finding, other than the enemies' ZoCs. By contrast, if this key is set, they will try to avoid traversing hexes on which they can be attacked by enemies. The larger the value of avoid_enemies, the more the units will try to stay out of the enemies' way. Notes:
    • Units are willing to take a path that is 'avoid_enemies' movement points longer for each enemy unit that can be avoided by doing so for each hex along the path. As an example, if avoid_enemies=1 and the shortest path crosses 2 hexes that can be reached by 3 enemies each, the unit is willing to take a path that is up to 6 hexes longer instead. If avoid_enemies=10 in the same situation, the unit will take a path up to 60 hexes longer.
    • Hexes adjacent to enemy units are always strongly avoided, independent of the value of avoid_enemies.
    • avoid_enemies is ignored if 'use_straight_line=true' is set.
    • Due to an issue with the path finding code, tunnels and teleports are ignored in Wesnoth 1.14 and before if 'avoid_enemies' is used. This has been fixed in Wesnoth 1.15.
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • [filter]: A Standard Unit Filter selecting the units to be moved. Defaults to all units of the side if not defined. The filter automatically includes the side= key set to the AI side.
  • ignore_enemy_at_goal=no and ignore_units=no: (boolean) In the default configuration, the Goto MAI does not move units if the path to all goal hexes is blocked by enemies. It is therefore possible to disable the Goto MAI by putting enemy units on all the goal hexes. That can be changed if either of these two keys is set to 'yes'.
    • 'ignore_enemy_at_goal=yes' makes the AI choose its goals while disregarding any enemy units at the goal hexes. Even so, a stiff rating penalty is applied to goal hexes occupied by enemies, thus that unoccupied goal hexes are chosen unless all possible goals are occupied by enemies. Note that this setting only ignores enemy units at the goal hexes themselves. It is still possible to disable the AI by putting enemies all around the goals.
    • 'ignore_units=yes' let's the AI ignore all enemy units when deciding which goal hex(es) to move toward.
    • In both cases, enemies are only ignored for deciding which unit to move toward which goal hex. For the actual move itself, all enemies and their ZoCs are considered as usual.
    • Both options only take effect if neither avoid_enemies is used, nor use_straight_line is set to 'yes', as neither of these consider enemies as blockers. Or in other words, if avoid_enemies is used, or use_straight_line=yes, it is unnecessary to set ignore_enemy_at_goal or ignore_units to yes.
  • release_unit_at_goal=no: (boolean) By default, a unit that reaches a goal location will stay there until the Goto Micro AI is deleted or changed (or until the conditions specified in the [goto_goals] SLF change). If this parameter is set, a unit that has reached its goal will not be controlled by this Micro AI any more starting from the next turn.
  • release_all_units_at_goal=no: (boolean) Same as release_unit_at_goal, but this will deactivate the Goto Micro AI for all units once the first unit reaches a goal.
  • remove_movement=yes: (boolean): (Version 1.15.11 and later only) By default, when the Goto MAI cannot move a unit (for example, because the path is blocked by enemies), its movement points are still removed. If this option is set to 'no', this step does not happen, so that other AI candidate actions (or even another Goto MAI with different parameters) can take over instead.
  • unique_goals=no: (boolean) If set to 'yes', each unit will be sent to a different goal location. Note that the best goals are recalculated each turn, so a unit might choose a different goal this turn from what it was heading for during the previous turn if the situation on the map has changed. Also note that if there are more units than goal locations, the left over units will not be handled by the Goto MAI but follow default behavior instead.
  • use_straight_line=no: (boolean) By default, units choose the route by which they will get to their goal locations in the smallest number of turns. If this parameter is set to 'yes', a straight line route (or something pretty close to it at least) will be chosen instead, irrespective of whether this leads into a dead end, whether it is blocked by enemies, etc.

Standard RCA AI aspects respected by this Micro AI:

  • [avoid]: (Version 1.15.0 and later only) The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.

Notes:

  • Depending on the parameters used, the Goto Micro AI might require a lot of path finding to be done. Thus, while it is possible to set up this AI to move many units to many different locations, a usage like that might require quite a long calculation time.

Goto Micro AI example usages:

Here are several examples of goto [micro_ai] tag usages from the "Goto" test scenario:

  • Send a unit toward a castle (similar to the RCA AI's Goto Candidate Action, but avoiding dead ends and areas ZoCed by enemies)
        [micro_ai]
            side=2
            ai_type=goto
            action=add
            ca_id=messenger1

            [filter]
                id=messenger1
            [/filter]
            [filter_location]
                x,y=6-7,2-4
                terrain=C*
            [/filter_location]
            ca_score=210001
        [/micro_ai]
  • Send all units of the side toward the southern border of the map
        [micro_ai]
            side=8
            ai_type=goto
            action=add

            [filter_location]
                 y=33
            [/filter_location]
            avoid_enemies=1
        [/micro_ai]
  • Send units to the four corners of the map (with each unit going to a different corner).
        [micro_ai]
            side=7
            ai_type=goto
            action=add

            [filter_location]
                x=1,1,44,44
                y=1,33,1,33
            [/filter_location]
            unique_goals=yes
        [/micro_ai]
  • Set up a guardian unit that doesn't move while no enemy unit is within 8 hexes (ironically, the Goto Micro AI can be used to keep units in place, although using one of the Guardian Micro AIs might often be a better idea)
        [micro_ai]
            side=3
            ai_type=goto
            action=add

            [filter]
                id=guard1
            [/filter]
            [filter_location]
                [filter]
                    id=guard1
                [/filter]
                [not]
                    [filter]
                        side=1
                    [/filter]
                    radius=8
                [/not]
            [/filter_location]
        [/micro_ai]

Guardian Micro AIs

General Comments on the Guardian Micro AIs

The Guardian Micro AIs can be used to set up different kind of guardian behaviors for a unit or a set of units. Four different types of guardians are available and are described below.

For a demonstration of several different guardian behaviors, check out the "Guardians" scenario from the test scenario.

Return Guardian (ai_type=return_guardian)

A 'return guardian' is a variation of the standard Wesnoth guardian. It has an assigned guard position (GP) to which it returns after attacks on approaching enemies:

  • If at GP with no enemy in reach, do nothing.
  • If at GP with an enemy in reach, attack. Note that the attack is done by the default AI, which might result in the guardian not attacking if the enemy is deemed too strong (this can be influenced by setting the default aggression value to a different value).
  • If not at GP, return there, no matter whether an enemy is in reach or not.
  • If enemies are blocking the way back to GP, do your best to move around them.
  • If the guardian ends up next to an enemy on the way back, attack that enemy after the move.

Enable the Return Guardian Micro AI by using

ai_type=return_guardian

in the [micro_ai] tag together with the following keys:

Required keys:

  • id or [filter]: The ID of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
    • If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
  • return_x,return_y: The coordinate of the hex the unit returns to after each attack. (Version 1.15.0 and later only) return_loc can be used instead with a named/special location.

Optional keys:

  • ca_score=100010: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. This AI consist of 2 CAs, one with score ca_score the other with ca_score-20. The default value is set so that the first CA gets executed right before the default combat CA, and the other right after. It usually will not make sense to change this value, but it is possible to do so for custom applications. (Version 1.13.6 and later only): This is now changed to 100100 and 99900 in order to avoid conflicts with the new high_XP_attacks candidate action.

Here's an example of a return guardian [micro_ai] tag usage from the "Guardians" test scenario:

        [micro_ai]
            side=2
            ai_type=return_guardian
            action=add

            [filter]
                id=return1
            [/filter]
            return_x,return_y=20,2
        [/micro_ai]

Stationed Guardian (ai_type=stationed_guardian)

A 'stationed guardian' is another variation of the standard Wesnoth guardian with a somewhat more complex behavior than that of the 'return guardian'. Two positions are defined for it, a 'station' and a 'guarded location', as well as a distance. The behavior is as follows:

  • If no enemy is within 'distance' of the guard's current position, do nothing. This is independent of the guardian being at its station or not.
  • Otherwise: If an enemy is within 'distance' of the guard, but not also within the same distance of the guarded location and the station (all of this simultaneously), move the guard in the direction of the station (or keep the guard in place if the station is unreachable).
  • Otherwise:
    • Pick the enemy unit that is closest to the guarded location.
    • If we can reach it, pick the adjacent hex with the highest defense rating and attack from there.
    • If not in reach, move toward this unit.

Enable the Stationed Guardian Micro AI by using

ai_type=stationed_guardian

in the [micro_ai] tag together with the following keys:

Required keys:

  • id or [filter]: The ID of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
    • If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
  • distance: The distance parameter as explained above
  • station_x,station_y: The x and y position of the hex that serves as the guardians station. (Version 1.15.0 and later only) station_loc can be used instead with a named/special location.
  • guard_x, guard_y: The x and y position of the guarded location. (Version 1.13.0 and later only) These are now optional keys, defaulting to station_x,station_y if not provided. (Version 1.15.0 and later only) guard_loc can be used instead with a named/special location.

Optional keys:

  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.

Here's an example of a stationed guardian [micro_ai] tag usage from the "Guardians" test scenario:

        [micro_ai]
            side=2
            ai_type=stationed_guardian
            action=add

            [filter]
                id=stationed1
            [/filter]
            distance=4
            station_x,station_y=2,14
            guard_x,guard_y=3,13
        [/micro_ai]

Coward (ai_type=coward)

Cowards are units that, like guardians, sit around doing nothing until an enemy comes into range. Unlike guardians, however, they run away once enemies approach. Applications might be wild animals, unarmed civilians getting in the way of a battle, etc. The coward macro can be called with two optional locations, 'seek' and 'avoid':

  • If neither is given, the coward retreats to the position farthest away from the approaching enemies.
  • If 'seek' is given, it preferentially goes toward that location (but getting away from enemies takes priority).
  • If 'avoid' is given, it in addition tries to avoid that location (with both maximizing distance from enemies and going toward 'seek' taking priority).
  • Both 'seek' and 'avoid' may consist of only one coordinate ('x' or 'y'), in which case not a single hex, but a line of hexes is sought or avoided.

Enable the Coward Micro AI by using

ai_type=coward

in the [micro_ai] tag together with the following keys:

Required keys:

  • id or [filter]: The ID of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
    • If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
  • distance: The distance within which an enemy must be to "scare" the unit

Optional keys:

  • attack_if_trapped='no': (Version 1.13.0 and later only) With the default settings, a coward never attacks. If this key is set to 'yes', the coward attacks the weakest (lowest hitpoints) enemy next to which it ends up after moving (such as a cornered animal would do, blindly lashing out without regards for its own safety).
  • avoid_x, avoid_y: The x and y coordinate of the hex to avoid. (Version 1.15.0 and later only) avoid_loc can be used instead with a named/special location.
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • [filter_second]: A Standard Unit Filter selecting the units from which the cowards flee. If not set, this defaults to all enemy units. Note, however, that no "enemy of AI side" condition is added if [filter_second] is specified, meaning that it can include allied and/or enemy units as desired (and even units on the same side as the coward).
  • seek_x, seek_y: The x and y coordinate of the hex to seek. (Version 1.15.0 and later only) seek_loc can be used instead with a named/special location.

Here's an example of a coward [micro_ai] tag usage from the "Guardians" test scenario:

        [micro_ai]
            side=2
            ai_type=coward
            action=add

            [filter]
                id=coward3
            [/filter]
            distance=5
            seek_x,seek_y=24,5
            avoid_x,avoid_y=24,15
        [/micro_ai]

Zone guardian (ai_type=zone_guardian)

A zone guardian is a unit that, as the name says, guards a zone. It moves randomly inside this zone until an enemy enters it (or a separately defined enemy zone, see below). Applications might be the defense of a castle, a nesting area or for protecting an unit. The zone macro can be called with an optional SLF, [filter_location_enemy]:

  • If not specified, the zone guard attacks any enemy coming inside its guard zone.
  • If [filter_location_enemy] is given, it attacks any enemy entering this zone and once there are no more enemies, it goes back to patrol in its basic zone.

Enable the Zone Guardian Micro AI by using

ai_type=zone_guardian

in the [micro_ai] tag together with the following keys:

Required keys:

  • id or [filter]: The ID of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
    • If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
  • [filter_location]: A Standard Location Filter designating the zone to guard.

Optional keys:

  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • [filter_location_enemy]: A Standard Location Filter designating the zone where enemies have to be attacked. If not given, it defaults to [filter_location].
  • station_x,station_y: By default, the zone guardian moves randomly within the zone if there is no enemy to attack. However, if station_x/y is given, it moves to this position instead during turns when it does not have an enemy to attack. This position does not need to be inside the zone defined above. Note: obviously it does not make sense to define [filter_location], [filter_location_enemy] and station_x/y all at the same time. Only [filter_location] and either one of the latter two (or none of them) should be provided for any zone guardian. (Version 1.15.0 and later only) station_loc can be used instead with a named/special location.

Here's an example of a zone guardian [micro_ai] tag usage from the "Guardians" test scenario:

        [micro_ai]
            side=2
            ai_type=zone_guardian
            action=add

            [filter]
                id=zone3
            [/filter]
            [filter_location]
                x,y=22-31,4-11  # This is intentionally chosen to extend past the lake
                terrain=W*
            [/filter_location]
            station_x,station_y=32,8
        [/micro_ai]

Hang Out Micro AI (ai_type=hang_out)

The Hang Out Micro AI instructs units of the AI side to "hang out" around a certain location, or locations, until a condition for mobilizing the side is met. If none of the optional keys are given, the AI controls all units of the side to hang around the leader while moving off castle tiles to make room for recruiting.

The AI works by moving each unit to its best hex first using the minimum amount of movement points required for this move. Once all AI units are in position, movement points are set to zero for all of them simultaneously such that they cannot be used by other AI candidate actions. This is done because the mobilizing condition might be met as result of one of the moves of the Hang Out AI, after which we want units to be able to continue with other AI actions.

For a demonstration, check out the "Hang Out and Messenger" scenario from the test scenario.

Enable the Hang Out Micro AI by using

ai_type=hang_out

in the [micro_ai] tag.

Hang Out specific keys for the [micro_ai] tag:

Required keys:

There are no required keys. In its default configuration, the Hang Out MAI controls all units of a side, keeping them as close to the side leader(s) as possible while moving off castle tiles to make room for recruiting. For this purpose, the candidate action score defaults to 170,000, which is just below the score of the default recruiting CA.

Optional keys:

  • [avoid]: A Standard Location Filter for the terrain which the AI units should avoid. If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists). If neither of these two exists, this parameter is set to default to all castle terrain (terrain=C*,C*^*,*^C*) so that units move off the castle to make room for recruiting. Note that this does not include keep terrain, otherwise the leader would be moved off the keep as well.
  • ca_score=170000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 170,000, which means that it is executed after the default recruitment CA, but before most of the other default CAs.
  • [filter]: A Standard Unit Filter selecting the units of the AI side participating in the Hang Out action (side= is always set and does not need to be provided). It defaults to all units of the side. The filter automatically includes the side= key set to the AI side.
  • [filter_location]: A Standard Location Filter describing the locations near which the AI units should hang out. This does not mean that the units only move onto terrain specified here, but that they minimize the distance to such terrain. It defaults to the position of the side leader(s).
  • [mobilize_condition]: Contains (WML Condition Tags) Once the condition set up here has been met, the Hang Out MAI is disabled and the side goes over to other AI activity. The Hang Out MAI remains disabled after this, even if the condition is not met any more later in the scenario.
  • mobilize_on_gold_less_than: (integer) Since side gold cannot be checked in a WML condition tag without storing it in a variable first, this key is provided separately. It disables the Hang Out Micro AI once the side gold goes below the value specified here for the first time.

Standard RCA AI aspects respected by this Micro AI:

  • [avoid]: The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.

Notes:

  • The Hang Out AI still takes effect if no locations to hang out at are found or if all map locations are to be avoided. In that case, it simply keeps all units at their current locations.

This is an example of a Hang Out Micro AI configuration from the "Hang Out and Messenger" test scenario:

        [micro_ai]
            side=1
            ai_type=hang_out
            action=add

            [avoid]
                terrain=C*,H*,M*,A*,S*,*^F*
            [/avoid]
            [mobilize_condition]
                [have_unit]
                    side=1
                    count=7-99
                [/have_unit]
            [/mobilize_condition]
        [/micro_ai]

Healer Support Micro AI (ai_type=healer_support)

The Healer Support Micro AI configures the healers of a side to stay behind the battle lines and heal injured and/or threatened units rather than participate in combat under all circumstances. You can set different levels of aggressiveness for the healers.

Notes

  • By default, all healers of the AI side are controlled by this AI. This includes in particular also the side leader, if the leader is a healer. If you do not want the leader to be included (and possibly be moved away from the keep etc.) use the [filter] tag with canrecruit=no (see below).
  • It is not always better to use this Micro AI than the default AI, as it takes healers (which can be strong units) away from the pool of units to choose for attacks.
  • (Version 1.15.3 and later only) This Micro AI now takes unit guardian status and the passive_leader aspect into account.

For a demonstration, check out the "Healers" scenario from the test scenario.

Enable the Healer Support Micro AI by using

ai_type=healer_support

in the [micro_ai] tag.

Healer Support specific keys for the [micro_ai] tag:

Required keys:

There are no required keys.

Optional keys:

  • [filter]: A Standard Unit Filter selecting the healer units. If set, only units on the AI side passing this filter and having the healing ability are considered by this Micro AI.
  • [filter_second]: A Standard Unit Filter selecting units to receive healing. If set, only units on the AI side passing this filter and the other healee selection criteria will be selected for healing by this Micro AI.
  • aggression=1.0: (float) Sets the aggressiveness of the AI. This parameter is set up as a float to accommodate future functionality, but it currently acts as a boolean: if set to zero, the AI will never let its healers participate in combat, for all other values it allows them to attack after all other units have attacked and if the healers cannot find any more units to support. The former behavior might be appropriate in scenarios with only one or few valuable healers, while the latter might work better in scenarios with many healers.
  • injured_units_only=no: (boolean) If set to 'yes', the AI will only move healers next to units that are already injured and skip units that currently have full hitpoints, but might get injured during the next enemy turn.
  • max_threats=9999: (integer) The maximum allowable number of enemies that can attack a hex in order for it to be considered for a healer. As an example, setting 'max_threats=0' means that the AI only moves healers to locations that are entirely safe from the enemy (assuming that none of the units currently on the map dies). Note that the value of this key is checked against the number of enemies that can make it to the hex, not the number of adjacent hexes from which the healer could be attacked.

Standard RCA AI aspects respected by this Micro AI:

  • [avoid]: The standard RCA AI aspect used to define locations that should be avoided by the AI. Note: as attacks by the healers are left to the default AI, there is no separate [avoid] tag for this Micro AI in order to prevent inconsistencies.

Notes:

  • The Healer Support Micro AI modifies the attacks aspect.
  • The CA evaluation scores of this AI are hard-coded. It does not work otherwise.

This is an example of a Healer Support Micro AI configuration from the "Healers" test scenario:

        [micro_ai]
            side=2
            ai_type=healer_support
            action=add

            aggression=0
        [/micro_ai]

Lurkers Micro AI (ai_type=lurkers)

The Lurker Micro AI controls some or all units of a side in "lurker mode". A lurker is a unit that is capable of moving across most terrains, but that only stops on and attacks from specific terrain. It might also have the ability to hide on this terrain (which is the reason why it is called a lurker).

Lurkers move individually without strategy and always attack the weakest enemy within their reach. If no enemy is in reach, the lurker does a random move instead - or it just sits and waits (lurks).

For a demonstration of different types of lurker behavior, check out the "Lurkers" scenario from the test scenario.

Enable the Lurkers Micro AI by using

ai_type=lurkers

in the [micro_ai] tag

Lurkers specific keys for the [micro_ai] tag:

Required keys:

  • [filter]: Specifies which units of the side are controlled by the Lurker Micro AI. This is a Standard Unit Filter. The filter automatically includes the side= key set to the AI side.
  • [filter_location]: Specifies the terrain from which the lurkers attack. This is a Standard Location Filter.

Optional keys:

  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • [filter_location_wander]: Specifies the terrain on which lurkers end their moves if there is no enemy in reach. This is a Standard Location Filter. If [filter_location_wander] is not given, it defaults to [filter_location].
  • stationary=no: (boolean) If set to yes, a lurker never moves if there is no enemy within attack range.

Here's an example of [micro_ai] tag usage from the "Lurkers" test scenario:

        [micro_ai]
            side=4
            ai_type=lurkers
            action=add

            [filter]
                type=Naga Fighter
            [/filter]
            [filter_location]
                terrain=W*,S*
            [/filter_location]
            [filter_location_wander]
                terrain=W*
            [/filter_location_wander]
        [/micro_ai]

Messenger Escort Micro AI (ai_type=messenger_escort)

The Messenger Escort Micro AI lets you define a set of waypoints through which it tries to move one or several of its units, the messenger(s). The other units escort the messenger, trying to protect it and attacking enemies that are in its way. Note that a messenger might not strictly hit intermediate waypoints, but that getting close is good enough, especially if a waypoint is occupied by an enemy unit. It does, however, always try to get to the last waypoint.

Notes on the use of several messengers: (Version 1.13.0 and later only)

  • This Micro AI can control several messengers at the same time, which can but do not have to move in a group. They can be put on the map altogether in one location, or be spread out on the map or across different turns.
  • The farther a messenger has moved through the chain of waypoints, the higher a priority it is for the AI, meaning that farther advanced (on the map) messengers are moved first, and that the escort units try to clear the way and stay with those messengers more so than with those further back on the map. This order can be inverted using the invert_order= key.
  • If several messengers are on the map, escort units might move from one to the other, the AI making a judgement call where they are needed most. Closeness to a messenger is generally the most important criterion, but not the only one.
  • If a messenger dies, the escort units previously staying with it now join one of the other messengers if there are any left (otherwise they follow default AI behavior).
  • If you want certain escort units to stay always with the same messenger, use several messenger [micro_ai] tags with different [filter]/[filter_second] combinations.

For a demonstration, check out the "Messenger" scenario from the test scenario.

Enable the Messenger Escort Micro AI by using

ai_type=messenger_escort

in the [micro_ai] tag.

Messenger Escort specific keys for the [micro_ai] tag:

Required keys:

  • id or [filter]: (Version 1.13.0 and later only) (Previous to 1.13.0, only id= was allowed.) The id of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
  • waypoint_x,waypoint_y: Comma-separated list of waypoint coordinates through which the messenger will go in the given order to reach its goal, given by the last coordinate. If you want the messenger to go directly to the goal, simply enter a single x,y coordinate here. Note that the messenger does not have to hit each waypoint exactly (except for the final one), getting close to them is good enough. (Version 1.15.0 and later only) waypoint_loc can be used instead with named/special locations.

Optional keys:

  • [avoid]: (Version 1.15.11 and later only) A Standard Location Filter for the locations which the AI units should avoid. If it is not given, the existence of the default (RCA) AI's [avoid] tag is checked (and used if it exists).
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate actions controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs. Note that the Messenger Escort AI consists of 3 CAs with scores ranging from ca_score-2 to ca_score.
  • enemy_death_chance=0.67 and messenger_death_chance=0.0: (both floats; ranging from 0 to 1) If the messenger is adjacent to an enemy at the end of the move, it will only attack the enemy if the chance of death of the enemy is >= enemy_death_chance and if the messenger's chance of death is <= messenger_death_chance (or if it is an attack at a range for which the enemy does not have a weapon).
  • [filter_second]: (Version 1.13.0 and later only) A Standard Unit Filter selecting the escort units. If not set, this defaults to all enemy units. The filter automatically includes the side= key set to the AI side.
  • invert_order=no: (Version 1.13.0 and later only) If set to 'yes', the order of priority with which messenger units are considered is inverted, starting with the messenger unit that is the least advanced on the map (see description above). In most cases, selecting this option results in worse performance of the AI, so use it with caution. (And obviously it has no effect at all if there is only one messenger controlled by the AI.)

Standard RCA AI aspects respected by this Micro AI:

  • [avoid]: (Version 1.15.11 and later only) The standard RCA AI aspect used to define locations that should be avoided by the AI. See above (under 'optional keys') for details.

Here's an example of [micro_ai] tag usage from the "Messenger Escort" test scenario:

        [micro_ai]
            side=2
            ai_type=messenger_escort
            action=add

            [filter]
                id=messenger
            [/filter]
            waypoint_x=31,24,27,28
            waypoint_y=20,14,7,1
        [/micro_ai]

Patrol Micro AI (ai_type=patrol)

The defines a number of waypoints for a unit (or units) to follow. Options can be set whether the route should be followed in a loop, as an out-and back, only once, whether units encountered along the way should be attacked, etc.

With the default settings, getting to the next waypoint takes priority over attacking for a patroller, but this can be overridden (as of Wesnoth 1.15.12, using the attack_range option). Unless instructed otherwise, the AI thus prefers to move the patrol unit around enemies rather than straight for them. Also, if a waypoint is occupied by a unit the AI is not instructed to attack, it will (eventually) abandon that waypoint once it gets close enough and move on to the next one.

For a demonstration of several different patrol behaviors, check out the "Patrols" scenario from the test scenario.

Enable the Patrol Micro AI it by using

ai_type=patrol

in the [micro_ai] tag.

Patrol specific keys for the [micro_ai] tag:

Required keys:

  • id or [filter]: The ID of a unit or a Standard Unit Filter selecting the units controlled by this Micro AI.
    • One or the other is required
    • If both are given, [filter] takes priority over id=
    • The AI contains an implicit filter for units on the AI side. Thus, if all AI units are to be selected, an empty [filter] tag can be used.
    • If several units match the filter, the order in which they are controlled is not guaranteed. If the order matters, set up several MAIs using the id= key and different values for ca_score=.
  • waypoint_x,waypoint_y: Comma-separated lists of the waypoint coordinates through which the patrol travels (in order). (Version 1.15.0 and later only) waypoint_loc can be used instead with named/special locations.

Optional keys:

  • attack: By default (if this key is not set), the patrol unit attacks any unit it ends up next to after a move, or that is within attack_range (see below). Alternatively, this parameter can be set to a comma-separated list of unit ids. If that is done, the patrol only attacks these units when it ends up next to them or if it gets within attack_range. It ignores any other unit. This can in turn be used to have the patroller not attack at all, by setting attack= to a non-existing id. The exception to this is an enemy on the last waypoint with one_time_only=yes, which will always be attacked.
  • attack_range=1: (Version 1.15.12 and later only) If the patrol comes within this many hexes of an enemy unit, it interrupts its patrol route and attacks that enemy (assuming it still has enough movement left to get to the enemy). The attack= instructions are taken into account for this. Note that the patrol generally tries to move around enemies, which means that for the default value of 1, enemies are usually not within attack range, except at the end of the move.
  • attack_invisible_enemies=no: (Version 1.15.12 and later only) If set to 'yes', the unit also attacks invisible enemies (according to the criteria set by attack and attack_range).
  • ca_score=300000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 300,000, which is higher than any of the RCA AI candidate actions. By setting it, for example, to 170,000, we can have it be executed after the default recruitment CA, but before most of the other default CAs.
  • one_time_only=no: (boolean) If set to 'yes', the unit goes through the patrol route only once and then hangs out at the last waypoint. It also always attacks any enemy unit on the last waypoint, independent of what attack= is set to.
  • out_and_back=no: (boolean) By default, a patrol unit returns to the first waypoint after reaching the last, doing the patrol route as a loop. If this parameter is set to 'yes', the unit instead reverses its course and perpetually does out and backs of the route.

Here's an example of [micro_ai] tag usage from the "Patrols" test scenario:

        [micro_ai]
            side=2
            ai_type=patrol
            action=add

            [filter]
                id=Konrad
            [/filter]
            waypoint_x=9,24,25
            waypoint_y=21,23,15
            one_time_only=yes
            attack=Gertburt
        [/micro_ai]

Protect Unit Micro AI (ai_type=protect_unit)

The Protect Unit Micro AI tries to move one or several units to a given location while keeping them safe from enemy attacks. It does so by keeping the protected units away from enemy units and close to friendly units. Other units on the AI side are controlled by the default Wesnoth AI.

For a demonstration, check out the "Protect Unit" and "The Elves Besieged" scenarios from the test scenario.

Enable the Protect Unit Micro AI by using

ai_type=protect_unit

in the [micro_ai] tag.

Protect Unit specific keys for the [micro_ai] tag:

Required keys:

  • [unit]: A separate [unit] tag is required for each protected unit(s). Each tag has required keys id, goal_x, goal_y for each unit, as shown in the example below. (Version 1.15.0 and later only) goal_loc can be used instead with a named/special location.

Optional keys:

  • disable_move_leader_to_keep=no: (boolean) If set to 'yes', side leaders protected by this AI do not try to return to their keep. This is necessary for this Micro AI to work with units that are side leaders and that are supposed to move to an off-keep location.

Notes:

Here's an example of [micro_ai] tag usage from the "HttT: The Elves Besieged" test scenario:

        [micro_ai]
            side=1
            ai_type=protect_unit
            action=add

            [unit]
                id=Delfador
                goal_x,goal_y=1,2
            [/unit]
            [unit]
                id=Konrad
                goal_x,goal_y=1,1
            [/unit]

            disable_move_leader_to_keep=true
        [/micro_ai]

Recruiting Micro AI

General Comments on the Recruiting Micro AIs

The Recruiting Micro AI replaces the default recruitment AI by alternative recruiting patterns. Currently there are two recruiting algorithms you can choose from, random recruiting and the rush recruiting used in the new (as of Version 1.11.1) Experimental AI (see below).

For a demonstration of a different recruiting pattern, check out the "Recruiting" scenario from the test scenario. You can also explore the unit choices by watching the Experimental AI in a multiplayer game.

Note: Obviously, the Recruitment Micro AI modifies the recruitment candidate action.

Random Recruitment AI (ai_type=recruit_random)

This AI randomly selects a unit type from the recruitment list of the side. The probability of choosing each type and the behavior in low-gold situations can be influenced with optional parameters.

Enable the Random Recruiting Micro AI by using

ai_type=recruit_random

in the [micro_ai] tag.

Required keys:

There are no required keys.

Optional keys:

  • ca_score=180000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 180,000. This is identical to the default Recruiting CA which it replaces.
  • [probability]: This tag sets the probability of selecting the given unit type. It has two required sub-keys:
    • type: comma-separated list of unit types to which this probability is to be applied
    • probability: (non-negative float) The probability with which these unit types is to be selected. All unit types for which no [probability] tag is defined receive a default probability of 1.0, thus values should be chosen relative to that. As an example, in the code below swordsmen and peasants are given a probability of 8, while no other units have assigned probabilities. Thus, each of these two unit types is 8 times more likely to be selected than any other individual unit type.
  • skip_low_gold_recruiting=no: (boolean) By default, the random recruitment AI chooses a unit to recruit only from those types for which it has sufficient gold. If this parameter is set to 'yes', it will instead choose from all available unit types and end recruiting for the turn if there is not enough gold to recruit it this turn (even if other, affordable unit types exist).

Here's an example of a random recruiting [micro_ai] tag usage from the "Recruiting" test scenario:

        [micro_ai]
            side=1
            ai_type=recruit_random
            action=add

            [probability]
                type=Swordsman,Peasant
                probability=8
            [/probability]

            skip_low_gold_recruiting=yes
        [/micro_ai]

Rush Recruitment AI (ai_type=recruit_rushers)

This AI replaces the default recruiting with the recruiting used in the Experimental AI as described here.

Enable the Rush Recruiting Micro AI by using

ai_type=recruit_rushers

in the [micro_ai] tag.

Required keys:

There are no required keys.

Optional keys:

  • ca_score=180000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 180,000. This is identical to the default Recruiting CA which it replaces.
  • (Version 1.15.2 and later only) high_level_fraction=0: (non-negative number) The approximate fraction of units of level 2 or higher to be recruited. This is defined as fraction of units on the map, not of new units being recruited during a turn or over several turns (which makes a difference if there are already units on the map). The effect is also cumulative per level (starting from level 2), meaning that 1/3 of L2 units will be recruited in the example above, 1/3*1/3=1/9 L3s etc. The default value is zero, which leaves the high-level unit recruiting to the default Experimental AI algorithm resulting usually in very few such units being recruited.
  • randomness=0.1: (number) A random number is applied to the rusher recruit engine's score to prevent the recruitment pattern from being too predictable. 0 causes no randomness to be applied, while larger numbers increase the random effect. A value of 1-2 generates results in which the random effect is approximately equal to the scored effect. Extremely high values are essentially entirely random.
  • (Version 1.17.6 and later only) reset_cache_each_turn=no: (bool) Many of the operations of the rush recruitment evaluation are expensive and are therefore cached. For the most part, this cache can be kept from turn to turn, but in case there are events that change, for example, the map or the recruit list, this parameter can be set to 'yes' to force a reset of the cache each turn.

Here's an example of a rush recruiting [micro_ai] tag usage from the "Recruiting" test scenario:

        [micro_ai]
            side=1
            ai_type=recruit_rushers
            action=add
         [/micro_ai]

Simple Attack Micro AI (ai_type=simple_attack)

The Simple Attack Micro AI is meant as an addition to the default combat candidate action for when one wants to force the AI to do attacks that it would otherwise not do (for example on units that are 1 XP from leveling) or to execute certain attacks before all others (for example, attack with all "expendable" units first). It is not set up to be a replacement for the default attacks. Some notes:

  • The algorithm is different from and simpler than that of the default combat CA. For example, no attack combinations are considered, only individual attacks. As a result, the default aspects (aggression, caution, [avoid], ...) are not taken into account. Also, if lots of units are involved, evaluation of this Micro AI is potentially quite a bit slower than of the default attacks.
  • If an attack matching the Standard Unit Filters described below is found, this attack will always be executed, no matter how bad the odds are. Thus, this Micro AI can be used to force the AI to do attacks it would otherwise avoid.
  • Other than selecting the attacker/defender units, this AI is currently not configurable. Let us know if you would like to see certain options to be added. (No guarantees that we will add them, but we will definitely consider them.)

For a demonstration, check out the "Simple Attack" scenario from the test scenario.

Enable the Simple Attack Micro AI by using

ai_type=simple_attack

in the [micro_ai] tag.

Simple Attack specific keys for the [micro_ai] tag

Required keys:

There are no required keys. It is, however, in general not desirable to use this AI without at least one of the optional Standard Unit Filters below, as this AI is not meant as a replacement of the default combat candidate action.

Optional keys:

  • ca_score=110000: (non-negative integer) The evaluation score of the candidate action controlling this Micro AI. By default, it is set to 110,000, which means that it is executed right before the default combat candidate action.
  • [filter]: A Standard Unit Filter selecting the units of the AI side participating in the Simple Attack action. It defaults to all units of the side. The filter automatically includes the side= key set to the AI side.
  • [filter_second]: A Standard Unit Filter selecting the units the AI should attack. It defaults to all enemy units. The filter automatically includes a Standard Side Filter set to all enemies of the AI side.
  • weapon=-1: (integer) The number of the weapon that should be used for this attack. Weapon numbers start at 1 (not 0). -1 stands for "best weapon" (by whatever criterion the AI chooses to use). Available from Wesnoth 1.11.8

Below are 2 examples of Simple Attack Micro AI configurations from the "Simple Attack" test scenario. The first one shows how to force the AI to attack with all Soulless and Walking Corpse units first:

        [micro_ai]
            side=2
            ai_type=simple_attack
            action=add

            ca_score=110000
            [filter]
                type=Soulless,Walking Corpse
            [/filter]
        [/micro_ai]

The second example executes attacks by Soulless on all enemy units that are 1 XP from leveling. Note that the Lua code in the preload event is there simply in order to code the "1 XP from advancing" condition. It is not needed for most other SUFs, as can be seen in the previous example.

    [event]
        name=preload
        first_time_only=no
        [lua]
            code=<<
                function close_to_advancing(unit)
                    if (unit.experience >= unit.max_experience-1) then
                        return true
                    else
                        return false
                    end
                end
            >>
        [/lua]
    [/event]

    [event]
        name=prestart
        [micro_ai]
            side=2
            ai_type=simple_attack
            action=add

            ca_score=110001
            [filter]
                type=Soulless  # No Walking Corpses; L0 units don't advance enemy
            [/filter]
            [filter_second]
                lua_function = "close_to_advancing"
            [/filter_second]
        [/micro_ai]
    [/event]

Several Simple Attack Micro AIs can be combined for the same AI side. The two examples above are both used (note the different values for ca_score) in the "Simple Attack" test scenario.

Custom Micro AIs

(Version 1.13.5 and later only)

From 1.13.5 onwards, adding a new Micro AI can be easily done without altering any core files or overriding the micro_ai tag. The [micro_ai] tag now looks up its ai_type parameter in the wesnoth.micro_ais table and uses the micro AI setup function found there to determine which keys are required and allowed and what candidate actions to add.

A micro AI setup function takes as its single parameter the contents of the [micro_ai] tag and returns three separate values:

  • required: A list of required keys and tags, as strings. Tags are indicated by enclosing them within square brackets in the string. If a key or tag in this list is missing from the [micro_ai] tag, an error will be printed. (Version 1.17.6 and later only) In order to enable better error handling, the syntax of this table has been changed. It is now of format { param1 = 'param1_type', ... }. The supported parameter types can be found at the link to examples below.
  • optional: Similar to above, a list of optional keys and tags, as strings. No error will be printed if a key or tag in this list is missing, nor will an error be printed if it is present (as would be the case for unrecognized keys or tags). (Version 1.17.6 and later only) The format of this table has been changed in the same way as for 'required'. Also, a warning message is now issued if the '[micro_ai]' tag contains a key or tag that is not listed in either 'required' or 'optional'.
  • ca_params: A table specifying the candidate actions that constitute the micro AI. It should contain an ai_id key (which specifies a base ID to be used for candidate actions of this micro AI) and a series of candidate action definitions. Each candidate action definition is a table containing the following keys:
    • ca_id: The ID used for the candidate action. This will be combined with the ai_id to produce the final ID.
    • location: Path to the Lua file that defines the candidate action.
    • score: The maximum score for the candidate action. If the [micro_ai] tag specified a ca_score parameter, the score here should normally be based on that.

(The return statement would thus look like return required, optional, ca_params.)

Examples of micro AI setup functions can be found in the default MAI definitions directory. See the Big Animals MAI definition for a simple example. For custom micro AIs, the setup code should be put into a [lua] tag inside a preload event.

Since the function has full access to the contents of the [micro_ai] tag, it can conditionally add candidate actions to ca_params depending on the values of other keys within the [micro_ai] tag. It can also perform other actions such as adding facets to an aspect; if it does such things, it should pay attention to the action key to determine whether it's being added or removed.

There are two useful helper functions that can be used by Micro AI setup functions requiring aspect changes. They can be brought into scope by a line similar to the following:

local MAIH = wesnoth.require("ai/micro_ais/micro_ai_helper.lua")
  • MAIH.add_aspects(side, aspect_params)
  • MAIH.delete_aspects(side, aspect_params)

The aspect_params parameter is an array of tables, each of which contains the following keys:

  • aspect: The aspect to change.
  • facet: The WML defining the facet. This must include an id key in order for the aspect to be correctly deleted. For maximum compatibility, incorporate the ca_id key from the [micro_ai] tag.


See also: Wesnoth AI

This page was last edited on 16 August 2023, at 17:35.