@inglorious/engine 24.6.0 → 24.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -286,9 +286,9 @@ A renderer checks the entity it draws: `renderText` wants a font size, so a type
286
286
 
287
287
  ## Documentation
288
288
 
289
- The best way to get started is with the official documentation, which includes a **[Quick Start Guide](https://inglorious-engine.vercel.app/?path=/docs/quick-start--docs)**.
289
+ The best way to get started is with the official documentation, which includes a **[Quick Start Guide](https://inglorious.dev/engine/?path=/docs/quick-start--docs)**.
290
290
 
291
- Full documentation is available at: **[https://inglorious-engine.vercel.app/](https://inglorious-engine.vercel.app/)**
291
+ Full documentation is available at: **[https://inglorious.dev/engine/](https://inglorious.dev/engine/)**
292
292
 
293
293
  ## Why Functional Programming?
294
294
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "24.6.0",
3
+ "version": "24.9.0",
4
4
  "description": "A JavaScript game engine written with global state, immutability, and pure functions in mind. Have fun(ctional programming) with it!",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/IngloriousCoderz/inglorious-forge.git",
10
10
  "directory": "packages/engine"
11
11
  },
12
- "homepage": "https://inglorious-engine.vercel.app/",
12
+ "homepage": "https://inglorious.dev/engine/",
13
13
  "bugs": {
14
14
  "url": "https://github.com/IngloriousCoderz/inglorious-forge/issues"
15
15
  },
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "sideEffects": false,
43
43
  "dependencies": {
44
- "@inglorious/utils": "^5.7.0"
44
+ "@inglorious/utils": "^5.9.0"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@inglorious/store": "^12.9.6",
@@ -0,0 +1,81 @@
1
+ const FIRST_FINGER = 0
2
+
3
+ /**
4
+ * Dragging across the scene, the same with a mouse and with a finger: a press on
5
+ * the scene (not on an entity: see `scenePress` and `sceneTouchStart`) starts a
6
+ * drag, moving draws it, letting go ends it. Only the first finger drags, so a
7
+ * second one resting on the screen does nothing.
8
+ *
9
+ * The entity keeps `pointer`, where the pointer is (null once a finger lifts, since
10
+ * there is then no pointer at all, while a mouse stays where it was), and `dragging`.
11
+ * Each move while dragging calls the type's `sceneDrag(entity, { from, to }, api)`,
12
+ * in the same event, so whatever it adds up is there for the next turn: a brush
13
+ * stroke, a pan, a line drawn. A game that should not drag at the moment (paused,
14
+ * say) returns early there. Moving the mouse without pressing only moves `pointer`,
15
+ * for a cursor of the game's own. Put it after the type's own behaviors, so it wraps
16
+ * them.
17
+ *
18
+ * @returns {Function} The behavior.
19
+ */
20
+ export function sceneDrag() {
21
+ return (type) => {
22
+ function start(entity, position, api) {
23
+ entity.pointer = position
24
+ entity.dragging = true
25
+ type.sceneDragStart?.(entity, position, api)
26
+ }
27
+
28
+ function move(entity, position, api) {
29
+ const from = entity.pointer
30
+ entity.pointer = position
31
+ if (!entity.dragging || !from) return
32
+ type.sceneDrag?.(entity, { from, to: position }, api)
33
+ }
34
+
35
+ function end(entity, api) {
36
+ if (!entity.dragging) return
37
+ entity.dragging = false
38
+ type.sceneDragEnd?.(entity, entity.pointer, api)
39
+ }
40
+
41
+ return {
42
+ create(entity, payload, api) {
43
+ type.create?.(entity, payload, api)
44
+ entity.pointer ??= null
45
+ entity.dragging ??= false
46
+ },
47
+
48
+ scenePress(entity, position, api) {
49
+ type.scenePress?.(entity, position, api)
50
+ start(entity, position, api)
51
+ },
52
+
53
+ mouseMove(entity, position, api) {
54
+ type.mouseMove?.(entity, position, api)
55
+ move(entity, position, api)
56
+ },
57
+
58
+ mouseUp(entity, position, api) {
59
+ type.mouseUp?.(entity, position, api)
60
+ end(entity, api)
61
+ },
62
+
63
+ sceneTouchStart(entity, position, api) {
64
+ type.sceneTouchStart?.(entity, position, api)
65
+ start(entity, position, api)
66
+ },
67
+
68
+ touchMove(entity, touch, api) {
69
+ type.touchMove?.(entity, touch, api)
70
+ if (touch.index === FIRST_FINGER) move(entity, touch.position, api)
71
+ },
72
+
73
+ touchEnd(entity, touch, api) {
74
+ type.touchEnd?.(entity, touch, api)
75
+ if (touch.index !== FIRST_FINGER) return
76
+ end(entity, api)
77
+ entity.pointer = null
78
+ },
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,170 @@
1
+ import { saveJSON } from "@inglorious/utils/files.js"
2
+
3
+ import { createRecorder, isSession } from "../core/recorder.js"
4
+
5
+ const NO_TURNS = 0
6
+ const STAMP_START = 0
7
+ const STAMP_LENGTH = 19 // "2026-12-01T13:42:32", to the second
8
+
9
+ // One recorder per entity: kept outside the state, which the store copies on every
10
+ // event, while a recording grows all game long.
11
+ const recorders = new Map()
12
+
13
+ /**
14
+ * Records an entity that holds a deterministic simulation, turned on `tick` (see the
15
+ * `ticks` system), and plays a recording back: runs with what the player did at each
16
+ * turn (see `createRecorder`). Put it last in the type's behaviors, so it wraps the
17
+ * `tick` and the events that start a run.
18
+ *
19
+ * What the simulation is stays the game's, told through the options:
20
+ *
21
+ * - `turn(entity)`: the simulation's turn, or null while there is no simulation. A
22
+ * `tick` that leaves the turn as it was (the game held it still) records nothing.
23
+ * - `state(entity)`: the simulation's state, whose fingerprint tells whether a replay
24
+ * ended where the recording did.
25
+ * - `about(entity)`: what it takes to start the simulation again, as plain data.
26
+ * - `input(entity)`: what the player did before this turn, read before `tick`; null
27
+ * for nothing.
28
+ * - `useInput(entity, input)`: puts a recorded input in place of the player's before
29
+ * `tick`; `undefined` where nothing was done.
30
+ * - `replayRun(entity, about)`: starts the simulation of a recorded run.
31
+ * - `startsRun`: the events after which a new run starts (a level started again, a
32
+ * new seed); the one before ends where it was. Ignored while replaying, so a replay
33
+ * is not knocked off its runs. `create` always starts one.
34
+ *
35
+ * It handles `saveRecording` (the session so far, downloaded as a JSON file),
36
+ * `replayLoad` (a session to play back, typically a file dropped on the page: see
37
+ * `onDroppedJSON` and `engine.notify`; on success it notifies `replayStart`, for the
38
+ * game to leave its menus) and `replayStop`. While replaying, `entity.replay` is
39
+ * `{ run, runs, diverged, over }`, else null; once `over`, `tick` holds the simulation
40
+ * still, and the player's input is still replaced by none.
41
+ *
42
+ * @param {Object} options
43
+ * @param {(entity: Object) => number | null} options.turn
44
+ * @param {(entity: Object) => *} options.state
45
+ * @param {(entity: Object) => *} options.about
46
+ * @param {(entity: Object) => *} options.input
47
+ * @param {(entity: Object, input: *) => void} options.useInput
48
+ * @param {(entity: Object, about: *) => void} options.replayRun
49
+ * @param {string[]} [options.startsRun] - Events that start a new run, besides `create`.
50
+ * @param {(session: Object) => boolean} [options.isPlayable] - Whether the game can play a session's runs (its levels still exist).
51
+ * @param {string} [options.format] - What the recordings are; a session of another format is refused.
52
+ * @param {string} [options.build] - Which build of the game made them.
53
+ * @param {string} [options.name] - The start of a saved file's name, followed by the time.
54
+ * @returns {Function} The behavior.
55
+ */
56
+ export function recorded({
57
+ turn,
58
+ state,
59
+ about,
60
+ input,
61
+ useInput,
62
+ replayRun,
63
+ startsRun = [],
64
+ isPlayable = () => true,
65
+ format = "recording",
66
+ build,
67
+ name = format,
68
+ }) {
69
+ const recorderOf = (entity) => recorders.get(entity.id)
70
+
71
+ /** Ends the run being recorded where the simulation is. */
72
+ function close(entity) {
73
+ recorderOf(entity).close(turn(entity) ?? NO_TURNS, state(entity))
74
+ }
75
+
76
+ /** Starts recording a run, if there is a simulation to record. */
77
+ function open(entity) {
78
+ if (turn(entity) != null) recorderOf(entity).open(about(entity))
79
+ }
80
+
81
+ function play(entity, run) {
82
+ replayRun(entity, run.about)
83
+ entity.replay = recorderOf(entity).progress()
84
+ }
85
+
86
+ return (type) => {
87
+ const runStarters = Object.fromEntries(
88
+ startsRun.map((event) => [
89
+ event,
90
+ (entity, payload, api) => {
91
+ if (entity.replay) return
92
+ close(entity)
93
+ type[event]?.(entity, payload, api)
94
+ open(entity)
95
+ },
96
+ ]),
97
+ )
98
+
99
+ return {
100
+ ...runStarters,
101
+
102
+ create(entity, payload, api) {
103
+ recorders.set(entity.id, createRecorder({ format, build }))
104
+ entity.replay = null
105
+ type.create?.(entity, payload, api)
106
+ open(entity)
107
+ },
108
+
109
+ tick(entity, dt, api) {
110
+ if (entity.replay?.over) {
111
+ useInput(entity, undefined) // the player's input is dropped, not saved up
112
+ return
113
+ }
114
+
115
+ const before = turn(entity)
116
+ if (before == null) {
117
+ type.tick?.(entity, dt, api)
118
+ return
119
+ }
120
+
121
+ const recorder = recorderOf(entity)
122
+ const done = entity.replay ? null : input(entity)
123
+ if (entity.replay) useInput(entity, recorder.input(before))
124
+
125
+ type.tick?.(entity, dt, api)
126
+
127
+ const after = turn(entity)
128
+ if (after === before) return
129
+ if (!entity.replay) {
130
+ recorder.record(before, done)
131
+ return
132
+ }
133
+
134
+ if (after < recorder.replayed().ticks) return
135
+ const next = recorder.finish(state(entity))
136
+ if (next) play(entity, next)
137
+ else entity.replay = { ...recorder.progress(), over: true }
138
+ },
139
+
140
+ saveRecording(entity, payload, api) {
141
+ type.saveRecording?.(entity, payload, api)
142
+ const session = recorderOf(entity).session(
143
+ turn(entity) ?? NO_TURNS,
144
+ state(entity),
145
+ )
146
+ const stamp = session.recordedAt
147
+ .slice(STAMP_START, STAMP_LENGTH)
148
+ .replaceAll(":", "-")
149
+ saveJSON(`${name}-${stamp}.json`, session)
150
+ },
151
+
152
+ replayLoad(entity, session, api) {
153
+ type.replayLoad?.(entity, session, api)
154
+ if (!isSession(session, format) || !isPlayable(session)) {
155
+ console.warn(`Not a ${format} this game can play back`)
156
+ return
157
+ }
158
+ close(entity)
159
+ play(entity, recorderOf(entity).load(session))
160
+ api.notify("replayStart")
161
+ },
162
+
163
+ replayStop(entity, payload, api) {
164
+ type.replayStop?.(entity, payload, api)
165
+ recorderOf(entity).stop()
166
+ entity.replay = null
167
+ },
168
+ }
169
+ }
170
+ }
@@ -0,0 +1,60 @@
1
+ // What a game is playing kept in the page's address, `/level-2?tank=base&seed=3`, so
2
+ // it can be shared as a link and a reload goes back to it: a page as the last segment
3
+ // of the path, settings in the query. Only noted, with `replaceState`, so Back does
4
+ // not step through every change. Outside a browser, reads give their fallbacks and
5
+ // notes do nothing.
6
+
7
+ const LAST = -1
8
+ const NONE = 0
9
+ const FROM_START = 0
10
+
11
+ /** The last segment of the address's path, `/level-2` → "level-2", "" at the root. */
12
+ export function pageInAddress() {
13
+ return globalThis.location?.pathname.split("/").at(LAST) ?? ""
14
+ }
15
+
16
+ /** The value under `key` in the address's query, if it is one of `choices`, else `fallback`. */
17
+ export function choiceInAddress(key, choices, fallback) {
18
+ const value = query().get(key)
19
+ return choices.includes(value) ? value : fallback
20
+ }
21
+
22
+ /** The whole number above zero under `key` in the address's query, else `fallback`. */
23
+ export function countInAddress(key, fallback) {
24
+ const number = Number(query().get(key))
25
+ return Number.isInteger(number) && number > NONE ? number : fallback
26
+ }
27
+
28
+ /** Notes `values` in the address's query, without reloading or adding to the history. */
29
+ export function noteInAddress(values) {
30
+ const address = query()
31
+ for (const [key, value] of Object.entries(values)) address.set(key, value)
32
+ replaceAddress(globalThis.location?.pathname, address)
33
+ }
34
+
35
+ /**
36
+ * Notes `page` as the last segment of the address's path, in place of the one there,
37
+ * but only if that is the root or one of `pages`: where the game is served from a
38
+ * file (`/html/123/index.html`, as on itch.io), the path is left alone, since a
39
+ * reload would not find it.
40
+ */
41
+ export function notePageInAddress(page, pages) {
42
+ const pathname = globalThis.location?.pathname ?? ""
43
+ const segments = pathname.split("/")
44
+ if (!["", ...pages].includes(segments.at(LAST))) return
45
+ replaceAddress([...segments.slice(FROM_START, LAST), page].join("/"), query())
46
+ }
47
+
48
+ function query() {
49
+ return new URLSearchParams(globalThis.location?.search ?? "")
50
+ }
51
+
52
+ function replaceAddress(pathname, query) {
53
+ if (!globalThis.history?.replaceState) return
54
+ const search = query.size ? `?${query}` : ""
55
+ globalThis.history.replaceState(
56
+ null,
57
+ "",
58
+ `${pathname}${search}${globalThis.location.hash}`,
59
+ )
60
+ }
@@ -124,6 +124,18 @@ export class Engine {
124
124
  return this._store.getState()
125
125
  }
126
126
 
127
+ /**
128
+ * Tells the game something from outside it, as its own entities would with
129
+ * `api.notify`: a file dropped on the page, a message from the host. The event is
130
+ * handled in the next frame, with the others.
131
+ *
132
+ * @param {string} type - The event.
133
+ * @param {*} [payload] - What comes with it.
134
+ */
135
+ notify(type, payload) {
136
+ this._store.notify(type, payload)
137
+ }
138
+
127
139
  /**
128
140
  * Updates the game state.
129
141
  *
@@ -0,0 +1,146 @@
1
+ import { fingerprint } from "@inglorious/utils/data-structures/object.js"
2
+
3
+ const FORMAT_VERSION = 1
4
+ const NO_TICKS = 0
5
+ const FIRST_RUN = 0
6
+ const COUNT_FROM = 1 // runs are counted from 1 for people
7
+ const NONE = 0
8
+
9
+ /**
10
+ * Records a deterministic simulation as what was done to it, turn by turn, and plays
11
+ * a recording back.
12
+ *
13
+ * A simulation that turns in fixed steps, with all its randomness in its own state
14
+ * (see `createRng`), gives the same state again from the same start and the same
15
+ * inputs at the same turns. So a game need not be recorded as states, only as how
16
+ * each run started and what the player did: small enough to save as a file, and to
17
+ * watch again at any speed.
18
+ *
19
+ * A session is every run played since the recorder was made or reset, a run being
20
+ * one simulation from its start: `about` is whatever the game needs to create it
21
+ * again (a level, a seed), `inputs` maps a turn to what was done before it, and
22
+ * `ticks` and `fingerprint` (see `fingerprint`) are where it ended, so a replay can
23
+ * tell whether it reached the same state. A recording made before a rule changed no
24
+ * longer does, and is better reported than trusted.
25
+ *
26
+ * Keep the recorder outside the game's state: it grows all game long, and a store
27
+ * that copies state on every event would copy it too.
28
+ *
29
+ * @param {Object} [options]
30
+ * @param {string} [options.format] - What the recordings are, written in each session and checked by `isSession`.
31
+ * @param {string} [options.build] - Which build of the game made them, for whoever reads the file.
32
+ */
33
+ export function createRecorder({ format = "recording", build } = {}) {
34
+ let runs = []
35
+ let current = null
36
+ let replay = null
37
+
38
+ return {
39
+ /** Forgets every run and stops any replay. */
40
+ reset() {
41
+ runs = []
42
+ current = null
43
+ replay = null
44
+ },
45
+
46
+ /** Starts recording a run, `about` being what it takes to start it again; not while replaying. */
47
+ open(about) {
48
+ if (replay) return
49
+ current = { about, inputs: {}, ticks: NO_TICKS, fingerprint: null }
50
+ },
51
+
52
+ /** Notes what was done before turn `tick` of the run being recorded; nothing is noted for nothing. */
53
+ record(tick, input) {
54
+ if (current && input != null) current.inputs[tick] = input
55
+ },
56
+
57
+ /** Ends the run being recorded at turn `tick`, in `state`; a run where no turn passed is dropped. */
58
+ close(tick, state) {
59
+ if (!current) return
60
+ if (tick > NO_TICKS) runs.push(ended(current, tick, state))
61
+ current = null
62
+ },
63
+
64
+ /** Every run so far, as plain data to save; the one being recorded ends at turn `tick`, in `state`. */
65
+ session(tick, state) {
66
+ const open =
67
+ current && tick > NO_TICKS ? [ended(current, tick, state)] : []
68
+ return {
69
+ format,
70
+ version: FORMAT_VERSION,
71
+ build,
72
+ recordedAt: new Date().toISOString(),
73
+ runs: [...runs, ...open],
74
+ }
75
+ },
76
+
77
+ /** Plays `session` back, returning its first run; nothing is recorded meanwhile. */
78
+ load(session) {
79
+ replay = { runs: session.runs, index: FIRST_RUN, diverged: NONE }
80
+ return replay.runs[FIRST_RUN]
81
+ },
82
+
83
+ /** The run being played back, or null. */
84
+ replayed() {
85
+ return replay?.runs[replay.index] ?? null
86
+ },
87
+
88
+ /** What was done before turn `tick` of the run being played back, if anything. */
89
+ input(tick) {
90
+ return replay?.runs[replay.index]?.inputs[tick]
91
+ },
92
+
93
+ /**
94
+ * The run being played back has reached its last turn, in `state`: counts it as
95
+ * diverged if that is not where it ended when recorded, and moves on to the next
96
+ * run, which it returns (null after the last).
97
+ */
98
+ finish(state) {
99
+ const run = replay.runs[replay.index]
100
+ if (run.fingerprint !== fingerprint(state)) replay.diverged += 1
101
+ replay.index += 1
102
+ return replay.runs[replay.index] ?? null
103
+ },
104
+
105
+ /** Where the replay is: its run, from 1, how many there are, and how many diverged; null when none. */
106
+ progress() {
107
+ if (!replay) return null
108
+ const { runs, index, diverged } = replay
109
+ return { run: index + COUNT_FROM, runs: runs.length, diverged }
110
+ },
111
+
112
+ /** Stops playing back; what comes next is recorded again. */
113
+ stop() {
114
+ replay = null
115
+ },
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Whether `session` looks like one a recorder of `format` saved, with at least one
121
+ * run. Whether its runs make sense for the game (a level that exists) is the game's
122
+ * to check.
123
+ *
124
+ * @param {*} session - Anything, typically a parsed file.
125
+ * @param {string} [format] - The recorder's format.
126
+ * @returns {boolean}
127
+ */
128
+ export function isSession(session, format = "recording") {
129
+ return (
130
+ session?.format === format &&
131
+ session.version === FORMAT_VERSION &&
132
+ Array.isArray(session.runs) &&
133
+ session.runs.length > NONE &&
134
+ session.runs.every(
135
+ (run) =>
136
+ run?.ticks > NO_TICKS &&
137
+ Number.isInteger(run.ticks) &&
138
+ typeof run.inputs === "object" &&
139
+ run.inputs !== null,
140
+ )
141
+ )
142
+ }
143
+
144
+ function ended(run, ticks, state) {
145
+ return { ...run, ticks, fingerprint: fingerprint(state) }
146
+ }
@@ -0,0 +1,24 @@
1
+ import type { Vector3 } from "@inglorious/utils/vector.js"
2
+
3
+ import type { Decorator, Entity, Handler } from "../../index"
4
+
5
+ export interface SceneDragEntity extends Entity {
6
+ /** Where the pointer is; null once a finger lifts. */
7
+ pointer?: Vector3 | null
8
+ /** Whether a drag is under way. */
9
+ dragging?: boolean
10
+ }
11
+
12
+ /**
13
+ * Dragging across the scene with a mouse or the first finger; each move while
14
+ * dragging calls the type's `sceneDrag(entity, { from, to }, api)`.
15
+ */
16
+ export function sceneDrag(): Decorator<{
17
+ create: Handler<SceneDragEntity, unknown>
18
+ scenePress: Handler<SceneDragEntity, Vector3>
19
+ mouseMove: Handler<SceneDragEntity, Vector3>
20
+ mouseUp: Handler<SceneDragEntity, Vector3>
21
+ sceneTouchStart: Handler<SceneDragEntity, Vector3>
22
+ touchMove: Handler<SceneDragEntity, { index: number; position: Vector3 }>
23
+ touchEnd: Handler<SceneDragEntity, { index: number }>
24
+ }>
@@ -0,0 +1,55 @@
1
+ import type { RecordedSession, ReplayProgress } from "../core/recorder"
2
+ import type { Decorator, Entity, Handler } from "../index"
3
+
4
+ export interface RecordedEntity extends Entity {
5
+ /** Where a replay is, and whether it is over; null when not replaying. */
6
+ replay?: (ReplayProgress & { over?: boolean }) | null
7
+ }
8
+
9
+ export interface RecordedOptions<
10
+ TEntity extends RecordedEntity = RecordedEntity,
11
+ About = unknown,
12
+ Input = unknown,
13
+ > {
14
+ /** The simulation's turn, or null while there is none. */
15
+ turn(entity: TEntity): number | null
16
+ /** The simulation's state, fingerprinted where a run ends. */
17
+ state(entity: TEntity): unknown
18
+ /** What it takes to start the simulation again. */
19
+ about(entity: TEntity): About
20
+ /** What the player did before this turn; null for nothing. */
21
+ input(entity: TEntity): Input | null
22
+ /** Puts a recorded input in place of the player's; undefined where nothing was done. */
23
+ useInput(entity: TEntity, input: Input | undefined): void
24
+ /** Starts the simulation of a recorded run. */
25
+ replayRun(entity: TEntity, about: About): void
26
+ /** Events after which a new run starts, besides `create`. */
27
+ startsRun?: string[]
28
+ /** Whether the game can play a session's runs. */
29
+ isPlayable?(session: RecordedSession<About, Input>): boolean
30
+ format?: string
31
+ build?: string
32
+ /** The start of a saved file's name. */
33
+ name?: string
34
+ }
35
+
36
+ /**
37
+ * Records an entity holding a deterministic simulation turned on `tick`, and plays
38
+ * recordings back. Put it last in the type's behaviors.
39
+ */
40
+ export function recorded<
41
+ TEntity extends RecordedEntity = RecordedEntity,
42
+ About = unknown,
43
+ Input = unknown,
44
+ >(
45
+ options: RecordedOptions<TEntity, About, Input>,
46
+ ): Decorator<
47
+ // and a handler for each of `startsRun`
48
+ Record<string, Handler<TEntity, unknown>> & {
49
+ create: Handler<TEntity, unknown>
50
+ tick: Handler<TEntity, number>
51
+ saveRecording: Handler<TEntity, unknown>
52
+ replayLoad: Handler<TEntity, RecordedSession<About, Input>>
53
+ replayStop: Handler<TEntity, unknown>
54
+ }
55
+ >
@@ -0,0 +1,20 @@
1
+ /** The last segment of the address's path, "" at the root. */
2
+ export function pageInAddress(): string
3
+
4
+ /** The value under `key` in the query, if it is one of `choices`, else `fallback`. */
5
+ export function choiceInAddress<T extends string>(
6
+ key: string,
7
+ choices: readonly T[],
8
+ fallback: T,
9
+ ): T
10
+
11
+ /** The whole number above zero under `key` in the query, else `fallback`. */
12
+ export function countInAddress(key: string, fallback: number): number
13
+
14
+ /** Notes `values` in the query, without reloading or adding to the history. */
15
+ export function noteInAddress(
16
+ values: Record<string, string | number | boolean>,
17
+ ): void
18
+
19
+ /** Notes `page` as the path's last segment, only in place of the root or one of `pages`. */
20
+ export function notePageInAddress(page: string, pages: readonly string[]): void
@@ -23,6 +23,9 @@ export class Engine {
23
23
  /** The entities as they are now. */
24
24
  getState(): EntitiesState
25
25
 
26
+ /** Tells the game something from outside it; handled in the next frame. */
27
+ notify(type: string, payload?: unknown): void
28
+
26
29
  /** Runs a frame, `dt` seconds after the last one. */
27
30
  update(dt: number): void
28
31
  }
@@ -0,0 +1,49 @@
1
+ /** One run: how it started, what was done at each turn, and where it ended. */
2
+ export interface RecordedRun<About = unknown, Input = unknown> {
3
+ about: About
4
+ inputs: Record<number, Input>
5
+ ticks: number
6
+ fingerprint: number
7
+ }
8
+
9
+ /** Every run of a session, as saved. */
10
+ export interface RecordedSession<About = unknown, Input = unknown> {
11
+ format: string
12
+ version: number
13
+ build?: string
14
+ recordedAt: string
15
+ runs: RecordedRun<About, Input>[]
16
+ }
17
+
18
+ /** Where a replay is: its run, from 1, how many there are, how many diverged. */
19
+ export interface ReplayProgress {
20
+ run: number
21
+ runs: number
22
+ diverged: number
23
+ }
24
+
25
+ export interface Recorder<About = unknown, Input = unknown> {
26
+ reset(): void
27
+ open(about: About): void
28
+ record(tick: number, input: Input | null | undefined): void
29
+ close(tick: number, state: unknown): void
30
+ session(tick: number, state: unknown): RecordedSession<About, Input>
31
+ load(session: RecordedSession<About, Input>): RecordedRun<About, Input>
32
+ replayed(): RecordedRun<About, Input> | null
33
+ input(tick: number): Input | undefined
34
+ finish(state: unknown): RecordedRun<About, Input> | null
35
+ progress(): ReplayProgress | null
36
+ stop(): void
37
+ }
38
+
39
+ /** Records a deterministic simulation as its inputs by turn, and plays a recording back. */
40
+ export function createRecorder<About = unknown, Input = unknown>(options?: {
41
+ format?: string
42
+ build?: string
43
+ }): Recorder<About, Input>
44
+
45
+ /** Whether a value looks like a session a recorder of `format` saved. */
46
+ export function isSession(
47
+ session: unknown,
48
+ format?: string,
49
+ ): session is RecordedSession