State machines, one click at a time
A hands-on introduction to hsm (Hierarchical State Machine), the library for Defold and TypeScript that ships with this toolchain. The diagrams run the real hsm in your browser, and only the Defold calls are imitated.
1. Four words to learn
A state machine is a way to write down how a thing behaves: the modes it can be in, called states, and what moves it from one to the next, called events. A state machine library such as hsm then does the rest: it makes every move follow the rules you set.
Each of those rules is a transition, and the data a machine carries along is its context. Here are all four words, for a machine that is asleep until something pokes it.
| Word | Meaning | Example |
|---|---|---|
| State | A mode the thing can be in. A state it is in right now is active. | asleep, awake |
| Event | Something that happens. You send it to the machine. | a poke: POKE |
| Transition | A rule: in this state, when this event happens, go to that state. | asleep + POKE goes to awake |
Context (ctx) | Your own data that the machine carries and can change. | how many times it woke up |
Try it
- A platform waits at the bottom, rides up when you step on it, and rides back down three seconds later. Name its states and its events.
Answer
- States:
waitingandraised. Events: you step on it, and three seconds pass. Time running out counts as something that happens. Lesson 8 shows how a machine keeps time.
2. Why bother?
You could keep track of a robot buddy with a few true/false variables, called flags.
Say the buddy can be awake, can follow you, and can rest when it gets tired. That is one flag for each:
let isAwake = false;
let isFollowing = false;
let isResting = false;
export function poke(): void {
isAwake = !isAwake;
}
export function seePlayer(): void {
if (isAwake) {
isFollowing = true;
}
}
export function runOutOfEnergy(): void {
isAwake = false;
isResting = true;
}It looks fine. But walk up to the buddy so that it follows you, then poke it to sleep. poke turns isAwake off and leaves isFollowing alone, so your buddy is now asleep and following you at the same time.
Three flags can be set eight different ways, and only four of them make sense: asleep, awake, following and resting. The other four are bugs like this one, each waiting for the right order of events, and nothing in the code keeps you away from them.
A hierarchical state machine does that by arranging its states as a hierarchy. Here is part of the tree you'll build for the buddy:
asleep
awake
├─ wander
└─ follow
restingThe buddy is always somewhere in this tree, and two rules say where it can be:
- Side by side means one or the other.
asleep,awakeandrestingsit side by side, so the buddy is in exactly one of them. The same goes forwanderandfollow: an awake buddy does one or the other. - Inside means both.
followsits insideawake, so a following buddy is awake too. When the buddy leavesawake, it leavesfollowwith it.
Look for a buddy that is asleep and following: the tree has no place for it. And the buddy moves from one state to another only by the rules you wrote down, so no order of events can land it anywhere else.
Try it
- The buddy runs out of energy while it follows you. Which flags are true afterward?
- You add a fourth flag,
isWaking. How many ways can four flags be set?
Answer
isFollowingandisResting: a buddy that rests and follows at once.runOutOfEnergyforgot one flag, and nothing warned you.- Sixteen. Every new flag doubles the count, and almost all of the new ones make no sense.
3. Your first machine
Now build the buddy. Start small: it sleeps until you poke it, and it counts how often it wakes.
Make a file named buddy-machine.ts:
import { defineMachine } from "@defold-typescript/types/hsm";
interface BuddyCtx {
wakes: number;
}
type BuddyEvent = { type: "POKE" };
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent>()({
initial: "/asleep",
states: {
asleep: {
on: { POKE: "/awake" },
},
awake: {
enter: (ctx) => {
ctx.wakes += 1;
},
on: { POKE: "/asleep" },
},
},
});
const buddy = buddyMachine.start({ wakes: 0 });
buddy.send({ type: "POKE" });
print(buddy.path);All four words are in there:
interface BuddyCtxis the context: the data the buddy carries.type BuddyEventlists every event the buddy understands. There is one so far.statesholds one block per state, andinitialsays which one to start in.on: { POKE: "/awake" }is a transition. Read it as "on aPOKE, go to/awake".enteris a function the machine calls each time the buddy arrives inawake. Here it counts the wake-ups.
Wherever you point at a state, you write its path: a /, then its name, like "/awake". It works like a file path, and the next lesson shows why that matters.
Using the machine
The last three lines put the buddy to work:
buddyMachine.start({ wakes: 0 })makes a running buddy and hands it its starting data.buddy.send({ type: "POKE" })sends it an event.buddy.pathis the state it's in now. Here it prints/awake.
You define the machine once and start it to get a running copy. Then you send events and read path to see where it is.
Note
Why two sets of parentheses? In defineMachine<BuddyCtx, BuddyEvent>()({ ... }) the first call is where you name your data and event types. The second takes your states, and TypeScript works out the state names from it. It's a TypeScript limitation, so always write it this way.
Try it
- You send the buddy five pokes. What is
ctx.wakesafterward, and why isn't it five? - Add a second
buddy.send({ type: "POKE" })above theprintline. What does it print now?
Answer
- Three.
enterruns when the buddy arrives inawake, and only the first, third and fifth pokes take it there. /asleep. The second poke uses the rule onawake, which goes back to/asleep.
4. States inside states
The buddy can sleep and wake. An awake buddy should do something, though: wander around, and follow you when it sees you.
Is following a third state, next to asleep and awake? You could write it that way. But a poke should put the buddy to sleep whether it wanders or follows, and you'd have to write that rule twice.
So put wander and follow inside awake, like files in a folder.
This is the first live diagram, so here is how to use one:
- A glowing box is a state the buddy is in right now.
- An event's name is a link. Press it to send that event.
- A filled name is an event the buddy takes right now. An underlined one still sends its event, and the log says what became of it.
- Point at a name, and every box that names the same event marks it.
- The drawing shows the buddy in its state. It hops when it takes an event, and shows a question mark at an event nobody takes.
- The log shows each step as it happens.
Wake the buddy with POKE, then press SEE_PLAYER. How many boxes glow now?
Two: follow, and awake around it. Now add them to your file. This is the first change to it, so here is how to read one:
- A line on green is new. Add it.
- A line on red goes away.
- Every other line is already in your file and shows you the place. A
// ...line stands for the lines left out.
type BuddyEvent = { type: "POKE" };
type BuddyEvent =
| { type: "POKE" }
| { type: "SEE_PLAYER" }
| { type: "LOSE_PLAYER" };
// ...
awake: {
initial: "/awake/wander",
enter: (ctx) => {
ctx.wakes += 1;
},
on: { POKE: "/asleep" },
states: {
wander: {
on: { SEE_PLAYER: "/awake/follow" },
},
follow: {
on: { LOSE_PLAYER: "/awake/wander" },
},
},
},
// ...
buddy.send({ type: "POKE" });
print(buddy.path);
print(buddy.matches("/awake")); states: { ... }insideawakeholds its children. A child's path continues its parent's, like a file in a folder:"/awake/follow".initial: "/awake/wander": a state with children must say which one to start in. Enteringawakealways continues intowander.on: { POKE: "/asleep" }didn't move. It's written once, onawake, and it works in both children.buddy.matches("/awake")asks "isawakeactive at all?" It is true in both children, whilebuddy.pathis the innermost state:"/awake/wander".
When the buddy is in follow it is also in awake. Both glow. The two rules from lesson 2 add up to this: one active state at each level.
Who handles the poke?
Put the buddy in follow and press POKE, with an eye on the log. follow has no rule for POKE. What happens to the event?
It climbs up to the parent. awake does have a rule, so the buddy goes to sleep. An event that no state handles is ignored.
Note
What the "h" in hsm means. It stands for hierarchical: states can sit inside other states, forming a tree, like folders. A plain state machine is flat, so every state that shares a rule has to repeat it. In a hierarchical one the parent holds the shared rule once, and its children get it for free.
Try it
- Press
SEE_PLAYERwhile the buddy is asleep. What does the log say? - Follow, poke the buddy to sleep, and poke it awake again. Is it wandering or following?
Answer
- Nobody handles it, so it is ignored, and the buddy shows a question mark.
asleephas no rule forSEE_PLAYERand no parent to ask. - Wandering. Entering
awakestarts at itsinitial, whatever the buddy was doing before. Lesson 15 shows how to change that.
5. Conditions and side effects
Now the buddy wanders and follows. A robot that bumps into things should lose a little energy with each bump, and stop to rest when it runs out.
One event, a bump, now has two possible outcomes. How does the machine pick one?
Two tools handle "it depends":
whenis a yes/no question. If the answer is no, that rule is skipped.runis code that runs when a rule is used, such as changing your data.
Wake the buddy and give it a small bump: press BUMP, and pick BUMP (cost 1) from the menu that opens. Which rule lights up, what does the buddy do, and what happens to ctx.energy?
First the buddy needs a battery, and two new events:
interface BuddyCtx {
wakes: number;
energy: number;
}
type BuddyEvent =
| { type: "POKE" }
| { type: "BUMP"; cost: number }
| { type: "RECHARGE" }
| { type: "SEE_PLAYER" }
| { type: "LOSE_PLAYER" };
// ...
const buddy = buddyMachine.start({ wakes: 0 });
const buddy = buddyMachine.start({ wakes: 0, energy: 3 });
buddy.send({ type: "POKE" });energy: numberjoins the context, andstarthands every buddy a full battery of 3.{ type: "BUMP"; cost: number }: an event can carry data. A bump says how much energy it costs.
Then the rules:
awake: {
initial: "/awake/wander",
enter: (ctx) => {
ctx.wakes += 1;
},
on: { POKE: "/asleep" },
on: {
POKE: "/asleep",
BUMP: [
{
to: "/resting",
when: (ctx, event) => ctx.energy <= event.cost,
run: (ctx) => {
ctx.energy = 0;
},
},
{
run: (ctx, event) => {
ctx.energy -= event.cost;
},
},
],
},
states: {
// ...
},
},
resting: {
on: {
RECHARGE: {
to: "/awake",
run: (ctx) => {
ctx.energy = 3;
},
},
},
},
},
});BUMP: [ ... ]is a list of rules. The machine tries them from top to bottom and uses the first one that passes, like an if/else.when: (ctx, event) => ctx.energy <= event.costasks: does this bump use up the energy that's left? If so, the buddy goes to/restingandrunempties the battery.- The second rule has no
when, so it always passes. It has notoeither, so the buddy stays where it is: nothing exits or enters, and onlyrunruns. restingis a new state next toasleepandawake.RECHARGEfills the battery and wakes the buddy.
A rule can be written three ways, and you have now seen all of them:
| Write a rule as | Example | Use it when |
|---|---|---|
| A state path | POKE: "/asleep" | You only need to move. Most rules. |
| An object | { to, when, run } | You need a condition or some code. Every field is optional. |
| A list of objects | [ {...}, {...} ] | You need if / else-if choices. |
Try it
- Give an awake buddy two small bumps, then a big one. Where is it, and what is
ctx.energy? - Bump the buddy while it's asleep. Does it lose energy?
- The buddy is in
followwhen the big bump lands. Which state handles it?
Answer
- In
/resting, with 0. After two small bumps the battery holds 1, a bump of cost 3 uses up what's left, and the first rule'swhensays yes. - No.
BUMPis written onawake, and a sleeping buddy isn't inawake, so the event is ignored. awake.followhas no rule forBUMP, so the event climbs to its parent, like the poke in lesson 4.
6. enter, exit, and the order of things
The buddy rests when it's tired, but in the game nothing shows it. Let's give it a light that is on while it's awake.
You know the hook that turns it on: enter runs when the buddy arrives in awake. But where do you turn it off? The buddy can leave awake by falling asleep or by getting tired, and a third way may come along tomorrow.
One hook covers them all: exit runs when the buddy leaves the state, wherever it goes next.
interface BuddyCtx {
light: Url;
wakes: number;
energy: number;
}
// ...
awake: {
initial: "/awake/wander",
enter: (ctx) => {
ctx.wakes += 1;
msg.post(ctx.light, "enable");
},
exit: (ctx) => msg.post(ctx.light, "disable"),
on: {
// ...
follow: {
on: { LOSE_PLAYER: "/awake/wander" },
on: { LOSE_PLAYER: "/awake/wander", SEE_PLAYER: "/awake/follow" },
},
// ...
const buddy = buddyMachine.start({ wakes: 0, energy: 3 });
const buddy = buddyMachine.start({ light: msg.url("#light"), wakes: 0, energy: 3 });
buddy.send({ type: "POKE" });light: Urlis the address of the buddy's light, a sprite on its game object, andmsg.url("#light")builds that address. It only means something inside a running game, so don't run the file yet. The next lesson moves thestartline to where it belongs.msg.post(ctx.light, "enable")shows the light on the way intoawake, and theexithook hides it on the way out.SEE_PLAYER: "/awake/follow"is a rule onfollowthat namesfollowitself. More about that one in a moment.
The order of a transition
Every transition does three steps, always in this order:
- Exit the old states, innermost first.
- Run the rule's
run. - Enter the new states, outermost first, continuing into each initial child.
You can watch all three in the lesson 5 diagram. Tire the buddy out, press RECHARGE and read the log: resting exits, the rule's run fills the battery, then awake is entered, then wander.
Leaving and coming back
A state you aren't leaving stays put. Going from /awake/follow to /awake/wander never exits awake, so the light stays on and wakes isn't counted again.
What about the new rule, the one where follow points at follow? That is the exception: a rule that names its own state leaves it and comes back. follow exits and enters again, and awake around it never notices.
Why would you want that? Because entering a state starts it fresh. In lesson 8 follow gets a timer, and seeing you again will start it over.
Pointing at the right state
Every target is the full path from the top, wherever the rule is written. A rule inside /awake/follow points at its sibling the same way a rule anywhere else would.
From /awake/follow, write | Means | Goes to |
|---|---|---|
"/awake/wander" | A full path | /awake/wander |
"/resting" | A full path | /resting |
"wander", "./wander" or "../resting" | Not a path: no leading / | Nothing: the machine refuses to start |
There are no shortcuts relative to the current state. A missing / or a misspelled path is usually caught by TypeScript as a compile error, before your game runs.
Try it
- The buddy is in
/awake/followand takes a bump that uses up its energy. What runs, and in what order? - The buddy follows you and sees you again. Does the light blink? Does
wakesgo up?
Answer
followexits first (it has no hook). Thenawakeexits, and its hook hides the light. Then the rule'srunempties the battery. Last,restingis entered.- No, and no. Only
followexits and enters.awakewas never left, so neither of its hooks runs.
7. Putting it in a Defold game
So far the buddy has lived at the bottom of its own file, started by a few lines that run once. A game has game objects, though, and maybe five buddies in one level.
So where does the machine go, and who starts it?
Step 1. buddy-machine.ts describes the machine and starts nothing. Take the lines at the bottom out:
},
},
});
const buddy = buddyMachine.start({ light: msg.url("#light"), wakes: 0, energy: 3 });
buddy.send({ type: "POKE" });
print(buddy.path);
print(buddy.matches("/awake")); What is left is a plain module. It compiles to .lua, and any script can import it.
Step 2. Make a script for the buddy's game object, next to that file:
import { defineScript } from "@defold-typescript/types";
import { buddyMachine } from "./buddy-machine";
const TOUCH = hash("touch");
export default defineScript({
init() {
msg.post(".", "acquire_input_focus");
msg.post("#light", "disable");
return {
buddy: buddyMachine.start({ light: msg.url("#light"), wakes: 0, energy: 3 }),
};
},
on_input(self, action_id, action) {
if (action_id === TOUCH && action.pressed) {
self.buddy.send({ type: "POKE" });
}
},
final(self) {
self.buddy.stop();
},
});initruns once for every game object that uses the script. It starts a machine for this buddy and keeps it onself.msg.post("#light", "disable"): the buddy starts asleep, so its light starts hidden.on_inputturns a click or a tap into aPOKE. Postingacquire_input_focusasks Defold to send input here at all.finalruns when the object is deleted.stop()exits every active state, so theirexithooks get to tidy up. Lesson 11 comes back to it.
Nothing in the game sends the other events yet. The diagrams do the sending, and lesson 10 lets Defold report when the player comes near.
Warning
Create machines in init. A machine started at the top of a script file is shared by every object that runs the script, so all your buddies would wake up together.
The buddy's code so far
import { defineMachine } from "@defold-typescript/types/hsm";
interface BuddyCtx {
light: Url;
wakes: number;
energy: number;
}
type BuddyEvent =
| { type: "POKE" }
| { type: "BUMP"; cost: number }
| { type: "RECHARGE" }
| { type: "SEE_PLAYER" }
| { type: "LOSE_PLAYER" };
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent>()({
initial: "/asleep",
states: {
asleep: {
on: { POKE: "/awake" },
},
awake: {
initial: "/awake/wander",
enter: (ctx) => {
ctx.wakes += 1;
msg.post(ctx.light, "enable");
},
exit: (ctx) => msg.post(ctx.light, "disable"),
on: {
POKE: "/asleep",
BUMP: [
{
to: "/resting",
when: (ctx, event) => ctx.energy <= event.cost,
run: (ctx) => {
ctx.energy = 0;
},
},
{
run: (ctx, event) => {
ctx.energy -= event.cost;
},
},
],
},
states: {
wander: {
on: { SEE_PLAYER: "/awake/follow" },
},
follow: {
on: { LOSE_PLAYER: "/awake/wander", SEE_PLAYER: "/awake/follow" },
},
},
},
resting: {
on: {
RECHARGE: {
to: "/awake",
run: (ctx) => {
ctx.energy = 3;
},
},
},
},
},
});
import { defineScript } from "@defold-typescript/types";
import { buddyMachine } from "./buddy-machine";
const TOUCH = hash("touch");
export default defineScript({
init() {
msg.post(".", "acquire_input_focus");
msg.post("#light", "disable");
return {
buddy: buddyMachine.start({ light: msg.url("#light"), wakes: 0, energy: 3 }),
};
},
on_input(self, action_id, action) {
if (action_id === TOUCH && action.pressed) {
self.buddy.send({ type: "POKE" });
}
},
final(self) {
self.buddy.stop();
},
});Try it
- You put three buddies in a level. How many machines are running, and how many times is
buddyMachinedefined? - Why can't
buddy-machine.tsexport the script as well?
Answer
- Three machines, one definition.
defineMachinedescribes a buddy once, and eachstartininitmakes a running copy with its own state and its own data. - A file that exports
defineScriptbecomes a script component, and nothing else can import it. The machine stays in a plain module so any script can use it.
8. Time and every-frame checks
The buddy is in a game now, and a game runs frame by frame. So far the buddy only moves when something pokes it. What if it should get bored of following after a few seconds, or nod off when nobody plays with it?
It needs a sense of time, and the machine can't feel time on its own. Somebody has to tell it how much has passed. That somebody is your script, once per frame:
};
},
update(self, dt) {
self.buddy.update(dt);
},
on_input(self, action_id, action) {Defold calls the script's update every frame with dt, the seconds since the last one, and the script passes it on. That one call gives every state two new keys:
afteris a timer: "after this many seconds in this state, go there."updateis a function that runs every frame while the state is active. Return a state path to move there, orundefinedto stay.
Wake the buddy, press SEE_PLAYER, and then keep your hands off. What does the bar on follow do when it fills up?
exit: (ctx) => msg.post(ctx.light, "disable"),
after: { 30: "/asleep" },
on: {
// ...
follow: {
after: { 4: "/awake/wander" },
on: { LOSE_PLAYER: "/awake/wander", SEE_PLAYER: "/awake/follow" },
},
},
},
resting: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/awake" : undefined;
},
on: {
RECHARGE: {after: { 4: "/awake/wander" }: four seconds after it starts to follow, the buddy gives up and wanders.after: { 30: "/asleep" }onawake: half a minute awake, and it nods off.updateonrestingadds each frame'sdtto the battery, andMath.minkeeps it from going past 3. Once it's full the hook returns"/awake"and the buddy gets up. Until then it returnsundefined, and the buddy keeps resting.
Four rules about time:
- Each state's timer starts at zero every time the state is entered.
- Timers count the
dtyou pass in. If you stop callingupdate, time stands still. Pause the diagram to see it. updatehooks get the first chance each frame. Timers only fire if none of them moved the machine.- At most one timer moves the machine in one
updatecall.
A parent's timer keeps running
Look at the two bars while the buddy follows you: one on follow, one on awake. Press SEE_PLAYER again when follow's bar is nearly full. Which bar starts over?
Only follow's. That is the rule from lesson 6 at work: SEE_PLAYER names follow's own state, so follow exits, enters again, and its clock starts from zero.
awake was never left. Its clock runs straight through, whatever its children do. "Follow for four seconds at a time, and sleep after thirty in total" takes two short lines.
Try it
- The buddy follows you, and you press
SEE_PLAYERevery three seconds. Does it ever wander? Does it ever fall asleep? - Give an awake buddy a bump of cost 3, then pause time. Does the battery fill?
Answer
- It never wanders, because
follow's four seconds start over each time. It does fall asleep:awake's thirty seconds keep counting through every restart. - No. The
updatehook only runs whenupdate(dt)is called, and a paused clock calls nothing.RECHARGEstill works, because it is an event.
9. Waiting for things to finish
A poke flips the buddy from asleep to awake in an instant, and its light snaps on. A sleepy robot should wake up slowly: fade the light in over a second, and only then count as awake.
So waking up is now a job that takes a while and then finishes. Who tells the machine that the fade is done? You could guess with a one-second timer. Better to let the animation say so itself.
Start work like that in a state's task. The task receives a finish function, and you call it with an event when the work is done.
This diagram runs at half speed, so you can catch the fade. Poke the buddy and watch the light: it glows dimly while waking is active. What happens at the end of the fade?
type BuddyEvent =
| { type: "POKE" }
| { type: "WAKING_DONE" }
| { type: "BUMP"; cost: number }
// ...
asleep: {
on: { POKE: "/awake" },
on: { POKE: "/waking" },
},
waking: {
task: (ctx, finish) => {
go.set(ctx.light, "tint.w", 0);
msg.post(ctx.light, "enable");
go.animate(ctx.light, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 1, 0, () => {
finish({ type: "WAKING_DONE" });
});
},
exit: (ctx) => {
go.cancel_animations(ctx.light, "tint.w");
msg.post(ctx.light, "disable");
},
on: { WAKING_DONE: "/awake", POKE: "/asleep" },
},
awake: {on: { POKE: "/waking" }: a poke no longer wakes the buddy outright. It starts the wake-up.taskruns whenwakingis entered. It shows the light fully see-through and asks Defold to fade it in over one second. When the fade ends, Defold calls the function at the end, andfinishhands the machine aWAKING_DONEevent.exitstops what the task started: it cancels the fade and hides the light. If the buddy goes on toawake,awake's ownentershows the light again at once.on: { WAKING_DONE: "/awake", POKE: "/asleep" }: the end of the fade wakes the buddy, and a poke during the fade sends it back to sleep.
Why the cleanup matters
Poke the buddy, and poke it again halfway through the fade. The light goes off, as it should.
Now switch off "Exit cleans up" and do the same. The fade keeps running on a buddy that is already asleep, so the light ends up fully on while the machine says asleep. That's the bug the cleanup in exit prevents.
One more thing is in the log. When the leftover fade ends, it still calls finish, and the machine ignores it, because waking was already left. A late finish can never wake a buddy that has moved on.
Warning
Always clean up in exit. exit runs however a state ends, including when the machine is stopped, so it's a reliable place to cancel animations, timers and requests.
Try it
- You poke the buddy, change your mind, and poke it again during the fade. Does
ctx.wakesgo up? - With "Exit cleans up" switched off, the late
finishis ignored. So why is the light still wrong?
Answer
- No.
wakesis counted inawake'senter, and the buddy never got there. - Ignoring the event protects the machine, not the sprite. The animation itself kept running, and only your
exithook can stop it.
10. Messages from Defold
Until now SEE_PLAYER and LOSE_PLAYER were events you made up, and nothing in the game sends them. Defold already knows when the player comes near. Give the buddy a trigger collision object, and Defold posts it a trigger_response message each time something walks in or out.
Do you have to turn that message into a SEE_PLAYER by hand? No. A Defold message can be an event just as it is.
import { defineMachine } from "@defold-typescript/types/hsm";
import { type MessageEvent, messageEvents } from "@defold-typescript/types/hsm/defold";
// ...
| { type: "RECHARGE" }
| { type: "SEE_PLAYER" }
| { type: "LOSE_PLAYER" };
| MessageEvent<"trigger_response">;
// ...
wander: {
on: { SEE_PLAYER: "/awake/follow" },
on: {
trigger_response: {
to: "/awake/follow",
when: (_ctx, event) => event.enter,
},
},
},
follow: {
after: { 4: "/awake/wander" },
on: { LOSE_PLAYER: "/awake/wander", SEE_PLAYER: "/awake/follow" },
on: {
trigger_response: [
{ to: "/awake/follow", when: (_ctx, event) => event.enter },
{ to: "/awake/wander" },
],
},
},
// ...
},
});
export const buddyEvents = messageEvents(["trigger_response"]); MessageEvent<"trigger_response">is Defold's message as a machine event. Itstypeis the message name, and it carries the message's fields:event.enteristruewhen the player walked in andfalsewhen they walked out.- In
wander, thewhenskips the rule when the player walks out, so only walking in starts a follow. The rule doesn't read the context, and the underscore in_ctxsays so. - In
follow, the list reads like an if/else again: walked in, follow afresh. Otherwise, back to wandering. messageEvents(["trigger_response"])builds the translator the script is about to use. Build it once, at the top of the module.
The script hands its messages over:
import { defineScript } from "@defold-typescript/types";
import { buddyMachine } from "./buddy-machine";
import { buddyEvents, buddyMachine } from "./buddy-machine";
// ...
self.buddy.send({ type: "POKE" });
}
},
on_message(self, message_id, message, sender) {
const event = buddyEvents.toEvent(message_id, message, sender);
if (event !== undefined) {
self.buddy.send(event);
}
},
final(self) {buddyEvents.toEvent(...)turns a message you listed into a typed event. For any other message it returnsundefined, which is why the script checks before it sends.
For the full rules, see the message bridge.
Try it
- The player walks out of the trigger while the buddy wanders. What happens?
- The buddy is asleep and the player walks in. Does it wake up?
- Your game also posts a
collision_responseto the buddy. Does the machine ever see it?
Answer
- Nothing. The only rule in
wanderhas awhenthat says no, there is no second rule to try, and the event is ignored. - No. Only the children of
awakehave a rule fortrigger_response. A poke is still the way to wake it. - No.
collision_responseisn't in the list given tomessageEvents, sotoEventreturnsundefinedand the script sends nothing.
11. One thing at a time
A new buddy starts asleep, and somebody has to poke it. Wouldn't it be nicer if it woke itself up the first time?
The buddy knows whether it has ever been awake: that's ctx.wakes. So asleep could check the number on the way in and send itself a poke.
But asleep's enter hook runs in the middle of a transition. Can a machine take a new event while it's still busy with the last one?
It can't, and it doesn't have to. An event sent from inside a hook or a run waits in a queue until the current transition, every exit and enter included, has finished. Then it gets its turn.
Press start({ wakes: 0 }) and read the log from the top. Can you find the line where the poke has to wait?
asleep: {
enter: (ctx, machine) => {
if (ctx.wakes === 0) machine.send({ type: "POKE" });
},
on: { POKE: "/waking" },
},enter: (ctx, machine) => ...: every hook gets the running machine as its last parameter, so it can send events to it.if (ctx.wakes === 0): only a buddy that has never been awake pokes itself.
Back to the log. enter /asleep comes first, then POKE queued, and only after that does asleep exit. Every queued event is handled before the outer call returns, so by the time start() hands you the buddy it is already in /waking.
From there the fade runs as it did in lesson 9, and the buddy ends up awake without anyone poking it.
What stop leaves behind
Now press "stop()". That is what the script's final does when the buddy's game object is deleted.
Every active state exits, innermost first, so the exit hooks run and the light goes off. After that path is undefined, and events do nothing.
Try it
- Press
start({ wakes: 1 }). What is different in the log? - Pause time, start with
wakesat 0 again, then poke the buddy while it is waking. Where does it end up, and why? - After "stop()", press
POKE. What does the log say?
Answer
- No poke is queued. This buddy has been awake before, so it stays in
/asleepuntil you poke it. - In
/wakingagain. Your poke sends it to/asleep, whoseenterfindswakesstill at 0 (the buddy never reachedawake) and queues another poke. - That
POKEis ignored because the machine is stopped. A stopped machine never starts again. To get a buddy back,starta new one.
12. The machine's own data
Look at what the script hands to start: a light, wakes: 0 and energy: 3.
The light makes sense. Only the script knows which sprite it is. But the two numbers? Only the machine ever uses them, and every script that starts a buddy has to get them right.
The machine can set up its own data, with one key: privateCtx.
interface BuddyCtx {
light: Url;
wakes: number;
energy: number;
}
// ...
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent>()({
privateCtx: () => ({ wakes: 0, energy: 3 }),
initial: "/asleep", return {
buddy: buddyMachine.start({ light: msg.url("#light"), wakes: 0, energy: 3 }),
buddy: buddyMachine.start({ light: msg.url("#light") }),
};privateCtxis a function that builds the machine's own fields, fresh for every buddy that starts.BuddyCtxkeeps only what a script hands in: the light.starttakes the light alone now, andself.buddy.ctxshows the light alone.
And the hooks? Not one of them changed. They still read ctx.wakes and ctx.energy, as before.
Note
Hidden, not locked. The fields are hidden by type only: at run time they sit on the same ctx as the light. A machine with no data of its own leaves privateCtx out. Private fields with privateCtx has the rules.
The buddy's code so far
import { defineMachine } from "@defold-typescript/types/hsm";
import { type MessageEvent, messageEvents } from "@defold-typescript/types/hsm/defold";
interface BuddyCtx {
light: Url;
}
type BuddyEvent =
| { type: "POKE" }
| { type: "WAKING_DONE" }
| { type: "BUMP"; cost: number }
| { type: "RECHARGE" }
| MessageEvent<"trigger_response">;
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent>()({
privateCtx: () => ({ wakes: 0, energy: 3 }),
initial: "/asleep",
states: {
asleep: {
enter: (ctx, machine) => {
if (ctx.wakes === 0) machine.send({ type: "POKE" });
},
on: { POKE: "/waking" },
},
waking: {
task: (ctx, finish) => {
go.set(ctx.light, "tint.w", 0);
msg.post(ctx.light, "enable");
go.animate(ctx.light, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 1, 0, () => {
finish({ type: "WAKING_DONE" });
});
},
exit: (ctx) => {
go.cancel_animations(ctx.light, "tint.w");
msg.post(ctx.light, "disable");
},
on: { WAKING_DONE: "/awake", POKE: "/asleep" },
},
awake: {
initial: "/awake/wander",
enter: (ctx) => {
ctx.wakes += 1;
msg.post(ctx.light, "enable");
},
exit: (ctx) => msg.post(ctx.light, "disable"),
after: { 30: "/asleep" },
on: {
POKE: "/asleep",
BUMP: [
{
to: "/resting",
when: (ctx, event) => ctx.energy <= event.cost,
run: (ctx) => {
ctx.energy = 0;
},
},
{
run: (ctx, event) => {
ctx.energy -= event.cost;
},
},
],
},
states: {
wander: {
on: {
trigger_response: {
to: "/awake/follow",
when: (_ctx, event) => event.enter,
},
},
},
follow: {
after: { 4: "/awake/wander" },
on: {
trigger_response: [
{ to: "/awake/follow", when: (_ctx, event) => event.enter },
{ to: "/awake/wander" },
],
},
},
},
},
resting: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/awake" : undefined;
},
on: {
RECHARGE: {
to: "/awake",
run: (ctx) => {
ctx.energy = 3;
},
},
},
},
},
});
export const buddyEvents = messageEvents(["trigger_response"]);import { defineScript } from "@defold-typescript/types";
import { buddyEvents, buddyMachine } from "./buddy-machine";
const TOUCH = hash("touch");
export default defineScript({
init() {
msg.post(".", "acquire_input_focus");
msg.post("#light", "disable");
return {
buddy: buddyMachine.start({ light: msg.url("#light") }),
};
},
update(self, dt) {
self.buddy.update(dt);
},
on_input(self, action_id, action) {
if (action_id === TOUCH && action.pressed) {
self.buddy.send({ type: "POKE" });
}
},
on_message(self, message_id, message, sender) {
const event = buddyEvents.toEvent(message_id, message, sender);
if (event !== undefined) {
self.buddy.send(event);
}
},
final(self) {
self.buddy.stop();
},
});Try it
- Two buddies start one after the other, and the first one wakes up twice. What is the second one's
wakes? - Each script should pick a name for its buddy. Does
namego inBuddyCtxor inprivateCtx?
Answer
- Zero.
privateCtxruns once for everystart, so each buddy gets numbers of its own. - In
BuddyCtx. The script hands it in, like the light.privateCtxis for what only the machine uses.
13. Watch it run
The diagrams have shown you every move the buddy makes. They were drawn for this page, though, and your buddy has outgrown them: it has a script, timers, a fade and messages now.
You can watch your own file run like that. The toolchain has a viewer named view. Point it at the file with the machine in it:
bunx @defold-typescript/cli view src/buddy-machine.tsIt prints an address. Open that in your browser, and there is your code, with the buddy's current state tinted.
| On the page | What it does |
|---|---|
| Start | Starts a buddy. Type its starting data first: { light: "#light" }. |
| The event buttons | One for each event the buddy can take right now. An event with data, like BUMP, reads it from the payload field: { cost: 1 }. |
| Play and Step | Play lets time run. Step moves it forward by one dt. |
| The ctx panel | Shows the buddy's data, wakes and energy included. |
| The log | Lists every event, every move and every Defold call. |
There is no Defold in your browser, so calls like msg.post and go.animate are written to the log and do nothing more. Who ends the fade, then? You do: press WAKING_DONE, and you are playing the engine's part.
In the real game
A browser is fine for trying things out. What about the buddy in the running game? One more import lets it report on itself:
import { defineScript } from "@defold-typescript/types";
import { inspect } from "@defold-typescript/types/hsm/debug";
import { buddyEvents, buddyMachine } from "./buddy-machine";
// ...
msg.post("#light", "disable");
return {
buddy: buddyMachine.start({ light: msg.url("#light") }),
};
const buddy = buddyMachine.start({ light: msg.url("#light") });
return { buddy, inspector: inspect(buddy, "buddy") };
},
update(self, dt) {
self.buddy.update(dt);
self.inspector.draw(".");
},inspect(buddy, "buddy")prints a line to the console for every move the buddy makes: where it was, where it went, and why.inspectoris whatinspecthands back. The script keeps it onself, next to the buddy.self.inspector.draw(".")writes the buddy's current state above its game object, every frame. The"."means "this object".
The console then reads something like this:
hsm buddy frame 0: inspecting [/waking]
hsm buddy frame 60: /waking -> /awake/wander (WAKING_DONE: /waking, 0) [/awake/wander]Both calls do nothing in a release build, so you can leave them in. Debug a machine explains every part of a line, and view has a page of its own.
Some of the lessons ahead still have a diagram. Every "Try it" is yours to run in view.
Try it
- Start the buddy in
viewand keep your hands off. Which state is tinted, and why doesn't it move on? - Press
WAKING_DONE, then Play, and sendBUMPwith{ cost: 3 }. What doesenergydo in the ctx panel?
Answer
/waking. The buddy poked itself on the way intoasleep, as in lesson 11, and now it waits for a fade that only the log knows about. PressWAKING_DONEto finish it.- It drops to 0 and then climbs back to 3 over three seconds, while
resting'supdatehook adds each frame'sdt. Then the hook returns"/awake", and the buddy is up again.
14. Decide at once
Now that you can watch, try something. Wake the buddy, send BUMP with { cost: 2.5 }, and poke it to sleep. Then poke it awake again.
It gets up with half a unit left in its battery, and the first small bump sends it straight to rest. Shouldn't a buddy that low on energy skip getting up and go rest instead?
So waking has to end in a decision: rest, or get up. Which state makes it? waking is there for the fade. In awake the light is already on, and that's too late.
Give the decision a state of its own. It needs no event and no timer, because it never waits. A state can hold rules that are tried the moment it is entered, and the key for them is always.
on: { WAKING_DONE: "/awake", POKE: "/asleep" },
on: { WAKING_DONE: "/checkup", POKE: "/asleep" },
},
checkup: {
always: [
{ to: "/resting", when: (ctx) => ctx.energy < 1 },
{
to: "/awake",
run: (ctx) => {
ctx.wakes += 1;
},
},
],
},
awake: {
initial: "/awake/wander",
enter: (ctx) => {
ctx.wakes += 1;
msg.post(ctx.light, "enable");
},
enter: (ctx) => msg.post(ctx.light, "enable"),
exit: (ctx) => msg.post(ctx.light, "disable"),
// ...
resting: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/awake" : undefined;
return ctx.energy >= 3 ? "/checkup" : undefined;
},
on: {
RECHARGE: {
to: "/awake",
to: "/checkup", WAKING_DONE: "/checkup": the end of the fade no longer leads straight toawake. It leads to the new state.always: [ ... ]is a list of rules with no event. The machine tries them as soon ascheckupis entered, top to bottom, and takes the first that passes. Less than 1 in the battery means/resting. Anything else means/awake.runon the second rule counts the wake-up, andawake'senteris back to one line. A rule'srunonly runs when that rule is taken, so a buddy sent off to rest isn't counted."/checkup"shows up twice more, inresting. A rested buddy passes the same check on its way up.
Here is the buddy with its checkup. Give it a bump of cost 2.5, poke it to sleep and poke it again. Which rule lights up when the fade ends?
The buddy never stays in checkup. By the time send returns, it has gone in and out again. So how do you know it was ever there? Read the log: it shows checkup entered and left again in one step.
Note
Checked after a move, not every frame. The machine looks at always when a move has just ended. A number that changes later, in a run or an update hook, goes unnoticed until the next move. To watch a value every frame, return a path from an update hook, as resting does.
For the full rules, see Move on at once with always.
Try it
- In
view, wake the buddy, sendBUMPwith{ cost: 2.5 }, pressPOKEtwice and thenWAKING_DONE. Where does the buddy end up, and what iswakes? - Why does the second rule have no
when?
Answer
- In
/resting, withwakesstill at 1.checkupfinds 0.5 in the battery, so the first rule passes, and therunthat counts belongs to the second rule. - So that one rule always passes. If every rule had a
whenand none of them passed, the buddy would sit incheckupwith nothing to move it on.
15. Remember where you were
The buddy follows you, bumps into a wall and has to rest. A few seconds later it is up again. What is it doing?
Wandering. Entering awake starts at its initial, as you saw in lesson 4. That's a pity, because it was in the middle of following you.
A state can remember which child it was in, and it takes one line: restoreDepth.
awake: {
restoreDepth: 1,
initial: "/awake/wander",
enter: (ctx) => msg.post(ctx.light, "enable"),restoreDepth: 1makesawakeremember which child was active when the buddy left, and go back to that child the next time it is entered.initialstays. The first time the buddy gets up there is nothing to remember yet, so it starts inwander.
Make the buddy follow you, give it a bump of cost 3 and wait. Which child is it in when it gets up?
Why the 1? It says how many levels down to remember. The children of awake have no children of their own, so one level is all there is.
A place, not a moment
What exactly comes back? Only which child. follow is entered afresh: its timer starts from zero, and the buddy follows you for a full four seconds.
It doesn't matter how the buddy left, either. Tired out, poked to sleep, nodded off after thirty seconds: awake remembers the child in every case.
For the full rules, see Resume with history.
Try it
- In
view, wake the buddy and sendtrigger_responsewith{ enter: true }. Then sendBUMPwith{ cost: 3 }and press Play. Which state is the buddy in when it gets up? - Take
restoreDepthout, save, and do the same. What changed? Put the line back afterward. - A brand-new buddy wakes up for the very first time. Which child does it start in?
Answer
/awake/follow. It was following when it ran out of energy, andawakeremembered.- It gets up in
/awake/wander. Without the key, every entry ofawakestarts atinitial. wander. There is nothing to remember yet, soinitialdecides.
16. Something every second
So far the battery only drains when the buddy bumps into something. A real robot uses energy just by being switched on.
How would you take a little energy away every second while the buddy is awake? An after timer fires once per stay. An update hook runs every frame, and you'd have to count the seconds yourself.
There is a key for exactly this: every.
exit: (ctx) => msg.post(ctx.light, "disable"),
after: { 30: "/asleep" },
every: {
1: (_ctx, machine) => machine.send({ type: "BUMP", cost: 1 / 16 }),
},
on: {
POKE: "/asleep",every: { 1: ... }runs its function each time another second has passed whileawakeis active. The first run comes one second after the buddy gets up.machine.send({ type: "BUMP", cost: 1 / 16 }): the buddy gives itself a very small bump. Why send an event, whenctx.energy -= 1 / 16is shorter? Because theBUMPrules from lesson 5 already know what to do when the battery runs out.(_ctx, machine): the function gets the context and the running machine, like a hook. This one only needs the machine.
A sixteenth each second: a full battery lasts 48 seconds of being awake.
Here is the buddy with its drain. Watch the bar on the every 1 s line fill up and start over. What does the log say each time it is full?
A run is not a move
Nothing exits and nothing enters when the function runs. The buddy stays where it is, and awake's clock keeps counting toward its thirty seconds.
And the event it sends? It waits its turn, like the poke in lesson 11.
For the full rules, see Repeat while a state is active.
Try it
- In
view, wake the buddy and press Play. What doesenergyshow after four seconds? - Pause, set
dtto 10 and press Step once. How many sixteenths does the buddy lose? - The buddy is asleep. Does its battery drain?
Answer
- 2.75. Four runs, a sixteenth each.
- One. However long a frame was,
everyruns once in it. A game that stalls for a moment doesn't empty the battery all at once. - No.
everyis written onawake, and it only runs whileawakeis active.
17. Delays that read the context
Look at the delays in your file: 4 seconds, 30 seconds, 1 second. Every one is a number you typed in.
What if a delay should depend on how the buddy is doing? A buddy that has run after you all afternoon should nap longer than a fresh one.
after and every each have a second way of being written, a list, where every entry carries a delay. And a delay can be a function.
Start with the nap:
privateCtx: () => ({ wakes: 0, energy: 3 }),
privateCtx: () => ({ wakes: 0, energy: 3, napSeconds: 2 }),
// ...
follow: {
after: { 4: "/awake/wander" },
after: {
4: {
to: "/awake/wander",
run: (ctx) => {
ctx.napSeconds = Math.min(5, ctx.napSeconds + 1);
},
},
},
on: {
// ...
resting: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/checkup" : undefined;
return undefined;
},
after: [
{
delay: (ctx) => ctx.napSeconds,
to: "/checkup",
when: (ctx) => ctx.energy >= 3,
run: (ctx) => {
ctx.napSeconds = 2;
},
},
],
on: {
RECHARGE: {napSeconds: 2is how long the next nap lasts. Only the machine uses it, so it lives inprivateCtx.4: { to, run }: a timer takes a rule object where it took a path, the way an event does. Whenfollowgives up after four seconds, itsrunmakes the next nap a second longer, up to five.delay: (ctx) => ctx.napSeconds: in the list form the delay sits inside the entry, and here it is a function. The machine calls it whenrestingis entered and waits that long.when: (ctx) => ctx.energy >= 3: a timer can have a condition too. Once the delay has passed, the rule still needs a full battery.
Two smaller things ride along. The nap rule's own run sets napSeconds back to 2, because a buddy that had its whole nap is fresh again. And the update hook of resting now returns undefined every time: it still fills the battery, but getting up is the timer's job.
A timer that waits for its condition
What happens when the two seconds are over and the battery isn't full yet? The timer doesn't give up. The machine asks its when again on every update, until the answer is yes or the buddy leaves the state.
So a nap lasts at least napSeconds, and as long as the battery needs. Whichever takes longer.
Give this buddy a bump of cost 3 and watch the timer line in resting. What does it say between two seconds and three?
When the delay is read
The machine reads a delay function once, each time the state is entered, right after the state's enter hook. That stay keeps its delay, whatever happens to the number meanwhile.
The same goes for every. Let's use it to save power:
after: { 30: "/asleep" },
every: {
1: (_ctx, machine) => machine.send({ type: "BUMP", cost: 1 / 16 }),
},
every: [
{
delay: (ctx) => (ctx.energy < 2 ? 2 : 1),
run: (_ctx, machine) => machine.send({ type: "BUMP", cost: 1 / 16 }),
},
],
on: {
POKE: "/asleep",every: [ ... ]is the list form again: each entry is adelayand therunit repeats.delay: (ctx) => (ctx.energy < 2 ? 2 : 1): a buddy that gets up with less than 2 in its battery takes it easy. It uses energy every two seconds, not every second.
For the full rules, see A delay that reads the context and Rules on a timer.
Try it
- In
view, wake the buddy, sendBUMPwith{ cost: 3 }and press Play. The nap is two seconds long. When does the buddy get up? - Wake a new buddy and let it give up following twice: send
trigger_responsewith{ enter: true }, wait four seconds, and do it again. Then tire it out. How long is this nap? - A buddy gets up with 2.5 in its battery, and ten seconds later it holds less than 2. How often does it use energy now?
Answer
- After three seconds. At two the timer is due, but the battery holds 2 and
whensays no, so the entry glows dimly inviewwhile it waits. A second later the battery is full and the rule is taken. - Four seconds. Each time
followgave up,napSecondswent up by one. The battery is full after three seconds, and this time it is the delay that keeps the buddy down. - Still every second. The delay was read when
awakewas entered, with 2.5 in the battery, and it holds for the whole stay.
18. Wait for several things
A buddy that wakes up should say so. Let's play a chirp while its light fades in.
Now waking starts two things, and it should move on when both are done. But finish only counts the first time it is called. Which of the two callbacks gets to call it?
Neither. You count the jobs, and call finish when the count is back at zero. The counter is called a waitGroup.
import { defineMachine } from "@defold-typescript/types/hsm";
import { defineMachine, waitGroup } from "@defold-typescript/types/hsm";
// ...
waking: {
task: (ctx, finish) => {
const group = waitGroup();
go.set(ctx.light, "tint.w", 0);
msg.post(ctx.light, "enable");
go.animate(ctx.light, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 1, 0, () => {
finish({ type: "WAKING_DONE" });
});
go.animate(ctx.light, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 1, 0, group.add());
sound.play("#chirp", {}, group.add());
group.wait(() => finish({ type: "WAKING_DONE" }));
return () => {
go.cancel_animations(ctx.light, "tint.w");
sound.stop("#chirp");
msg.post(ctx.light, "disable");
};
},
exit: (ctx) => {
go.cancel_animations(ctx.light, "tint.w");
msg.post(ctx.light, "disable");
},
on: { WAKING_DONE: "/checkup", POKE: "/asleep" },waitGroup()makes a counter for work that is still going on.group.add()counts one job and hands back the function that reports it done. It goes where the callback used to go: once for the fade, once for the chirp.group.wait(...)runs its function once every job has reported. Only then doesfinishsendWAKING_DONE.return () => { ... }: a task can hand back its own cleanup. The machine calls it on every way out of the state, just as it calledexit, so theexithook is gone.
Which one is done first, the fade or the chirp? It doesn't matter. That's the whole point of counting.
Here is the buddy with its chirp. Press the restart button, the first one in the row, and watch jobs pending in the readout while the buddy wakes. Which job reports first, and when does the buddy move on?
Note
wait goes last. Call group.wait after every add. A group with nothing to wait for calls back at once.
exit, or the function a task returns?
Both run however the state ends, a stopped machine included. Pick the one that reads better.
A task that starts something and stops it again keeps both halves in one place when it returns the cleanup. A state with no task still has exit.
For the full rules, see Wait for something to finish.
Try it
- In
view, start a buddy and read the log. Which two Defold calls iswakingwaiting on, and how do you get past them? - In the game, the chirp is shorter than the one-second fade. When does the buddy move on?
- You poke the buddy halfway through the fade, and the chirp would have ended a moment later. Does the buddy wake up?
Answer
go.animateandsound.play. Neither reports back in the browser, so pressWAKING_DONEto play the engine's part.- When the fade ends. The group waits for the slowest job.
- No. The cleanup stops the chirp and cancels the fade. And if a report still came in,
wakinghas been left: a latefinishis ignored, as in lesson 9.
19. A scripted routine
When the buddy spots you, it starts to follow at once. A friendly robot would say hello first: a chirp, two blinks of its light, and then off it goes.
That's a little script. Do this, wait, do that, wait. You could build it from states and timers, with one state for every step, and two blinks alone would take four of them.
sequence lets you write the steps from top to bottom, the way you'd say them out loud.
import { defineMachine, waitGroup } from "@defold-typescript/types/hsm";
import { sequence } from "@defold-typescript/types/hsm/async";
import { type MessageEvent, messageEvents } from "@defold-typescript/types/hsm/defold";
// ...
| { type: "WAKING_DONE" }
| { type: "GREETING_DONE" }
| { type: "BUMP"; cost: number }
// ...
trigger_response: {
to: "/awake/follow",
to: "/awake/greeting",
when: (_ctx, event) => event.enter,
},
},
},
greeting: {
task: sequence(async (ctx, signal) => {
await new Promise<void>((resolve) => sound.play("#chirp", {}, () => resolve()));
if (signal.aborted) return;
for (let blink = 0; blink < 2; blink++) {
msg.post(ctx.light, "disable");
await signal.wait(0.2);
msg.post(ctx.light, "enable");
await signal.wait(0.2);
}
return { type: "GREETING_DONE" };
}),
exit: () => sound.stop("#chirp"),
on: { GREETING_DONE: "/awake/follow" },
},
follow: {sequence(async (ctx, signal) => { ... })turns a function into atask. The steps run in order, and eachawaitpauses the routine while the rest of the game carries on.await signal.wait(0.2)pauses for a fifth of a second. If the buddy leavesgreetingin the meantime, the wait never ends, and the lines after it never run.if (signal.aborted) return;: waiting for the chirp is not asignal.wait, so it can end after the buddy has left. By thensignal.abortedistrue, and the routine stops before it touches the light.return { type: "GREETING_DONE" }: the event a sequence returns is sent to the machine, the wayfinishsends one. Here it leads on tofollow.
wander now goes to greeting when you walk in, and follow comes after the hello.
Here is the buddy with its hello. Press trigger_response (enter true) and watch the list in greeting. Which step is marked while the light is off? The diagram plays Defold's timer with its own clock, so pausing it holds the routine too.
Cleanup in a sequence
Leaving the state cancels the wait that is pending. That's the sequence's own cleanup, and you get it for free.
Anything else the routine started is still yours to stop, and the place is exit: here it stops the chirp. Never put cleanup after an await. By the time that line would run, the buddy may be somewhere else.
Note
A clock of its own. signal.wait counts real time with a Defold timer, not the dt you pass to update. In view there is no such timer, so press GREETING_DONE to end the routine yourself.
For the full rules, see Scripted sequences.
Try it
- In
view, wake the buddy and sendtrigger_responsewith{ enter: true }. Which state is tinted, and which call does the log show? - In the game, you walk in and straight out again while the buddy greets you. Does it still follow?
- The buddy runs out of energy in the middle of its greeting, rests, and gets up. What does it do first?
Answer
/awake/greeting, and the log showssound.play. The routine is waiting for the chirp to end, which never happens in the browser. PressGREETING_DONEto move on.- Yes. Neither
greetingnorawakehas a rule fortrigger_response, so walking out is ignored. The routine ends, the buddy follows, and four seconds later it gives up. - It greets you again.
awakeremembersgreetingas the child it left, and entering a state starts its task from the top.
20. Two things at once
A resting buddy fills its battery. It should also show that it's resting: blink its light slowly, on and off, until the battery is full.
Blinking takes two states, shown and hidden. Filling takes two as well: filling and full. So which of the four is a resting buddy in?
Two of them at once. The battery doesn't care what the light is doing, and the light only wants to know when the battery is done.
Remember the rule from lesson 4, one active state at each level? It has one exception, and you ask for it by name: a state marked parallel keeps all its children active together.
First the battery:
resting: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return undefined;
},
type: "parallel",
after: [
// ...
RECHARGE: {
to: "/checkup",
run: (ctx) => {
ctx.energy = 3;
},
},
},
states: {
battery: {
initial: "/resting/battery/filling",
states: {
filling: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/resting/battery/full" : undefined;
},
},
full: {},
},
},
},
},
},
});type: "parallel"makes every child ofrestingactive at the same time. Each child is called a region, and each region has a current state of its own.batteryis the first region. The refill hook moved into itsfillingstate, and when the battery is full it returns"/resting/battery/full": a move inside the region.- No
initialonresting: there is nothing to choose. Every region is entered, and each region's owninitialsays where it starts.
Then the light:
full: {},
},
},
lamp: {
initial: "/resting/lamp/shown",
exit: (ctx) => msg.post(ctx.light, "disable"),
states: {
shown: {
enter: (ctx) => msg.post(ctx.light, "enable"),
after: {
0.5: {
to: "/resting/lamp/hidden",
when: (_ctx, machine) => !machine.matches("/resting/battery/full"),
},
},
},
hidden: {
enter: (ctx) => msg.post(ctx.light, "disable"),
after: { 0.5: "/resting/lamp/shown" },
},
},
},
},
},
},
});lampis the second region.shownandhiddenhand the light back and forth every half second.when: (_ctx, machine) => ...: awhengets the running machine as well, and can ask it which states are active. Oncebatteryis infull, the timer inshownkeeps waiting, and the light stays on.exitonlamphides the light when the buddy leavesresting, whichever of the two states it was in.
The battery knows nothing about the light. Each region minds its own business, and one when is the only place where they meet.
Where is the buddy now?
path has room for one state, and a resting buddy is in two. So path gives you the first region's state, and regions are ordered by name: battery comes before lamp.
For the whole picture there is leaves, a list with one path per region:
/resting/battery/filling
/resting/lamp/shownmatches says yes for every active state in every region, and inspect prints all the leaves between its square brackets.
Events and regions
An event is offered to every region, and each one may take it. resting's own rules, like RECHARGE, only get the event when no region took it.
Here is the buddy with its two regions. Once it's awake, press BUMP (cost 3) and count the glowing boxes inside resting. Then press RECHARGE and read the log: who is asked before resting? For a nap that outlasts the battery, press start() with napSeconds = 5 and tire the buddy out again.
For the full rules, see Run regions side by side with parallel.
The buddy's code so far
import { defineMachine, waitGroup } from "@defold-typescript/types/hsm";
import { sequence } from "@defold-typescript/types/hsm/async";
import { type MessageEvent, messageEvents } from "@defold-typescript/types/hsm/defold";
interface BuddyCtx {
light: Url;
}
type BuddyEvent =
| { type: "POKE" }
| { type: "WAKING_DONE" }
| { type: "GREETING_DONE" }
| { type: "BUMP"; cost: number }
| { type: "RECHARGE" }
| MessageEvent<"trigger_response">;
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent>()({
privateCtx: () => ({ wakes: 0, energy: 3, napSeconds: 2 }),
initial: "/asleep",
states: {
asleep: {
enter: (ctx, machine) => {
if (ctx.wakes === 0) machine.send({ type: "POKE" });
},
on: { POKE: "/waking" },
},
waking: {
task: (ctx, finish) => {
const group = waitGroup();
go.set(ctx.light, "tint.w", 0);
msg.post(ctx.light, "enable");
go.animate(ctx.light, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 1, 0, group.add());
sound.play("#chirp", {}, group.add());
group.wait(() => finish({ type: "WAKING_DONE" }));
return () => {
go.cancel_animations(ctx.light, "tint.w");
sound.stop("#chirp");
msg.post(ctx.light, "disable");
};
},
on: { WAKING_DONE: "/checkup", POKE: "/asleep" },
},
checkup: {
always: [
{ to: "/resting", when: (ctx) => ctx.energy < 1 },
{
to: "/awake",
run: (ctx) => {
ctx.wakes += 1;
},
},
],
},
awake: {
restoreDepth: 1,
initial: "/awake/wander",
enter: (ctx) => msg.post(ctx.light, "enable"),
exit: (ctx) => msg.post(ctx.light, "disable"),
after: { 30: "/asleep" },
every: [
{
delay: (ctx) => (ctx.energy < 2 ? 2 : 1),
run: (_ctx, machine) => machine.send({ type: "BUMP", cost: 1 / 16 }),
},
],
on: {
POKE: "/asleep",
BUMP: [
{
to: "/resting",
when: (ctx, event) => ctx.energy <= event.cost,
run: (ctx) => {
ctx.energy = 0;
},
},
{
run: (ctx, event) => {
ctx.energy -= event.cost;
},
},
],
},
states: {
wander: {
on: {
trigger_response: {
to: "/awake/greeting",
when: (_ctx, event) => event.enter,
},
},
},
greeting: {
task: sequence(async (ctx, signal) => {
await new Promise<void>((resolve) => sound.play("#chirp", {}, () => resolve()));
if (signal.aborted) return;
for (let blink = 0; blink < 2; blink++) {
msg.post(ctx.light, "disable");
await signal.wait(0.2);
msg.post(ctx.light, "enable");
await signal.wait(0.2);
}
return { type: "GREETING_DONE" };
}),
exit: () => sound.stop("#chirp"),
on: { GREETING_DONE: "/awake/follow" },
},
follow: {
after: {
4: {
to: "/awake/wander",
run: (ctx) => {
ctx.napSeconds = Math.min(5, ctx.napSeconds + 1);
},
},
},
on: {
trigger_response: [
{ to: "/awake/follow", when: (_ctx, event) => event.enter },
{ to: "/awake/wander" },
],
},
},
},
},
resting: {
type: "parallel",
after: [
{
delay: (ctx) => ctx.napSeconds,
to: "/checkup",
when: (ctx) => ctx.energy >= 3,
run: (ctx) => {
ctx.napSeconds = 2;
},
},
],
on: {
RECHARGE: {
to: "/checkup",
run: (ctx) => {
ctx.energy = 3;
},
},
},
states: {
battery: {
initial: "/resting/battery/filling",
states: {
filling: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/resting/battery/full" : undefined;
},
},
full: {},
},
},
lamp: {
initial: "/resting/lamp/shown",
exit: (ctx) => msg.post(ctx.light, "disable"),
states: {
shown: {
enter: (ctx) => msg.post(ctx.light, "enable"),
after: {
0.5: {
to: "/resting/lamp/hidden",
when: (_ctx, machine) => !machine.matches("/resting/battery/full"),
},
},
},
hidden: {
enter: (ctx) => msg.post(ctx.light, "disable"),
after: { 0.5: "/resting/lamp/shown" },
},
},
},
},
},
},
});
export const buddyEvents = messageEvents(["trigger_response"]);import { defineScript } from "@defold-typescript/types";
import { inspect } from "@defold-typescript/types/hsm/debug";
import { buddyEvents, buddyMachine } from "./buddy-machine";
const TOUCH = hash("touch");
export default defineScript({
init() {
msg.post(".", "acquire_input_focus");
msg.post("#light", "disable");
const buddy = buddyMachine.start({ light: msg.url("#light") });
return { buddy, inspector: inspect(buddy, "buddy") };
},
update(self, dt) {
self.buddy.update(dt);
self.inspector.draw(".");
},
on_input(self, action_id, action) {
if (action_id === TOUCH && action.pressed) {
self.buddy.send({ type: "POKE" });
}
},
on_message(self, message_id, message, sender) {
const event = buddyEvents.toEvent(message_id, message, sender);
if (event !== undefined) {
self.buddy.send(event);
}
},
final(self) {
self.buddy.stop();
},
});Try it
- In
view, wake the buddy, sendBUMPwith{ cost: 3 }and press Play. Which states are tinted? - Wake a new buddy and change
napSecondsto 5 in the ctx panel before you tire it out. What does the light do in the last second of the nap?
Answer
resting, both regions, and one state inside each:filling, andshownorhiddentaking turns.- It stays on. The battery is full after three seconds, so
batterysits infulland thewheninshownsays no. The nap rule onrestinggets the buddy up at five.
21. Name a group of states
Give the buddy's game object a small label named hint that says "poke me". When should it show?
Not while the buddy is waking up, because it's in the middle of something. Not while it rests, because a poke does nothing there. So the script would ask matches("/waking"), and then matches("/resting"), and one day you'd add a third state and have to find every place that asks.
waking and resting have something in common, and yet they share no parent. A group of states can have a name without living in the same folder. The name is called a tag.
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent>()({
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent, "busy">()({
// ...
waking: {
tags: ["busy"],
task: (ctx, finish) => {
// ...
resting: {
type: "parallel",
tags: ["busy"],
after: [ self.buddy.update(dt);
self.inspector.draw(".");
label.set_text("#hint", self.buddy.hasTag("busy") ? "" : "poke me");
},"busy", the third type indefineMachine<...>, lists the tag names this machine may use. For more than one, write"busy" | "sleepy".tags: ["busy"]hangs the name on a state. It holds while that state is active, children included: all ofresting, in both regions.self.buddy.hasTag("busy")asks whether any active state carries the tag. The script names no state at all.
Here is the buddy with its tag. Press the restart button and watch hasTag("busy") in the readout: what does it say while the buddy is in waking, and when does the answer change? Then tire it out with BUMP (cost 3).
Why not a flag? You could set ctx.busy = true in every enter and back to false in every exit. And you'd be right back in lesson 2, with a flag that can disagree with the state. A tag can't disagree. It is read straight off the active states.
A tag is only a name. It has no rules and no hooks, so behavior that states share still goes on a parent.
For the full rules, see Name a group of states with tags.
Try it
- Start the buddy in
viewand look at the tinted state in your code. Is the buddy busy? PressWAKING_DONE: and now? - You add a state named
charging, and the hint should hide there too. What do you change inbuddy.ts? - You type
hasTag("bussy")by mistake. What happens?
Answer
- Yes, then no. The buddy starts in
/waking, which carries the tag.checkup,awakeandwanderdon't. - Nothing. Give the new state
tags: ["busy"], and the script's question already covers it. - It doesn't compile. Only the names listed in
defineMachine<...>are accepted, intagsand inhasTagalike.
22. Events nobody took
Walk past a resting buddy and nothing happens. Its trigger tells it you're there, the buddy has no rule for that while it rests, and the event is ignored, as you saw in lesson 4.
From the outside, though, "the buddy ignored you" looks exactly like "the game is broken". Wouldn't a little beep be friendlier?
You could add a rule for every event the buddy doesn't want. There is a shorter way: one hook that runs for any event nobody took.
resting: {
type: "parallel",
tags: ["busy"],
unhandled: () => sound.play("#beep"),
after: [unhandledruns each time the machine ignores an event whilerestingis active, whatever the event is.
The beep changes nothing else. The event is still ignored, and the buddy stays where it is. The hook reacts. It doesn't take the event.
Asking first
A tap is different. Your script decides to send that poke, so it can ask before it sends:
on_input(self, action_id, action) {
if (action_id === TOUCH && action.pressed) {
if (action_id === TOUCH && action.pressed && self.buddy.can({ type: "POKE" })) {
self.buddy.send({ type: "POKE" });self.buddy.can({ type: "POKE" })answers a question: is there a rule, in some active state, that would take this event right now? Anywhenis checked too.
Asking is free. No hook runs, no run runs, and nothing moves. A resting buddy says no, so the tap sends nothing, and there is nothing to beep about.
So the two work as a pair. can is for the events you choose to send. unhandled is for the ones that simply arrive.
Here is the buddy with its beep. Tire it out with BUMP (cost 3), then press trigger_response (enter true): the log names the hook, and beeps goes up. The readout asks can for you. A name sends its event either way, so the buddy also beeps at a POKE that your script would have held back.
For the full rules, see React to an unhandled event and Ask whether an event would be taken.
Try it
- In
view, tire the buddy out and look at the event buttons. Is there aPOKE? What wouldcan({ type: "POKE" })say? - In the game, you walk up to a resting buddy. What do you hear, and does the buddy move?
- An awake buddy has 1 left in its battery. What does
can({ type: "BUMP", cost: 0.5 })say? The rule that would take it has noto.
Answer
- No button, and
cansaysfalse.viewoffers one button for each event that an active state has a rule for, and nothing inrestinghas a rule forPOKE. - A beep, and no. The
trigger_responseis ignored, sounhandledruns, and nothing exits or enters. true. The firstBUMPrule'swhensays no, but the second rule always passes. A rule with notostill takes its event.
23. Listen from outside
inspect prints a line for every move. How does it know? It isn't part of the buddy's machine, and no state calls it.
It listens. A running machine tells anyone who asks about each move and each ignored event, and your script can ask the same way. You might play a sound on every move, count moves for an award, or keep a log of your own.
Let's keep a log:
const buddy = buddyMachine.start({ light: msg.url("#light") });
buddy.onMove((from, to, cause) => {
print(`buddy: ${from} -> ${to} (${cause}), now in ${buddy.path}`);
});
buddy.onUnhandled((event) => {
print(`buddy dropped ${event.type} in ${buddy.path}`);
pprint(buddy.ctx);
});
return { buddy, inspector: inspect(buddy, "buddy") };buddy.onMove(...)calls your function after every move, with the state the buddy left, the state it entered, and the cause: an event, a timer, anupdatehook or analwaysrule.buddy.pathis where the buddy is by the time you're called.buddy.onUnhandled(...)calls your function with each event the machine ignored, after the buddy's ownunhandledhooks.pprint(buddy.ctx)prints the buddy's data next to it.
Remember "hidden, not locked" from lesson 12? Here you can see it. pprint prints wakes, energy and napSeconds along with the light, because at run time they all sit in one table. Type buddy.ctx.energy, though, and it doesn't compile.
What a listener hears
- Not the first entry. A new buddy's way into its first state is not a move.
- Not a rule with no
to. A small bump changes the battery and moves nothing. - Each region on its own. While the buddy rests, every blink of
lampis a move fromshowntohiddenor back.tois the lamp's new state, andpathstill names the battery's.
Each onMove and onUnhandled call hands back a function. Call it, and that listener is removed.
Here is the buddy with both listeners. The second list holds what they printed, without the pprint. Tire the buddy out with BUMP (cost 3) and watch the lamp: every blink is a move, and path keeps naming the battery's state. Then press trigger_response (enter true): the buddy beeps first, and your listener hears the drop after it.
For everything a running machine offers, see MachineInstance.
Try it
- In
view, wake the buddy and sendBUMPwith{ cost: 1 }. How many moves does the log show? - Your listener prints
toandbuddy.path. When are the two different? - In the game, the buddy has just nodded off after its thirty seconds, and your log says it dropped a
BUMP. Where did that come from?
Answer
- None. The small bump uses the rule with no
to: the log shows the event, and no move follows it. - While the buddy rests. A blink moves the
lampregion, sotois/resting/lamp/hiddenor/resting/lamp/shown, andpathstays withbattery, the first region. - From
awake's ownevery. Its thirtieth run sent aBUMPin the sameupdatethat put the buddy to sleep. The event waited its turn, and by then nobody was awake to take it.
24. Keep going after a hot reload
You change a number in buddy-machine.ts and save. With hot reload on, Defold runs the changed file again while the game keeps going. That builds a new machine.
But your buddy is already running, and it was started from the old one. How does a buddy that is halfway across the room get the new rules?
Give the machine a name:
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent, "busy">()({
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent, "busy">("buddy")({
privateCtx: () => ({ wakes: 0, energy: 3, napSeconds: 2 }),("buddy")is a key: a name for this definition. It goes in the first pair of parentheses, the one that has been empty since lesson 3.
When the file runs again, defineMachine finds the machine it built under that key the first time and puts the new states into it. Every running buddy picks them up on its next update.
And the buddy itself? It stays where it is. It keeps its ctx, and it keeps its state, as long as that state still exists in the new file.
Two things to remember:
- One key per machine. Two machines with the same key would overwrite each other on every reload.
- Define it at the top of a module, never inside
init, so it runs once each time the file loads.
view reloads the same way when you save, so you can try it right now.
For the full rules, see Hot reload.
Try it
- In
view, wake the buddy and get it tofollow. Now changefollow's4to10in your editor and save. Where is the buddy after the reload? - Take the key out and do the same. What is different?
- With the key back in, rename
followtochase, in its name and in every path that points at it, and save while the buddy follows. Where does it go?
Answer
- Still in
/awake/follow, with its data untouched. The new delay holds from now on. - The buddy starts over, as a new buddy would. Without a key, the saved file builds a machine that no running buddy belongs to.
- To
/awake/wander. Its state is gone, so it moves to the closest parent that still exists,awake, and enters from that parent'sinitial.
25. Save and load
The player quits while the buddy is resting. The next day the game starts, and the buddy is asleep, pokes itself and wakes up as if nothing had happened.
Shouldn't it come back where it was? What would you have to write down to make that work?
Where it is. And you already know the word for that: leaves.
const TOUCH = hash("touch");
const SAVE_FILE = sys.get_save_file("my_game", "buddy");
type BuddyPath = NonNullable<ReturnType<typeof buddyMachine.start>["path"]>;
// ...
msg.post("#light", "disable");
const buddy = buddyMachine.start({ light: msg.url("#light") });
const save = sys.load(SAVE_FILE) as { at?: BuddyPath[] };
const buddy = buddyMachine.start({ light: msg.url("#light") }, save.at);
buddy.onMove((from, to, cause) => {
// ...
final(self) {
sys.save(SAVE_FILE, { at: [...self.buddy.leaves] });
self.buddy.stop();sys.save(SAVE_FILE, { at: [...self.buddy.leaves] })writes the active states to a file as the buddy's object goes away. The[...]makes a copy:leavesis one list that the machine keeps changing, andstop()on the next line empties it.sys.load(SAVE_FILE)reads the file back. No save yet? Thensave.atisundefined, and the buddy starts the way it always did.start(..., save.at): the second thingstarttakes is a list of paths to start at.BuddyPathmeans "any path of this machine". The line reads that off the machine, so you never list the paths by hand.
What comes back
Starting at saved paths is an ordinary start. enter hooks run from the outside in, tasks start, and every timer begins at zero. A buddy saved in resting starts a new nap.
Only the states were saved. privateCtx runs as it does for any new buddy, so the battery is full and wakes is 0 again. That data is yours to save too, if your game needs it.
And an old save? If a path names a state you have since removed, the buddy starts in the closest parent that still exists.
Here is the buddy with a save. Tire it out with BUMP (cost 3), press sys.save(..., { at: leaves }), then RECHARGE to get it up. Now press start(..., save.at): a new buddy starts in resting, with a full battery and wakes at 0. Give it two seconds.
For the full rules, see Start at saved paths.
Try it
- In
view, tire the buddy out. Which paths wouldleaveshold right now? - A save holds
/resting/battery/fulland/resting/lamp/hidden. What does the loaded buddy do in its first three seconds? - A save holds
/awake/follow. The loaded buddy runs out of energy and rests. Which child ofawakeis it in when it gets up?
Answer
- Two:
/resting/battery/filling, and/resting/lamp/shownor/resting/lamp/hidden. One path per region, the innermost tinted state of each. - Its light comes on after half a second and stays on, because
batteryis infull. Two seconds in, the nap rule finds the battery full and gets the buddy up. follow. It started there, so that is the childawakewas left from, andrestoreDepthbrings it back.
26. A second machine
The buddy fills its own battery, slowly. Let's build it a charging dock: the buddy asks for a charge, the dock takes two seconds, and then it tells the buddy the battery is full.
The dock is a game object of its own, with states of its own: idle and charging. Do they go into the buddy's machine, as one more region?
No. A region is a part of the buddy. The dock is a different thing, on a different object, and tomorrow it might serve three buddies. A second thing gets a second machine.
How do two machines talk? The way any two game objects do, and you know it from lesson 10: with messages.
The dock
Make a file named dock-machine.ts:
import { defineMachine } from "@defold-typescript/types/hsm";
import { type MessageEvent, messageEvents } from "@defold-typescript/types/hsm/defold";
declare global {
interface CustomMessages {
charge_me: {};
charged: {};
}
}
interface DockCtx {
customer?: Url;
}
type DockEvent = MessageEvent<"charge_me">;
export const dockMachine = defineMachine<DockCtx, DockEvent>("dock")({
initial: "/idle",
states: {
idle: {
on: {
charge_me: {
to: "/charging",
run: (ctx, event) => {
ctx.customer = event.sender;
},
},
},
},
charging: {
after: {
2: {
to: "/idle",
run: (ctx) => {
if (ctx.customer !== undefined) msg.post(ctx.customer, "charged");
},
},
},
},
},
});
export const dockEvents = messageEvents(["charge_me"]);declare global { ... }tells TypeScript about two messages of your own,charge_meandcharged. Neither carries any data, so each is{}.MessageEvent<"charge_me">makes the first one an event, like the buddy'strigger_response.event.sender: every message event knows who sent it. The dock keeps that address inctx.customer.2: { to, run }: two seconds later the dock goes back toidle, and the rule'srunpostschargedto whoever asked.
Its script, dock.ts, has the same shape as the buddy's:
import { defineScript } from "@defold-typescript/types";
import { inspect } from "@defold-typescript/types/hsm/debug";
import { dockEvents, dockMachine } from "./dock-machine";
export default defineScript({
init() {
const dock = dockMachine.start({});
return { dock, inspector: inspect(dock, "dock") };
},
update(self, dt) {
self.dock.update(dt);
self.inspector.draw(".");
},
on_message(self, message_id, message, sender) {
const event = dockEvents.toEvent(message_id, message, sender);
if (event !== undefined) {
self.dock.send(event);
}
},
final(self) {
self.dock.stop();
},
});The buddy asks
interface BuddyCtx {
light: Url;
dock: Url;
}
// ...
| { type: "BUMP"; cost: number }
| { type: "RECHARGE" }
| MessageEvent<"trigger_response">;
| MessageEvent<"trigger_response" | "charged">;
// ...
tags: ["busy"],
enter: (ctx) => msg.post(ctx.dock, "charge_me"),
unhandled: () => sound.play("#beep"),
// ...
on: {
RECHARGE: {
charged: {
to: "/checkup",
// ...
export const buddyEvents = messageEvents(["trigger_response"]);
export const buddyEvents = messageEvents(["trigger_response", "charged"]); const save = sys.load(SAVE_FILE) as { at?: BuddyPath[] };
const buddy = buddyMachine.start({ light: msg.url("#light") }, save.at);
const buddy = buddyMachine.start({ light: msg.url("#light"), dock: msg.url("/dock#dock") }, save.at); dock: UrljoinsBuddyCtx, and the script hands in the address of the dock's script: an object nameddockwith a script component nameddock.enteronrestingpostscharge_meon the way in.chargedtakes the place ofRECHARGE, in the event list and inresting's rules. The made-up event has become a real message.messageEvents([..., "charged"]): the translator passes the new message on to the machine.
Follow one round trip. The buddy runs out of energy, enters resting and posts charge_me. The dock moves to charging and remembers who asked. Two seconds later it posts charged, and the buddy passes through checkup and gets up, a second before its own battery would have been full.
Neither file imports the other. The buddy knows the dock by an address. The dock knows the buddy only as the sender of a message, so it works for any object that asks.
And if no dock answers? The buddy still has its own battery region and its nap.
For the full rules, see Separate objects talk with messages.
The buddy's code so far
import { defineMachine, waitGroup } from "@defold-typescript/types/hsm";
import { sequence } from "@defold-typescript/types/hsm/async";
import { type MessageEvent, messageEvents } from "@defold-typescript/types/hsm/defold";
interface BuddyCtx {
light: Url;
dock: Url;
}
type BuddyEvent =
| { type: "POKE" }
| { type: "WAKING_DONE" }
| { type: "GREETING_DONE" }
| { type: "BUMP"; cost: number }
| MessageEvent<"trigger_response" | "charged">;
export const buddyMachine = defineMachine<BuddyCtx, BuddyEvent, "busy">("buddy")({
privateCtx: () => ({ wakes: 0, energy: 3, napSeconds: 2 }),
initial: "/asleep",
states: {
asleep: {
enter: (ctx, machine) => {
if (ctx.wakes === 0) machine.send({ type: "POKE" });
},
on: { POKE: "/waking" },
},
waking: {
tags: ["busy"],
task: (ctx, finish) => {
const group = waitGroup();
go.set(ctx.light, "tint.w", 0);
msg.post(ctx.light, "enable");
go.animate(ctx.light, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 1, 0, group.add());
sound.play("#chirp", {}, group.add());
group.wait(() => finish({ type: "WAKING_DONE" }));
return () => {
go.cancel_animations(ctx.light, "tint.w");
sound.stop("#chirp");
msg.post(ctx.light, "disable");
};
},
on: { WAKING_DONE: "/checkup", POKE: "/asleep" },
},
checkup: {
always: [
{ to: "/resting", when: (ctx) => ctx.energy < 1 },
{
to: "/awake",
run: (ctx) => {
ctx.wakes += 1;
},
},
],
},
awake: {
restoreDepth: 1,
initial: "/awake/wander",
enter: (ctx) => msg.post(ctx.light, "enable"),
exit: (ctx) => msg.post(ctx.light, "disable"),
after: { 30: "/asleep" },
every: [
{
delay: (ctx) => (ctx.energy < 2 ? 2 : 1),
run: (_ctx, machine) => machine.send({ type: "BUMP", cost: 1 / 16 }),
},
],
on: {
POKE: "/asleep",
BUMP: [
{
to: "/resting",
when: (ctx, event) => ctx.energy <= event.cost,
run: (ctx) => {
ctx.energy = 0;
},
},
{
run: (ctx, event) => {
ctx.energy -= event.cost;
},
},
],
},
states: {
wander: {
on: {
trigger_response: {
to: "/awake/greeting",
when: (_ctx, event) => event.enter,
},
},
},
greeting: {
task: sequence(async (ctx, signal) => {
await new Promise<void>((resolve) => sound.play("#chirp", {}, () => resolve()));
if (signal.aborted) return;
for (let blink = 0; blink < 2; blink++) {
msg.post(ctx.light, "disable");
await signal.wait(0.2);
msg.post(ctx.light, "enable");
await signal.wait(0.2);
}
return { type: "GREETING_DONE" };
}),
exit: () => sound.stop("#chirp"),
on: { GREETING_DONE: "/awake/follow" },
},
follow: {
after: {
4: {
to: "/awake/wander",
run: (ctx) => {
ctx.napSeconds = Math.min(5, ctx.napSeconds + 1);
},
},
},
on: {
trigger_response: [
{ to: "/awake/follow", when: (_ctx, event) => event.enter },
{ to: "/awake/wander" },
],
},
},
},
},
resting: {
type: "parallel",
tags: ["busy"],
enter: (ctx) => msg.post(ctx.dock, "charge_me"),
unhandled: () => sound.play("#beep"),
after: [
{
delay: (ctx) => ctx.napSeconds,
to: "/checkup",
when: (ctx) => ctx.energy >= 3,
run: (ctx) => {
ctx.napSeconds = 2;
},
},
],
on: {
charged: {
to: "/checkup",
run: (ctx) => {
ctx.energy = 3;
},
},
},
states: {
battery: {
initial: "/resting/battery/filling",
states: {
filling: {
update: (ctx, dt) => {
ctx.energy = Math.min(3, ctx.energy + dt);
return ctx.energy >= 3 ? "/resting/battery/full" : undefined;
},
},
full: {},
},
},
lamp: {
initial: "/resting/lamp/shown",
exit: (ctx) => msg.post(ctx.light, "disable"),
states: {
shown: {
enter: (ctx) => msg.post(ctx.light, "enable"),
after: {
0.5: {
to: "/resting/lamp/hidden",
when: (_ctx, machine) => !machine.matches("/resting/battery/full"),
},
},
},
hidden: {
enter: (ctx) => msg.post(ctx.light, "disable"),
after: { 0.5: "/resting/lamp/shown" },
},
},
},
},
},
},
});
export const buddyEvents = messageEvents(["trigger_response", "charged"]);import { defineScript } from "@defold-typescript/types";
import { inspect } from "@defold-typescript/types/hsm/debug";
import { buddyEvents, buddyMachine } from "./buddy-machine";
const TOUCH = hash("touch");
const SAVE_FILE = sys.get_save_file("my_game", "buddy");
type BuddyPath = NonNullable<ReturnType<typeof buddyMachine.start>["path"]>;
export default defineScript({
init() {
msg.post(".", "acquire_input_focus");
msg.post("#light", "disable");
const save = sys.load(SAVE_FILE) as { at?: BuddyPath[] };
const buddy = buddyMachine.start({ light: msg.url("#light"), dock: msg.url("/dock#dock") }, save.at);
buddy.onMove((from, to, cause) => {
print(`buddy: ${from} -> ${to} (${cause}), now in ${buddy.path}`);
});
buddy.onUnhandled((event) => {
print(`buddy dropped ${event.type} in ${buddy.path}`);
pprint(buddy.ctx);
});
return { buddy, inspector: inspect(buddy, "buddy") };
},
update(self, dt) {
self.buddy.update(dt);
self.inspector.draw(".");
label.set_text("#hint", self.buddy.hasTag("busy") ? "" : "poke me");
},
on_input(self, action_id, action) {
if (action_id === TOUCH && action.pressed && self.buddy.can({ type: "POKE" })) {
self.buddy.send({ type: "POKE" });
}
},
on_message(self, message_id, message, sender) {
const event = buddyEvents.toEvent(message_id, message, sender);
if (event !== undefined) {
self.buddy.send(event);
}
},
final(self) {
sys.save(SAVE_FILE, { at: [...self.buddy.leaves] });
self.buddy.stop();
},
});Try it
- Run
viewtwice, once on each machine file, and put the two tabs side by side. Start the buddy with{ light: "#light", dock: "dock" }and tire it out. Now carry the messages yourself: which buttons do you press, and in which tab? - A second buddy asks for a charge while the dock is busy with the first. What happens to its message?
- Why does the dock post to
event.senderand not to an address it was started with?
Answer
- The buddy's log shows
charge_megoing out. In the dock's tab, presscharge_mewith{ sender: "buddy" }, then Play for two seconds, and its log showschargedgoing out. Back in the buddy's tab, presscharged: the buddy passescheckupand gets up. - It is ignored, because
charginghas no rule forcharge_me. The second buddy isn't stuck: its own battery fills, and its nap rule gets it up. - So that it needs to know nothing in advance. Any object that posts
charge_megets its answer, and the dock never has to be told who its buddies are.
27. Designing your own
You have built a whole buddy, and a dock to go with it. How would you start on a machine of your own? The same way, step by step:
- List the modes. What can this thing be doing? Each one is a state. The buddy has
asleep,waking,checkup,awakeandresting. - List what can happen. Pokes, bumps, messages, timeouts. Each is an event, an
afteror anevery. - Draw the arrows. For each state, which events move it, and where?
- Look for groups. States that share arrows can live inside a parent, the way
wanderandfollowshareawake's poke and bump. States that only share a name get a tag, likebusy. - Look for things that happen at once. Parts that don't depend on each other become regions of a
parallelstate, likebatteryandlamp. - Add conditions last.
whenandrunhandle the "it depends" cases, like a bump that may or may not tire the buddy out. A state that only decides getsalways, likecheckup. - Plan cleanup. Whatever a state starts, its
exitor the function itstaskreturns should stop.wakingstarts a fade and a chirp, sowakingstops both. - Split the data. What a script hands in goes in the context. What only the machine uses goes in
privateCtx. - Count the things. One thing, one machine. A second object, like the dock, gets a machine of its own, and the two talk with messages.
Common beginner mistakes
- Forgetting to call
update(dt), so timers never fire. - Forgetting
initialon a state that has children. - Writing
"resting"when you meant"/resting". Every path starts with/. - Expecting
send()inside a hook to happen instantly. - Cleaning up anywhere other than
exitor the function ataskreturns, such as after anawait. - Starting the machine at the top of a script file instead of in
init. - Expecting
alwaysto watch a value every frame. It is checked after a move. - Calling
group.waitbefore the lastgroup.add. - Giving two machines the same hot reload key.
- Expecting a saved start to bring back timers or data. It brings back the states.
Try it
- Design a machine for a coin. It bobs until the player touches it, plays a one-second sparkle, and is then gone. Name its states, its events and its cleanup.
Answer
- States:
bobbing,collectedandgone. Events: atrigger_responsefrom the player, and aDONEthat the sparkle'staskhands tofinish. Cleanup:collectedcancels the sparkle in itsexit, in case the coin is deleted halfway through.