@automataframework/core 0.0.1-preview.11.sha-74ef211 → 0.0.1-preview.13.sha-fade17d

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/dist/browser.d.ts +6 -0
  3. package/dist/browser.js +5 -0
  4. package/dist/features/audio/audio.d.ts +18 -0
  5. package/dist/features/audio/audio.js +67 -0
  6. package/dist/features/audio/queue.d.ts +13 -0
  7. package/dist/features/audio/queue.js +12 -0
  8. package/dist/features/content/kinds.d.ts +6 -0
  9. package/dist/features/content/kinds.js +10 -0
  10. package/dist/features/content/load.d.ts +11 -0
  11. package/dist/features/content/load.js +77 -0
  12. package/dist/features/content/locate.d.ts +15 -0
  13. package/dist/features/content/locate.js +116 -0
  14. package/dist/features/content/manifest.d.ts +34 -0
  15. package/dist/features/content/manifest.js +15 -0
  16. package/dist/features/content/problems.d.ts +6 -0
  17. package/dist/features/content/problems.js +16 -0
  18. package/dist/features/game/game.d.ts +37 -0
  19. package/dist/features/game/game.js +33 -0
  20. package/dist/features/game/random.d.ts +3 -0
  21. package/dist/features/game/random.js +8 -0
  22. package/dist/features/game/tick.d.ts +3 -0
  23. package/dist/features/game/tick.js +10 -0
  24. package/dist/features/input/controls.d.ts +45 -0
  25. package/dist/features/input/controls.js +45 -0
  26. package/dist/features/input/loop.d.ts +16 -0
  27. package/dist/features/input/loop.js +48 -0
  28. package/dist/features/input/read.d.ts +27 -0
  29. package/dist/features/input/read.js +150 -0
  30. package/dist/features/plays/hash.d.ts +3 -0
  31. package/dist/features/plays/hash.js +16 -0
  32. package/dist/features/plays/plays.d.ts +32 -0
  33. package/dist/features/plays/plays.js +47 -0
  34. package/dist/features/saves/saves.d.ts +24 -0
  35. package/dist/features/saves/saves.js +116 -0
  36. package/dist/features/saves/store.d.ts +3 -0
  37. package/dist/features/saves/store.js +23 -0
  38. package/dist/features/upgrade/upgrade.d.ts +7 -0
  39. package/dist/features/upgrade/upgrade.js +36 -0
  40. package/dist/index.d.ts +19 -0
  41. package/dist/index.js +11 -0
  42. package/dist/lib/result.d.ts +16 -0
  43. package/dist/lib/result.js +2 -0
  44. package/package.json +5 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Automata Framework
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,6 @@
1
+ export { createAudio } from './features/audio/audio.ts';
2
+ export { readInputs } from './features/input/read.ts';
3
+ export type { InputEnv } from './features/input/read.ts';
4
+ export { startLoop } from './features/input/loop.ts';
5
+ export type { LoopEnv } from './features/input/loop.ts';
6
+ export { browserStore } from './features/saves/store.ts';
@@ -0,0 +1,5 @@
1
+ // `@automataframework/core/browser`: the parts that need a browser. The main entry never imports this file.
2
+ export { createAudio } from './features/audio/audio.js';
3
+ export { readInputs } from './features/input/read.js';
4
+ export { startLoop } from './features/input/loop.js';
5
+ export { browserStore } from './features/saves/store.js';
@@ -0,0 +1,18 @@
1
+ import { type SoundOptions } from './queue.ts';
2
+ type Bus = 'master' | 'music' | 'effects';
3
+ /**
4
+ * Sound through the Web Audio API: a master volume with a music bus and an effects bus under it. Browsers keep sound
5
+ * off until the person first touches or presses something, so it wakes on the first one.
6
+ */
7
+ export declare function createAudio(): {
8
+ play: (id: string, options?: SoundOptions) => void;
9
+ /** Makes a sound ready to play by its id, from the bytes of a sound file. */
10
+ load(id: string, bytes: ArrayBuffer): Promise<void>;
11
+ /** Plays what the game asked for with `playSound` since the last call. Call it once a frame. */
12
+ playQueued(): void;
13
+ stop(id: string): void;
14
+ setGain(bus: Bus, value: number): void;
15
+ mute(on: boolean): void;
16
+ gain: (bus: string) => number;
17
+ };
18
+ export {};
@@ -0,0 +1,67 @@
1
+ import { takeSounds } from './queue.js';
2
+ /**
3
+ * Sound through the Web Audio API: a master volume with a music bus and an effects bus under it. Browsers keep sound
4
+ * off until the person first touches or presses something, so it wakes on the first one.
5
+ */
6
+ export function createAudio() {
7
+ const context = new AudioContext();
8
+ const master = context.createGain();
9
+ master.connect(context.destination);
10
+ const buses = { master, music: context.createGain(), effects: context.createGain() };
11
+ for (const bus of [buses.music, buses.effects])
12
+ bus.connect(master);
13
+ const sounds = new Map();
14
+ const playing = new Map();
15
+ let masterVolume = 1;
16
+ let muted = false;
17
+ const wake = () => void context.resume().catch(() => { });
18
+ for (const type of ['pointerdown', 'keydown'])
19
+ globalThis.addEventListener?.(type, wake, { once: true });
20
+ function play(id, options = {}) {
21
+ const buffer = sounds.get(id);
22
+ if (!buffer)
23
+ return;
24
+ const source = context.createBufferSource();
25
+ source.buffer = buffer;
26
+ source.loop = options.loop === true;
27
+ const volume = context.createGain();
28
+ volume.gain.value = options.volume ?? 1;
29
+ source.connect(volume).connect(buses[options.bus ?? 'effects']);
30
+ const voices = playing.get(id) ?? new Set();
31
+ playing.set(id, voices);
32
+ voices.add(source);
33
+ source.addEventListener('ended', () => voices.delete(source));
34
+ source.start();
35
+ }
36
+ return {
37
+ play,
38
+ /** Makes a sound ready to play by its id, from the bytes of a sound file. */
39
+ async load(id, bytes) {
40
+ sounds.set(id, await context.decodeAudioData(bytes));
41
+ },
42
+ /** Plays what the game asked for with `playSound` since the last call. Call it once a frame. */
43
+ playQueued() {
44
+ for (const sound of takeSounds())
45
+ play(sound.id, sound.options);
46
+ },
47
+ stop(id) {
48
+ for (const source of playing.get(id) ?? [])
49
+ source.stop();
50
+ },
51
+ setGain(bus, value) {
52
+ const clamped = Math.min(1, Math.max(0, value));
53
+ if (bus === 'master') {
54
+ masterVolume = clamped;
55
+ if (!muted)
56
+ master.gain.value = clamped;
57
+ }
58
+ else
59
+ buses[bus].gain.value = clamped;
60
+ },
61
+ mute(on) {
62
+ muted = on;
63
+ master.gain.value = on ? 0 : masterVolume;
64
+ },
65
+ gain: (bus) => buses[bus]?.gain.value ?? 0,
66
+ };
67
+ }
@@ -0,0 +1,13 @@
1
+ export type SoundOptions = {
2
+ volume?: number;
3
+ bus?: 'effects' | 'music';
4
+ loop?: boolean;
5
+ };
6
+ export type QueuedSound = {
7
+ id: string;
8
+ options: SoundOptions;
9
+ };
10
+ /** Asks for a sound. A game's `update` calls this; it only writes a line in a list. The browser plays the list (`createAudio().playQueued()`); in Node nobody does, so it is silent and keeps no more than the newest 256. */
11
+ export declare function playSound(id: string, options?: SoundOptions): void;
12
+ /** Hands over the sounds asked for since the last call, and forgets them. */
13
+ export declare function takeSounds(): QueuedSound[];
@@ -0,0 +1,12 @@
1
+ const limit = 256;
2
+ const queue = [];
3
+ /** Asks for a sound. A game's `update` calls this; it only writes a line in a list. The browser plays the list (`createAudio().playQueued()`); in Node nobody does, so it is silent and keeps no more than the newest 256. */
4
+ export function playSound(id, options = {}) {
5
+ queue.push({ id, options });
6
+ if (queue.length > limit)
7
+ queue.shift();
8
+ }
9
+ /** Hands over the sounds asked for since the last call, and forgets them. */
10
+ export function takeSounds() {
11
+ return queue.splice(0);
12
+ }
@@ -0,0 +1,6 @@
1
+ import type { ZodType } from 'zod';
2
+ /** Every schema this package knows, by name. A game adds its own kinds with `defineKind`. */
3
+ export declare const schemas: Record<string, ZodType>;
4
+ /** A game's own kind of content file. A file of a kind nobody defined is checked for its first three lines only. */
5
+ export declare function defineKind(kind: string, schema: ZodType): void;
6
+ export declare const kindSchema: (kind: string) => ZodType | undefined;
@@ -0,0 +1,10 @@
1
+ import { envelopeSchema, manifestSchema } from './manifest.js';
2
+ /** Every schema this package knows, by name. A game adds its own kinds with `defineKind`. */
3
+ export const schemas = { manifest: manifestSchema, envelope: envelopeSchema };
4
+ const kinds = new Map();
5
+ /** A game's own kind of content file. A file of a kind nobody defined is checked for its first three lines only. */
6
+ export function defineKind(kind, schema) {
7
+ kinds.set(kind, schema);
8
+ schemas[`kind:${kind}`] = schema;
9
+ }
10
+ export const kindSchema = (kind) => kinds.get(kind);
@@ -0,0 +1,11 @@
1
+ import { type Result } from '../../lib/result.ts';
2
+ import { type Manifest } from './manifest.ts';
3
+ export type Read = (path: string) => Promise<string>;
4
+ export type Content = {
5
+ manifest: Manifest;
6
+ files: Record<string, unknown>;
7
+ };
8
+ /** Reads `automata.json`, then every file it lists. A file it does not list is never read. */
9
+ export declare function loadGame(read: Read): Promise<Result<Content>>;
10
+ /** A loaded content file by its id. */
11
+ export declare function content<T>(id: string): T;
@@ -0,0 +1,77 @@
1
+ import { fail, ok } from '../../lib/result.js';
2
+ import { kindSchema } from './kinds.js';
3
+ import { parseJson } from './locate.js';
4
+ import { envelopeSchema, manifestSchema } from './manifest.js';
5
+ import { fromZod, problem } from './problems.js';
6
+ let loaded;
7
+ /** Reads and checks one JSON file. */
8
+ async function readJson(read, file, listedAt) {
9
+ let text;
10
+ try {
11
+ text = await read(file);
12
+ }
13
+ catch {
14
+ return fail([
15
+ problem(listedAt?.file ?? file, listedAt?.line ?? 1, `${file} is not there.`, `Put ${file} in the game's folder, or take it out of automata.json.`),
16
+ ]);
17
+ }
18
+ const parsed = parseJson(text);
19
+ if (!parsed.ok)
20
+ return fail([problem(file, parsed.line, `${parsed.message}.`, `Fix line ${parsed.line} of ${file}.`)]);
21
+ return ok(parsed);
22
+ }
23
+ /** Reads `automata.json`, then every file it lists. A file it does not list is never read. */
24
+ export async function loadGame(read) {
25
+ const top = await readJson(read, 'automata.json');
26
+ if (!top.ok)
27
+ return top;
28
+ const m = manifestSchema.safeParse(top.value.value);
29
+ if (!m.success)
30
+ return fail(fromZod('automata.json', m.error, top.value.lineOf));
31
+ const manifest = m.data;
32
+ const problems = [];
33
+ const files = {};
34
+ const seen = new Set();
35
+ for (const [index, entry] of manifest.content.entries()) {
36
+ if (seen.has(entry.id)) {
37
+ problems.push(problem('automata.json', top.value.lineOf(['content', index, 'id']), `The id "${entry.id}" is used twice.`, 'Give each file its own id.'));
38
+ continue;
39
+ }
40
+ seen.add(entry.id);
41
+ // oxlint-disable-next-line no-await-in-loop -- one file after another keeps the problems in file order
42
+ const file = await readJson(read, entry.path, {
43
+ file: 'automata.json',
44
+ line: top.value.lineOf(['content', index, 'path']),
45
+ });
46
+ if (!file.ok) {
47
+ problems.push(...file.problems);
48
+ continue;
49
+ }
50
+ const envelope = envelopeSchema.safeParse(file.value.value);
51
+ if (!envelope.success) {
52
+ problems.push(...fromZod(entry.path, envelope.error, file.value.lineOf));
53
+ continue;
54
+ }
55
+ if (envelope.data.id !== entry.id || envelope.data.kind !== entry.kind) {
56
+ problems.push(problem(entry.path, file.value.lineOf(['id']), `${entry.path} says it is "${envelope.data.kind}" "${envelope.data.id}", but automata.json lists it as "${entry.kind}" "${entry.id}".`, `Make the "id" and "kind" in ${entry.path} the same as in automata.json.`));
57
+ continue;
58
+ }
59
+ const schema = kindSchema(entry.kind);
60
+ const checked = schema?.safeParse(file.value.value);
61
+ if (checked && !checked.success) {
62
+ problems.push(...fromZod(entry.path, checked.error, file.value.lineOf));
63
+ continue;
64
+ }
65
+ files[entry.id] = checked ? checked.data : file.value.value;
66
+ }
67
+ if (problems.length > 0)
68
+ return fail(problems);
69
+ loaded = { manifest, files };
70
+ return ok(loaded);
71
+ }
72
+ /** A loaded content file by its id. */
73
+ export function content(id) {
74
+ if (!loaded || !(id in loaded.files))
75
+ throw new Error(`No content file "${id}" is loaded. Is it listed in automata.json?`);
76
+ return loaded.files[id];
77
+ }
@@ -0,0 +1,15 @@
1
+ export type Path = (string | number)[];
2
+ export type Parsed = {
3
+ ok: true;
4
+ value: unknown;
5
+ lineOf(path: Path): number;
6
+ } | {
7
+ ok: false;
8
+ line: number;
9
+ message: string;
10
+ };
11
+ /**
12
+ * Reads JSON and remembers where each value starts, so a mistake in a file can name its line. The built-in
13
+ * `JSON.parse` says where only in some engines, so this one does it the same everywhere.
14
+ */
15
+ export declare function parseJson(text: string): Parsed;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Reads JSON and remembers where each value starts, so a mistake in a file can name its line. The built-in
3
+ * `JSON.parse` says where only in some engines, so this one does it the same everywhere.
4
+ */
5
+ export function parseJson(text) {
6
+ const starts = new Map();
7
+ let i = 0;
8
+ const lineAt = (offset) => text.slice(0, offset).split('\n').length;
9
+ const stop = (message) => {
10
+ throw Object.assign(new Error(message), { offset: i });
11
+ };
12
+ const space = () => {
13
+ while (i < text.length && ' \t\r\n'.includes(text.charAt(i)))
14
+ i++;
15
+ };
16
+ const word = (w, value) => {
17
+ if (!text.startsWith(w, i))
18
+ return stop(`I did not understand this (expected ${w})`);
19
+ i += w.length;
20
+ return value;
21
+ };
22
+ const string = () => {
23
+ const start = i++;
24
+ while (i < text.length && text.charAt(i) !== '"') {
25
+ if (text.charAt(i) === '\n')
26
+ stop('A word in quotes does not end on its line');
27
+ i += text.charAt(i) === '\\' ? 2 : 1;
28
+ }
29
+ if (i >= text.length) {
30
+ i = start;
31
+ stop('A word in quotes never ends');
32
+ }
33
+ i++;
34
+ return JSON.parse(text.slice(start, i));
35
+ };
36
+ const value = (path) => {
37
+ space();
38
+ starts.set(path.join('\u0000'), i);
39
+ const c = text.charAt(i);
40
+ if (c === '{') {
41
+ i++;
42
+ const out = {};
43
+ space();
44
+ if (text.charAt(i) === '}')
45
+ return (i++, out);
46
+ for (;;) {
47
+ space();
48
+ if (text.charAt(i) !== '"')
49
+ stop('Expected a name in quotes here');
50
+ const key = string();
51
+ space();
52
+ if (text.charAt(i++) !== ':')
53
+ stop('Expected a ":" after the name');
54
+ out[key] = value([...path, key]);
55
+ space();
56
+ const next = text.charAt(i++);
57
+ if (next === '}')
58
+ return out;
59
+ if (next !== ',')
60
+ stop('Expected "," or "}" here');
61
+ }
62
+ }
63
+ if (c === '[') {
64
+ i++;
65
+ const out = [];
66
+ space();
67
+ if (text.charAt(i) === ']')
68
+ return (i++, out);
69
+ for (;;) {
70
+ out.push(value([...path, out.length]));
71
+ space();
72
+ const next = text.charAt(i++);
73
+ if (next === ']')
74
+ return out;
75
+ if (next !== ',')
76
+ stop('Expected "," or "]" here');
77
+ }
78
+ }
79
+ if (c === '"')
80
+ return string();
81
+ if (c === 't')
82
+ return word('true', true);
83
+ if (c === 'f')
84
+ return word('false', false);
85
+ if (c === 'n')
86
+ return word('null', null);
87
+ const num = /^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(i));
88
+ if (!num)
89
+ return stop(i >= text.length ? 'The file ends too soon' : 'I did not understand this');
90
+ i += num[0].length;
91
+ return Number(num[0]);
92
+ };
93
+ try {
94
+ const result = value([]);
95
+ space();
96
+ if (i < text.length)
97
+ stop('There is more after the end of the file');
98
+ return {
99
+ ok: true,
100
+ value: result,
101
+ lineOf(path) {
102
+ // A path that is not there points at the closest parent that is.
103
+ for (let n = path.length; n >= 0; n--) {
104
+ const at = starts.get(path.slice(0, n).join('\u0000'));
105
+ if (at !== undefined)
106
+ return lineAt(at);
107
+ }
108
+ return 1;
109
+ },
110
+ };
111
+ }
112
+ catch (error) {
113
+ const e = error;
114
+ return { ok: false, line: lineAt(e.offset ?? i), message: e.message };
115
+ }
116
+ }
@@ -0,0 +1,34 @@
1
+ import { z } from 'zod';
2
+ /** `automata.json`: what a game is and which files it loads. Formats may change. */
3
+ export declare const manifestSchema: z.ZodObject<{
4
+ format: z.ZodLiteral<1>;
5
+ id: z.ZodString;
6
+ name: z.ZodString;
7
+ size: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>;
8
+ languages: z.ZodArray<z.ZodString>;
9
+ start: z.ZodEnum<{
10
+ menu: "menu";
11
+ play: "play";
12
+ }>;
13
+ content: z.ZodArray<z.ZodObject<{
14
+ id: z.ZodString;
15
+ kind: z.ZodString;
16
+ path: z.ZodString;
17
+ }, z.core.$strip>>;
18
+ assets: z.ZodArray<z.ZodObject<{
19
+ id: z.ZodString;
20
+ kind: z.ZodEnum<{
21
+ font: "font";
22
+ image: "image";
23
+ sound: "sound";
24
+ }>;
25
+ path: z.ZodString;
26
+ }, z.core.$strip>>;
27
+ }, z.core.$strip>;
28
+ export type Manifest = z.infer<typeof manifestSchema>;
29
+ /** What every content file starts with. */
30
+ export declare const envelopeSchema: z.ZodObject<{
31
+ format: z.ZodNumber;
32
+ id: z.ZodString;
33
+ kind: z.ZodString;
34
+ }, z.core.$loose>;
@@ -0,0 +1,15 @@
1
+ import { z } from 'zod';
2
+ const id = z.string().regex(/^[a-z][a-z0-9-]*$/, 'use small letters, numbers and dashes, starting with a letter');
3
+ /** `automata.json`: what a game is and which files it loads. Formats may change. */
4
+ export const manifestSchema = z.object({
5
+ format: z.literal(1),
6
+ id,
7
+ name: z.string().min(1),
8
+ size: z.tuple([z.number().int().positive(), z.number().int().positive()]),
9
+ languages: z.array(z.string().min(2)).min(1),
10
+ start: z.enum(['menu', 'play']),
11
+ content: z.array(z.object({ id, kind: id, path: z.string().min(1) })),
12
+ assets: z.array(z.object({ id, kind: z.enum(['image', 'sound', 'font']), path: z.string().min(1) })),
13
+ });
14
+ /** What every content file starts with. */
15
+ export const envelopeSchema = z.looseObject({ format: z.number().int().positive(), id, kind: id });
@@ -0,0 +1,6 @@
1
+ import type { ZodError } from 'zod';
2
+ import type { Problem } from '../../lib/result.ts';
3
+ import type { Path } from './locate.ts';
4
+ export declare const problem: (file: string, line: number, message: string, fix: string) => Problem;
5
+ /** Turns what zod found into one plain problem each. */
6
+ export declare function fromZod(file: string, error: ZodError, lineOf: (path: Path) => number): Problem[];
@@ -0,0 +1,16 @@
1
+ export const problem = (file, line, message, fix) => ({
2
+ file,
3
+ line,
4
+ message,
5
+ fix,
6
+ });
7
+ /** Turns what zod found into one plain problem each. */
8
+ export function fromZod(file, error, lineOf) {
9
+ return error.issues.map((issue) => {
10
+ const path = issue.path.filter((p) => typeof p !== 'symbol');
11
+ const where = path.length === 0 ? 'the file' : `"${path.join('.')}"`;
12
+ if (issue.code === 'invalid_type' && issue.input === undefined)
13
+ return problem(file, lineOf(path), `${where} is missing.`, `Add ${where} to ${file}.`);
14
+ return problem(file, lineOf(path), `${where} is not right: ${issue.message}.`, `Change ${where} in ${file}.`);
15
+ });
16
+ }
@@ -0,0 +1,37 @@
1
+ export type Player = {
2
+ id: number;
3
+ };
4
+ export type State<G> = {
5
+ tick: number;
6
+ seed: number;
7
+ players: Player[];
8
+ outcome: null | 'win' | 'lose';
9
+ /** The named place for the physics world's saved form (slice 3). Always null in 1a. */
10
+ physics: unknown;
11
+ game: G;
12
+ };
13
+ export type PlayerInput = {
14
+ down: string[];
15
+ sticks: Record<string, [number, number]>;
16
+ };
17
+ /** One per player, in the same order as `state.players`. */
18
+ export type Inputs = PlayerInput[];
19
+ export type Start = {
20
+ players: number;
21
+ seed: number;
22
+ };
23
+ export type Game<G> = {
24
+ init(start: Start): G;
25
+ /** May change the state and return it. Runs in plain Node: no drawing, no clock, no `Math.random`. */
26
+ update(state: State<G>, inputs: Inputs): State<G>;
27
+ draw?(state: State<G>): void;
28
+ };
29
+ export declare function newState<G>(game: Game<G>, start: Start): State<G>;
30
+ export declare const win: (state: State<unknown>) => void;
31
+ export declare const lose: (state: State<unknown>) => void;
32
+ /** Used by `step`: makes `inputs` the ones the game's functions read. */
33
+ export declare function setInputs(inputs: Inputs): void;
34
+ export declare const isDown: (action: string, player?: number) => boolean;
35
+ /** True for the one tick where the action went down. */
36
+ export declare const wasPressed: (action: string, player?: number) => boolean;
37
+ export declare const stick: (action: string, player?: number) => [number, number];
@@ -0,0 +1,33 @@
1
+ export function newState(game, start) {
2
+ resetInputs();
3
+ return {
4
+ tick: 0,
5
+ seed: start.seed | 0,
6
+ players: Array.from({ length: start.players }, (_, id) => ({ id })),
7
+ outcome: null,
8
+ physics: null,
9
+ game: game.init(start),
10
+ };
11
+ }
12
+ export const win = (state) => {
13
+ state.outcome ??= 'win';
14
+ };
15
+ export const lose = (state) => {
16
+ state.outcome ??= 'lose';
17
+ };
18
+ // Input is held here, not in the state, so `update` reads it with plain calls like `isDown('left')`.
19
+ let now = [];
20
+ let before = [];
21
+ function resetInputs() {
22
+ now = [];
23
+ before = [];
24
+ }
25
+ /** Used by `step`: makes `inputs` the ones the game's functions read. */
26
+ export function setInputs(inputs) {
27
+ before = now;
28
+ now = inputs;
29
+ }
30
+ export const isDown = (action, player = 0) => now[player]?.down.includes(action) ?? false;
31
+ /** True for the one tick where the action went down. */
32
+ export const wasPressed = (action, player = 0) => isDown(action, player) && !(before[player]?.down.includes(action) ?? false);
33
+ export const stick = (action, player = 0) => now[player]?.sticks[action] ?? [0, 0];
@@ -0,0 +1,3 @@
1
+ import type { State } from './game.ts';
2
+ /** A seeded number from 0 up to (not including) 1. The seed lives in the state, so a saved game keeps its dice. */
3
+ export declare function random(state: State<unknown>): number;
@@ -0,0 +1,8 @@
1
+ /** A seeded number from 0 up to (not including) 1. The seed lives in the state, so a saved game keeps its dice. */
2
+ export function random(state) {
3
+ state.seed = (state.seed + 0x6d2b79f5) | 0;
4
+ let t = state.seed;
5
+ t = Math.imul(t ^ (t >>> 15), t | 1);
6
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
7
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
8
+ }
@@ -0,0 +1,3 @@
1
+ import { type Game, type Inputs, type State } from './game.ts';
2
+ /** Runs `update` once with `inputs` as the ones `isDown` reads. The browser calls this 60 times a second. */
3
+ export declare function step<G>(game: Game<G>, state: State<G>, inputs: Inputs): State<G>;
@@ -0,0 +1,10 @@
1
+ import { setInputs } from './game.js';
2
+ /** Runs `update` once with `inputs` as the ones `isDown` reads. The browser calls this 60 times a second. */
3
+ export function step(game, state, inputs) {
4
+ setInputs(inputs);
5
+ if (state.outcome !== null)
6
+ return state;
7
+ const next = game.update(state, inputs);
8
+ next.tick += 1;
9
+ return next;
10
+ }
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod';
2
+ /** What one thing a player can do. A stick action's `keys` are four: left, right, up, down. */
3
+ export type Action = {
4
+ id: string;
5
+ label: string;
6
+ kind: 'button' | 'stick';
7
+ keys: string[];
8
+ pad: string[];
9
+ canTap?: boolean;
10
+ };
11
+ /** The `controls` content kind: every action, and each player's own keys where they differ. Formats may change. */
12
+ export type Controls = {
13
+ format: 1;
14
+ id: string;
15
+ actions: Action[];
16
+ players: {
17
+ keys?: Record<string, string[]>;
18
+ }[];
19
+ };
20
+ /** One player's bindings: key codes and pad inputs for each action, and the actions set to tap on, tap off. */
21
+ export type Bindings = {
22
+ keys: Record<string, string[]>;
23
+ pad: Record<string, string[]>;
24
+ tap: string[];
25
+ };
26
+ export declare const controlsSchema: z.ZodObject<{
27
+ format: z.ZodLiteral<1>;
28
+ id: z.ZodString;
29
+ actions: z.ZodArray<z.ZodObject<{
30
+ id: z.ZodString;
31
+ label: z.ZodString;
32
+ kind: z.ZodEnum<{
33
+ button: "button";
34
+ stick: "stick";
35
+ }>;
36
+ keys: z.ZodArray<z.ZodString>;
37
+ pad: z.ZodArray<z.ZodString>;
38
+ canTap: z.ZodOptional<z.ZodBoolean>;
39
+ }, z.core.$strip>>;
40
+ players: z.ZodArray<z.ZodObject<{
41
+ keys: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString>>>;
42
+ }, z.core.$strip>>;
43
+ }, z.core.$loose>;
44
+ /** The bindings a game starts with: one per entry of `players` (one when there are none), each with its own keys. */
45
+ export declare function defaultBindings(controls: Controls): Bindings[];