# State machine

> A guard made with useStateMachine: it patrols, chases, attacks, searches and goes back to its post.

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

A guard made with `useStateMachine`: it **patrols** between two posts, **chases** the hero when it sees him ahead, **attacks** when he is close, **searches** looking both ways when it loses him, and goes **back** to its post. Each state says what it does on the way in (`onEnter`, here its animation) and every frame (`onUpdate`), and changes with `machine.go()`. Arrow keys or A and D walk; stand behind the guard and it will not see you.

The guard is a piece made with `useSpawn`, and the machine is its own. The HUD reads it three ways: `useWatch(fn, [machine])` for the state, `machine.time` every frame for how long it has been in it, and `machine.onChange` for the last change. The swing ends on the animation's `onEnd`, which sends the guard back to the chase.

## 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;
    };

    const machine = useStateMachine('patrol', {
        patrol: {
            onEnter: () => show('walk'),
            onUpdate: (delta) => {
                if (seesHero()) {
                    machine.go('chase');

                    return;
                }

                walk(GUARD.patrolSpeed, delta);

                // Turns round at each end of its round.
                const fromPost = sprite.transform.x - GUARD.post;

                if (fromPost * facing > GUARD.patrolReach) {
                    face(-facing);
                }
            }
        },
        chase: {
            onEnter: () => show('walk'),
            onUpdate: (delta) => {
                face(hero.x - sprite.transform.x);

                if (distance() < GUARD.reach) {
                    machine.go('attack');
                } else if (distance() > GUARD.lose) {
                    machine.go('search');
                } else {
                    walk(GUARD.chaseSpeed, delta);
                }
            }
        },
        attack: {
            // Leaves when the swing ends: see onEnd below.
            onEnter: () => show('attack')
        },
        search: {
            onEnter: () => show('idle'),
            onUpdate: () => {
                if (seesHero()) {
                    machine.go('chase');
                } else if (machine.time > GUARD.searchSeconds) {
                    machine.go('back');
                } else if (Math.floor(machine.time / GUARD.lookEvery) % 2 === 1) {
                    face(-1);
                } else {
                    face(1);
                }
            }
        },
        back: {
            onEnter: () => show('walk'),
            onUpdate: (delta) => {
                if (seesHero()) {
                    machine.go('chase');

                    return;
                }

                face(GUARD.post - sprite.transform.x);
                walk(GUARD.backSpeed, delta);

                if (Math.abs(GUARD.post - sprite.transform.x) < 2) {
                    machine.go('patrol');
                }
            }
        }
    });

    // The swing has landed: the hero is pushed away if still in reach, and the chase goes on.
    animation.onEnd(() => {
        if (!machine.is('attack')) {
            return;
        }

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

        machine.go('chase');
    });

    return {
        machine
    };
};
```

`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>;
};

export const Hud = ({ guard }: 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: 150,
            y: 28
        },
        tint: '#8c88b8'
    });

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

    // A machine can be watched: this runs on the first frame and on every change of state.
    useWatch(() => {
        state.text = 'GUARD: ' + guard.state.toUpperCase();
    }, [guard]);

    // Its time changes every frame, so it is read every frame.
    useUpdate(() => {
        time.text = guard.time.toFixed(1) + 's';
    });

    guard.onChange((to, from) => {
        last.text = from.toUpperCase() + ' > ' + 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: guard.api.machine
    });

    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,
    // Slower than the hero when chasing, so he can get away.
    patrolSpeed: 40,
    chaseSpeed: 70,
    backSpeed: 60,
    // Seen ahead of it within this distance; lost beyond the second one.
    sight: 140,
    lose: 170,
    // Close enough to swing.
    reach: 40,
    // 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
    }
};
```
