9. Act on changing state

To keep mining without restarting the spell for each order, check the golem and ore stock repeatedly. Request another job only when the workshop needs it.

Check again with OnTick

OnStart runs at startup. The game calls OnTick periodically while the script runs. A handler called at a particular time like this is an event handler.

Put the rule "order when the golem is free and stock is below the target" inside OnTick. Each call reads the current state, so the script can skip orders while the golem is mining.

Combine two conditions

A && B is true only when both A and B are true. This example checks that the golem is free and total ore is below 100.

ArcaneScript
public class Program : ArcaneProgram
{
    public void OnTick()
    {
        var golem = Workshop.Golems[0];
        if (golem.IsIdle && Workshop.Resources[ResourceKind.Ore].Total < 100)
        {
            var result = golem.Mine(Mineral.Ore, 20);
            if (!result.Ok)
            {
                Workshop.Log.Write("Mining was not accepted.");
            }
        }
    }
}

The ! in !result.Ok reverses true and false. Here it makes the log run when the request was not accepted.

State when checkedAction on this call
Free, with 0 oreRequest 20 ore
Mining, with less than 100 oreMake no request
Free, with at least 100 oreMake no request

100 is a threshold checked before ordering. If you own 90 ore when you order 20, the completed job can bring it to 110.

Stop the script

Stop the script when you finish observing it. This stops new automatic requests. Accepted jobs continue while you are online.

Resuming after rejoining uses another event, OnRestored. Keep values between calls lists the events. For now follow how OnTick reads the current state on each call.

Exercise

Change the spell to order when total ore is below 60. Will it order if stock is exactly 60 and the golem is free?

Show example solutionHide example solution

Change Total < 100 to Total < 60. At exactly 60, the condition 60 < 60 is false, so the autonomous spell makes no request.