# States inside states

> The guard of State machine, now calm or in combat, each with states of its own made with useStateMachine({ parent, state }).

Example `nested-states`, running at https://nacatamalon.com/en/examples/nested-states. The whole catalogue: https://nacatamalon.com/llms/examples.md.

The guard of *State machine*, now **calm** or in **combat**, each with states of its own: calm patrols, searches and goes back; combat approaches, swings and recovers. Each inner machine is a `useStateMachine` given `{ parent: guard, state: 'calm' }`: it runs only while the guard is in that state, and is left and entered with it. Arrow keys or A and D walk.

What holds for every move of a state is written once, in that state's `onUpdate`, which runs before the inner one. Calm looks out for the hero for all three of its moves; combat notices when he got away, and sends the guard back with `calm.go('search')`, which takes it to calm straight into searching rather than patrolling. Each machine has its own `time`, so the HUD shows how long the guard has been in combat and how long in this move of it.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Hall } from './scenes/hall';
import { ACTIONS, HEIGHT, WIDTH } from './settings';

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    smooth: false,
    background: '#1b1a2b',
    actions: ACTIONS
});

// Declare Scenes
game({
    Hall
});
```

`components/guard.ts`:

```ts
import { createSprite, createSpriteAtlas, useLoadTexture, useSpriteAnimation, useStateMachine } from 'nacatamalon';
import type { THero } from './hero';
import { CLIPS, FLOOR_Y, GUARD, SHEETS } from '../settings';

type TGuardProps = {
    hero: THero;
};

export const Guard = ({ hero }: TGuardProps) => {
    // Each clip is its own image, so each has its own sheet.
    const sheets = {
        idle: createSpriteAtlas({
            texture: useLoadTexture({
                src: SHEETS.idle
            }),
            columns: 4
        }),
        walk: createSpriteAtlas({
            texture: useLoadTexture({
                src: SHEETS.walk
            }),
            columns: 6
        }),
        attack: createSpriteAtlas({
            texture: useLoadTexture({
                src: SHEETS.attack
            }),
            columns: 6
        })
    };

    const sprite = createSprite({
        atlas: sheets.idle,
        anchor: {
            x: 0.5,
            y: 1
        },
        transform: {
            x: GUARD.post,
            y: FLOOR_Y,
            scaleX: 2,
            scaleY: 2
        }
    });

    const animation = useSpriteAnimation(sprite, {
        clips: CLIPS
    });

    let facing = 1;

    const show = (clip: keyof typeof CLIPS) => {
        sprite.atlas = sheets[clip];
        animation.play(clip);
    };

    const face = (direction: number) => {
        facing = direction < 0 ? -1 : 1;
        sprite.flipX = facing < 0;
    };

    const walk = (speed: number, delta: number) => {
        sprite.transform.x += facing * speed * delta;
    };

    // It starts looking left, towards where the hero comes in.
    face(-1);

    const distance = () => Math.abs(hero.x - sprite.transform.x);

    // In front of it and near enough: it does not see behind its back.
    const seesHero = () => {
        const ahead = (hero.x - sprite.transform.x) * facing;

        return ahead > 0 && ahead < GUARD.sight;
    };

    // The guard is calm or in combat. What holds for every move of each is written once, here.
    const guard = useStateMachine('calm', {
        calm: {
            onUpdate: () => {
                if (seesHero()) {
                    guard.go('combat');
                }
            }
        },
        combat: {
            onUpdate: () => {
                // Lost him: back to calm, but straight into searching, not patrolling.
                if (distance() > GUARD.lose) {
                    calm.go('search');
                }
            }
        }
    });

    // The states inside calm. None of them looks out for the hero: calm does it for all three.
    const calm = useStateMachine('patrol', {
        patrol: {
            onEnter: () => show('walk'),
            onUpdate: (delta) => {
                walk(GUARD.patrolSpeed, delta);

                // Turns round at each end of its round.
                if ((sprite.transform.x - GUARD.post) * facing > GUARD.patrolReach) {
                    face(-facing);
                }
            }
        },
        search: {
            onEnter: () => show('idle'),
            onUpdate: () => {
                if (calm.time > GUARD.searchSeconds) {
                    calm.go('back');
                } else if (Math.floor(calm.time / GUARD.lookEvery) % 2 === 1) {
                    face(-1);
                } else {
                    face(1);
                }
            }
        },
        back: {
            onEnter: () => show('walk'),
            onUpdate: (delta) => {
                face(GUARD.post - sprite.transform.x);
                walk(GUARD.backSpeed, delta);

                if (Math.abs(GUARD.post - sprite.transform.x) < 2) {
                    calm.go('patrol');
                }
            }
        }
    }, {
        parent: guard,
        state: 'calm'
    });

    // The states inside combat. None of them checks whether the hero got away: combat does.
    const combat = useStateMachine('approach', {
        approach: {
            onEnter: () => show('walk'),
            onUpdate: (delta) => {
                face(hero.x - sprite.transform.x);

                if (distance() < GUARD.reach) {
                    combat.go('swing');
                } else {
                    walk(GUARD.approachSpeed, delta);
                }
            }
        },
        swing: {
            // Leaves when the swing ends: see onEnd below.
            onEnter: () => show('attack')
        },
        recover: {
            onEnter: () => show('idle'),
            onUpdate: () => {
                if (combat.time > GUARD.recoverSeconds) {
                    combat.go('approach');
                }
            }
        }
    }, {
        parent: guard,
        state: 'combat'
    });

    // The swing has landed: the hero is pushed away if still in reach, and the guard gets its breath.
    animation.onEnd(() => {
        if (!combat.is('swing')) {
            return;
        }

        if (distance() < GUARD.reach + 8) {
            hero.knock(facing);
        }

        combat.go('recover');
    });

    return {
        guard,
        calm,
        combat
    };
};
```

`components/hero.ts`:

```ts
import { createSprite, createSpriteAtlas, useActions, useLoadTexture, useSpriteAnimation, useUpdate } from 'nacatamalon';
import { clamp } from 'nacatamalon/math';
import { FLOOR_Y, HERO, WIDTH } from '../settings';

export const Hero = () => {
    // Gammix, the same one who dances in Gammix Dance: three pictures of him bobbing.
    const sprite = createSprite({
        atlas: createSpriteAtlas({
            texture: useLoadTexture({
                src: '/example-assets/assets/gammix-bob.png',
                key: 'gammix-bob'
            }),
            columns: 3
        }),
        frame: 0,
        // His feet end 8 pixels above the bottom of each 64-pixel picture: stood on them, not on the
        // empty rows under them.
        anchor: {
            x: 0.5,
            y: 56 / 64
        },
        transform: {
            x: HERO.startX,
            y: FLOOR_Y
        }
    });

    const animation = useSpriteAnimation(sprite, {
        clips: {
            stand: {
                frames: [0],
                fps: 1
            },
            walk: {
                frames: [0, 1, 2, 1],
                fps: 10
            }
        },
        play: 'stand'
    });

    const input = useActions();
    let push = 0;

    useUpdate((delta) => {
        const walk = input.value('right') - input.value('left');
        const clip = walk === 0 ? 'stand' : 'walk';

        if (animation.clip !== clip) {
            animation.play(clip);
        }

        if (walk !== 0) {
            sprite.flipX = walk < 0;
        }

        // A knock fades out on its own.
        push *= Math.max(0, 1 - 6 * delta);
        sprite.transform.x = clamp(sprite.transform.x + (walk * HERO.speed + push) * delta, 24, WIDTH - 24);
    });

    return {
        get x() {
            return sprite.transform.x;
        },
        knock: (direction: number) => {
            push = direction * HERO.knockback;
        }
    };
};

export type THero = ReturnType<typeof Hero>;
```

`components/hud.ts`:

```ts
import { createText, useUpdate, useWatch } from 'nacatamalon';
import type { TStateMachine } from 'nacatamalon';
import { WIDTH } from '../settings';

type THudProps = {
    guard: TStateMachine<string>;
    calm: TStateMachine<string>;
    combat: TStateMachine<string>;
};

export const Hud = ({ guard, calm, combat }: THudProps) => {
    createText({
        text: 'ARROWS / A D  WALK',
        transform: {
            x: 8,
            y: 8
        },
        tint: '#8c88b8'
    });

    const state = createText({
        text: '',
        transform: {
            x: 8,
            y: 28
        },
        tint: '#ffd166'
    });

    const time = createText({
        text: '',
        transform: {
            x: 8,
            y: 44
        },
        tint: '#8c88b8'
    });

    const last = createText({
        text: 'NO CHANGE YET',
        transform: {
            x: WIDTH - 8,
            y: 8
        },
        anchor: {
            x: 1,
            y: 0
        },
        tint: '#8c88b8'
    });

    // Of the two inside, the one that is running.
    const inside = () => (calm.active ? calm : combat);

    useWatch(() => {
        state.text = guard.state.toUpperCase() + ' > ' + inside().state.toUpperCase();
    }, [guard, calm, combat]);

    // Each machine has its own time: in combat, and in this move of it.
    useUpdate(() => {
        time.text = guard.time.toFixed(1) + 's  ' + inside().time.toFixed(1) + 's';
    });

    for (const [name, machine] of [['guard', guard], ['calm', calm], ['combat', combat]] as const) {
        machine.onChange((to, from) => {
            last.text = (name + ' ' + from + ' > ' + to).toUpperCase();
        });
    }
};
```

`scenes/hall.ts`:

```ts
import { createScene, createSprite, useSpawn } from 'nacatamalon';
import { Guard } from '../components/guard';
import { Hero } from '../components/hero';
import { Hud } from '../components/hud';
import { FLOOR_Y, GUARD, HEIGHT, WIDTH } from '../settings';

export const Hall = () => {
    createSprite({
        width: WIDTH,
        height: HEIGHT - FLOOR_Y,
        tint: '#2e2b45',
        anchor: {
            x: 0,
            y: 0
        },
        transform: {
            x: 0,
            y: FLOOR_Y
        }
    });

    // The two ends of the guard's round.
    for (const x of [GUARD.post - GUARD.patrolReach, GUARD.post + GUARD.patrolReach]) {
        createSprite({
            width: 2,
            height: 10,
            tint: '#5a5680',
            anchor: {
                x: 0.5,
                y: 1
            },
            transform: {
                x,
                y: FLOOR_Y
            }
        });
    }

    const hero = useSpawn(Hero)();

    const guard = useSpawn(Guard)({
        hero: hero.api
    });

    useSpawn(Hud)(guard.api);

    return createScene();
};
```

`settings.ts`:

```ts
import { INPUT } from 'nacatamalon';

export const WIDTH = 480;
export const HEIGHT = 270;
export const FLOOR_Y = 210;
export const ACTIONS = INPUT.ACTION_PRESETS.platformer;

export const HERO = {
    startX: 60,
    speed: 120,
    knockback: 320
};

export const GUARD = {
    // Where it keeps watch, and how far it walks to each side of it.
    post: 330,
    patrolReach: 70,
    patrolSpeed: 40,
    // Slower than the hero in combat, so he can get away.
    approachSpeed: 70,
    backSpeed: 60,
    // Seen ahead of it within this distance; lost beyond the second one.
    sight: 140,
    lose: 170,
    // Close enough to swing, and how long it gets its breath back after one.
    reach: 40,
    recoverSeconds: 0.5,
    // How long it looks around before going back, and how often it turns while it does.
    searchSeconds: 2.4,
    lookEvery: 0.6
};

const SHEET = '/example-assets/assets/charracters/business_enemies/1/';

export const SHEETS = {
    idle: SHEET + 'Idle.png',
    walk: SHEET + 'Walk.png',
    attack: SHEET + 'Attack.png'
};

export const CLIPS = {
    idle: {
        frames: [0, 1, 2, 3],
        fps: 6
    },
    walk: {
        frames: [0, 1, 2, 3, 4, 5],
        fps: 10
    },
    attack: {
        frames: [0, 1, 2, 3, 4, 5],
        fps: 12,
        loop: false
    }
};
```
