Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(game): gameplay asks for actions, and settings survive the app closing

esengine7e16fb59177d
diff --git a/examples/celestial-heights/src/actions.ts b/examples/celestial-heights/src/actions.ts
new file mode 100644
index 000000000..3e8611b03
--- /dev/null
+++ b/examples/celestial-heights/src/actions.ts
@@ -0,0 +1,25 @@
+import {
+ defineInputMap, Axis2D, Button, Keys2D, Stick, Key, GpButton, GamepadButton,
+} from 'esengine';
+
+/**
+ * Gameplay asks for named actions, never for keys — which is what makes the
+ * settings menu able to rebind them and a gamepad able to answer them. The map
+ * registers its own per-frame evaluation.
+ */
+export const Actions = defineInputMap({
+ Move: Axis2D(
+ Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'),
+ Keys2D('ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'),
+ Stick('left'),
+ ),
+ Attack: Button(Key('Space'), GpButton(GamepadButton.West)),
+ Pause: Button(Key('Escape'), GpButton(GamepadButton.Start)),
+ Pack: Button(Key('Tab'), GpButton(GamepadButton.North)),
+ Language: Button(Key('KeyL')),
+ Save: Button(Key('F5')),
+ Load: Button(Key('F9')),
+});
+
+/** Where the player's own bindings live; `Actions.save/load` own the format. */
+export const BINDINGS_KEY = 'celestial-heights.bindings';
diff --git a/examples/celestial-heights/src/main.ts b/examples/celestial-heights/src/main.ts
index 252b09e61..8cd2b909b 100644
--- a/examples/celestial-heights/src/main.ts
+++ b/examples/celestial-heights/src/main.ts
@@ -1,8 +1,9 @@
import {
- addSystemToSchedule, addSystemSetToSchedule, defineSystemSet, Schedule,
+ addStartupSystem, addSystemToSchedule, addSystemSetToSchedule, defineSystemSet, Schedule,
} from 'esengine';
import './components';
+import './actions';
import { session } from './state';
import { playerMoveSystem, playerAttackSystem } from './systems/player';
import {
@@ -11,7 +12,7 @@ import {
import { healthBarSystem, hitFlashSystem, vitalityMeterSystem } from './systems/feedback';
import { cameraBindSystem, navFromTerrainSystem, gateSystem } from './systems/world';
import { pauseInputSystem, pauseTimeSystem, pauseOverlaySystem } from './systems/pause';
-import { cycleLanguageSystem } from './systems/settings';
+import { applySettingsSystem, cycleLanguageSystem } from './systems/settings';
import {
saveRunSystem, loadRunSystem, applyRestoreSystem, rememberRosterSystem,
} from './systems/save';
@@ -28,6 +29,8 @@ import { perceiverFacingSystem } from './ai/wisp';
// The world systems run every frame rather than at startup: an area switch
// brings a new camera, a new terrain and a new player, and startup is long past.
+addStartupSystem(applySettingsSystem);
+
addSystemToSchedule(Schedule.PreUpdate, navFromTerrainSystem);
addSystemToSchedule(Schedule.PreUpdate, cameraBindSystem);
addSystemToSchedule(Schedule.PreUpdate, rememberRosterSystem);
diff --git a/examples/celestial-heights/src/settings.ts b/examples/celestial-heights/src/settings.ts
new file mode 100644
index 000000000..010f28c79
--- /dev/null
+++ b/examples/celestial-heights/src/settings.ts
@@ -0,0 +1,27 @@
+import { Storage } from 'esengine';
+
+/**
+ * What the player chose, as opposed to what the run is. Kept apart from the save
+ * slot on purpose: settings outlive a run and follow the person, not the game.
+ */
+export interface Settings {
+ locale: string;
+ /** Draw hit sparks and the other flourishes. */
+ effects: boolean;
+}
+
+const KEY = 'celestial-heights.settings';
+
+export const DEFAULTS: Settings = { locale: '', effects: true };
+
+export function loadSettings(): Settings {
+ const stored = Storage.getJSON<Partial<Settings>>(KEY);
+ return {
+ locale: typeof stored?.locale === 'string' ? stored.locale : DEFAULTS.locale,
+ effects: typeof stored?.effects === 'boolean' ? stored.effects : DEFAULTS.effects,
+ };
+}
+
+export function saveSettings(settings: Settings): void {
+ Storage.setJSON(KEY, settings);
+}
diff --git a/examples/celestial-heights/src/systems/inventory.ts b/examples/celestial-heights/src/systems/inventory.ts
index 8e1f87a5d..0c1abf9d1 100644
--- a/examples/celestial-heights/src/systems/inventory.ts
+++ b/examples/celestial-heights/src/systems/inventory.ts
@@ -1,12 +1,13 @@
import {
defineSystem, Query, Mut, Res, Commands, GetWorld,
- Input, Transform, UINode, UIDisplay, Text, Localization,
+ Transform, UINode, UIDisplay, Text, Localization,
ArrayDataSource, createListView, spawnUIEntity, px, uiPlugin,
UIPositionType, TextAlign, TextVerticalAlign,
} from 'esengine';
import type { Entity, World, TextData, UIVisualData } from 'esengine';
import { UIVisual } from 'esengine';
import { Item, Player } from '../components';
+import { Actions } from '../actions';
import { ITEM_COLOR, PICKUP_RADIUS } from '../config';
import { session } from '../state';
@@ -37,9 +38,9 @@ export const pickupSystem = defineSystem(
);
export const inventoryInputSystem = defineSystem(
- [Res(Input)],
- (input) => {
- if (input.isKeyPressed('Tab')) session.inventoryOpen = !session.inventoryOpen;
+ [],
+ () => {
+ if (Actions.pressed('Pack')) session.inventoryOpen = !session.inventoryOpen;
},
{ name: 'InventoryInputSystem' },
);
diff --git a/examples/celestial-heights/src/systems/pause.ts b/examples/celestial-heights/src/systems/pause.ts
index 1f354b757..e90dad1d3 100644
--- a/examples/celestial-heights/src/systems/pause.ts
+++ b/examples/celestial-heights/src/systems/pause.ts
@@ -1,6 +1,5 @@
-import {
- defineSystem, Query, Mut, Res, ResMut, Input, Time, UINode, UIDisplay,
-} from 'esengine';
+import { defineSystem, Query, Mut, ResMut, Time, UINode, UIDisplay } from 'esengine';
+import { Actions } from '../actions';
import { PauseOverlay } from '../components';
import { session } from '../state';
@@ -8,9 +7,9 @@ import { session } from '../state';
// pause, and the others have to be able to draw it and to stop the world.
export const pauseInputSystem = defineSystem(
- [Res(Input)],
- (input) => {
- if (input.isKeyPressed('Escape')) session.paused = !session.paused;
+ [],
+ () => {
+ if (Actions.pressed('Pause')) session.paused = !session.paused;
},
{ name: 'PauseInputSystem' },
);
diff --git a/examples/celestial-heights/src/systems/player.ts b/examples/celestial-heights/src/systems/player.ts
index 4943532b0..d963a45fa 100644
--- a/examples/celestial-heights/src/systems/player.ts
+++ b/examples/celestial-heights/src/systems/player.ts
@@ -1,7 +1,6 @@
-import {
- defineSystem, Query, Mut, Res, Input, CharacterController,
-} from 'esengine';
+import { defineSystem, Query, Mut, CharacterController } from 'esengine';
import { Player, Facing, MeleeAttack } from '../components';
+import { Actions } from '../actions';
import { DEPTH_FORESHORTEN } from '../config';
/**
@@ -10,15 +9,12 @@ import { DEPTH_FORESHORTEN } from '../config';
* physics world's business and not this system's.
*/
export const playerMoveSystem = defineSystem(
- [Query(Mut(CharacterController), Mut(Facing), Player), Res(Input)],
- (players, input) => {
+ [Query(Mut(CharacterController), Mut(Facing), Player)],
+ (players) => {
+ const move = Actions.axis2d('Move');
for (const [, cc, facing, player] of players) {
- let dx = 0;
- let dy = 0;
- if (input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp')) dy += 1;
- if (input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown')) dy -= 1;
- if (input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft')) dx -= 1;
- if (input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight')) dx += 1;
+ const dx = move.x;
+ const dy = move.y;
if (dx === 0 && dy === 0) {
cc.velocity.x = 0;
@@ -39,9 +35,9 @@ export const playerMoveSystem = defineSystem(
/** Turns the attack key into the same `pending` flag the wisps' brain sets. */
export const playerAttackSystem = defineSystem(
- [Query(Mut(MeleeAttack), Player), Res(Input)],
- (players, input) => {
- if (!input.isKeyPressed('Space')) return;
+ [Query(Mut(MeleeAttack), Player)],
+ (players) => {
+ if (!Actions.pressed('Attack')) return;
for (const [, attack] of players) attack.pending = true;
},
{ name: 'PlayerAttackSystem' },
diff --git a/examples/celestial-heights/src/systems/save.ts b/examples/celestial-heights/src/systems/save.ts
index 295fcb9ac..b41fc09ab 100644
--- a/examples/celestial-heights/src/systems/save.ts
+++ b/examples/celestial-heights/src/systems/save.ts
@@ -1,15 +1,16 @@
import {
defineSystem, Query, Mut, Res, Commands, GetWorld,
- Input, Transform, Name, SceneManager, Localization, transitionTo,
+ Transform, Name, SceneManager, Localization, transitionTo,
} from 'esengine';
import { Enemy, Health, Player } from '../components';
import { saves, SLOT, type RunState } from '../save';
+import { Actions } from '../actions';
import { session } from '../state';
export const saveRunSystem = defineSystem(
- [Query(Transform, Health, Player), Query(Name, Enemy), Res(Input), Res(SceneManager), Res(Localization)],
- (players, living, input, scenes, i18n) => {
- if (!input.isKeyPressed('F5')) return;
+ [Query(Transform, Health, Player), Query(Name, Enemy), Res(SceneManager), Res(Localization)],
+ (players, living, scenes, i18n) => {
+ if (!Actions.pressed('Save')) return;
const area = scenes.getActive();
if (!area) return;
// Which enemies the scene HAD, minus the ones still standing: a save
@@ -34,9 +35,9 @@ export const saveRunSystem = defineSystem(
);
export const loadRunSystem = defineSystem(
- [Res(Input), Res(SceneManager), Res(Localization)],
- (input, scenes, i18n) => {
- if (!input.isKeyPressed('F9')) return;
+ [Res(SceneManager), Res(Localization)],
+ (scenes, i18n) => {
+ if (!Actions.pressed('Load')) return;
const run = saves.load<RunState>(SLOT);
if (!run) return;
i18n.setLocale(run.locale);
diff --git a/examples/celestial-heights/src/systems/settings.ts b/examples/celestial-heights/src/systems/settings.ts
index 0f3203d6f..21475eace 100644
--- a/examples/celestial-heights/src/systems/settings.ts
+++ b/examples/celestial-heights/src/systems/settings.ts
@@ -1,4 +1,22 @@
-import { defineSystem, Res, Input, Localization } from 'esengine';
+import { defineSystem, Res, Localization } from 'esengine';
+import { Actions, BINDINGS_KEY } from '../actions';
+import { loadSettings, saveSettings } from '../settings';
+import { session } from '../state';
+
+/**
+ * Reads back what the player chose last time — their language, whether effects
+ * are drawn, and their own key bindings, which the input map serializes itself.
+ */
+export const applySettingsSystem = defineSystem(
+ [Res(Localization)],
+ (i18n) => {
+ const settings = loadSettings();
+ if (settings.locale) i18n.setLocale(settings.locale);
+ session.effects = settings.effects;
+ Actions.load(BINDINGS_KEY);
+ },
+ { name: 'ApplySettingsSystem' },
+);
/**
* Cycles the language. Every bound `Text` re-flows on the next frame from its
@@ -6,13 +24,14 @@ import { defineSystem, Res, Input, Localization } from 'esengine';
* settings menu will call once it exists.
*/
export const cycleLanguageSystem = defineSystem(
- [Res(Input), Res(Localization)],
- (input, i18n) => {
- if (!input.isKeyPressed('KeyL')) return;
+ [Res(Localization)],
+ (i18n) => {
+ if (!Actions.pressed('Language')) return;
const locales = i18n.availableLocales();
if (locales.length < 2) return;
const next = (locales.indexOf(i18n.locale) + 1) % locales.length;
i18n.setLocale(locales[next]);
+ saveSettings({ locale: locales[next], effects: session.effects });
},
{ name: 'CycleLanguageSystem' },
);
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index 6da0bd437..ddbe94684 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -77,7 +77,7 @@ export const KNOWN_GAPS = {
rollback: 'hot-update-demo swaps forward; nothing exercises a failed manifest rolling back',
// Present in the engine and shown by non-golden samples, but never carried
// through the chain by a project the release argues from.
- settings: 'no project persists graphics/audio/language/rebinds and reads them back — Celestial Heights P3',
+ settings: 'Celestial Heights persists language, effects and key bindings and reads them back at boot; volume waits on the game having sound',
controller: 'input-actions binds a gamepad, but no golden run drives one — Celestial Heights P5',
// Measured: hello-world exports a 2.82MB single file, video-puzzle 3.22MB — so
// the floor is the runtime, not the game, and no project reaches the 2MB cap.