# Bodies on a map

> Retro bodies on a tilemap: walls, ledges, slopes a ball rolls down and a crate stands on, a belt, and coin tiles taken with onTileEnter.

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

Retro bodies on a map. Nothing here is told about the tiles: the world finds the scene's maps, and every dynamic body is stopped by their walls, stands on their ledges from above, and on a slope does what the old games did: a crate stands where it lands, a ball rolls down.

A belt (`push` on a tile) carries what stands on it. The coins are tiles with nothing solid about them, only `props: { coin: true }`: a ball rolling over one is told with `onTileEnter`, which hands it the tile and its cell, and `setTile` takes it out of the map. **Click** to drop a ball or a crate.

## 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/ball.ts`:

```ts
import { createPixels, createPixelTexture, fillCircle } from 'nacatamalon/pixels';

// A white disc, painted once for the scene and tinted per ball. Odd-sized so it has a middle
// pixel and comes out round.
export const paintBall = (size: number) => {
    const side = size | 1;
    const pixels = createPixels(side, side);
    fillCircle(pixels, (side - 1) / 2, (side - 1) / 2, (side - 1) / 2, '#ffffff');
    return createPixelTexture(pixels);
};
```

`art/tiles.ts`:

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

// The tiles of the map, eight pixels a side, painted from rows of letters.
export const paintTiles = () => sheetFromRows({
    ground: ['gggggggg', 'gGggGggG', 'GdGddGdG', 'dddddddd', 'dDdddddD', 'dddDdddd', 'dddddddd', 'DdddddDd'],
    earth: ['dddddddd', 'dDdddddD', 'dddDdddd', 'dddddddd', 'ddddDddd', 'dDdddddd', 'ddddddDd', 'dddddddd'],
    ledge: ['ssssssss', 'SSSSSSSS', '.S....S.', '.S....S.', '........', '........', '........', '........'],
    up: ['.......g', '......gG', '.....gGd', '....gGdd', '...gGddd', '..gGdddd', '.gGddddd', 'gGdddddd'],
    down: ['g.......', 'Gg......', 'dGg.....', 'ddGg....', 'dddGg...', 'ddddGg..', 'dddddGg.', 'ddddddGg'],
    belt: ['SSSSSSSS', 'YsYsYsYs', 'SSSSSSSS', 'S.S.S.S.', 'SSSSSSSS', 'dddddddd', 'dDdddddD', 'dddddddd'],
    coin: ['........', '..yyyy..', '.yYYYYy.', '.yYyyYy.', '.yYyyYy.', '.yYYYYy.', '..yyyy..', '........'],
    ladder: ['Y......Y', 'YyyyyyyY', 'Y......Y', 'Y......Y', 'Y......Y', 'YyyyyyyY', 'Y......Y', 'Y......Y'],
}, {
    g: '#6abe30',
    G: '#37946e',
    d: '#8f563b',
    D: '#663931',
    s: '#9badb7',
    S: '#696a6a',
    y: '#fbf236',
    Y: '#df7126',
});
```

`components/drop.ts`:

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

// A ball or a crate dropped onto the map. A ball takes the coins it rolls over.
export const Drop = (x: number, y: number, color: string, ball: TTexture | null, collected: () => void) => {
    createSprite({
        ...(ball !== null ? { texture: ball } : {}),
        tint: color,
        width: ball !== null ? 7 : 8,
        height: ball !== null ? 7 : 8,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: ball !== null ? { shape: 'circle', radius: 3.5 } : { shape: 'rect', width: 8, height: 8 },
        // A ball bounces a little and slows down a little as it rolls.
        bounce: ball !== null ? 0.3 : 0,
        drag: ball !== null ? 15 : 0,
    });

    if (ball === null) {
        return;
    }
    getRetroBody2d(useSelf())?.onTileEnter(({ tile, cell }) => {
        if (tile.props?.coin === true) {
            setTile(cell.map, cell.layer, cell.column, cell.row, 0);
            collected();
        }
    });
};
```

`components/world.ts`:

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

import { paintTiles } from '../art/tiles';
import { ROWS, LEGEND } from '../data/level';

// The map: what each tile is to a body is written on it. Solid, a ledge (one way), a slope, a belt
// that carries what stands on it, and coins that are only pictures with something written on them.
export const World = () => {
    const tiles = paintTiles();
    const { frames } = tiles;

    return createTilemap({
        doc: {
            cell: 8,
            width: ROWS[0].length,
            height: ROWS.length,
            tiles: {
                1: { frame: frames.ground, solid: true },
                2: { frame: frames.earth, solid: true },
                3: { frame: frames.ledge, oneWay: true },
                4: { frame: frames.up, slope: [0, 1] },
                5: { frame: frames.down, slope: [1, 0] },
                6: { frame: frames.belt, solid: true, push: { x: 40, y: 0 } },
                7: { frame: frames.coin, props: { coin: 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
        }),
    });
};
```

`data/level.ts`:

```ts
// Which tile each character is: `#` ground, `=` earth, `-` a ledge, `u` a slope up to the right, `d`
// one down, `>` a belt, `o` a coin.
export const LEGEND: Record<string, number> = { '#': 1, '=': 2, '-': 3, 'u': 4, 'd': 5, '>': 6, 'o': 7 };

export const ROWS = [
    '=............................=',
    '=............................=',
    '=............................=',
    '=............................=',
    '=....o..o..o.................=',
    '=.-----------................=',
    '=............................=',
    '=..................o..o..o...=',
    '=.................----------.=',
    '=............................=',
    '=............................=',
    '=............................=',
    '=............................=',
    '=...........oo...............=',
    '=...........ud...............=',
    '=..........u==d..............=',
    '=...o.o.o.u====d.....>>>>>>..=',
    '##############################',
    '==============================',
    '==============================',
];
```

`scenes/demo.ts`:

```ts
import { createScene, createText, useCamera2d, usePointer, useRetroWorld2d, useSpawn, useTimer } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';

import * as Settings from '../settings';
import { World } from '../components/world';
import { Drop } from '../components/drop';
import { paintBall } from '../art/ball';

export const Scene = () => {
    const rng = useRandom();

    // The map is 240 by 160: seen twice as big.
    useCamera2d({
        zoom: 2
    });
    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 500
        }
    });

    useSpawn(World)();

    let coins = 0;
    const counter = createText({
        text: 'COINS 0',
        transform: {
            x: 40,
            y: 10
        }
    });
    const ball = paintBall(7);
    const spawn = useSpawn(Drop, { name: 'Drop', parent: 'scene' });
    let count = 0;
    const drop = (x: number, y: number) => {
        if (count >= Settings.MOST) {
            return;
        }
        count++;
        spawn(x, y, rng.choose(Settings.PALETTE), count % 2 === 0 ? ball : null, () => {
            coins++;
            counter.text = `COINS ${coins}`;
        });
    };

    const timer = useTimer();
    const rain = timer.every(0.5, () => {
        drop(rng.rand(16, 224), 8);
        if (count >= 24) {
            rain.cancel();
        }
    });
    usePointer().onDown((info) => drop(info.worldX, info.worldY));

    return createScene();
};
```

`settings.ts`:

```ts
// Retro bodies on a map. Nothing here is told about the tiles: the world finds the scene's maps and
// every dynamic body is stopped by their walls, stands on their ledges from above, and on a slope
// does what the old games did: a crate stands where it lands, a ball rolls down.
//
// A belt (`push` on a tile) carries what stands on it. The coins are tiles with nothing solid about
// them, only `props: { coin: true }`: a ball rolling over one is told with `onTileEnter`, which
// hands it the tile and its cell, and `setTile` takes it out of the map.

export const WIDTH = 480;
export const HEIGHT = 320;
export const MOST = 40;
export const PALETTE = ['#ff6b6b', '#5db6ff', '#ffd93d', '#c77dff', '#ffffff'];
```
