# Store and persistence

> createGameStore split across files (state and actions), saved to localStorage so the pet survives a reload.

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

`createGameStore` holds what is still true across scenes and sessions. It is split across files the way a real project would be: `stores/pet/state.ts` (plain JSON, what gets saved), two files of actions, and one `index.ts` that puts them together. **F** feeds, **P** plays, **R** resets; the bars go down over time. **Reload the page and the pet is exactly where you left it.**

`useStore(petStore, selector, handler)` reacts only when the selected value changes: the console logs the mood flip, not every frame. Saving to IndexedDB is one line, and a server of your own is an adapter with two functions, `load` and `save`.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { createPetStore } from './stores/pet';
import { clearGameStores } from 'nacatamalon/authoring';
import { createPetScene } from './scenes/demo';

// This host runs the project again on every edit. Forget the previous run's store index.
clearGameStores();

const petStore = createPetStore();

petStore.load().then((found) => {
    console.log('[pet] saved game found:', found, JSON.stringify(petStore.state));

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

    // Declare Scenes
    game({
        Pet: createPetScene(petStore)
    });
});
```

`components/pet.ts`:

```ts
import { createSprite, createText, useKeyboard, useLoadBitmapFont, useStore, useUpdate } from 'nacatamalon';
import * as Settings from '../settings';
import type { TPetStore } from '../stores/pet';
import { bar } from '../helpers/bar';

export const Pet = (petStore: TPetStore) => {
    const font = useLoadBitmapFont(Settings.ARCADE);
    const keys = useKeyboard();

    createText({
        text: 'HUNGER',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.WHITE,
        anchor: {
            x: 0,
            y: 0.5
        },
        transform: {
            x: 20,
            y: 30
        }
    });
    createText({
        text: 'HAPPY',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.WHITE,
        anchor: {
            x: 0,
            y: 0.5
        },
        transform: {
            x: 20,
            y: 56
        }
    });

    const hungerBar = bar(30);
    const happyBar = bar(56);

    const fed = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.WHITE,
        transform: {
            x: 20,
            y: 80
        }
    });

    createText({
        text: 'F FEED  P PLAY  R RESET',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.WHITE,
        anchor: {
            x: 0.5,
            y: 0
        },
        transform: {
            x: 170,
            y: 200
        }
    });

    // Read straight away: the store is already loaded when the scene starts.
    const content = () => petStore.state.hunger > 30 && petStore.state.happy > 30;

    const pet = createSprite({
        tint: content() ? Settings.BODY : Settings.RED,
        width: 64,
        height: 64,
        transform: {
            x: 170,
            y: 140
        }
    });

    // Only when the mood flips, not on every frame the bars go down. And it stops by itself if
    // the scene goes away.
    useStore(petStore, (s) => s.hunger > 30 && s.happy > 30, (isContent) => {
        pet.tint = isContent ? Settings.BODY : Settings.RED;
        console.log('[pet] mood ->', isContent ? 'content' : 'unhappy');
    });

    useUpdate((delta) => {
        petStore.actions.decay(delta);

        if (keys.justPressed('f')) {
            petStore.actions.feed();
        }

        if (keys.justPressed('p')) {
            petStore.actions.play();
        }

        // reset() goes back to the state the store was created with.
        if (keys.justPressed('r')) {
            petStore.reset();
        }

        const { hunger, happy, timesFed } = petStore.state;

        hungerBar.width = (hunger / 100) * Settings.BAR_WIDTH;
        hungerBar.tint = hunger > 30 ? Settings.GREEN : Settings.RED;
        happyBar.width = (happy / 100) * Settings.BAR_WIDTH;
        happyBar.tint = happy > 30 ? Settings.GREEN : Settings.RED;
        fed.text = 'FED ' + timesFed;
    });
};
```

`helpers/bar.ts`:

```ts
import { createSprite } from 'nacatamalon';
import * as Settings from '../settings';

export const bar = (y: number) => {
    createSprite({
        tint: Settings.TRACK,
        anchor: {
            x: 0,
            y: 0.5
        },
        width: Settings.BAR_WIDTH,
        height: 14,
        transform: {
            x: 120,
            y: y
        }
    });

    return createSprite({
        tint: Settings.GREEN,
        anchor: {
            x: 0,
            y: 0.5
        },
        width: Settings.BAR_WIDTH,
        height: 14,
        transform: {
            x: 120,
            y: y
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { Pet } from '../components/pet';
import type { TPetStore } from '../stores/pet';
export const createPetScene = (store: TPetStore) => () => {
    useSpawn(Pet)(store);

    return createScene();
};
```

`settings.ts`:

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

export const WIDTH = 340;
export const HEIGHT = 220;
export const ARCADE = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};

export const GREEN = getColor('#5bd75b');
export const RED = getColor('#e5533b');
export const TRACK = getColor('#2a2740');
export const BODY = getColor('#8ab4f8');
export const WHITE = getColor('#ffffff');

export const BAR_WIDTH = 200;
// Anchored on its left edge, so changing its width grows it to the right.
```

`stores/pet/actions/care.ts`:

```ts
import type { TStoreSet } from 'nacatamalon';
import type { PetState } from '../state';

// set changes the live state in place: no copies, even for something that changes every frame.
export const careActions = (set: TStoreSet<PetState>) => ({
    feed: () => set((s) => {
        s.hunger = Math.min(100, s.hunger + 15);
        s.timesFed++;
    }),
    play: () => set((s) => {
        s.happy = Math.min(100, s.happy + 15);
    }),
});
```

`stores/pet/actions/life.ts`:

```ts
import type { TStoreSet } from 'nacatamalon';
import type { PetState } from '../state';

export const lifeActions = (set: TStoreSet<PetState>) => ({
    decay: (delta: number) => set((s) => {
        s.hunger = Math.max(0, s.hunger - delta * 3);
        s.happy = Math.max(0, s.happy - delta * 2);
    }),
});
```

`stores/pet/index.ts`:

```ts
import { createGameStore, localStorageAdapter } from 'nacatamalon';
import { petState } from './state';
import { careActions } from './actions/care';
import { lifeActions } from './actions/life';

// Made at startup and shared by the game's scenes: it outlives any one scene.
//
// persist saves it in localStorage by itself (at most every 250 ms), so it survives a reload.
// Saving somewhere else is this one line:
//   indexedDbAdapter('pet-game')         bigger saves, save slots
//   an adapter of your own               a server or an external database: two functions,
//                                        load(key) and save(key, state)
// mode: 'manual' would only save on petStore.save(), like a save point.
export const createPetStore = () => createGameStore({
    key: 'nacatamalon-demo-pet',
    state: petState,
    actions: (set) => ({
        ...careActions(set),
        ...lifeActions(set),
    }),
    persist: {
        adapter: localStorageAdapter(),
        mode: 'auto'
    },
});

export type TPetStore = ReturnType<typeof createPetStore>;
```

`stores/pet/state.ts`:

```ts
export type PetState = {
    hunger: number;   // 0..100
    happy: number;    // 0..100
    timesFed: number;
};

// A brand-new pet. load() puts a saved game over these, so a field added later
// still gets its value when an old save is loaded.
export const petState: PetState = {
    hunger: 70,
    happy: 70,
    timesFed: 0,
};
```
