Repository navigation
Expand file tree
/
Copy pathsettings.ts
More file actions
427 lines (375 loc) · 18 KB
/
Copy pathsettings.ts
File metadata and controls
427 lines (375 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import { DEFAULT_KEYS, keyCodesOf, PLAYER_KEYS } from './default-keys';
import { PAD } from './gamepad';
import { isRecord, loadJSON, onExternalChange, saveJSON } from './storage';
/**
* Arcade-wide player settings, shared by the hub and every game (saved on this device).
* No Phaser here, so the hub can use it without loading the game engine.
*/
/** Actions players can rebind. Game-specific extras (e.g. Stack's rotate keys) keep their defaults. */
export const REBINDABLE = ['left', 'right', 'up', 'down', 'action', 'alt', 'pause', 'mute'] as const;
export type RebindableAction = (typeof REBINDABLE)[number];
/** The two seats of a local two-player game. */
export const SEATS = [1, 2] as const;
export type Seat = (typeof SEATS)[number];
/** Actions each seat has keys of its own for. Pause and Mute are shared by both seats instead. */
export const SEAT_ACTIONS = ['left', 'right', 'up', 'down', 'action', 'alt'] as const satisfies readonly Exclude<RebindableAction, SharedAction>[];
export type SeatAction = (typeof SEAT_ACTIONS)[number];
/** Human-readable default keys per action, for the settings screen. */
export const DEFAULT_KEY_LABELS: Record<RebindableAction, string> = {
left: '← / A',
right: '→ / D',
up: '↑ / W',
down: '↓ / S',
action: 'Space / Enter',
alt: 'Shift / X',
pause: 'P / Esc',
mute: 'M',
};
/** keyCodes behind the default keys (DEFAULT_KEYS), for start prompts and for spotting clashes when rebinding. */
export const DEFAULT_KEY_CODES = Object.fromEntries(REBINDABLE.map((a) => [a, keyCodesOf(DEFAULT_KEYS[a])])) as Record<RebindableAction, number[]>;
/** Human-readable default keys per seat in two-player modes, for the settings screen. */
export const DEFAULT_SEAT_KEY_LABELS: Record<Seat, Record<SeatAction, string>> = {
1: { left: 'A', right: 'D', up: 'W', down: 'S', action: 'Space', alt: 'Shift' },
2: { left: '←', right: '→', up: '↑', down: '↓', action: 'Enter', alt: 'Ctrl' },
};
/** keyCodes behind each seat's default keys (PLAYER_KEYS). */
const seatDefaultCodes = (seat: Seat) => Object.fromEntries(SEAT_ACTIONS.map((a) => [a, keyCodesOf(PLAYER_KEYS[seat][a])])) as Record<SeatAction, number[]>;
export const DEFAULT_SEAT_KEY_CODES: Record<Seat, Record<SeatAction, number[]>> = { 1: seatDefaultCodes(1), 2: seatDefaultCodes(2) };
/** The gamepad button behind each action by default (standard mapping). The left stick always moves as well. */
export const DEFAULT_PAD_BUTTONS: Record<RebindableAction, number> = {
left: PAD.left,
right: PAD.right,
up: PAD.up,
down: PAD.down,
action: PAD.a,
alt: PAD.b,
pause: PAD.start,
mute: PAD.back,
};
export interface PadBinding {
/** Button index in the gamepad's `buttons` list. */
button: number;
}
/** Highest gamepad button index a binding may use; standard pads have 17 buttons. */
const MAX_PAD_BUTTON = 31;
/** The highest `KeyboardEvent.keyCode` a key can have, and room for the longest key name shown for it. */
const MAX_KEY_CODE = 255;
const MAX_KEY_LABEL = 24;
export interface KeyBinding {
/** KeyboardEvent.keyCode, which Phaser uses for its keys. */
code: number;
/** What to show the player, e.g. "K" or "Space". */
label: string;
}
export type Palette = 'neon' | 'colorblind';
/** Options for the on-screen controls shown on touch screens. */
export interface TouchSettings {
/** A short vibration when an on-screen button is pressed (where the device supports it). */
haptics: boolean;
/** Size multiplier for the on-screen stick and buttons. */
scale: number;
/** Left-handed layout: the stick and buttons swap sides. */
mirrored: boolean;
}
export const TOUCH_SCALE_MIN = 0.8;
export const TOUCH_SCALE_MAX = 1.5;
/** The next on-screen button size for a menu that steps through them: 10% bigger, wrapping from the largest back to the smallest. */
export function nextTouchScale(scale: number): number {
const next = Math.round(scale * 10) + 1;
return next > Math.round(TOUCH_SCALE_MAX * 10) ? TOUCH_SCALE_MIN : next / 10;
}
/**
* How fast games run, as a share of full speed. Anything below 1 is an assist for players who need
* more time to react, and a run played that way is kept off the records (shared/frame.ts).
*/
export const GAME_SPEEDS = [1, 0.85, 0.7] as const;
export type GameSpeed = (typeof GAME_SPEEDS)[number];
/** The game speed on offer that is closest to `value`, so a saved or typed number can never run a game faster than full speed or slower than the slowest. */
export function toGameSpeed(value: number): GameSpeed {
return GAME_SPEEDS.reduce((best, speed) => (Math.abs(speed - value) < Math.abs(best - value) ? speed : best));
}
/** The next game speed for a menu that steps through them: one step slower, wrapping from the slowest back to full speed. */
export function nextGameSpeed(speed: number): GameSpeed {
return GAME_SPEEDS[(GAME_SPEEDS.indexOf(toGameSpeed(speed)) + 1) % GAME_SPEEDS.length];
}
export interface Settings {
/** Master volume, 0 to 1. */
volume: number;
muted: boolean;
/** Turns off screen shake, flashes and decorative animation. */
reducedMotion: boolean;
/** 'colorblind' swaps the neon colors for a color-vision-deficiency-safe set (Okabe-Ito based). */
palette: Palette;
/** Custom keyboard keys per action, replacing that action's default keys. */
bindings: Partial<Record<RebindableAction, KeyBinding>>;
/** Custom keyboard keys per seat for two-player modes, replacing that seat's default key for the action. */
seatBindings: Partial<Record<Seat, Partial<Record<SeatAction, KeyBinding>>>>;
/** Custom gamepad button per action, replacing that action's default button on every player's pad. */
padBindings: Partial<Record<RebindableAction, PadBinding>>;
/** Gamepads rumble on impacts (where the gamepad and the browser support it). */
rumble: boolean;
touch: TouchSettings;
/** Game speed assist: 1 is full speed, lower values slow every game down. */
gameSpeed: GameSpeed;
}
const KEY = 'settings';
/** Bumped when the saved shape changes, so a later version can tell old saves apart. */
const SAVE_VERSION = 1;
/** A saved key binding, if it is well formed. A key code is a small whole number; anything else (a hand-edited save, a damaged backup) keeps the default key. */
function savedKeyBinding(b: unknown): KeyBinding | undefined {
if (isRecord(b) && Number.isInteger(b.code) && (b.code as number) > 0 && (b.code as number) <= MAX_KEY_CODE && typeof b.label === 'string') {
return { code: b.code as number, label: b.label.slice(0, MAX_KEY_LABEL) };
}
return undefined;
}
/** Keeps only the well-formed fields of a saved value; anything missing or malformed falls back to its default. */
function sanitize(raw: unknown): Partial<Settings> {
if (!isRecord(raw)) return {};
const out: Partial<Settings> = {};
if (typeof raw.volume === 'number' && Number.isFinite(raw.volume)) out.volume = Math.min(1, Math.max(0, raw.volume));
if (typeof raw.muted === 'boolean') out.muted = raw.muted;
if (typeof raw.reducedMotion === 'boolean') out.reducedMotion = raw.reducedMotion;
if (typeof raw.rumble === 'boolean') out.rumble = raw.rumble;
if (raw.palette === 'neon' || raw.palette === 'colorblind') out.palette = raw.palette;
if (typeof raw.gameSpeed === 'number' && Number.isFinite(raw.gameSpeed)) out.gameSpeed = toGameSpeed(raw.gameSpeed);
if (isRecord(raw.bindings)) {
const bindings: Settings['bindings'] = {};
for (const action of REBINDABLE) {
const b = savedKeyBinding(raw.bindings[action]);
if (b) bindings[action] = b;
}
out.bindings = bindings;
}
if (isRecord(raw.seatBindings)) {
const seatBindings: Settings['seatBindings'] = {};
for (const seat of SEATS) {
const saved = raw.seatBindings[seat];
if (!isRecord(saved)) continue;
const keys: Partial<Record<SeatAction, KeyBinding>> = {};
for (const action of SEAT_ACTIONS) {
const b = savedKeyBinding(saved[action]);
if (b) keys[action] = b;
}
seatBindings[seat] = keys;
}
out.seatBindings = seatBindings;
}
if (isRecord(raw.padBindings)) {
const padBindings: Settings['padBindings'] = {};
for (const action of REBINDABLE) {
const b = raw.padBindings[action];
if (isRecord(b) && Number.isInteger(b.button) && (b.button as number) >= 0 && (b.button as number) <= MAX_PAD_BUTTON) {
padBindings[action] = { button: b.button as number };
}
}
out.padBindings = padBindings;
}
if (isRecord(raw.touch)) {
const t = raw.touch;
const base = defaults().touch;
out.touch = {
haptics: typeof t.haptics === 'boolean' ? t.haptics : base.haptics,
scale: typeof t.scale === 'number' && Number.isFinite(t.scale) ? Math.min(TOUCH_SCALE_MAX, Math.max(TOUCH_SCALE_MIN, t.scale)) : base.scale,
mirrored: typeof t.mirrored === 'boolean' ? t.mirrored : base.mirrored,
};
}
return out;
}
function save(overrides: Partial<Settings>): void {
saveJSON(KEY, { version: SAVE_VERSION, ...overrides });
}
function prefersReducedMotion(): boolean {
try {
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
} catch {
return false;
}
}
function defaults(): Settings {
return {
volume: 0.8,
muted: false,
reducedMotion: prefersReducedMotion(),
palette: 'neon',
bindings: {},
seatBindings: {},
padBindings: {},
rumble: true,
touch: { haptics: true, scale: 1, mirrored: false },
gameSpeed: 1,
};
}
/**
* Only what the player has explicitly changed is saved. Everything else resolves from defaults()
* on each load, so an option the player never touched (reduced motion) keeps following the OS.
*/
function readOverrides(): Partial<Settings> {
return sanitize(loadJSON<unknown>(KEY, {}));
}
let overrides: Partial<Settings> = readOverrides();
let current: Settings = { ...defaults(), ...overrides };
const listeners = new Set<(s: Settings) => void>();
// Settings changed in another tab (e.g. on the hub while a game is open): adopt them, so a later
// write from this tab, such as toggling mute, does not put the old values back.
onExternalChange(KEY, () => {
overrides = readOverrides();
current = { ...defaults(), ...overrides };
listeners.forEach((fn) => fn(current));
});
export function getSettings(): Readonly<Settings> {
return current;
}
export function updateSettings(patch: Partial<Settings>): Settings {
overrides = { ...overrides, ...patch };
current = { ...defaults(), ...overrides };
save(overrides);
listeners.forEach((fn) => fn(current));
return current;
}
export function resetSettings(): Settings {
overrides = {};
current = defaults();
save(overrides);
listeners.forEach((fn) => fn(current));
return current;
}
/** The keyCodes that currently trigger an action for a solo player: the custom key, or the defaults. */
export function keyCodesFor(action: RebindableAction): number[] {
const custom = current.bindings[action];
return custom ? [custom.code] : DEFAULT_KEY_CODES[action];
}
/** The other action, if any, that a key already triggers (through its custom key or its defaults). */
export function keyClash(action: RebindableAction, code: number): RebindableAction | undefined {
return REBINDABLE.find((other) => other !== action && keyCodesFor(other).includes(code));
}
/**
* The action, if any, that stops `action` going back to its default keys: one that has since been
* given one of them.
*/
export function keyRestoreBlocker(action: RebindableAction): RebindableAction | undefined {
return REBINDABLE.find((other) => {
const custom = current.bindings[other];
return other !== action && custom !== undefined && DEFAULT_KEY_CODES[action].includes(custom.code);
});
}
/**
* Upper-case key name(s) for on-screen prompts, following the player's bindings: "K" when rebound,
* otherwise the defaults ("P / ESC"). `first` keeps only the first default key ("SPACE").
*/
export function keyLabel(action: RebindableAction, first = false): string {
const custom = current.bindings[action];
const label = custom ? custom.label : DEFAULT_KEY_LABELS[action];
return (first && !custom ? label.split(' / ')[0] : label).toUpperCase();
}
/** The gamepad button that currently triggers an action: the custom one, or the default. */
export function padButtonFor(action: RebindableAction): number {
return current.padBindings[action]?.button ?? DEFAULT_PAD_BUTTONS[action];
}
/** The other action, if any, that a gamepad button already triggers (its custom button, or its default). */
export function padClash(action: RebindableAction, button: number): RebindableAction | undefined {
return REBINDABLE.find((other) => other !== action && padButtonFor(other) === button);
}
/**
* The action, if any, that stops `action` going back to its default button: one that has since been
* given it.
*/
export function padRestoreBlocker(action: RebindableAction): RebindableAction | undefined {
return REBINDABLE.find((other) => other !== action && current.padBindings[other]?.button === DEFAULT_PAD_BUTTONS[action]);
}
const PAD_BUTTON_NAMES = ['A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT', 'Back', 'Start', 'Left stick', 'Right stick', 'D-pad up', 'D-pad down', 'D-pad left', 'D-pad right'];
/** What to call a gamepad button, by its index in the standard mapping: "A", "Start", "D-pad up", or "Button 17". */
export function padButtonLabel(button: number): string {
return PAD_BUTTON_NAMES[button] ?? `Button ${button}`;
}
/** Actions both players share in two-player modes, where every other key belongs to one seat. */
export type SharedAction = 'pause' | 'mute';
const SHARED_ACTIONS: readonly SharedAction[] = ['pause', 'mute'];
/**
* The keyCodes that trigger an action for one seat of a two-player game: the seat's custom key, or
* its default half of the keyboard (W A S D Space Shift, or the arrows Enter Ctrl).
*/
export function seatKeyCodesFor(seat: Seat, action: SeatAction): number[] {
const custom = current.seatBindings[seat]?.[action];
return custom ? [custom.code] : DEFAULT_SEAT_KEY_CODES[seat][action];
}
/** What a key does in two-player modes: an action of one seat, or (with no seat) one both players share. */
export interface SeatKeyUse {
seat?: Seat;
action: RebindableAction;
}
/** The seat and action a key currently belongs to in two-player modes, if any. `except` leaves one seat's action out. */
export function seatKeyUse(code: number, except?: { seat: Seat; action: SeatAction }): SeatKeyUse | undefined {
for (const seat of SEATS) {
for (const action of SEAT_ACTIONS) {
if (except?.seat === seat && except.action === action) continue;
if (seatKeyCodesFor(seat, action).includes(code)) return { seat, action };
}
}
return undefined;
}
/**
* What stops a seat's action taking a key: another seat action (of either player) that already uses
* it, or Pause or Mute. The default Pause and Mute keys stay off limits even while those are rebound,
* because two-player modes fall back to them when a seat takes the rebound key (sharedKeyCodes).
*/
export function seatKeyClash(seat: Seat, action: SeatAction, code: number): SeatKeyUse | undefined {
const taken = seatKeyUse(code, { seat, action });
if (taken) return taken;
const shared = SHARED_ACTIONS.find((other) => DEFAULT_KEY_CODES[other].includes(code) || current.bindings[other]?.code === code);
return shared && { action: shared };
}
/**
* The seat action, if any, that stops a seat's action going back to its default key: one (of either
* player) that has since been given that key.
*/
export function seatKeyRestoreBlocker(seat: Seat, action: SeatAction): SeatKeyUse | undefined {
const codes = DEFAULT_SEAT_KEY_CODES[seat][action];
for (const otherSeat of SEATS) {
for (const other of SEAT_ACTIONS) {
const custom = current.seatBindings[otherSeat]?.[other];
if ((otherSeat !== seat || other !== action) && custom && codes.includes(custom.code)) return { seat: otherSeat, action: other };
}
}
return undefined;
}
/**
* Key names of one seat for a two-player game's help text, like helpKeys(): `written` is returned as
* is while the seat has none of the actions rebound, and each action's current key is listed once
* one is ("J, D").
*/
export function seatHelpKeys(seat: Seat, actions: SeatAction | readonly SeatAction[], written: string): string {
const list = typeof actions === 'string' ? [actions] : actions;
const custom = current.seatBindings[seat] ?? {};
if (!list.some((action) => custom[action])) return written;
return list.map((action) => custom[action]?.label ?? DEFAULT_SEAT_KEY_LABELS[seat][action]).join(', ');
}
/** The player's own key for a shared action, unless one of the two-player seats already uses that key. */
function sharedBinding(action: SharedAction): KeyBinding | undefined {
const custom = current.bindings[action];
return custom && !seatKeyUse(custom.code) ? custom : undefined;
}
/** The keyCodes that trigger Pause or Mute in two-player modes: the custom key if no seat uses it, or the defaults. */
export function sharedKeyCodes(action: SharedAction): number[] {
const custom = sharedBinding(action);
return custom ? [custom.code] : DEFAULT_KEY_CODES[action];
}
/** Like keyLabel(), for Pause or Mute in two-player modes. */
export function sharedKeyLabel(action: SharedAction): string {
return (sharedBinding(action)?.label ?? DEFAULT_KEY_LABELS[action]).toUpperCase();
}
/**
* Key names for a game's help text. `written` is how the help words the default keys ("P", "← →",
* "arrows / WASD") and is returned as is while none of the actions is rebound. Once one is, each
* action's current keys are listed instead ("K", or "J, → / D"), so the help never names a key that
* no longer works.
*/
export function helpKeys(actions: RebindableAction | readonly RebindableAction[], written: string): string {
const list = typeof actions === 'string' ? [actions] : actions;
if (!list.some((action) => current.bindings[action])) return written;
return list.map((action) => current.bindings[action]?.label ?? DEFAULT_KEY_LABELS[action]).join(', ');
}
/** Calls `fn` whenever settings change. Returns an unsubscribe function. */
export function onSettingsChange(fn: (s: Settings) => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}