LuaAI

From The Battle for Wesnoth Wiki
Revision as of 19:51, 18 January 2014 by Alarantalara (talk | contribs) (Add Lua category)

This is a page containing information on configuring the AI using Lua. In addition to the technical information on this page, a tutorial-style guide is also available at Lua AI Howto.

NB: previous contents of the page moved to http://wiki.wesnoth.org/LuaAI(old)

Aspects

Patch r49721 enabled users to write aspects using Lua. This simplifies the definition of aspects that are meant to change depending on the game state. A good example could be aggression, which changes depending on the time of the day(since ToD affects the actual battle performance of your forces).
Static aggression:

[aspect]
	id="aggression"
	engine="lua"
	value="0.3"
[/aspect]

Dynamic aggression:

[aspect]
	id=aggression
	engine=lua
	     
	code=<<
		wesnoth.fire("store_time_of_day")
		local value = 0
		tod = tostring(wesnoth.get_variable('time_of_day').name) 
		if (tod == 'Morning') then
			value = 0.2
		else
			value = 1
		end
	
		wesnoth.fire("clear_variable", {name = "time_of_day"})
		return value
	>>      
[/aspect]

Note: the way of getting the ToD is hacky here, but I will create a more elegant method soon(Nephro).
Also note the difference between 'code' and 'value' attributes, this is important.

At the moment, it is possible to create the following aspects using Lua(the list will be constantly updated):

advancements                                 // string[] or function (see below)
aggression                                   // double
attack_depth                                 // int
avoid                                        // exposed as map_location[], where map_location is a table of form {x, y}
caution                                      // double
grouping                                     // string
leader_aggression                            // double
leader_goal                                  // exposed as a config
leader_value                                 // double
number_of_possible_recruits_to_force_recruit // double
passive_leader                               // bool
passive_leader_shares_keep                   // bool
recruitment_ignore_bad_combat                // bool
recruitment_ignore_bad_movement              // bool
recruitment_pattern                          // string[]
scout_village_targeting                      // double
simple_targeting                             // bool
support_villages                             // bool
village_value                                // double
villages_per_scout                           // int



Note: simple numeric, bool and string aspect creation can be enabled just by adding a specific factory to registry.cpp, this will also soon be done.

To get the value of a specific aspect in Lua we have to use the

ai.get_<aspect_name>()

function. E.g.

local aggression = ai.get_aggression()

Aspect: advancements

This aspect can be used to define to what unit a specific unit on the map should advance. It can be used in multiple ways:

  1. Lua returns a String of the Form "Javelineer, Footpad".
    When the AI advances a Spearman he will become a Javelineer (because Javelineer is a member of the list).
  2. Lua returns a function of the Form advance(x, y) which itself returns a string.
  3.  		[ai]
    			[aspect]
    				id=advancements
    				engine=lua
    				
    				code=<<
    					function advance(x, y)
    						local unit = wesnoth.get_unit(x, y)
    						if(unit.id == 'bob') then
    							return 'Swordsman'
    						else
    							return 'Javelineer'
    						end
    					end
    					return advance
    				>>
    			[/aspect]
    		[/ai]
    

    When a unit advances advance(x, y) is called with the current location of the unit as parameter. You may use wesnoth.get_unit(x, y) to retrieve the unit object itself. Note that the return value of advance(x, y) could also be a list (like in 1.).

  4. Just for completeness: The aspect will work without Lua and can then look like this:
  5. [ai]
    	advancements = "Javelineer, Footpad"
    [/ai]
    

Note that this aspect only affects attacking units. When a defending unit advances it is still decided randomly. That is because Wesnoths design don't allow the AI to make out of turn decisions.

Preload event

It is a good idea to have such a preload event in your scenario if you are intending to use Lua for AI programming or customizing. The code of this event will most probably be moved out to a macro(except for the line that requires patrol.lua, since it is not necessary).

[event]
    name=preload
    first_time_only=no
    [lua]
        code = <<
            H = wesnoth.require "lua/helper.lua"
            W = H.set_wml_action_metatable {}
            _ = wesnoth.textdomain "my-campaign" 
	    ai = {}
	    ca_counter = 0
		
            H.set_wml_var_metatable(_G)

	    wesnoth.require("ai/lua/patrol.lua")

	    >>
	[/lua]
[/event]

The code attribute can be further expanded by any Lua code needed. For example, we can set up some global variables there or include additional code libraries("wesnoth.require("ai/lua/patrol.lua")" - includes code that handles patrolling of units).

Engine code

In the engine tag you should define functions that will handle evaluation and execution of your custom candidate actions and stages. You can also run some code that is intended to be run once in the beginning.
The definition of the [engine] tag should be place inside the [ai] tag.

[engine]
    name="lua"
    code= <<
        -- your engine code here
    >>
[/engine]

Stages

Once the engine has been set up, we can start adding stages to the configuration of our AI.
To add a stage we just use the [stage] tag.

[stage]
    engine=lua
    code=<<
        -- Code for stage execution here
        -- It is better to call predefined functions for the [engine] code, 
        -- than to define the functions here, to keep the structure of the stages clear
    >>
[/stage]

Candidate actions

This is an example from the current version of the lua_ai arena. The stage with an id "ca_loop" is the RCA AI loop stage, as we can see from its name. Currently it has two candidate actions, both Lua backed.

            [stage]
                name=testing_ai_default::candidate_action_evaluation_loop
		id=ca_loop
                [candidate_action]
                    engine=lua
                    name=first
		    id=firstca
                    evaluation="return (...):candidate_action_evaluation_hello()"
                    execution="local ai, cfg = ...; ai:candidate_action_execution_hello(cfg)"
                [/candidate_action]
                [candidate_action]
                    engine=lua
                    name=second
                    evaluation="return (...):candidate_action_evaluation_hello2()"
                    execution="(...):candidate_action_execution_hello2()"
                [/candidate_action]
            [/stage]

Basically, we need to have an engine attribute, an evaluation and execution functions. The syntax (...):foo() means "call eng.foo(eng) where eng is whatever the engine code returns". We can also add, remove, modify candidate actions on the fly, using wesnoth.wml_actions.modify_ai() functionality. Behavior(sticky) candidate actions use this approach.


Behavior(sticky) candidate actions

Sometimes we need a specific unit to do a specific action in our scenario, e.g. we want a scout unit to patrol between 3 places on the map, to provide us with visibility needed. In this case we can create a sticky candidate action that will tie itself to the unit, and remove itself when the unit has died. The syntax for defining a sticky candidate action is the following:

[event]
	name=side 2 turn 1
	first_time_only=yes	
        [add_ai_behavior]
           side=2
           [filter]
                name="Rark"
           [/filter]
	   sticky=yes
	   loop_id=ca_loop
           evaluation="return patrol_eval_rark()"
           execution="patrol_rark()"
        [/add_ai_behavior]
[/event]

Here the behavior CA is added to the configuration of the AI when the event triggers. Obviously this will happen when side 2 gets its first turn, but the event can be whatever needed. The definition is very similar to a simple candidate action, but here we also filter out a unit and state that we want the behavior to be sticky. If we don't, the action will not try to remove itself, when the unit gets killed, and this could cause errors.
Such CAs can also be added from inside other CA or stage code using wesnoth.wml_actions.add_ai_behavior(cfg) function.

Sticky candidate actions never execute more than once per turn. Therefore, if the action consists of a series of goals, the CA must evaluate and execute each goal as it is achieved within itself and not rely on being called multiple times.

Behavior function library

Behaviors are defined using generators. A behavior generator receives arguments(unit info, configuration, etc) and returns a pair of functions: evaluator and executor. These functions are to be passed to the add_ai_behavior tag, or directly to the function.

Patrolling

The only behavior defined at the moment is the patrol behavior. After calling patrol_gen(name, locations), we receive a pair of functions to use for creation of candidate actions
Inclusion of the patrolling code:

wesnoth.require("ai/lua/patrol.lua")

Usage:

local patrol_rark = patrol_gen("Rark", {{x=14, y=7}, {x=15, y=7}, {x=15, y=8}, {x=14, y=8}})
-- patrol_rark.exec -- execution function
-- patrol_rark.eval -- evaluation function

As you can see, the first argument is the name of the unit, the second is a table of coordinates of arbitrary length.

Goals and targets

When deciding what move to do next, the AI uses targets(markers on the map, pointing to villages, units, locations, etc). Targets are produced by goal objects. There are multiple predefined goal objects of different types in the C++ implementation, but now it is possible to define goal objects in Lua.

[goal]
	name=lua_goal
	value=6
	engine=lua
	code = <<
		local t = {
	 	    t[1] = {value=2.3, type=3, loc={x=5, y=6} }
	 	    t[2] = {value=2.4, type=4, loc={x=4, y=16} }
 		}
 		return t
 	>>
[/goal]

As you can see, the return value must be a table containing 0 or more targets. Each target must contain the three fields: "loc", "type", "value". This code will then be parsed by the Lua engine and the targets will be available to use to any engine desired. To get the targets inside Lua, a simple

local tg = ai.get_targets() 

must be called. tg will contain a table of the same format, as one described in the goal definition code upper.


Persistence

If you need to store some data between save/load routines, you probably need a place to store the data. For this purpose, a field named "data" is automatically added to the return value of your engine code. The save routine will find this field, convert it to a config and store its content in readable format. When the scenario gets loaded back, the engine code will inject the data back in the AI context. All other data will be lost. Note that all content of "data" needs to be in WML table format, otherwise it will not be saved.


Debug access to the AI tree

wesnoth.debug_ai(side) 

-- has been added. The function only works in debug mode and returns a table containing the component tree of the active AI for a side, the engine functions and the accessor to the ai.* table of the LuaAI Also allows the user to execute stages and evaluate/execute candidate actions(eval and exec can be run independently).

Structure of the table(example):

{
    stage_hello = function: 0x6dc24c0,
    ai = #the ai table,
    data = {
               },
    do_moves = function: 0x6dc2590,
    candidate_action_evaluation_hello = function: 0x6dc2560,
    candidate_action_evaluation_hello2 = function: 0x6dc2640,
    components = {
                         id = "",
                         stage = {
                                         another_stage = {
                                                                 name = "another_stage",
                                                                 id = "",
                                                                 exec = function: 0x17cd3bb,
                                                                 engine = "lua",
                                                                 stg_ptr = "userdata: 0x7c5a8d0"
                                                             },
                                         testing_ai_default::candidate_action_evaluation_loop = {
                                                                                                         name = "testing_ai_default::candidate_action_evaluation_loop",
                                                                                                       candidate_action = {
                                                                                                                                  external = {
                                                                                                                                                     name = "external",
                                                                                                                                                     id = "",
                                                                                                                                                     exec = function: 0x17cd2f3,
                                                                                                                                                     engine = "lua",
                                                                                                                                                     ca_ptr = "userdata: 0x6fb3600"
                                                                                                                                                 },
                                                                                                                                  second = {
                                                                                                                                                   name = "second",
                                                                                                                                                   id = "",
                                                                                                                                                   exec = function: 0x17cd2f3,
                                                                                                                                                   engine = "lua",
                                                                                                                                                   ca_ptr = "userdata: 0x6fb2f50"
                                                                                                                                               }
                                                                                                                              },
                                                                                                       id = "ca_loop",
                                                                                                       exec = function: 0x17cd3bb,
                                                                                                       engine = "",
                                                                                                       stg_ptr = "userdata: 0x6fb2728"
                                                                                                   }
                                    },
                        engine = "",
                        name = ""
                    },
   candidate_action_execution_hello2 = function: 0x6dc2670,
   candidate_action_execution_hello = function: 0x6dc2530

}

The fields described as " name = function: 0xXXXXXXXX" are functions and can be called to using the usual function call syntax of Lua.

wesnoth.debug_ai(2).ai -- will return the AI table of the Lua AI context.
wesnoth.debug_ai(2).stage[another_stage].exec() -- will execute the stage.
wesnoth.debug_ai(2).ai.get_aggression() -- will the return the current value of the aggression aspect of the AI

Therefore, we have up-to-date access to the whole AI, including the data segment.

NB!: the back-end of this function will be refactored quite drastically and that may involve usage syntax changes. This shouldn't be a big problem, since this function is only used for debugging and won't work in non-debug mode. If something suddenly stops working for you, come back to this page and watch the updates.