dopaminejs 2.4.0 → 3.0.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.
Files changed (83) hide show
  1. package/README.md +40 -50
  2. package/dist/DataService-E4pGQ1V3.cjs +1 -0
  3. package/dist/DataService-MfmvkqXR.js +737 -0
  4. package/dist/core.cjs +1 -0
  5. package/dist/core.js +2 -0
  6. package/dist/dopamine.cjs +1 -37
  7. package/dist/dopamine.js +3 -858
  8. package/dist/games.cjs +1 -0
  9. package/dist/games.js +82 -0
  10. package/dist/host-CkRL74ck.js +814 -0
  11. package/dist/host-Pzb-QBPU.cjs +37 -0
  12. package/dist/style.css +395 -2
  13. package/dist/testing.cjs +1 -0
  14. package/dist/testing.js +474 -0
  15. package/package.json +28 -8
  16. package/spec/README.md +227 -0
  17. package/spec/VERSION +1 -0
  18. package/spec/fixtures/achievements.json +611 -0
  19. package/spec/fixtures/levels.json +421 -0
  20. package/spec/fixtures/merge.json +1739 -0
  21. package/spec/fixtures/migrate.json +916 -0
  22. package/spec/fixtures/scores.json +755 -0
  23. package/spec/fixtures/streaks.json +924 -0
  24. package/spec/schema.json +61 -0
  25. package/src/dopamine/audio/SoundManager.js +78 -24
  26. package/src/dopamine/core/DataService.js +25 -5
  27. package/src/dopamine/core/DopamineError.js +7 -0
  28. package/src/dopamine/core/RewardSystem.js +366 -368
  29. package/src/dopamine/core/achievements.js +49 -0
  30. package/src/dopamine/core/clock.js +11 -0
  31. package/src/dopamine/core/levels.js +4 -0
  32. package/src/dopamine/core/merge.js +68 -0
  33. package/src/dopamine/core/middleware.js +58 -0
  34. package/src/dopamine/core/store.js +261 -0
  35. package/src/dopamine/core/streaks.js +55 -0
  36. package/src/dopamine/effects/ParticleSystem.js +33 -3
  37. package/src/dopamine/feel/haptics.js +21 -0
  38. package/src/dopamine/feel/motion.js +9 -0
  39. package/src/dopamine/host.js +358 -0
  40. package/src/dopamine/ui/RewardUI.js +569 -0
  41. package/src/games.js +138 -0
  42. package/src/index.js +14 -33
  43. package/src/progression.js +16 -0
  44. package/src/testing.js +489 -0
  45. package/types/core.d.ts +35 -0
  46. package/types/games.d.ts +46 -0
  47. package/types/index.d.ts +348 -373
  48. package/types/testing.d.ts +96 -0
  49. package/dist/ScreenShake-9jgNXPS6.cjs +0 -1
  50. package/dist/ScreenShake-CLvO1wx4.js +0 -827
  51. package/dist/engine.cjs +0 -1
  52. package/dist/engine.js +0 -2
  53. package/src/core/Animator.js +0 -62
  54. package/src/core/Collider.js +0 -86
  55. package/src/core/Component.js +0 -38
  56. package/src/core/DopamineKernel.js +0 -170
  57. package/src/core/EventBus.js +0 -206
  58. package/src/core/Game.js +0 -90
  59. package/src/core/GameObject.js +0 -99
  60. package/src/core/PluginRegistry.js +0 -359
  61. package/src/core/Scene.js +0 -107
  62. package/src/core/Sprite.js +0 -51
  63. package/src/core/SystemRegistry.js +0 -263
  64. package/src/core/Vector2.js +0 -50
  65. package/src/dopamine/components/ParticleEmitter.js +0 -50
  66. package/src/dopamine/components/ScreenShake.js +0 -50
  67. package/src/dopamine/components/index.js +0 -2
  68. package/src/dopamine/index.js +0 -93
  69. package/src/dopamine/ui/GameUI.js +0 -420
  70. package/src/dopamine/utils/TextureGenerator.js +0 -90
  71. package/src/engine.js +0 -38
  72. package/src/interfaces/IAudioSystem.js +0 -58
  73. package/src/interfaces/IParticleSystem.js +0 -51
  74. package/src/interfaces/IPhysicsSystem.js +0 -52
  75. package/src/interfaces/ISystem.js +0 -48
  76. package/src/interfaces/index.js +0 -7
  77. package/src/renderer/Renderer.js +0 -45
  78. package/src/systems/Director.js +0 -34
  79. package/src/systems/Input.js +0 -81
  80. package/src/systems/Loader.js +0 -48
  81. package/src/systems/Physics.js +0 -210
  82. package/src/systems/Ticker.js +0 -91
  83. package/src/systems/deprecate.js +0 -38
package/types/index.d.ts CHANGED
@@ -13,15 +13,18 @@
13
13
  export interface PlayerStreak {
14
14
  current: number;
15
15
  longest: number;
16
- /** Local calendar day, YYYY-MM-DD. Not UTC. */
17
- lastPlayDate: string;
16
+ /** Local calendar day, YYYY-MM-DD. Not UTC. Absent until the first play. */
17
+ lastPlayDate?: string;
18
18
  }
19
19
 
20
20
  export interface UnlockedAchievement {
21
21
  unlockedAt: number;
22
22
  seen: boolean;
23
+ /** XP the achievement paid when it was unlocked. */
24
+ reward: number;
23
25
  }
24
26
 
27
+ /** A frozen copy of the player with the derived values. */
25
28
  export interface Player {
26
29
  name: string;
27
30
  xp: number;
@@ -31,18 +34,86 @@ export interface Player {
31
34
  lastPlayedAt: number;
32
35
  streak: PlayerStreak;
33
36
  achievements: Record<string, UnlockedAchievement>;
34
- /** Per-game stats. Games add their own keys. */
35
- stats: Record<string, Record<string, number>>;
37
+ /** Per-activity stats: `plays`, `best`, and any other number a result carried. */
38
+ stats: Record<string, { plays: number; best: number } & Record<string, number>>;
39
+ }
40
+
41
+ /**
42
+ * The saved document. It merges: see `merge`. Treat it as opaque and pass it
43
+ * to `merge`, `validate` and `import`.
44
+ */
45
+ export interface PlayerDocument {
46
+ v: 3;
47
+ name: string;
48
+ createdAt: number;
49
+ lastPlayedAt: number;
50
+ level: number;
51
+ longest: number;
52
+ /** Local days, YYYY-MM-DD, sorted, at most the last 400. */
53
+ playDates: string[];
54
+ xpBy: Record<string, number>;
55
+ xpSpentBy: Record<string, number>;
56
+ gamesBy: Record<string, number>;
57
+ playsBy: Record<string, Record<string, number>>;
58
+ best: Record<string, number>;
59
+ sumsBy: Record<string, Record<string, Record<string, number>>>;
60
+ achievements: Record<string, UnlockedAchievement>;
61
+ }
62
+
63
+ export interface Clock {
64
+ now(): number;
65
+ /** Local calendar day, YYYY-MM-DD, never UTC. Defaults to now. */
66
+ localDate(ms?: number): string;
67
+ }
68
+
69
+ export type DopamineErrorCode =
70
+ | 'invalid_document' | 'unsupported_version' | 'too_many_devices'
71
+ | 'plugin_api' | 'plugin_order' | 'plugin_requires' | 'plugin_invalid'
72
+ | 'plugin_duplicate' | 'plugin_event' | 'invalid_progress' | 'disposed';
73
+
74
+ export class DopamineError extends Error {
75
+ constructor(code: string, message?: string);
76
+ readonly code: DopamineErrorCode | string;
77
+ }
78
+
79
+ export interface ValidateOptions {
80
+ /** Fills missing timestamps. Default 0. */
81
+ now?: number;
82
+ /** A local date (YYYY-MM-DD). When set, play dates older than 400 days counting from it are dropped. Default: none are dropped. */
83
+ today?: string;
84
+ /** XP a 2.x save already holds for each achievement id. Default: the built-ins. */
85
+ rewards?: Record<string, number>;
86
+ }
87
+
88
+ /** Clean any value into a version 3 document, or throw a DopamineError. Pure. */
89
+ export function validate(input: unknown, options?: ValidateOptions): PlayerDocument;
90
+ /**
91
+ * Join two saves. Pure, and the same in any order or grouping.
92
+ * @throws DopamineError `too_many_devices`, `unsupported_version`, `invalid_document`.
93
+ */
94
+ export function merge(a: unknown, b: unknown, options?: ValidateOptions): PlayerDocument;
95
+
96
+ export interface Middleware {
97
+ beforeXP?(context: { amount: number; reason: string }): Partial<{ amount: number; reason: string }> | false | void | Promise<Partial<{ amount: number; reason: string }> | false | void>;
98
+ afterXP?(context: { amount: number; reason: string; total: number; level: number }): void | Promise<void>;
99
+ beforeRecord?(context: { activity: string; result: GameResult }): Partial<{ activity: string; result: GameResult }> | false | void | Promise<Partial<{ activity: string; result: GameResult }> | false | void>;
100
+ afterRecord?(context: { activity: string; result: GameResult; xp: number }): void | Promise<void>;
101
+ beforeUnlock?(context: { id: string; reward: number }): Partial<{ reward: number }> | false | void | Promise<Partial<{ reward: number }> | false | void>;
102
+ afterUnlock?(context: { id: string; reward: number }): void | Promise<void>;
36
103
  }
37
104
 
38
105
  export interface AchievementDefinition {
39
106
  name: string;
40
107
  description?: string;
41
- /** Rendered as HTML, so an <img> or inline SVG is allowed here. */
42
- icon?: string;
108
+ /**
109
+ * A string is shown as allowlisted SVG or text, or as HTML when RewardUI
110
+ * is built with `safeIcons: false`. A Node is moved into the popup, not
111
+ * copied.
112
+ */
113
+ icon?: string | Node;
43
114
  /** Omitted means 0. Never undefined at runtime. */
44
115
  xp?: number;
45
- check(player: Player, gameName?: string, result?: GameResult): boolean;
116
+ check(player: Player, activity?: string, result?: GameResult): boolean;
46
117
  }
47
118
 
48
119
  export interface GameResult {
@@ -67,21 +138,36 @@ export interface AddXPResult {
67
138
 
68
139
  export interface RewardSystemConfig {
69
140
  achievements?: Record<string, AchievementDefinition>;
70
- /** Mirror reward events onto a kernel EventBus. */
71
- events?: EventBus;
72
- /** Alternative to `events`; the kernel's bus is used. */
73
- kernel?: DopamineKernel;
141
+ /** Time source. Tests pass one; the default reads the system clock. */
142
+ clock?: Clock;
143
+ /**
144
+ * What marks today as a play day. `'any'` (default): `record()` or
145
+ * `addXP()`. `'record'`: `record()` only. XP from an achievement reward
146
+ * never marks a day.
147
+ */
148
+ streakDays?: 'any' | 'record';
74
149
  }
75
150
 
76
151
  export type RewardEvent =
77
152
  | 'xp_gained'
78
153
  | 'level_up'
79
154
  | 'achievement_unlocked'
80
- | 'new_high_score'
155
+ /** Payload `{ activity, score }`. */
156
+ | 'personal_best'
81
157
  /** Payload `{ current, longest }`. Fires when the day rolls over. */
82
158
  | 'streak_updated'
83
159
  /** Payload `{ key }`. The storage write failed; state lives in memory only. */
84
- | 'save_failed';
160
+ | 'save_failed'
161
+ /**
162
+ * Payload `{ key, reason, error?, backedUp? }`. `reason: 'read'`: storage
163
+ * could not be read, so nothing is saved this session (call `init()` again
164
+ * to retry). `reason: 'corrupt'`: the saved value was not JSON; it is kept
165
+ * under `player_corrupt` as a JSON string and a new player starts. If that
166
+ * backup fails, `backedUp` is false and nothing is saved this session.
167
+ * A `load()` override must pass its third argument on, or a failed read
168
+ * looks like an empty one.
169
+ */
170
+ | 'load_failed';
85
171
 
86
172
  export class EventEmitter {
87
173
  on(event: string, callback: (data?: unknown) => void): () => void;
@@ -93,12 +179,27 @@ export class EventEmitter {
93
179
  export class RewardSystem extends EventEmitter {
94
180
  constructor(dataService: DataService, config?: RewardSystemConfig);
95
181
 
96
- player: Player | null;
97
182
  achievements: Record<string, AchievementDefinition>;
98
- /** Kernel bus events are mirrored onto, if one was supplied. */
99
- events: EventBus | null;
183
+ /**
184
+ * True when the last `init()` could not read the saved player, so nothing
185
+ * is saved until `init()` is called again and the read works.
186
+ */
187
+ readonly loadFailed: boolean;
100
188
 
101
189
  init(): Promise<Player>;
190
+ /** A frozen copy of the player with the derived values. */
191
+ snapshot(): Player;
192
+ /** The versioned document, a detached copy. */
193
+ export(): PlayerDocument;
194
+ /**
195
+ * Merge a document into this player. Unless `silent`, announces the XP,
196
+ * level and achievements that went up.
197
+ */
198
+ import(doc: unknown, options?: { silent?: boolean }): Promise<Player>;
199
+ /** Hooks run in `use` order. Returns a function that removes it. */
200
+ use(middleware: Middleware): () => void;
201
+ /** Adds a rule at runtime. Returns a function that removes it. */
202
+ defineAchievement(id: string, definition: AchievementDefinition): () => void;
102
203
  save(): Promise<void>;
103
204
 
104
205
  /** @throws TypeError if `amount` is not finite. */
@@ -107,12 +208,13 @@ export class RewardSystem extends EventEmitter {
107
208
 
108
209
  /**
109
210
  * Persists once for the whole call, not once per internal mutation.
110
- * @throws TypeError for an empty or reserved game name, or a `score` that
111
- * is not a finite number.
211
+ * @throws TypeError for an empty or reserved activity name, or a `score`
212
+ * that is not a finite number.
213
+ * @returns false when a `beforeRecord` hook rejected it.
112
214
  */
113
- recordGame(gameName: string, result?: GameResult): Promise<void>;
215
+ record(activity: string, result?: GameResult): Promise<boolean>;
114
216
 
115
- checkAchievements(gameName: string, result: GameResult): Promise<AchievementDefinition[]>;
217
+ checkAchievements(activity: string, result: GameResult): Promise<AchievementDefinition[]>;
116
218
  unlockAchievement(achievementId: string): Promise<boolean>;
117
219
  getUnlockedAchievements(): Array<AchievementDefinition & UnlockedAchievement & { id: string }>;
118
220
  getUnseenAchievements(): Array<AchievementDefinition & UnlockedAchievement & { id: string }>;
@@ -153,7 +255,13 @@ export class DataService {
153
255
  storage: StorageLike | AsyncStorageLike;
154
256
  prefix: string;
155
257
  save(key: string, data: unknown): Promise<boolean>;
156
- load<T = unknown>(key: string, defaultValue?: T | null): Promise<T | null>;
258
+ /**
259
+ * Resolves `defaultValue` when the read fails, unless `strict` is set:
260
+ * then a storage error rejects as is, and unparseable data rejects with
261
+ * `code: 'DOPAMINE_CORRUPT'` and the raw string on `raw`. `RewardSystem`
262
+ * relies on this, so an override must pass `options` on.
263
+ */
264
+ load<T = unknown>(key: string, defaultValue?: T | null, options?: { strict?: boolean }): Promise<T | null>;
157
265
  clear(key: string): Promise<void>;
158
266
  }
159
267
 
@@ -162,40 +270,136 @@ export function createMemoryStorage(): StorageLike;
162
270
  /** localStorage if present and writable, otherwise an in-memory store. */
163
271
  export function resolveStorage(): StorageLike;
164
272
 
273
+ export interface Haptics {
274
+ /** A 10 ms buzz. */
275
+ tap(): void;
276
+ /** Buzzes 10, 40, 10 ms. */
277
+ double(): void;
278
+ setEnabled(enabled: boolean): void;
279
+ }
280
+
281
+ /** Silent where the Vibration API is missing or blocked. */
282
+ export function createHaptics(options?: { nav?: { vibrate?: (pattern: number | number[]) => unknown }; enabled?: boolean }): Haptics;
283
+
284
+ /** The reduced-motion query, or `{ matches: false }` without matchMedia. */
285
+ export function prefersReducedMotion(win?: { matchMedia?: (query: string) => { matches: boolean } }): { matches: boolean };
286
+
165
287
  // ---------------------------------------------------------------------------
166
288
  // UI
167
289
  // ---------------------------------------------------------------------------
168
290
 
169
- export interface SummaryData {
170
- score: number | string;
171
- /** Label to value pairs. Rendered as text. */
172
- metrics?: Record<string, number | string>;
173
- /** Defaults to reloading the page. */
174
- onReplay?: () => void;
175
- /** Exit button is omitted when this is not supplied. */
176
- onExit?: () => void;
291
+ export interface RewardUIConfig {
292
+ /**
293
+ * A string icon (achievement or streak) is parsed as SVG and rebuilt from
294
+ * an allowlist of elements and attributes, and any other string is shown
295
+ * as text. The string must be well-formed XML, so `&nbsp;` falls back to
296
+ * text. An `<svg>` with no xmlns is accepted. Default true. False renders
297
+ * string icons as HTML, for icons you trust.
298
+ */
299
+ safeIcons?: boolean;
300
+ /** Replaces the built-in popup strings. Rendered as text. */
301
+ text?: {
302
+ /** Default `LEVEL UP!`. */
303
+ levelUp?: string;
304
+ /** Default `Achievement Unlocked!`. */
305
+ achievementUnlocked?: string;
306
+ };
307
+ icons?: {
308
+ /**
309
+ * A string follows `safeIcons`, a Node is moved into the badge, not
310
+ * copied. Default is a fire emoji.
311
+ */
312
+ streak?: string | Node;
313
+ };
314
+ /**
315
+ * Add the stylesheet from code, once per page, and remove it on destroy.
316
+ * A string is used as the CSS text. Default false: import
317
+ * `dopaminejs/style.css` instead.
318
+ */
319
+ injectCss?: boolean | string;
320
+ }
321
+
322
+ export interface HudState {
323
+ xp: number;
324
+ level: number;
325
+ /** Position within the current level, 0 to 1. */
326
+ progress?: number;
327
+ streak: number;
328
+ /** XP total that marks the next level. */
329
+ next?: number;
330
+ }
331
+
332
+ export type PopupKind = 'achievement' | 'level' | 'notice' | 'custom';
333
+
334
+ export interface Popup {
335
+ kind: PopupKind;
336
+ /** Achievement name, notice message, or the level-up heading. */
337
+ title?: string;
338
+ /** Achievement description, or the new level for `level`. */
339
+ body?: string;
340
+ /** A string follows `safeIcons`. A Node is appended. */
341
+ icon?: string | Node;
342
+ /** An extra line under an achievement, such as `+50 XP`. */
343
+ meta?: string;
344
+ tier?: 'common' | 'rare' | 'legendary';
345
+ }
346
+
347
+ export interface FloatingText {
348
+ text: string;
349
+ x?: number;
350
+ y?: number;
351
+ color?: string;
352
+ /** A CSS font size such as `32px`. */
353
+ size?: string;
354
+ }
355
+
356
+ export interface BurstOptions {
357
+ count?: number;
358
+ color?: string;
359
+ }
360
+
361
+ export type BurstKind = 'confetti' | 'sparkle' | 'fire' | 'stars' | 'coins';
362
+
363
+ export interface RewardUILike {
364
+ hud(state: HudState): void;
365
+ popup(popup: Popup): void;
366
+ text(text: FloatingText): void;
367
+ readonly root: HTMLElement | null;
368
+ destroy(): void;
369
+ }
370
+
371
+ export interface ParticleRenderer {
372
+ /** An unknown kind does nothing. */
373
+ burst(kind: BurstKind, at?: { x: number; y: number }, opts?: BurstOptions): void;
374
+ destroy(): void;
375
+ }
376
+
377
+ export interface SoundPlayer {
378
+ /** An unknown key does nothing. */
379
+ play(key: string): unknown;
380
+ /** Optional. Adds a key and returns a remover. `SoundManager` has it. */
381
+ register?(key: string, source: string | SoundSynth): () => void;
382
+ destroy(): void;
177
383
  }
178
384
 
179
- export class GameUI {
180
- constructor(particleSystem: ParticleSystem);
385
+ export interface Parts {
386
+ readonly ui: RewardUILike | null;
387
+ readonly particles: ParticleRenderer | null;
388
+ readonly sound: SoundPlayer | null;
389
+ readonly haptics: Haptics | null;
390
+ }
181
391
 
182
- container: HTMLElement | null;
392
+ export class RewardUI implements RewardUILike {
393
+ /** `parts.particles` is read on every call. */
394
+ constructor(parts?: Pick<Parts, 'particles'>, config?: RewardUIConfig);
183
395
 
184
- /** `progress` is the position within the current level, 0 to 1. */
185
- updateXP(current: number, needed: number, total: number, progress?: number): void;
186
- updateLevel(level: number): void;
187
- updateStreak(days: number): void;
396
+ readonly root: HTMLElement | null;
188
397
 
189
- showAchievement(achievement: AchievementDefinition): void;
190
- showLevelUp(oldLevel: number, newLevel: number): void;
191
- showFloatingText(text: string, x: number, y: number, color?: string, size?: string): void;
192
- showCombo(multiplier: number, x: number, y: number): void;
193
- showNearMiss(x: number, y: number): void;
194
- showLuckyMoment(multiplier: number, x: number, y: number): void;
195
- showNotification(message: string, type?: 'normal' | 'rare' | 'legendary'): void;
196
- showSummary(data: SummaryData): HTMLElement;
398
+ hud(state: HudState): void;
399
+ popup(popup: Popup): void;
400
+ text(text: FloatingText): void;
197
401
 
198
- /** Removes the overlay, any transient popups, and all pending timers. */
402
+ /** Removes the overlay, any transient popups, the injected styles and all pending timers. */
199
403
  destroy(): void;
200
404
  }
201
405
 
@@ -243,8 +447,10 @@ export class ParticleSystem {
243
447
 
244
448
  registerSprite(key: string, url: string): void;
245
449
  registerEffect(name: string, callback: (x: number, y: number, ...args: unknown[]) => void): void;
246
- play(name: string, x: number, y: number, ...args: unknown[]): void;
450
+ /** `play(name, { x, y })` or `play(name, x, y)`. */
451
+ play(name: string, x: number | { x: number; y: number }, y?: number, ...args: unknown[]): void;
247
452
  emit(config: ParticleConfig): void;
453
+ burst(kind: BurstKind, at?: { x: number; y: number }, opts?: BurstOptions): void;
248
454
 
249
455
  confetti(x: number, y: number, count?: number): void;
250
456
  coinShower(x: number, y: number, count?: number): void;
@@ -270,6 +476,9 @@ export interface SoundManagerConfig {
270
476
  customSounds?: Record<string, string>;
271
477
  }
272
478
 
479
+ /** A synth key. `later` is a timeout that destroy() cancels. */
480
+ export type SoundSynth = (sound: SoundManager, later: (fn: () => void, ms: number) => void) => void;
481
+
273
482
  export class SoundManager {
274
483
  constructor(config?: SoundManagerConfig);
275
484
 
@@ -279,22 +488,31 @@ export class SoundManager {
279
488
 
280
489
  /** Returns false when no Web Audio API is available, rather than throwing. */
281
490
  initAudio(): boolean;
491
+ /** Calls initAudio() on the first of `events` on `target`, then removes its listeners. Returns a remover. */
492
+ unlockOn(target: EventTarget, events?: string[]): () => void;
282
493
  setVolume(value: number): number;
283
494
  getVolume(): number;
284
495
  toggleMute(): boolean;
285
496
 
286
497
  registerSound(key: string, url: string): void;
498
+ /**
499
+ * Add a key. A string is a file URL. A function is a synth, called as
500
+ * `(sound, later)` when the key plays; `later` is a timeout that destroy()
501
+ * cancels. Returns a remover.
502
+ */
503
+ register(key: string, source: string | SoundSynth): () => void;
287
504
  /** Registers every key, then loads the files. Before the audio context exists they load when it is created. */
288
505
  preloadSounds(soundMap: Record<string, string>): Promise<void>;
289
506
  loadSound(key: string, url: string): Promise<void>;
507
+ /** Presets: `xp`, `level_up`, `achievement`, `personal_best`, `click`, `error`. An unknown key is ignored. */
290
508
  play(key: string): Promise<void>;
291
509
  playTone(frequency: number, duration: number, type?: OscillatorType, volume?: number): void;
292
510
 
293
- playJump(force?: boolean): void;
294
- playScore(force?: boolean): void;
295
- playGameOver(force?: boolean): void;
296
511
  playClick(force?: boolean): void;
297
- playSuccess(force?: boolean): void;
512
+ playXP(force?: boolean): void;
513
+ playLevelUp(force?: boolean): void;
514
+ playAchievement(force?: boolean): void;
515
+ playPersonalBest(force?: boolean): void;
298
516
  playError(force?: boolean): void;
299
517
 
300
518
  /** Cancels queued tones, closes the audio context, drops decoded buffers. */
@@ -302,346 +520,103 @@ export class SoundManager {
302
520
  }
303
521
 
304
522
  // ---------------------------------------------------------------------------
305
- // Kernel
523
+ // Host and plugins
306
524
  // ---------------------------------------------------------------------------
307
525
 
308
- export interface EventBusEvents {
309
- TICK: 'tick';
310
- FIXED_UPDATE: 'fixed_update';
311
- RENDER: 'render';
312
- COLLISION_ENTER: 'collision_enter';
313
- COLLISION_EXIT: 'collision_exit';
314
- XP_GAINED: 'xp_gained';
315
- LEVEL_UP: 'level_up';
316
- ACHIEVEMENT_UNLOCKED: 'achievement_unlocked';
317
- NEW_HIGH_SCORE: 'new_high_score';
318
- STREAK_UPDATED: 'streak_updated';
319
- SYSTEM_REGISTERED: 'system_registered';
320
- SYSTEM_UNREGISTERED: 'system_unregistered';
321
- PLUGIN_LOADED: 'plugin_loaded';
322
- PLUGIN_UNLOADED: 'plugin_unloaded';
323
- }
324
-
325
- export class EventBus {
326
- static readonly Events: EventBusEvents;
327
-
328
- /** Higher priority runs first. */
329
- on(event: string, callback: (data?: any) => void, priority?: number): this;
330
- once(event: string, callback: (data?: any) => void): this;
331
- /** Removes every registration of `callback` for `event`. */
332
- off(event: string, callback: (data?: any) => void): this;
333
- /** A throwing listener is logged and does not abort the remaining ones. */
334
- emit(event: string, data?: any): void;
335
- clear(event?: string): void;
336
- hasListeners(event: string): boolean;
337
- }
338
-
339
- export interface ISystemLike {
340
- init?(kernel: DopamineKernel): void;
341
- update?(dt: number): void;
342
- fixedUpdate?(dt: number): void;
343
- destroy?(): void;
344
- }
345
-
346
- export interface SystemRegisterOptions {
347
- /** Higher runs earlier. Default 0. */
348
- priority?: number;
349
- /** Names of systems that must update first. */
350
- dependencies?: string[];
351
- }
352
-
353
- export class SystemRegistry {
354
- constructor(kernel: DopamineKernel);
355
- register(name: string, system: ISystemLike, options?: SystemRegisterOptions): this;
356
- get<T = ISystemLike>(name: string): T | undefined;
357
- has(name: string): boolean;
358
- unregister(name: string): boolean;
359
- update(dt: number): void;
360
- fixedUpdate(dt: number): void;
361
- getSystemNames(): string[];
362
- clear(): void;
363
- }
526
+ /** The plugin API version this build accepts. */
527
+ export const HOST_API: 3;
364
528
 
365
- export interface Plugin {
366
- name: string;
367
- version?: string;
368
- init(kernel: DopamineKernel): void | Promise<void>;
369
- destroy?(): void;
370
- }
371
-
372
- export class PluginRegistry {
373
- constructor(kernel: DopamineKernel);
374
- use(plugin: Plugin): this;
375
- useAsync(plugin: Plugin): Promise<this>;
376
- /** Calls the plugin's `destroy()`, then unregisters the systems it registered during `init()`. */
377
- remove(name: string): boolean;
378
- get(name: string): Plugin | undefined;
379
- has(name: string): boolean;
380
- getPluginNames(): string[];
381
- getLoadOrder(): string[];
382
- clear(): void;
383
- }
384
-
385
- export interface KernelConfig {
386
- width?: number;
387
- height?: number;
388
- backgroundColor?: string;
389
- canvas?: HTMLCanvasElement;
390
- renderer?: Record<string, unknown>;
391
- /** Seconds per fixed update. Default 1/60. */
392
- fixedTimestep?: number;
393
- }
394
-
395
- export class DopamineKernel {
396
- constructor(config?: KernelConfig);
397
-
398
- config: KernelConfig;
399
- events: EventBus;
400
- systems: SystemRegistry;
401
- plugins: PluginRegistry;
402
- fixedTimestep: number;
403
-
404
- readonly physics: Physics;
405
- readonly input: Input;
406
- readonly loader: Loader;
407
- readonly renderer: Renderer;
408
- readonly ticker: Ticker;
409
-
410
- start(): void;
411
- stop(): void;
412
- destroy(): void;
413
- }
414
-
415
- // ---------------------------------------------------------------------------
416
- // Engine core
417
- // ---------------------------------------------------------------------------
418
-
419
- export class Vector2 {
420
- constructor(x?: number, y?: number);
421
- x: number;
422
- y: number;
423
- add(v: Vector2): Vector2;
424
- sub(v: Vector2): Vector2;
425
- scale(s: number): Vector2;
426
- distance(v: Vector2): number;
427
- normalize(): Vector2;
428
- clone(): Vector2;
429
- static distance(a: Vector2, b: Vector2): number;
430
- }
431
-
432
- export class Component {
433
- gameObject: GameObject | null;
434
- kernel: DopamineKernel | null;
435
- onAttach(): void;
436
- onDetach(): void;
437
- update(dt: number): void;
438
- render(ctx: CanvasRenderingContext2D): void;
439
- }
440
-
441
- export interface BoxBounds {
442
- left: number;
443
- right: number;
444
- top: number;
445
- bottom: number;
446
- }
447
-
448
- export interface CircleBounds {
449
- x: number;
450
- y: number;
451
- radius: number;
452
- }
453
-
454
- /** A box collider returns edges, a circle collider returns centre and radius. */
455
- export type Bounds = BoxBounds | CircleBounds;
456
-
457
- export class Collider extends Component {
458
- constructor(type?: 'box' | 'circle', width?: number, height?: number, radius?: number);
459
- type: 'box' | 'circle';
460
- width: number;
461
- height: number;
462
- radius: number;
463
- tag: string | null;
464
- getBounds(): Bounds;
465
- }
466
-
467
- export class Sprite extends Component {
468
- constructor(image: HTMLImageElement | HTMLCanvasElement);
469
- setFrame(x: number, y: number, w: number, h: number): void;
470
- setTexture(image: HTMLImageElement | HTMLCanvasElement): void;
471
- }
472
-
473
- export class Animator extends Component {
474
- addAnimation(name: string, frames: unknown[], fps?: number, loop?: boolean): void;
475
- play(name: string): void;
476
- }
477
-
478
- export class GameObject {
479
- constructor(x?: number, y?: number);
480
- x: number;
481
- y: number;
482
- rotation: number;
483
- scale: { x: number; y: number };
484
- components: Component[];
485
- children: GameObject[];
486
- parent: GameObject | null;
487
- kernel: DopamineKernel | null;
488
- tag?: string;
489
- addChild(child: GameObject): GameObject;
490
- addComponent<T extends Component>(component: T): T;
491
- getComponent<T extends Component>(type: new (...args: any[]) => T): T | undefined;
492
- update(dt: number): void;
493
- render(ctx: CanvasRenderingContext2D): void;
494
- }
495
-
496
- export class Scene {
497
- gameObjects: GameObject[];
498
- kernel: DopamineKernel | null;
499
- onEnter(): void;
500
- onExit(): void;
501
- add(gameObject: GameObject): GameObject;
502
- remove(gameObject: GameObject): void;
503
- update(dt: number): void;
504
- render(ctx: CanvasRenderingContext2D): void;
505
- }
506
-
507
- export class Renderer {
508
- constructor(options?: Record<string, unknown>);
509
- canvas: HTMLCanvasElement;
510
- ctx: CanvasRenderingContext2D;
511
- clear(): void;
512
- resize(width: number, height: number): void;
513
- }
514
-
515
- export class Ticker {
516
- add(callback: (dt: number) => void): void;
517
- remove(callback: (dt: number) => void): void;
518
- /** Cancels any pending frame first, so restarting cannot double-step. */
519
- start(): void;
520
- stop(): void;
521
- running: boolean;
522
- callbacks: Set<(dt: number) => void>;
523
- }
524
-
525
- export class Loader {
526
- init(kernel: DopamineKernel): void;
527
- destroy(): void;
528
- loadImage(key: string, url: string): Promise<HTMLImageElement>;
529
- get(key: string): HTMLImageElement | undefined;
530
- }
529
+ export type PartName = 'ui' | 'particles' | 'sound' | 'haptics';
531
530
 
532
- export class Input {
533
- init(kernel: DopamineKernel): void;
534
- destroy(): void;
535
- isKeyDown(key: string): boolean;
536
- isMouseButtonDown(button?: number): boolean;
537
- mouse: { x: number; y: number };
538
- }
531
+ /** A part is a value, a factory, or `false` for none. A factory returning null means the default. */
532
+ export type PartOption<T> = T | false | null | ((env: HostEnv) => T | null | undefined);
539
533
 
540
- /** Payload of `collision_enter` and `collision_exit` on the kernel event bus. */
541
- export interface CollisionEvent {
542
- a: Collider;
543
- b: Collider;
534
+ export interface HostEnv {
535
+ hasDom: boolean;
536
+ reducedMotion: boolean;
544
537
  }
545
538
 
546
- export class Physics {
547
- init(kernel: DopamineKernel): void;
548
- fixedUpdate(dt: number): void;
549
- destroy(): void;
550
- add(collider: Collider): void;
551
- /** Emits `collision_exit` for each pair the collider was overlapping in. */
552
- remove(collider: Collider): void;
553
- /**
554
- * Emits `collision_enter` once when a pair starts to overlap and
555
- * `collision_exit` once when it stops. `onCollisionEnter` on a component
556
- * runs on every step while the pair overlaps.
557
- */
558
- step(): void;
559
- /** Every collider that overlaps `source`. With a tag, only colliders carrying it. */
560
- checkOverlap(source: Collider, targetTag?: string): Collider[];
561
- addBody(body: Collider): void;
562
- removeBody(body: Collider): void;
563
- checkCollision(a: Collider, b: Collider): boolean;
564
- /** Not implemented. Always null. */
565
- raycast(origin: Vector2, direction: Vector2, distance: number): null;
566
- /** Not implemented. */
567
- setGravity(x: number, y: number): void;
568
- }
569
-
570
- export class Director {
571
- constructor(game: Game);
572
- run(scene: Scene): void;
573
- }
574
-
575
- export class Game {
576
- constructor(config?: KernelConfig);
577
- kernel: DopamineKernel;
578
- scene: Scene | null;
579
- start(): void;
580
- stop(): void;
581
- setScene(newScene: Scene): void;
582
- destroy(): void;
539
+ export interface PluginStorage {
540
+ getItem(key: string): string | null | Promise<string | null>;
541
+ setItem(key: string, value: string): void | Promise<void>;
542
+ removeItem(key: string): void | Promise<void>;
583
543
  }
584
544
 
585
- export class TextureGenerator {
586
- static createGround(width: number, height: number, color?: string): HTMLCanvasElement;
587
- static createCharacterSheet(colorBody: string, colorDetail: string): HTMLCanvasElement;
545
+ export interface Logger {
546
+ debug(...args: unknown[]): void;
547
+ info(...args: unknown[]): void;
548
+ warn(...args: unknown[]): void;
549
+ error(...args: unknown[]): void;
588
550
  }
589
551
 
590
- export class ParticleEmitter extends Component {
591
- constructor(particleSystem: ParticleSystem);
592
- play(effectName: string, options?: Record<string, unknown>): void;
552
+ /** The host bus as a plugin sees it. */
553
+ export interface PluginEvents {
554
+ /** Removed by the host when the plugin is disposed, even if the plugin forgets. */
555
+ on(event: string, callback: (data: any) => void): () => void;
556
+ off(event: string, callback: (data: any) => void): void;
557
+ /** The event name must start with `<plugin name>:`. */
558
+ emit(event: string, data?: unknown): void;
593
559
  }
594
560
 
595
- export class ScreenShake extends Component {
596
- shake(intensity?: number, duration?: number): void;
561
+ export interface PluginContext {
562
+ progress: RewardSystem;
563
+ /** Live getters. Read them at call time, never keep them. */
564
+ parts: Readonly<Parts>;
565
+ events: PluginEvents;
566
+ /** Keys are prefixed with `dopamine_plugin_<name>:`. */
567
+ storage: PluginStorage;
568
+ clock: Clock;
569
+ log: Logger;
570
+ env: HostEnv;
571
+ /** The handle another plugin passed to `expose`, or null. */
572
+ plugin(name: string): unknown | null;
573
+ expose(handle: unknown): void;
597
574
  }
598
575
 
599
- /** Deprecated singletons kept for v1 compatibility. Prefer kernel.<system>. */
600
- export const GlobalLoader: Loader;
601
- export const GlobalInput: Input;
602
- export const GlobalPhysics: Physics;
603
-
604
- // ---------------------------------------------------------------------------
605
- // Interfaces
606
- // ---------------------------------------------------------------------------
607
-
608
- export const ISystem: Record<string, unknown>;
609
- export const System: Record<string, unknown>;
610
- export const IPhysicsSystem: Record<string, unknown>;
611
- export const IAudioSystem: Record<string, unknown>;
612
- export const IParticleSystem: Record<string, unknown>;
613
-
614
- // ---------------------------------------------------------------------------
615
- // Facade
616
- // ---------------------------------------------------------------------------
617
-
618
- export interface DopamineConfig {
619
- data?: DataServiceConfig;
620
- rewards?: RewardSystemConfig;
621
- sound?: SoundManagerConfig;
622
- particles?: ParticleSystemConfig;
623
- }
576
+ export type Disposer = () => void;
624
577
 
625
- export interface DopamineSubsystems {
626
- rewardSystem: RewardSystem;
627
- gameUI: GameUI;
628
- particleSystem: ParticleSystem;
629
- soundManager: SoundManager;
578
+ export interface DopaminePlugin {
579
+ name: string;
580
+ version: string;
581
+ api: 3;
582
+ /** Plugins that must already be installed. */
583
+ after?: string[];
584
+ /** Parts that must be set. */
585
+ requires?: PartName[];
586
+ install(context: PluginContext): Disposer | void | Promise<Disposer | void>;
587
+ }
588
+
589
+ export interface DopamineOptions {
590
+ progress?: RewardSystem | ((env: HostEnv) => RewardSystem | null) | null;
591
+ ui?: PartOption<RewardUILike>;
592
+ particles?: PartOption<ParticleRenderer>;
593
+ sound?: PartOption<SoundPlayer>;
594
+ haptics?: PartOption<Haptics>;
595
+ storage?: StorageLike;
596
+ clock?: Clock;
597
+ /** Passed to the default progress object. See `RewardSystemConfig`. */
598
+ streakDays?: 'any' | 'record';
599
+ plugins?: DopaminePlugin[];
600
+ log?: Partial<Logger>;
601
+ }
602
+
603
+ export interface Dopamine {
604
+ progress: RewardSystem;
605
+ /** Getters only. */
606
+ parts: Readonly<Parts>;
607
+ /** The progress emitter. Plugin events are `name:event`. */
608
+ events: EventEmitter;
609
+ /** Resolves with the host once plugins are installed and progress is loaded. */
610
+ ready: Promise<Dopamine>;
611
+ /** Install a plugin later. Returns its disposer. */
612
+ use(plugin: DopaminePlugin): Disposer;
613
+ /** Disposes plugins in reverse, then the parts, then clears the bus. */
614
+ dispose(): void;
630
615
  }
631
616
 
632
617
  /**
633
- * Wires DataService, RewardSystem, SoundManager, ParticleSystem and GameUI
634
- * together and binds the UI to reward events.
618
+ * Builds the feedback layer from parts and installs plugins on it. A sync
619
+ * caller gets a usable host at once. Plugins that are refused throw here; an
620
+ * async install that fails rejects `ready`.
635
621
  */
636
- export default class Dopamine {
637
- constructor(config?: DopamineConfig);
638
- config: DopamineConfig;
639
- dataService: DataService;
640
- rewardSystem: RewardSystem;
641
- soundManager: SoundManager;
642
- particleSystem: ParticleSystem;
643
- gameUI: GameUI;
644
- init(): Promise<DopamineSubsystems>;
645
- /** Removes the overlay and canvas, closes audio, detaches from reward events. */
646
- destroy(): void;
647
- }
622
+ export function createDopamine(options?: DopamineOptions): Dopamine;