Settings Manager
Player preferences (volume, language, controls, screen shake) with defaults, checked values and saving, and a change event so the game updates straight away.
Files: settings-manager.js (the component, no dependencies) and settings-manager.test.mjs (4 tests).
Copy settings-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createSettings } from "./settings-manager.js";
const settings = createSettings({
key: "my-game:settings",
schema: {
musicVolume: { type: "number", min: 0, max: 1, default: 0.8 },
language: { type: "choice", options: ["en", "es", "fr"], default: "en" },
screenShake: { type: "boolean", default: true },
playerName: { type: "string", maxLength: 16, default: "" },
},
});
settings.onChange((key, value) => { if (key === "musicVolume") audio.setVolume("music", value); });
settings.set("musicVolume", 0.5);
API
createSettings({ schema, key, storage }) → settingssettings.get(key) / settings.all() (a copy)settings.set(key, value) → the value kept (numbers are clamped and stepped, wrong types are refused and the old value kept)settings.reset(key?)one setting, or all, back to defaultsettings.onChange(fn) → offfn(key, value, oldValue); fired once per key for reset()settings.applyAll()fire onChange for every key (call once at start so the game picks up saved values)
Types: number { min, max, step }, boolean, choice { options }, string { maxLength }, object (stored as is).
Saved values that no longer fit the schema fall back to the default. New schema keys get their default.
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes, no engine code involved. |
Tests
Node tests: defaults, saving and loading, clamping and steps, refusing bad values, choices, change events, reset, damaged saved settings, blocked storage.
Run them with node --test toolkit/components/settings-manager/ (Node 20 or newer, nothing to install).