# Game systems

> Code for the whole game with registerGameSystem: a clock of the time played, achievements that listen to a store and a reset key, running through every change of level and whatever level the game starts on.

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

Press **space** to go to the other level, and **R** to wipe the progress.

Some code belongs to the whole game rather than to a scene. `registerGameSystem(name, fn)`, called once before `createGame`, runs `fn` when the game starts, before its first scene, in a box no change of scene touches, and goes on until the game ends. Its `useUpdate` runs every frame before the scenes'. Here there are three, in `systems/`:

- **clock**: counts the time played, whatever level is on. A paused game pauses it too.
- **achievements**: watches the store and unlocks a title after ten seconds played, or after three visits to a level.
- **reset key**: **R** wipes the progress from any level, without either level knowing.

They draw nothing: the levels show what they keep, from a store. Change the scene the game starts on in `index.ts` to `'Cave'` and the three systems run just the same; a scene that launched them would be missing then, as it is when the editor plays one level straight away.

## Code

`index.ts`:

```ts
import { createGame, registerGameSystem } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';
import { makeLevel } from './scenes/level';
import { clock } from './systems/clock';
import { achievements } from './systems/achievements';
import { resetKey } from './systems/reset_key';

// The game's systems, before the game is made. Each runs once in it, before its first scene.
registerGameSystem('clock', clock);
registerGameSystem('achievements', achievements);
registerGameSystem('reset-key', resetKey);

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: '#05080f',
});

// Declare Scenes. Start on 'Cave' instead and the systems run just the same.
game({
    Meadow: makeLevel('MEADOW', 'Cave', '#6fb3e0', '#3f8a3a'),
    Cave: makeLevel('CAVE', 'Meadow', '#1d1a2e', '#4a3b2c'),
}, 'Meadow');
```

`scenes/level.ts`:

```ts
import { createScene, createSprite, createText, getColor, useKeyboard, useScene, useStore, useUpdate } from 'nacatamalon';
import { progress } from '../stores/progress';
import { WIDTH, HEIGHT } from '../settings';

// A level knows nothing of the systems: it counts its visit, shows what the store holds and changes
// to the other level on SPACE.
export const makeLevel = (title: string, next: string, sky: string, ground: string) => () => {
    const scene = useScene();
    const keys = useKeyboard();
    progress.set((s) => { s.visits += 1; });

    createSprite({ anchor: { x: 0, y: 0 }, width: WIDTH, height: HEIGHT, tint: getColor(sky) });
    createSprite({ anchor: { x: 0, y: 0 }, width: WIDTH, height: 50, tint: getColor(ground), transform: { x: 0, y: HEIGHT - 50 } });
    createText({ text: title, style: { fontSize: 16 }, tint: '#f2f6fa', transform: { x: 16, y: 14 } });

    const played = createText({ text: '', style: { fontSize: 8 }, tint: '#f2f6fa', transform: { x: 16, y: 44 } });
    const visits = createText({ text: '', style: { fontSize: 8 }, tint: '#f2f6fa', transform: { x: 16, y: 58 } });
    const unlocked = createText({ text: '', style: { fontSize: 8 }, tint: '#ffd34d', transform: { x: 16, y: 72 } });
    createText({ text: 'SPACE OTHER LEVEL   R RESET', style: { fontSize: 8 }, tint: '#f2f6fa', transform: { x: 16, y: HEIGHT - 20 } });

    // Shown now, and again each time the store changes them.
    const showVisits = (count: number) => { visits.text = `VISITS ${count}`; };
    const showUnlocked = (titles: string) => { unlocked.text = titles === '' ? '' : `UNLOCKED ${titles}`; };
    showVisits(progress.state.visits);
    showUnlocked(progress.state.unlocked.join('  '));
    useStore(progress, (s) => s.visits, showVisits);
    useStore(progress, (s) => s.unlocked.join('  '), showUnlocked);

    useUpdate(() => {
        played.text = `PLAYED ${progress.state.seconds.toFixed(1)} S`;
        if (keys.justPressed(' ')) scene.change(next);
    });
    return createScene();
};
```

`stores/progress.ts`:

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

// What the systems keep and the levels show. A store, because it outlives every scene.
export const progress = createGameStore({
    key: 'game-systems-progress',
    state: { seconds: 0, visits: 0, unlocked: [] as string[] },
});
```

`systems/achievements.ts`:

```ts
import { useStore } from 'nacatamalon';
import { progress } from '../stores/progress';

const unlock = (title: string) => progress.set((s) => {
    if (!s.unlocked.includes(title)) s.unlocked.push(title);
});

// Listens to the store for the whole game: whichever level changed it, it hears. Its listeners leave
// with it when the game ends.
export const achievements = () => {
    useStore(progress, (s) => s.seconds >= 10, (played) => { if (played) unlock('TEN SECONDS'); });
    useStore(progress, (s) => s.visits >= 3, (travelled) => { if (travelled) unlock('EXPLORER'); });
};
```

`systems/clock.ts`:

```ts
import { useUpdate } from 'nacatamalon';
import { progress } from '../stores/progress';

// Every frame of the game, before any level's own updates. It stops while the game is paused, as the
// levels do, so the time played is only the time played.
export const clock = () => {
    useUpdate((delta) => {
        progress.set((s) => { s.seconds += delta; });
    });
};
```

`systems/reset_key.ts`:

```ts
import { useKeyboard, useUpdate } from 'nacatamalon';
import { progress } from '../stores/progress';

// A key that works in every level, with no level knowing about it.
export const resetKey = () => {
    const keys = useKeyboard();
    useUpdate(() => {
        if (keys.justPressed('r')) progress.reset();
    });
};
```

`settings.ts`:

```ts
// Game systems: code that belongs to the whole game, not to a scene. Registered once in index.ts,
// before createGame, each one starts with the game, before its first scene, and goes on through every
// change of scene until the game ends. They draw nothing; the levels show what they keep, from a
// store.
//
// - systems/clock.ts: counts the time played, whatever level is on. Paused game, paused clock.
// - systems/achievements.ts: watches the store and unlocks a title when the player has played ten
//   seconds, or been to three levels.
// - systems/reset_key.ts: R wipes the progress, from any level, without either level knowing.
//
// Change the second argument of game(...) in index.ts to 'Cave': the game starts there and the three
// systems run all the same. A scene that launched the others would be missing then, as it would be
// when the editor plays one level straight away.
//
// SPACE goes to the other level, R resets.

export const WIDTH = 320;
export const HEIGHT = 180;
```
