# Sheepdog

> A field from above: moveTowards for the dog, accelerateTowards for the sheep, bounds stop, onTileExit for the pond, a gate switched off with enabled.

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

A field seen from above, with no gravity. The dog runs after the pointer, the sheep run away from the dog, and the job is to get them all into the pen.

`moveTowards` takes the dog to the pointer at its speed and stops it there. `accelerateTowards` speeds a sheep away from a dog that comes close, and it drifts to a stop. `bounds: 'stop'` makes the world the field, and nothing gets out of it. `onTileEnter` and `onTileExit` slow the dog to a crawl in the pond and let it run again out of it. **Space** opens and closes the gate, its body switched off with `enabled`. The ball's bounce is by axis: it keeps all its speed off the side fences and little off the others.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { installRetroPhysics2d } from 'nacatamalon/retro-physics2d';

import * as Settings from './settings';
import { Scene } from './scenes/demo';

// The one line that makes retro bodies move. Nothing to load: no WebAssembly, no waiting.
installRetroPhysics2d();

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#0a0a18',
});

// Declare Scenes
game({
    Scene
}, 'Scene');
```

`art/tiles.ts`:

```ts
import { sheetFromRows } from 'nacatamalon/pixels';

// The tiles of the field, eight pixels a side, painted from rows of letters.
export const paintTiles = () => sheetFromRows({
    grass: ['gggggggg', 'ggGggggg', 'gggggGgg', 'gggggggg', 'gGgggggg', 'ggggggGg', 'gggggggg', 'gggGgggg'],
    water: ['bbbbbbbb', 'bbBBbbbb', 'bbbbbbbb', 'bbbbbBBb', 'bbbbbbbb', 'bBBbbbbb', 'bbbbbbbb', 'bbbbBBbb'],
    fence: ['.wwwwww.', 'wWWWWWWw', '.wwwwww.', '.w....w.', '.wwwwww.', 'wWWWWWWw', '.wwwwww.', '.w....w.'],
}, {
    g: '#4b8b3b',
    G: '#3a6f2e',
    b: '#3f74b5',
    B: '#6aa0e0',
    w: '#a07040',
    W: '#6b4a2b',
});
```

`components/ball.ts`:

```ts
import { createSprite, useRetroBody2d, useSelf } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';

// A ball to push about. Its bounce is by axis: off the field's sides it keeps all its speed, off
// its top and bottom only a little, so it runs on along the field.
export const Ball = (x: number, y: number) => {
    createSprite({
        tint: '#ff6b6b',
        width: 6,
        height: 6,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'circle',
            radius: 3
        },
        bounds: 'stop',
        bounce: {
            x: 1,
            y: 0.3
        },
        drag: 10,
        mass: 0.3,
    });
    getRetroBody2d(useSelf())!.setLinearVelocity(70, 40);
};
```

`components/dog.ts`:

```ts
import { createSprite, usePointer, useRetroBody2d, useSelf, useUpdate } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';

import * as Settings from '../settings';

// The dog runs after the pointer, slower in the pond.
export const Dog = (x: number, y: number) => {
    createSprite({
        tint: '#2b2b2b',
        width: 8,
        height: 8,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: 8,
            height: 8
        },
        bounds: 'stop',
    });

    const body = getRetroBody2d(useSelf())!;
    const pointer = usePointer();

    // A tile is told once as it starts touching it and once as it stops, and the dog can be on
    // several pond tiles at a time: it is wading while it touches any.
    let wet = 0;
    body.onTileEnter(({ tile }) => {
        if (tile.props?.water === true) {
            wet++;
        }
    });
    body.onTileExit(({ tile }) => {
        if (tile.props?.water === true) {
            wet--;
        }
    });

    useUpdate(() => {
        const at = pointer.position();
        if (at === null) {
            return;
        }
        // Asked every frame, as the pointer moves: it sets the dog's velocity, and stops it there.
        body.moveTowards({ x: at.worldX, y: at.worldY }, wet > 0 ? Settings.DOG.wading : Settings.DOG.speed);
    });
};
```

`components/field.ts`:

```ts
import { createSpriteAtlas, createTilemap } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';

import * as Settings from '../settings';
import { paintTiles } from '../art/tiles';
import { ROWS, LEGEND } from '../data/field';

// The field. The fence is solid; the pond is not, only written on: the dog reads it as it goes in.
export const Field = () => {
    const tiles = paintTiles();
    const { frames } = tiles;

    return createTilemap({
        doc: {
            cell: Settings.CELL,
            width: ROWS[0].length,
            height: ROWS.length,
            tiles: {
                1: { frame: frames.grass },
                2: { frame: frames.water, props: { water: true } },
                3: { frame: frames.fence, solid: true },
            },
            layers: [
                {
                    name: 'ground',
                    order: 'under',
                    data: ROWS.flatMap((row) => [...row].map((character) => LEGEND[character] ?? 0)),
                }
            ],
        },
        atlas: createSpriteAtlas({
            texture: createPixelTexture(tiles.pixels),
            columns: tiles.columns
        }),
    });
};
```

`components/gate.ts`:

```ts
import { createSprite, getColor, useKeyboard, useRetroBody2d, useUpdate } from 'nacatamalon';

import * as Settings from '../settings';

const SHUT = getColor('#a07040');
const OPEN = getColor('#3a6f2e');

// The pen's gate: a body that Space switches off and on. Switched off, it stops nothing and nothing
// touches it; it stays where it is, ready to close.
export const Gate = (said: (open: boolean) => void) => {
    const sprite = createSprite({
        tint: SHUT,
        width: Settings.GATE.width,
        height: Settings.GATE.height,
        transform: {
            x: Settings.GATE.x,
            y: Settings.GATE.y
        }
    });
    const gate = useRetroBody2d({
        body: 'static',
        collider: {
            shape: 'rect',
            width: Settings.GATE.width,
            height: Settings.GATE.height
        },
    });
    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed(' ')) {
            gate.enabled = !gate.enabled;
            sprite.tint = gate.enabled ? SHUT : OPEN;
            said(!gate.enabled);
        }
    });
};
```

`components/sheep.ts`:

```ts
import { createSprite, useRetroBody2d, useSelf, useUpdate } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';
import type { TGameObject } from 'nacatamalon';

import * as Settings from '../settings';

// A sheep stays put until the dog comes close, then runs the other way.
export const Sheep = (x: number, y: number, dog: TGameObject) => {
    const sprite = createSprite({
        tint: '#f4f1e8',
        width: 9,
        height: 7,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: 9,
            height: 7
        },
        bounds: 'stop',
        maxSpeed: Settings.SHEEP.speed,
        drag: 80,
    });

    const body = getRetroBody2d(useSelf())!;
    const there = (dog.drawables[0] as { transform: { x: number; y: number } }).transform;

    useUpdate(() => {
        const here = sprite.transform;
        const dx = here.x - there.x;
        const dy = here.y - there.y;
        const far = Math.hypot(dx, dy);
        if (far < Settings.SHEEP.fear && far > 0) {
            // Towards a point straight away from the dog: speeding up, never past its maxSpeed.
            body.accelerateTowards({ x: here.x + dx / far * 100, y: here.y + dy / far * 100 }, Settings.SHEEP.flee);
        } else {
            // Nothing pushing it: its drag slows it down.
            body.acceleration.x = 0;
            body.acceleration.y = 0;
        }
    });
};
```

`data/field.ts`:

```ts
// Which tile each character is: `.` grass, `w` the pond, `#` the fence. The gap in the fence is
// where the gate goes.
export const LEGEND: Record<string, number> = { '.': 1, 'w': 2, '#': 3 };

export const ROWS = [
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '..............................',
    '..............................',
    '........................#.....',
    '....wwwwww..............#.....',
    '...wwwwwwww.............#.....',
    '...wwwwwwww.............#.....',
    '....wwwwww..............#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
    '........................#.....',
];
```

`scenes/demo.ts`:

```ts
import { createScene, createText, useCamera2d, useRetroWorld2d, useSpawn, useUpdate } from 'nacatamalon';

import * as Settings from '../settings';
import { Field } from '../components/field';
import { Dog } from '../components/dog';
import { Sheep } from '../components/sheep';
import { Gate } from '../components/gate';
import { Ball } from '../components/ball';

export const Scene = () => {
    // The field is 240 by 160: seen twice as big.
    useCamera2d({
        zoom: 2
    });
    // No gravity, seen from above, and the world ends where the field does: what stops at its
    // edges (bounds: 'stop') cannot leave it.
    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 0
        },
        bounds: {
            x: 0,
            y: 0,
            width: Settings.FIELD.width,
            height: Settings.FIELD.height
        }
    });

    useSpawn(Field)();
    const dog = useSpawn(Dog, 'Dog')(40, 80);
    const sheep = useSpawn(Sheep, 'Sheep');
    const flock = [
        sheep(90, 40, dog),
        sheep(110, 60, dog),
        sheep(100, 100, dog),
        sheep(130, 120, dog),
        sheep(140, 80, dog),
    ];
    useSpawn(Ball, 'Ball')(60, 30);

    const gate = createText({
        text: 'SPACE: OPEN',
        transform: {
            x: 60,
            y: 150
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });
    useSpawn(Gate, 'Gate')((open: boolean) => {
        gate.text = open ? 'SPACE: SHUT' : 'SPACE: OPEN';
    });

    const counter = createText({
        text: '',
        transform: {
            x: 200,
            y: 150
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });
    useUpdate(() => {
        const penned = flock.filter((one) => (one.drawables[0] as { transform: { x: number } }).transform.x > Settings.PEN).length;
        counter.text = penned === flock.length ? 'ALL IN!' : `PEN ${penned}/${flock.length}`;
    });

    return createScene();
};
```

`settings.ts`:

```ts
// A field seen from above, with no gravity. The dog runs after the pointer, the sheep run away from
// the dog, and the job is to get them all into the pen.
//
//   moveTowards: the dog heads for the pointer at its speed and stops on it.
//   accelerateTowards: a sheep that has the dog close speeds up away from it, and drifts to a stop.
//   bounds: 'stop': the world is the field, and nothing gets out of it.
//   onTileEnter / onTileExit: the dog wades through the pond at a crawl, and runs again out of it.
//   enabled: Space opens the gate (its body switched off) and closes it again.
//   bounce by axis: the ball keeps all its speed off the side fences and little off the others.

export const WIDTH = 480;
export const HEIGHT = 320;
// The field is the map: 30 by 20 cells of 8 pixels, seen twice as big.
export const CELL = 8;
export const FIELD = { width: 240, height: 160 };
export const DOG = { speed: 90, wading: 30 };
export const SHEEP = { count: 5, fear: 48, flee: 400, speed: 45 };
// Where the pen begins: right of the fence.
export const PEN = 200;
export const GATE = { x: 196, y: 80, width: 8, height: 16 };
```
