createGameStorefunctionnacatamalon
createGameStore(config: TGameStoreConfig<S, A>) => TGameStore<S, A>Makes a store: data of the game that outlives a scene (lives, coins, options, a pet), with a way to be told when it changes and, optionally, to be saved and loaded.
A signal says that something happened; a store holds what is still true. Make it once, in a file of its own, and import it wherever it is needed: like a signal, it belongs to the page, not to a scene or a game.
- Read:
store.state.hunger, anywhere. - Change: an action, or
store.set((s) => { s.hunger -= 1; }). The state is changed in place. - React:
useStore(store, selector, handler)in a scene,store.subscribe(...)anywhere else. Everyone listening is told straight away, inside thesetthat changed it. - Keep it:
persistwithlocalStorageAdapter(),indexedDbAdapter(name)or an adapter of your own, thenload()when the game starts.
Parameters
configTGameStoreConfig<S, A>Its
key, its startingstate, itsactions, and how it saves itself (persist).
Example
declare const pet: TSprite;
const GREEN = getColor('#40c040');
const RED = getColor('#e04040');
// stores/pet.ts
export const petStore = createGameStore({
key: 'pet',
state: { hunger: 70, timesFed: 0 },
actions: (set) => ({
feed: () => set((s) => { s.hunger = Math.min(100, s.hunger + 15); s.timesFed++; }),
}),
persist: { adapter: localStorageAdapter() },
});
// when the game starts
await petStore.load();
// in a scene
useStore(petStore, (s) => s.hunger > 30, (content) => { pet.tint = content ? GREEN : RED; });