@automataframework/core 0.0.1-preview.11.sha-74ef211 → 0.0.1-preview.12.sha-e1e5dd9
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/LICENSE +21 -0
- package/dist/browser.d.ts +6 -0
- package/dist/browser.js +5 -0
- package/dist/features/audio/audio.d.ts +18 -0
- package/dist/features/audio/audio.js +67 -0
- package/dist/features/audio/queue.d.ts +13 -0
- package/dist/features/audio/queue.js +12 -0
- package/dist/features/content/kinds.d.ts +6 -0
- package/dist/features/content/kinds.js +10 -0
- package/dist/features/content/load.d.ts +11 -0
- package/dist/features/content/load.js +77 -0
- package/dist/features/content/locate.d.ts +15 -0
- package/dist/features/content/locate.js +116 -0
- package/dist/features/content/manifest.d.ts +34 -0
- package/dist/features/content/manifest.js +15 -0
- package/dist/features/content/problems.d.ts +6 -0
- package/dist/features/content/problems.js +16 -0
- package/dist/features/game/game.d.ts +37 -0
- package/dist/features/game/game.js +33 -0
- package/dist/features/game/random.d.ts +3 -0
- package/dist/features/game/random.js +8 -0
- package/dist/features/game/tick.d.ts +3 -0
- package/dist/features/game/tick.js +10 -0
- package/dist/features/input/controls.d.ts +45 -0
- package/dist/features/input/controls.js +45 -0
- package/dist/features/input/loop.d.ts +16 -0
- package/dist/features/input/loop.js +48 -0
- package/dist/features/input/read.d.ts +27 -0
- package/dist/features/input/read.js +150 -0
- package/dist/features/plays/hash.d.ts +3 -0
- package/dist/features/plays/hash.js +16 -0
- package/dist/features/plays/plays.d.ts +32 -0
- package/dist/features/plays/plays.js +47 -0
- package/dist/features/saves/saves.d.ts +24 -0
- package/dist/features/saves/saves.js +116 -0
- package/dist/features/saves/store.d.ts +3 -0
- package/dist/features/saves/store.js +23 -0
- package/dist/features/upgrade/upgrade.d.ts +7 -0
- package/dist/features/upgrade/upgrade.js +36 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +11 -0
- package/dist/lib/result.d.ts +16 -0
- package/dist/lib/result.js +2 -0
- package/package.json +5 -5
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { defineKind } from '../content/kinds.js';
|
|
3
|
+
const id = z.string().regex(/^[a-z][a-z0-9-]*$/, 'use small letters, numbers and dashes, starting with a letter');
|
|
4
|
+
export const controlsSchema = z
|
|
5
|
+
.looseObject({
|
|
6
|
+
format: z.literal(1),
|
|
7
|
+
id,
|
|
8
|
+
actions: z
|
|
9
|
+
.array(z.object({
|
|
10
|
+
id,
|
|
11
|
+
label: z.string().min(1),
|
|
12
|
+
kind: z.enum(['button', 'stick']),
|
|
13
|
+
keys: z.array(z.string().min(1)),
|
|
14
|
+
pad: z.array(z.string().min(1)),
|
|
15
|
+
canTap: z.boolean().optional(),
|
|
16
|
+
}))
|
|
17
|
+
.min(1),
|
|
18
|
+
players: z.array(z.object({ keys: z.record(z.string(), z.array(z.string())).optional() })),
|
|
19
|
+
})
|
|
20
|
+
.superRefine((controls, context) => {
|
|
21
|
+
const seen = new Set();
|
|
22
|
+
for (const [index, action] of controls.actions.entries()) {
|
|
23
|
+
if (seen.has(action.id))
|
|
24
|
+
context.addIssue({ code: 'custom', path: ['actions', index, 'id'], message: 'is used twice' });
|
|
25
|
+
seen.add(action.id);
|
|
26
|
+
if (action.kind === 'stick' && action.keys.length !== 0 && action.keys.length !== 4)
|
|
27
|
+
context.addIssue({
|
|
28
|
+
code: 'custom',
|
|
29
|
+
path: ['actions', index, 'keys'],
|
|
30
|
+
message: 'a stick needs four keys: left, right, up, down',
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
defineKind('controls', controlsSchema);
|
|
35
|
+
/** The bindings a game starts with: one per entry of `players` (one when there are none), each with its own keys. */
|
|
36
|
+
export function defaultBindings(controls) {
|
|
37
|
+
return Array.from({ length: Math.max(1, controls.players.length) }, (_, player) => {
|
|
38
|
+
const own = controls.players[player]?.keys ?? {};
|
|
39
|
+
return {
|
|
40
|
+
keys: Object.fromEntries(controls.actions.map((action) => [action.id, own[action.id] ?? action.keys])),
|
|
41
|
+
pad: Object.fromEntries(controls.actions.map((action) => [action.id, action.pad])),
|
|
42
|
+
tap: [],
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** What the loop needs from the browser. A test hands in its own. */
|
|
2
|
+
export type LoopEnv = {
|
|
3
|
+
frame(callback: (time: number) => void): number;
|
|
4
|
+
cancel(id: number): void;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Calls `step` 60 times a second and `draw` once a frame. An error in either goes to `onError` once and stops the loop.
|
|
8
|
+
*/
|
|
9
|
+
export declare function startLoop(run: {
|
|
10
|
+
step(): void;
|
|
11
|
+
draw(): void;
|
|
12
|
+
onError(error: unknown): void;
|
|
13
|
+
}, env?: LoopEnv): {
|
|
14
|
+
pause(): void;
|
|
15
|
+
resume(): void;
|
|
16
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const stepMs = 1000 / 60;
|
|
2
|
+
// A frame that comes late (a hidden tab, a long pause) counts as at most this long, so nothing runs a burst of missed steps.
|
|
3
|
+
const longestFrameMs = 100;
|
|
4
|
+
const browserEnv = () => ({
|
|
5
|
+
frame: (callback) => requestAnimationFrame(callback),
|
|
6
|
+
cancel: (id) => cancelAnimationFrame(id),
|
|
7
|
+
});
|
|
8
|
+
/**
|
|
9
|
+
* Calls `step` 60 times a second and `draw` once a frame. An error in either goes to `onError` once and stops the loop.
|
|
10
|
+
*/
|
|
11
|
+
export function startLoop(run, env = browserEnv()) {
|
|
12
|
+
let id;
|
|
13
|
+
let last;
|
|
14
|
+
let owed = 0;
|
|
15
|
+
const frame = (time) => {
|
|
16
|
+
id = undefined;
|
|
17
|
+
owed += Math.min(longestFrameMs, last === undefined ? 0 : time - last);
|
|
18
|
+
last = time;
|
|
19
|
+
try {
|
|
20
|
+
while (owed >= stepMs) {
|
|
21
|
+
run.step();
|
|
22
|
+
owed -= stepMs;
|
|
23
|
+
}
|
|
24
|
+
run.draw();
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
owed = 0;
|
|
28
|
+
run.onError(error);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
id = env.frame(frame);
|
|
32
|
+
};
|
|
33
|
+
const resume = () => {
|
|
34
|
+
if (id !== undefined)
|
|
35
|
+
return;
|
|
36
|
+
last = undefined;
|
|
37
|
+
id = env.frame(frame);
|
|
38
|
+
};
|
|
39
|
+
resume();
|
|
40
|
+
return {
|
|
41
|
+
pause() {
|
|
42
|
+
if (id !== undefined)
|
|
43
|
+
env.cancel(id);
|
|
44
|
+
id = undefined;
|
|
45
|
+
},
|
|
46
|
+
resume,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Inputs } from '../game/game.ts';
|
|
2
|
+
import type { Bindings, Controls } from './controls.ts';
|
|
3
|
+
type Events = Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
|
|
4
|
+
/** Where input comes from. The browser's own by default; a test hands in its own. */
|
|
5
|
+
export type InputEnv = {
|
|
6
|
+
events: Events;
|
|
7
|
+
pads(): (Gamepad | null)[];
|
|
8
|
+
};
|
|
9
|
+
type Vector = [number, number];
|
|
10
|
+
/**
|
|
11
|
+
* Reads the keyboard, the gamepads and the touch controls into the `Inputs` a game's `update` takes, one entry per
|
|
12
|
+
* entry of `bindings` (player 1 first). When two kinds are used at once, touch beats the pad and the pad beats the keys.
|
|
13
|
+
* Player `n` reads only the pad with index `n` and only the keys in `bindings[n]`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function readInputs(controls: Controls, bindings: Bindings[], env?: InputEnv): {
|
|
16
|
+
/** The inputs for this tick. A press that began and ended since the last call still counts once. */
|
|
17
|
+
read(): Inputs;
|
|
18
|
+
/** Which kind of control was used last, so the game can show the right buttons. */
|
|
19
|
+
lastUsed: () => 'touch' | 'pad' | 'keys';
|
|
20
|
+
/** The players (0 is player 1) whose gamepad was there and is not any more. */
|
|
21
|
+
padsMissing: () => number[];
|
|
22
|
+
/** What the on-screen controls call: a button is held (`true`) or let go (`false`); a stick is pushed `[x, y]` or let go. */
|
|
23
|
+
touch(action: string, value: boolean | Vector, player?: number): void;
|
|
24
|
+
/** Stops listening. */
|
|
25
|
+
stop(): void;
|
|
26
|
+
};
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
const deadzone = 0.2;
|
|
2
|
+
const browserEnv = () => ({
|
|
3
|
+
events: globalThis,
|
|
4
|
+
pads: () => Array.from(globalThis.navigator?.getGamepads?.() ?? []),
|
|
5
|
+
});
|
|
6
|
+
const press = (pad, button) => pad.buttons[button]?.pressed === true;
|
|
7
|
+
const axis = (pad, index) => pad.axes[index] ?? 0;
|
|
8
|
+
/** One pad input as true or false: `button:3`, `axis:0:+` or `axis:0:-`. */
|
|
9
|
+
function padDown(pad, id) {
|
|
10
|
+
const [kind, index, sign] = id.split(':');
|
|
11
|
+
const n = Number(index);
|
|
12
|
+
if (kind === 'button')
|
|
13
|
+
return press(pad, n);
|
|
14
|
+
if (kind === 'axis')
|
|
15
|
+
return sign === '-' ? axis(pad, n) < -0.5 : axis(pad, n) > 0.5;
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
/** One pad input as a push in two directions: `stick:left`, `stick:right` or `dpad`. Down is positive, as on the screen. */
|
|
19
|
+
function padVector(pad, id) {
|
|
20
|
+
if (id === 'dpad')
|
|
21
|
+
return [Number(press(pad, 15)) - Number(press(pad, 14)), Number(press(pad, 13)) - Number(press(pad, 12))];
|
|
22
|
+
if (id !== 'stick:left' && id !== 'stick:right')
|
|
23
|
+
return [0, 0];
|
|
24
|
+
const start = id === 'stick:left' ? 0 : 2;
|
|
25
|
+
const vector = [axis(pad, start), axis(pad, start + 1)];
|
|
26
|
+
const length = Math.hypot(...vector);
|
|
27
|
+
if (length < deadzone)
|
|
28
|
+
return [0, 0];
|
|
29
|
+
return length > 1 ? [vector[0] / length, vector[1] / length] : vector;
|
|
30
|
+
}
|
|
31
|
+
const nonzero = (vector) => vector !== undefined && (vector[0] !== 0 || vector[1] !== 0);
|
|
32
|
+
/**
|
|
33
|
+
* Reads the keyboard, the gamepads and the touch controls into the `Inputs` a game's `update` takes, one entry per
|
|
34
|
+
* entry of `bindings` (player 1 first). When two kinds are used at once, touch beats the pad and the pad beats the keys.
|
|
35
|
+
* Player `n` reads only the pad with index `n` and only the keys in `bindings[n]`.
|
|
36
|
+
*/
|
|
37
|
+
export function readInputs(controls, bindings, env = browserEnv()) {
|
|
38
|
+
const held = new Set();
|
|
39
|
+
const keysPending = new Set();
|
|
40
|
+
const touchHeld = new Map();
|
|
41
|
+
const touchPending = new Set();
|
|
42
|
+
const latched = new Set();
|
|
43
|
+
const wasDown = new Set();
|
|
44
|
+
const seenPads = new Set();
|
|
45
|
+
let used = 'keys';
|
|
46
|
+
let padBusy = false;
|
|
47
|
+
const onDown = (event) => {
|
|
48
|
+
const code = event.code;
|
|
49
|
+
held.add(code);
|
|
50
|
+
keysPending.add(code);
|
|
51
|
+
used = 'keys';
|
|
52
|
+
};
|
|
53
|
+
const onUp = (event) => void held.delete(event.code);
|
|
54
|
+
const onBlur = () => held.clear();
|
|
55
|
+
env.events.addEventListener('keydown', onDown);
|
|
56
|
+
env.events.addEventListener('keyup', onUp);
|
|
57
|
+
env.events.addEventListener('blur', onBlur);
|
|
58
|
+
/** Which player's pads are there, and which were there and have gone. */
|
|
59
|
+
function scan(pads) {
|
|
60
|
+
const pad = (player) => pads.find((one) => one?.connected && one.index === player) ?? undefined;
|
|
61
|
+
const missing = [];
|
|
62
|
+
let busy = false;
|
|
63
|
+
for (let player = 0; player < bindings.length; player += 1) {
|
|
64
|
+
const one = pad(player);
|
|
65
|
+
if (one) {
|
|
66
|
+
seenPads.add(player);
|
|
67
|
+
busy ||= one.buttons.some((button) => button.pressed) || one.axes.some((value) => Math.abs(value) > 0.5);
|
|
68
|
+
}
|
|
69
|
+
else if (seenPads.has(player))
|
|
70
|
+
missing.push(player);
|
|
71
|
+
}
|
|
72
|
+
if (busy && !padBusy)
|
|
73
|
+
used = 'pad';
|
|
74
|
+
padBusy = busy;
|
|
75
|
+
return { pad, missing };
|
|
76
|
+
}
|
|
77
|
+
const keyOn = (code) => code !== undefined && (held.has(code) || keysPending.has(code)) ? 1 : 0;
|
|
78
|
+
const keyVector = (codes) => [keyOn(codes[1]) - keyOn(codes[0]), keyOn(codes[3]) - keyOn(codes[2])];
|
|
79
|
+
return {
|
|
80
|
+
/** The inputs for this tick. A press that began and ended since the last call still counts once. */
|
|
81
|
+
read() {
|
|
82
|
+
const { pad } = scan(env.pads());
|
|
83
|
+
const inputs = bindings.map((own, player) => {
|
|
84
|
+
const down = [];
|
|
85
|
+
const sticks = {};
|
|
86
|
+
const one = pad(player);
|
|
87
|
+
for (const action of controls.actions) {
|
|
88
|
+
const key = `${player}:${action.id}`;
|
|
89
|
+
const codes = own.keys[action.id] ?? [];
|
|
90
|
+
const padIds = own.pad[action.id] ?? [];
|
|
91
|
+
const touch = touchHeld.get(key);
|
|
92
|
+
if (action.kind === 'stick') {
|
|
93
|
+
const fromTouch = Array.isArray(touch) ? touch : undefined;
|
|
94
|
+
const fromPad = one ? padIds.map((id) => padVector(one, id)).find(nonzero) : undefined;
|
|
95
|
+
const chosen = [fromTouch, fromPad, keyVector(codes)].find(nonzero);
|
|
96
|
+
if (chosen)
|
|
97
|
+
sticks[action.id] = chosen;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const raw = touch === true ||
|
|
101
|
+
touchPending.has(key) ||
|
|
102
|
+
(one !== undefined && padIds.some((id) => padDown(one, id))) ||
|
|
103
|
+
codes.some((code) => held.has(code) || keysPending.has(code));
|
|
104
|
+
if (own.tap.includes(action.id) && action.canTap === true) {
|
|
105
|
+
if (raw && !wasDown.has(key)) {
|
|
106
|
+
if (latched.has(key))
|
|
107
|
+
latched.delete(key);
|
|
108
|
+
else
|
|
109
|
+
latched.add(key);
|
|
110
|
+
}
|
|
111
|
+
if (latched.has(key))
|
|
112
|
+
down.push(action.id);
|
|
113
|
+
}
|
|
114
|
+
else if (raw)
|
|
115
|
+
down.push(action.id);
|
|
116
|
+
if (raw)
|
|
117
|
+
wasDown.add(key);
|
|
118
|
+
else
|
|
119
|
+
wasDown.delete(key);
|
|
120
|
+
}
|
|
121
|
+
return { down, sticks };
|
|
122
|
+
});
|
|
123
|
+
keysPending.clear();
|
|
124
|
+
touchPending.clear();
|
|
125
|
+
return inputs;
|
|
126
|
+
},
|
|
127
|
+
/** Which kind of control was used last, so the game can show the right buttons. */
|
|
128
|
+
lastUsed: () => used,
|
|
129
|
+
/** The players (0 is player 1) whose gamepad was there and is not any more. */
|
|
130
|
+
padsMissing: () => scan(env.pads()).missing,
|
|
131
|
+
/** What the on-screen controls call: a button is held (`true`) or let go (`false`); a stick is pushed `[x, y]` or let go. */
|
|
132
|
+
touch(action, value, player = 0) {
|
|
133
|
+
const key = `${player}:${action}`;
|
|
134
|
+
const released = value === false || (Array.isArray(value) && !nonzero(value));
|
|
135
|
+
if (released)
|
|
136
|
+
touchHeld.delete(key);
|
|
137
|
+
else {
|
|
138
|
+
touchHeld.set(key, value);
|
|
139
|
+
touchPending.add(key);
|
|
140
|
+
used = 'touch';
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
/** Stops listening. */
|
|
144
|
+
stop() {
|
|
145
|
+
env.events.removeEventListener('keydown', onDown);
|
|
146
|
+
env.events.removeEventListener('keyup', onUp);
|
|
147
|
+
env.events.removeEventListener('blur', onBlur);
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const offset = 0xcbf29ce484222325n;
|
|
2
|
+
const prime = 0x100000001b3n;
|
|
3
|
+
const mask = 0xffffffffffffffffn;
|
|
4
|
+
const sorted = (_key, value) => {
|
|
5
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
6
|
+
return value;
|
|
7
|
+
return Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
8
|
+
};
|
|
9
|
+
/** A 64-bit FNV-1a of the state's JSON with its keys sorted, as 16 hex digits. The same state always gives the same text. */
|
|
10
|
+
export function hashState(state) {
|
|
11
|
+
let hash = offset;
|
|
12
|
+
for (const byte of new TextEncoder().encode(JSON.stringify(state, sorted) ?? 'undefined')) {
|
|
13
|
+
hash = ((hash ^ BigInt(byte)) * prime) & mask;
|
|
14
|
+
}
|
|
15
|
+
return hash.toString(16).padStart(16, '0');
|
|
16
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Game, type Inputs, type State } from '../game/game.ts';
|
|
2
|
+
/** Every input a player made, in runs of the same inputs, and where the play ended: enough to play it again exactly. */
|
|
3
|
+
export type Play = {
|
|
4
|
+
format: 1;
|
|
5
|
+
id: string;
|
|
6
|
+
game: string;
|
|
7
|
+
build: string;
|
|
8
|
+
seed: number;
|
|
9
|
+
players: number;
|
|
10
|
+
runs: [ticks: number, inputs: Inputs][];
|
|
11
|
+
end: {
|
|
12
|
+
tick: number;
|
|
13
|
+
hash: string;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
/** `about` says which game and build made the play; a replay in CI uses it to find the right one. */
|
|
17
|
+
export declare function recordPlay<G>(game: Game<G>, start: {
|
|
18
|
+
players: number;
|
|
19
|
+
seed: number;
|
|
20
|
+
}, about?: {
|
|
21
|
+
game: string;
|
|
22
|
+
build: string;
|
|
23
|
+
}): {
|
|
24
|
+
push(inputs: Inputs): State<G>;
|
|
25
|
+
finish(): Play;
|
|
26
|
+
};
|
|
27
|
+
/** Plays the recording again from its seed. `same` says the end is the very one it was recorded with. */
|
|
28
|
+
export declare function replayPlay<G>(game: Game<G>, play: Play): {
|
|
29
|
+
state: State<G>;
|
|
30
|
+
hash: string;
|
|
31
|
+
same: boolean;
|
|
32
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { newState } from '../game/game.js';
|
|
2
|
+
import { step } from '../game/tick.js';
|
|
3
|
+
import { upgrade } from '../upgrade/upgrade.js';
|
|
4
|
+
import { hashState } from './hash.js';
|
|
5
|
+
/** `about` says which game and build made the play; a replay in CI uses it to find the right one. */
|
|
6
|
+
export function recordPlay(game, start, about = { game: '', build: '' }) {
|
|
7
|
+
let state = newState(game, start);
|
|
8
|
+
const runs = [];
|
|
9
|
+
let lastText = '';
|
|
10
|
+
return {
|
|
11
|
+
push(inputs) {
|
|
12
|
+
const copy = structuredClone(inputs);
|
|
13
|
+
const text = JSON.stringify(copy);
|
|
14
|
+
const last = runs[runs.length - 1];
|
|
15
|
+
if (last && text === lastText)
|
|
16
|
+
last[0] += 1;
|
|
17
|
+
else
|
|
18
|
+
runs.push([1, copy]);
|
|
19
|
+
lastText = text;
|
|
20
|
+
state = step(game, state, copy);
|
|
21
|
+
return state;
|
|
22
|
+
},
|
|
23
|
+
finish: () => ({
|
|
24
|
+
format: 1,
|
|
25
|
+
id: `play-${start.seed}`,
|
|
26
|
+
...about,
|
|
27
|
+
seed: start.seed,
|
|
28
|
+
players: start.players,
|
|
29
|
+
runs: structuredClone(runs),
|
|
30
|
+
end: { tick: state.tick, hash: hashState(state) },
|
|
31
|
+
}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Plays the recording again from its seed. `same` says the end is the very one it was recorded with. */
|
|
35
|
+
export function replayPlay(game, play) {
|
|
36
|
+
const upgraded = upgrade('play', play);
|
|
37
|
+
const file = (upgraded.ok ? upgraded.value : play);
|
|
38
|
+
let state = newState(game, { players: file.players, seed: file.seed });
|
|
39
|
+
if (!upgraded.ok)
|
|
40
|
+
return { state, hash: '', same: false };
|
|
41
|
+
for (const [ticks, inputs] of file.runs) {
|
|
42
|
+
for (let n = 0; n < ticks; n += 1)
|
|
43
|
+
state = step(game, state, structuredClone(inputs));
|
|
44
|
+
}
|
|
45
|
+
const hash = hashState(state);
|
|
46
|
+
return { state, hash, same: hash === file.end.hash && state.tick === file.end.tick };
|
|
47
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Result } from '../../lib/result.ts';
|
|
2
|
+
import type { State } from '../game/game.ts';
|
|
3
|
+
/** Where saves go. The browser's version is `browserStore` in `@automataframework/core/browser`. */
|
|
4
|
+
export type KeyValue = {
|
|
5
|
+
get(key: string): string | null;
|
|
6
|
+
set(key: string, value: string): void;
|
|
7
|
+
remove(key: string): void;
|
|
8
|
+
};
|
|
9
|
+
export declare const slots: readonly ['auto', '1', '2', '3'];
|
|
10
|
+
export declare function createSaves(store: KeyValue, gameId: string, now: () => number): {
|
|
11
|
+
/** The slots that hold a save that can be read, in slot order. A damaged one is left out. */
|
|
12
|
+
list(): {
|
|
13
|
+
slot: string;
|
|
14
|
+
savedAt: number;
|
|
15
|
+
tick: number;
|
|
16
|
+
}[];
|
|
17
|
+
write(slot: string, state: State<unknown>): Result<true>;
|
|
18
|
+
read(slot: string): Result<State<unknown>>;
|
|
19
|
+
/** The slot's save as plain JSON text, for a person to keep; empty when the slot holds nothing. */
|
|
20
|
+
exportSlot(slot: string): string;
|
|
21
|
+
/** Checks `text` first and writes only if it is a save of this game at a format this game knows. */
|
|
22
|
+
importInto(slot: string, text: string): Result<true>;
|
|
23
|
+
canStore(): boolean;
|
|
24
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { fail, ok } from '../../lib/result.js';
|
|
3
|
+
import { problem } from '../content/problems.js';
|
|
4
|
+
import { upgrade } from '../upgrade/upgrade.js';
|
|
5
|
+
export const slots = ['auto', '1', '2', '3'];
|
|
6
|
+
const stateSchema = z.looseObject({
|
|
7
|
+
tick: z.number(),
|
|
8
|
+
seed: z.number(),
|
|
9
|
+
players: z.array(z.looseObject({ id: z.number() })),
|
|
10
|
+
outcome: z.union([z.literal('win'), z.literal('lose'), z.null()]),
|
|
11
|
+
game: z.unknown(),
|
|
12
|
+
});
|
|
13
|
+
const fileSchema = z.looseObject({
|
|
14
|
+
format: z.literal(1),
|
|
15
|
+
id: z.string(),
|
|
16
|
+
game: z.string(),
|
|
17
|
+
savedAt: z.number(),
|
|
18
|
+
tick: z.number(),
|
|
19
|
+
state: stateSchema,
|
|
20
|
+
});
|
|
21
|
+
const cannotKeep = () => [
|
|
22
|
+
problem('this device', 1, "This device can't keep saves right now.", 'Free some space or leave private browsing, then save again.'),
|
|
23
|
+
];
|
|
24
|
+
const known = (slot) => slots.includes(slot);
|
|
25
|
+
const label = (slot) => `save slot ${slot}`;
|
|
26
|
+
const noSlot = (slot) => fail([problem(label(slot), 1, `There is no save slot "${slot}".`, `Use one of: ${slots.join(', ')}.`)]);
|
|
27
|
+
export function createSaves(store, gameId, now) {
|
|
28
|
+
const keyOf = (slot) => `automata:${gameId}:save:${slot}`;
|
|
29
|
+
const stored = (slot) => {
|
|
30
|
+
try {
|
|
31
|
+
return store.get(keyOf(slot));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Text to a checked save file for this game, or one plain problem. */
|
|
38
|
+
function parse(slot, text) {
|
|
39
|
+
const where = label(slot);
|
|
40
|
+
let json;
|
|
41
|
+
try {
|
|
42
|
+
json = JSON.parse(text);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return fail([
|
|
46
|
+
problem(where, 1, 'This save is damaged and cannot be read.', 'Pick another save, or start a new game.'),
|
|
47
|
+
]);
|
|
48
|
+
}
|
|
49
|
+
const upgraded = upgrade('save', json);
|
|
50
|
+
if (!upgraded.ok)
|
|
51
|
+
return upgraded;
|
|
52
|
+
const checked = fileSchema.safeParse(upgraded.value);
|
|
53
|
+
if (!checked.success)
|
|
54
|
+
return fail([
|
|
55
|
+
problem(where, 1, 'This is not a save this game can read.', 'Pick another save, or start a new game.'),
|
|
56
|
+
]);
|
|
57
|
+
if (checked.data.game !== gameId)
|
|
58
|
+
return fail([problem(where, 1, 'This save is from another game.', 'Import a save made by this game.')]);
|
|
59
|
+
return ok(checked.data);
|
|
60
|
+
}
|
|
61
|
+
function put(slot, file) {
|
|
62
|
+
try {
|
|
63
|
+
store.set(keyOf(slot), JSON.stringify(file));
|
|
64
|
+
return ok(true);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return fail(cannotKeep());
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
/** The slots that hold a save that can be read, in slot order. A damaged one is left out. */
|
|
72
|
+
list() {
|
|
73
|
+
return slots.flatMap((slot) => {
|
|
74
|
+
const text = stored(slot);
|
|
75
|
+
const file = text === null ? undefined : parse(slot, text);
|
|
76
|
+
return file?.ok ? [{ slot, savedAt: file.value.savedAt, tick: file.value.tick }] : [];
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
write(slot, state) {
|
|
80
|
+
if (!known(slot))
|
|
81
|
+
return noSlot(slot);
|
|
82
|
+
return put(slot, { format: 1, id: `${gameId}-${slot}`, game: gameId, savedAt: now(), tick: state.tick, state });
|
|
83
|
+
},
|
|
84
|
+
read(slot) {
|
|
85
|
+
if (!known(slot))
|
|
86
|
+
return noSlot(slot);
|
|
87
|
+
const text = stored(slot);
|
|
88
|
+
if (text === null)
|
|
89
|
+
return fail([problem(label(slot), 1, 'Nothing is saved here yet.', 'Pick a slot that has a save.')]);
|
|
90
|
+
const file = parse(slot, text);
|
|
91
|
+
return file.ok ? ok(file.value.state) : file;
|
|
92
|
+
},
|
|
93
|
+
/** The slot's save as plain JSON text, for a person to keep; empty when the slot holds nothing. */
|
|
94
|
+
exportSlot(slot) {
|
|
95
|
+
return known(slot) ? (stored(slot) ?? '') : '';
|
|
96
|
+
},
|
|
97
|
+
/** Checks `text` first and writes only if it is a save of this game at a format this game knows. */
|
|
98
|
+
importInto(slot, text) {
|
|
99
|
+
if (!known(slot))
|
|
100
|
+
return noSlot(slot);
|
|
101
|
+
const file = parse(slot, text);
|
|
102
|
+
return file.ok ? put(slot, { ...file.value, id: `${gameId}-${slot}` }) : file;
|
|
103
|
+
},
|
|
104
|
+
canStore() {
|
|
105
|
+
const key = `automata:${gameId}:probe`;
|
|
106
|
+
try {
|
|
107
|
+
store.set(key, '1');
|
|
108
|
+
store.remove(key);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The browser's local storage, or plain memory for this visit when the browser refuses (private mode, storage full). */
|
|
2
|
+
export function browserStore() {
|
|
3
|
+
const memory = new Map();
|
|
4
|
+
const fallback = {
|
|
5
|
+
get: (key) => memory.get(key) ?? null,
|
|
6
|
+
set: (key, value) => void memory.set(key, value),
|
|
7
|
+
remove: (key) => void memory.delete(key),
|
|
8
|
+
};
|
|
9
|
+
try {
|
|
10
|
+
const storage = globalThis.localStorage;
|
|
11
|
+
const probe = 'automata:probe';
|
|
12
|
+
storage.setItem(probe, '1');
|
|
13
|
+
storage.removeItem(probe);
|
|
14
|
+
return {
|
|
15
|
+
get: (key) => storage.getItem(key),
|
|
16
|
+
set: (key, value) => storage.setItem(key, value),
|
|
17
|
+
remove: (key) => storage.removeItem(key),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return fallback;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Result } from '../../lib/result.ts';
|
|
2
|
+
type Step = (old: unknown) => unknown;
|
|
3
|
+
/** Teaches `upgrade` how to turn a file of `kind` at format `from` into format `from + 1`. */
|
|
4
|
+
export declare function addUpgrade(kind: string, from: number, up: Step): void;
|
|
5
|
+
/** Runs every step from the file's format to the newest. Upgrading a file that is already newest changes nothing. */
|
|
6
|
+
export declare function upgrade(kind: string, file: unknown): Result<unknown>;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { fail, ok } from '../../lib/result.js';
|
|
2
|
+
import { problem } from '../content/problems.js';
|
|
3
|
+
const steps = new Map();
|
|
4
|
+
/** The newest format of a kind: one past its last step, or 1 when it has none. */
|
|
5
|
+
const newest = (kind) => Math.max(1, ...[...(steps.get(kind)?.keys() ?? [])].map((from) => from + 1));
|
|
6
|
+
/** Teaches `upgrade` how to turn a file of `kind` at format `from` into format `from + 1`. */
|
|
7
|
+
export function addUpgrade(kind, from, up) {
|
|
8
|
+
const forKind = steps.get(kind) ?? new Map();
|
|
9
|
+
forKind.set(from, up);
|
|
10
|
+
steps.set(kind, forKind);
|
|
11
|
+
}
|
|
12
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
|
+
/** Runs every step from the file's format to the newest. Upgrading a file that is already newest changes nothing. */
|
|
14
|
+
export function upgrade(kind, file) {
|
|
15
|
+
const where = `a ${kind} file`;
|
|
16
|
+
if (!isObject(file) || typeof file.format !== 'number' || !Number.isInteger(file.format) || file.format < 0)
|
|
17
|
+
return fail([
|
|
18
|
+
problem(where, 1, `This is not a ${kind} file: it has no format number.`, `Use a file this game made.`),
|
|
19
|
+
]);
|
|
20
|
+
const last = newest(kind);
|
|
21
|
+
if (file.format > last)
|
|
22
|
+
return fail([
|
|
23
|
+
problem(where, 1, `This ${kind} file is from a newer version (format ${file.format}) than this game knows (format ${last}).`, 'Update the game, then try again.'),
|
|
24
|
+
]);
|
|
25
|
+
let current = file;
|
|
26
|
+
for (let format = file.format; format < last; format += 1) {
|
|
27
|
+
const step = steps.get(kind)?.get(format);
|
|
28
|
+
if (!step)
|
|
29
|
+
return fail([
|
|
30
|
+
problem(where, 1, `This ${kind} file is at format ${file.format} and there is no way to bring format ${format} up to ${format + 1}.`, 'Use a newer file, or ask for the missing step to be added.'),
|
|
31
|
+
]);
|
|
32
|
+
const next = step(current);
|
|
33
|
+
current = isObject(next) ? { ...next, format: format + 1 } : next;
|
|
34
|
+
}
|
|
35
|
+
return ok(current);
|
|
36
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type { Game, Inputs, Player, PlayerInput, Start, State } from './features/game/game.ts';
|
|
2
|
+
export { isDown, lose, newState, stick, wasPressed, win } from './features/game/game.ts';
|
|
3
|
+
export { random } from './features/game/random.ts';
|
|
4
|
+
export { step } from './features/game/tick.ts';
|
|
5
|
+
export { defineKind, schemas } from './features/content/kinds.ts';
|
|
6
|
+
export { content, loadGame } from './features/content/load.ts';
|
|
7
|
+
export type { Content, Read } from './features/content/load.ts';
|
|
8
|
+
export type { Manifest } from './features/content/manifest.ts';
|
|
9
|
+
export { addUpgrade, upgrade } from './features/upgrade/upgrade.ts';
|
|
10
|
+
export { controlsSchema, defaultBindings } from './features/input/controls.ts';
|
|
11
|
+
export type { Action, Bindings, Controls } from './features/input/controls.ts';
|
|
12
|
+
export { createSaves, slots } from './features/saves/saves.ts';
|
|
13
|
+
export type { KeyValue } from './features/saves/saves.ts';
|
|
14
|
+
export { hashState } from './features/plays/hash.ts';
|
|
15
|
+
export { recordPlay, replayPlay } from './features/plays/plays.ts';
|
|
16
|
+
export type { Play } from './features/plays/plays.ts';
|
|
17
|
+
export { playSound } from './features/audio/queue.ts';
|
|
18
|
+
export type { SoundOptions } from './features/audio/queue.ts';
|
|
19
|
+
export type { Problem, Result } from './lib/result.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { isDown, lose, newState, stick, wasPressed, win } from './features/game/game.js';
|
|
2
|
+
export { random } from './features/game/random.js';
|
|
3
|
+
export { step } from './features/game/tick.js';
|
|
4
|
+
export { defineKind, schemas } from './features/content/kinds.js';
|
|
5
|
+
export { content, loadGame } from './features/content/load.js';
|
|
6
|
+
export { addUpgrade, upgrade } from './features/upgrade/upgrade.js';
|
|
7
|
+
export { controlsSchema, defaultBindings } from './features/input/controls.js';
|
|
8
|
+
export { createSaves, slots } from './features/saves/saves.js';
|
|
9
|
+
export { hashState } from './features/plays/hash.js';
|
|
10
|
+
export { recordPlay, replayPlay } from './features/plays/plays.js';
|
|
11
|
+
export { playSound } from './features/audio/queue.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** One mistake in a game's files, written so a person can act on it. */
|
|
2
|
+
export type Problem = {
|
|
3
|
+
file: string;
|
|
4
|
+
line: number;
|
|
5
|
+
message: string;
|
|
6
|
+
fix: string;
|
|
7
|
+
};
|
|
8
|
+
export type Result<T> = {
|
|
9
|
+
ok: true;
|
|
10
|
+
value: T;
|
|
11
|
+
} | {
|
|
12
|
+
ok: false;
|
|
13
|
+
problems: Problem[];
|
|
14
|
+
};
|
|
15
|
+
export declare const ok: <T>(value: T) => Result<T>;
|
|
16
|
+
export declare const fail: (problems: Problem[]) => Result<never>;
|