dopaminejs 2.5.0 → 3.1.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 (81) hide show
  1. package/README.md +55 -50
  2. package/dist/DataService-D1uL6E8R.cjs +1 -0
  3. package/dist/DataService-DN6xwvXU.js +745 -0
  4. package/dist/core.cjs +1 -1
  5. package/dist/core.js +2 -2
  6. package/dist/dopamine.cjs +1 -37
  7. package/dist/dopamine.js +3 -635
  8. package/dist/games.cjs +1 -0
  9. package/dist/games.js +82 -0
  10. package/dist/host-7FzZ-yO7.cjs +37 -0
  11. package/dist/host-CdjhXPy-.js +815 -0
  12. package/dist/style.css +395 -2
  13. package/dist/testing.cjs +1 -0
  14. package/dist/testing.js +475 -0
  15. package/package.json +24 -9
  16. package/spec/README.md +228 -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 +957 -0
  22. package/spec/fixtures/scores.json +755 -0
  23. package/spec/fixtures/streaks.json +967 -0
  24. package/spec/schema.json +61 -0
  25. package/src/dopamine/audio/SoundManager.js +54 -24
  26. package/src/dopamine/core/DopamineError.js +7 -0
  27. package/src/dopamine/core/RewardSystem.js +359 -374
  28. package/src/dopamine/core/achievements.js +49 -0
  29. package/src/dopamine/core/clock.js +11 -0
  30. package/src/dopamine/core/levels.js +4 -0
  31. package/src/dopamine/core/merge.js +68 -0
  32. package/src/dopamine/core/middleware.js +58 -0
  33. package/src/dopamine/core/store.js +261 -0
  34. package/src/dopamine/core/streaks.js +55 -0
  35. package/src/dopamine/effects/ParticleSystem.js +30 -0
  36. package/src/dopamine/host.js +360 -0
  37. package/src/dopamine/ui/{GameUI.js → RewardUI.js} +166 -202
  38. package/src/games.js +138 -0
  39. package/src/index.js +11 -34
  40. package/src/progression.js +3 -0
  41. package/src/testing.js +490 -0
  42. package/types/core.d.ts +9 -1
  43. package/types/games.d.ts +46 -0
  44. package/types/index.d.ts +311 -385
  45. package/types/testing.d.ts +96 -0
  46. package/dist/DataService-BPXCldpo.cjs +0 -1
  47. package/dist/DataService-CH9_gv_8.js +0 -398
  48. package/dist/ScreenShake-9jgNXPS6.cjs +0 -1
  49. package/dist/ScreenShake-CLvO1wx4.js +0 -827
  50. package/dist/engine.cjs +0 -1
  51. package/dist/engine.js +0 -2
  52. package/src/core/Animator.js +0 -62
  53. package/src/core/Collider.js +0 -86
  54. package/src/core/Component.js +0 -38
  55. package/src/core/DopamineKernel.js +0 -170
  56. package/src/core/EventBus.js +0 -206
  57. package/src/core/Game.js +0 -90
  58. package/src/core/GameObject.js +0 -99
  59. package/src/core/PluginRegistry.js +0 -359
  60. package/src/core/Scene.js +0 -107
  61. package/src/core/Sprite.js +0 -51
  62. package/src/core/SystemRegistry.js +0 -263
  63. package/src/core/Vector2.js +0 -50
  64. package/src/dopamine/components/ParticleEmitter.js +0 -50
  65. package/src/dopamine/components/ScreenShake.js +0 -50
  66. package/src/dopamine/components/index.js +0 -2
  67. package/src/dopamine/index.js +0 -93
  68. package/src/dopamine/utils/TextureGenerator.js +0 -90
  69. package/src/engine.js +0 -38
  70. package/src/interfaces/IAudioSystem.js +0 -58
  71. package/src/interfaces/IParticleSystem.js +0 -51
  72. package/src/interfaces/IPhysicsSystem.js +0 -52
  73. package/src/interfaces/ISystem.js +0 -48
  74. package/src/interfaces/index.js +0 -7
  75. package/src/renderer/Renderer.js +0 -45
  76. package/src/systems/Director.js +0 -34
  77. package/src/systems/Input.js +0 -81
  78. package/src/systems/Loader.js +0 -48
  79. package/src/systems/Physics.js +0 -210
  80. package/src/systems/Ticker.js +0 -91
  81. 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,22 +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
108
  /**
42
- * A string is rendered as HTML (an <img> or inline SVG is allowed), or as
43
- * allowlisted SVG or text when GameUI is built with `safeIcons: true`. A
44
- * Node is moved into the popup, not copied.
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.
45
112
  */
46
113
  icon?: string | Node;
47
114
  /** Omitted means 0. Never undefined at runtime. */
48
115
  xp?: number;
49
- check(player: Player, gameName?: string, result?: GameResult): boolean;
116
+ check(player: Player, activity?: string, result?: GameResult): boolean;
50
117
  }
51
118
 
52
119
  export interface GameResult {
@@ -71,19 +138,32 @@ export interface AddXPResult {
71
138
 
72
139
  export interface RewardSystemConfig {
73
140
  achievements?: Record<string, AchievementDefinition>;
74
- /** Mirror reward events onto a kernel EventBus. */
75
- events?: EventBus;
76
- /** Alternative to `events`; the kernel's bus is used. */
77
- kernel?: DopamineKernel;
141
+ /**
142
+ * `false` defines none of the built-in achievements (`first_game`,
143
+ * `level_5`, `level_10`, `streak_3`, `streak_7`). Default `true`. A save
144
+ * that already holds one keeps it and its XP. Any other value means `true`.
145
+ */
146
+ builtinAchievements?: boolean;
147
+ /** Time source. Tests pass one; the default reads the system clock. */
148
+ clock?: Clock;
149
+ /**
150
+ * What marks today as a play day. `'any'` (default): `record()` or
151
+ * `addXP()`. `'record'`: `record()` only. XP from an achievement reward
152
+ * never marks a day.
153
+ */
154
+ streakDays?: 'any' | 'record';
78
155
  }
79
156
 
80
157
  export type RewardEvent =
81
158
  | 'xp_gained'
82
159
  | 'level_up'
83
160
  | 'achievement_unlocked'
84
- | 'new_high_score'
161
+ /** Payload `{ activity, score }`. */
162
+ | 'personal_best'
85
163
  /** Payload `{ current, longest }`. Fires when the day rolls over. */
86
164
  | 'streak_updated'
165
+ /** Payload `{}`. `reset()` replaced the player and saved it. */
166
+ | 'player_reset'
87
167
  /** Payload `{ key }`. The storage write failed; state lives in memory only. */
88
168
  | 'save_failed'
89
169
  /**
@@ -107,17 +187,36 @@ export class EventEmitter {
107
187
  export class RewardSystem extends EventEmitter {
108
188
  constructor(dataService: DataService, config?: RewardSystemConfig);
109
189
 
110
- player: Player | null;
111
190
  achievements: Record<string, AchievementDefinition>;
112
- /** Kernel bus events are mirrored onto, if one was supplied. */
113
- events: EventBus | null;
114
191
  /**
115
192
  * True when the last `init()` could not read the saved player, so nothing
116
- * is saved until `init()` is called again and the read works.
193
+ * is saved until `init()` is called again and the read works, or `reset()` is called.
117
194
  */
118
195
  readonly loadFailed: boolean;
119
196
 
120
197
  init(): Promise<Player>;
198
+ /** A frozen copy of the player with the derived values. */
199
+ snapshot(): Player;
200
+ /** The versioned document, a detached copy. */
201
+ export(): PlayerDocument;
202
+ /**
203
+ * Merge a document into this player. Unless `silent`, announces the XP,
204
+ * level and achievements that went up.
205
+ */
206
+ import(doc: unknown, options?: { silent?: boolean }): Promise<Player>;
207
+ /**
208
+ * Replaces the player with a new one and saves it. The device id is kept.
209
+ * Emits `player_reset` after the save. Writes even after a failed load,
210
+ * without a backup of the save it replaces, and then `loadFailed` is false.
211
+ * Call it after `init()` has resolved, not while `init()` is pending. A
212
+ * `record()` already in flight when it runs lands in the new player. Called
213
+ * from inside a hook, the write happens when the outer record or unlock finishes.
214
+ */
215
+ reset(): Promise<Player>;
216
+ /** Hooks run in `use` order. Returns a function that removes it. */
217
+ use(middleware: Middleware): () => void;
218
+ /** Adds a rule at runtime. Returns a function that removes it. */
219
+ defineAchievement(id: string, definition: AchievementDefinition): () => void;
121
220
  save(): Promise<void>;
122
221
 
123
222
  /** @throws TypeError if `amount` is not finite. */
@@ -126,12 +225,13 @@ export class RewardSystem extends EventEmitter {
126
225
 
127
226
  /**
128
227
  * Persists once for the whole call, not once per internal mutation.
129
- * @throws TypeError for an empty or reserved game name, or a `score` that
130
- * is not a finite number.
228
+ * @throws TypeError for an empty or reserved activity name, or a `score`
229
+ * that is not a finite number.
230
+ * @returns false when a `beforeRecord` hook rejected it.
131
231
  */
132
- recordGame(gameName: string, result?: GameResult): Promise<void>;
232
+ record(activity: string, result?: GameResult): Promise<boolean>;
133
233
 
134
- checkAchievements(gameName: string, result: GameResult): Promise<AchievementDefinition[]>;
234
+ checkAchievements(activity: string, result: GameResult): Promise<AchievementDefinition[]>;
135
235
  unlockAchievement(achievementId: string): Promise<boolean>;
136
236
  getUnlockedAchievements(): Array<AchievementDefinition & UnlockedAchievement & { id: string }>;
137
237
  getUnseenAchievements(): Array<AchievementDefinition & UnlockedAchievement & { id: string }>;
@@ -205,23 +305,13 @@ export function prefersReducedMotion(win?: { matchMedia?: (query: string) => { m
205
305
  // UI
206
306
  // ---------------------------------------------------------------------------
207
307
 
208
- export interface SummaryData {
209
- score: number | string;
210
- /** Label to value pairs. Rendered as text. */
211
- metrics?: Record<string, number | string>;
212
- /** Defaults to reloading the page. */
213
- onReplay?: () => void;
214
- /** Exit button is omitted when this is not supplied. */
215
- onExit?: () => void;
216
- }
217
-
218
- export interface GameUIConfig {
308
+ export interface RewardUIConfig {
219
309
  /**
220
- * When true, a string icon (achievement or streak) is parsed as SVG and
221
- * rebuilt from an allowlist of elements and attributes, and any other
222
- * string is shown as text. The string must be well-formed XML, so
223
- * `&nbsp;` falls back to text. An `<svg>` with no xmlns is accepted.
224
- * Default false: string icons are HTML.
310
+ * A string icon (achievement or streak) is parsed as SVG and rebuilt from
311
+ * an allowlist of elements and attributes, and any other string is shown
312
+ * as text. The string must be well-formed XML, so `&nbsp;` falls back to
313
+ * text. An `<svg>` with no xmlns is accepted. Default true. False renders
314
+ * string icons as HTML, for icons you trust.
225
315
  */
226
316
  safeIcons?: boolean;
227
317
  /** Replaces the built-in popup strings. Rendered as text. */
@@ -230,38 +320,103 @@ export interface GameUIConfig {
230
320
  levelUp?: string;
231
321
  /** Default `Achievement Unlocked!`. */
232
322
  achievementUnlocked?: string;
233
- /** Default `CLOSE CALL!`. */
234
- nearMiss?: string;
235
323
  };
236
324
  icons?: {
237
325
  /**
238
- * A string is HTML (unless `safeIcons` is on), a Node is moved into
239
- * the badge, not copied. Default is a fire emoji.
326
+ * A string follows `safeIcons`, a Node is moved into the badge, not
327
+ * copied. Default is a fire emoji.
240
328
  */
241
329
  streak?: string | Node;
242
330
  };
331
+ /**
332
+ * Add the stylesheet from code, once per page, and remove it on destroy.
333
+ * A string is used as the CSS text. Default false: import
334
+ * `dopaminejs/style.css` instead.
335
+ */
336
+ injectCss?: boolean | string;
337
+ }
338
+
339
+ export interface HudState {
340
+ xp: number;
341
+ level: number;
342
+ /** Position within the current level, 0 to 1. */
343
+ progress?: number;
344
+ streak: number;
345
+ /** XP total that marks the next level. */
346
+ next?: number;
347
+ }
348
+
349
+ export type PopupKind = 'achievement' | 'level' | 'notice' | 'custom';
350
+
351
+ export interface Popup {
352
+ kind: PopupKind;
353
+ /** Achievement name, notice message, or the level-up heading. */
354
+ title?: string;
355
+ /** Achievement description, or the new level for `level`. */
356
+ body?: string;
357
+ /** A string follows `safeIcons`. A Node is appended. */
358
+ icon?: string | Node;
359
+ /** An extra line under an achievement, such as `+50 XP`. */
360
+ meta?: string;
361
+ tier?: 'common' | 'rare' | 'legendary';
362
+ }
363
+
364
+ export interface FloatingText {
365
+ text: string;
366
+ x?: number;
367
+ y?: number;
368
+ color?: string;
369
+ /** A CSS font size such as `32px`. */
370
+ size?: string;
243
371
  }
244
372
 
245
- export class GameUI {
246
- constructor(particleSystem: ParticleSystem, config?: GameUIConfig);
373
+ export interface BurstOptions {
374
+ count?: number;
375
+ color?: string;
376
+ }
247
377
 
248
- container: HTMLElement | null;
378
+ export type BurstKind = 'confetti' | 'sparkle' | 'fire' | 'stars' | 'coins';
249
379
 
250
- /** `progress` is the position within the current level, 0 to 1. */
251
- updateXP(current: number, needed: number, total: number, progress?: number): void;
252
- updateLevel(level: number): void;
253
- updateStreak(days: number): void;
380
+ export interface RewardUILike {
381
+ hud(state: HudState): void;
382
+ popup(popup: Popup): void;
383
+ text(text: FloatingText): void;
384
+ readonly root: HTMLElement | null;
385
+ destroy(): void;
386
+ }
254
387
 
255
- showAchievement(achievement: AchievementDefinition): void;
256
- showLevelUp(oldLevel: number, newLevel: number): void;
257
- showFloatingText(text: string, x: number, y: number, color?: string, size?: string): void;
258
- showCombo(multiplier: number, x: number, y: number): void;
259
- showNearMiss(x: number, y: number): void;
260
- showLuckyMoment(multiplier: number, x: number, y: number): void;
261
- showNotification(message: string, type?: 'normal' | 'rare' | 'legendary'): void;
262
- showSummary(data: SummaryData): HTMLElement;
388
+ export interface ParticleRenderer {
389
+ /** An unknown kind does nothing. */
390
+ burst(kind: BurstKind, at?: { x: number; y: number }, opts?: BurstOptions): void;
391
+ destroy(): void;
392
+ }
263
393
 
264
- /** Removes the overlay, any transient popups, and all pending timers. */
394
+ export interface SoundPlayer {
395
+ /** An unknown key does nothing. */
396
+ play(key: string): unknown;
397
+ /** Optional. Adds a key and returns a remover. `SoundManager` has it. */
398
+ register?(key: string, source: string | SoundSynth): () => void;
399
+ destroy(): void;
400
+ }
401
+
402
+ export interface Parts {
403
+ readonly ui: RewardUILike | null;
404
+ readonly particles: ParticleRenderer | null;
405
+ readonly sound: SoundPlayer | null;
406
+ readonly haptics: Haptics | null;
407
+ }
408
+
409
+ export class RewardUI implements RewardUILike {
410
+ /** `parts.particles` is read on every call. */
411
+ constructor(parts?: Pick<Parts, 'particles'>, config?: RewardUIConfig);
412
+
413
+ readonly root: HTMLElement | null;
414
+
415
+ hud(state: HudState): void;
416
+ popup(popup: Popup): void;
417
+ text(text: FloatingText): void;
418
+
419
+ /** Removes the overlay, any transient popups, the injected styles and all pending timers. */
265
420
  destroy(): void;
266
421
  }
267
422
 
@@ -309,8 +464,10 @@ export class ParticleSystem {
309
464
 
310
465
  registerSprite(key: string, url: string): void;
311
466
  registerEffect(name: string, callback: (x: number, y: number, ...args: unknown[]) => void): void;
312
- play(name: string, x: number, y: number, ...args: unknown[]): void;
467
+ /** `play(name, { x, y })` or `play(name, x, y)`. */
468
+ play(name: string, x: number | { x: number; y: number }, y?: number, ...args: unknown[]): void;
313
469
  emit(config: ParticleConfig): void;
470
+ burst(kind: BurstKind, at?: { x: number; y: number }, opts?: BurstOptions): void;
314
471
 
315
472
  confetti(x: number, y: number, count?: number): void;
316
473
  coinShower(x: number, y: number, count?: number): void;
@@ -336,6 +493,9 @@ export interface SoundManagerConfig {
336
493
  customSounds?: Record<string, string>;
337
494
  }
338
495
 
496
+ /** A synth key. `later` is a timeout that destroy() cancels. */
497
+ export type SoundSynth = (sound: SoundManager, later: (fn: () => void, ms: number) => void) => void;
498
+
339
499
  export class SoundManager {
340
500
  constructor(config?: SoundManagerConfig);
341
501
 
@@ -352,17 +512,24 @@ export class SoundManager {
352
512
  toggleMute(): boolean;
353
513
 
354
514
  registerSound(key: string, url: string): void;
515
+ /**
516
+ * Add a key. A string is a file URL. A function is a synth, called as
517
+ * `(sound, later)` when the key plays; `later` is a timeout that destroy()
518
+ * cancels. Returns a remover.
519
+ */
520
+ register(key: string, source: string | SoundSynth): () => void;
355
521
  /** Registers every key, then loads the files. Before the audio context exists they load when it is created. */
356
522
  preloadSounds(soundMap: Record<string, string>): Promise<void>;
357
523
  loadSound(key: string, url: string): Promise<void>;
524
+ /** Presets: `xp`, `level_up`, `achievement`, `personal_best`, `click`, `error`. An unknown key is ignored. */
358
525
  play(key: string): Promise<void>;
359
526
  playTone(frequency: number, duration: number, type?: OscillatorType, volume?: number): void;
360
527
 
361
- playJump(force?: boolean): void;
362
- playScore(force?: boolean): void;
363
- playGameOver(force?: boolean): void;
364
528
  playClick(force?: boolean): void;
365
- playSuccess(force?: boolean): void;
529
+ playXP(force?: boolean): void;
530
+ playLevelUp(force?: boolean): void;
531
+ playAchievement(force?: boolean): void;
532
+ playPersonalBest(force?: boolean): void;
366
533
  playError(force?: boolean): void;
367
534
 
368
535
  /** Cancels queued tones, closes the audio context, drops decoded buffers. */
@@ -370,346 +537,105 @@ export class SoundManager {
370
537
  }
371
538
 
372
539
  // ---------------------------------------------------------------------------
373
- // Kernel
374
- // ---------------------------------------------------------------------------
375
-
376
- export interface EventBusEvents {
377
- TICK: 'tick';
378
- FIXED_UPDATE: 'fixed_update';
379
- RENDER: 'render';
380
- COLLISION_ENTER: 'collision_enter';
381
- COLLISION_EXIT: 'collision_exit';
382
- XP_GAINED: 'xp_gained';
383
- LEVEL_UP: 'level_up';
384
- ACHIEVEMENT_UNLOCKED: 'achievement_unlocked';
385
- NEW_HIGH_SCORE: 'new_high_score';
386
- STREAK_UPDATED: 'streak_updated';
387
- SYSTEM_REGISTERED: 'system_registered';
388
- SYSTEM_UNREGISTERED: 'system_unregistered';
389
- PLUGIN_LOADED: 'plugin_loaded';
390
- PLUGIN_UNLOADED: 'plugin_unloaded';
391
- }
392
-
393
- export class EventBus {
394
- static readonly Events: EventBusEvents;
395
-
396
- /** Higher priority runs first. */
397
- on(event: string, callback: (data?: any) => void, priority?: number): this;
398
- once(event: string, callback: (data?: any) => void): this;
399
- /** Removes every registration of `callback` for `event`. */
400
- off(event: string, callback: (data?: any) => void): this;
401
- /** A throwing listener is logged and does not abort the remaining ones. */
402
- emit(event: string, data?: any): void;
403
- clear(event?: string): void;
404
- hasListeners(event: string): boolean;
405
- }
406
-
407
- export interface ISystemLike {
408
- init?(kernel: DopamineKernel): void;
409
- update?(dt: number): void;
410
- fixedUpdate?(dt: number): void;
411
- destroy?(): void;
412
- }
413
-
414
- export interface SystemRegisterOptions {
415
- /** Higher runs earlier. Default 0. */
416
- priority?: number;
417
- /** Names of systems that must update first. */
418
- dependencies?: string[];
419
- }
420
-
421
- export class SystemRegistry {
422
- constructor(kernel: DopamineKernel);
423
- register(name: string, system: ISystemLike, options?: SystemRegisterOptions): this;
424
- get<T = ISystemLike>(name: string): T | undefined;
425
- has(name: string): boolean;
426
- unregister(name: string): boolean;
427
- update(dt: number): void;
428
- fixedUpdate(dt: number): void;
429
- getSystemNames(): string[];
430
- clear(): void;
431
- }
432
-
433
- export interface Plugin {
434
- name: string;
435
- version?: string;
436
- init(kernel: DopamineKernel): void | Promise<void>;
437
- destroy?(): void;
438
- }
439
-
440
- export class PluginRegistry {
441
- constructor(kernel: DopamineKernel);
442
- use(plugin: Plugin): this;
443
- useAsync(plugin: Plugin): Promise<this>;
444
- /** Calls the plugin's `destroy()`, then unregisters the systems it registered during `init()`. */
445
- remove(name: string): boolean;
446
- get(name: string): Plugin | undefined;
447
- has(name: string): boolean;
448
- getPluginNames(): string[];
449
- getLoadOrder(): string[];
450
- clear(): void;
451
- }
452
-
453
- export interface KernelConfig {
454
- width?: number;
455
- height?: number;
456
- backgroundColor?: string;
457
- canvas?: HTMLCanvasElement;
458
- renderer?: Record<string, unknown>;
459
- /** Seconds per fixed update. Default 1/60. */
460
- fixedTimestep?: number;
461
- }
462
-
463
- export class DopamineKernel {
464
- constructor(config?: KernelConfig);
465
-
466
- config: KernelConfig;
467
- events: EventBus;
468
- systems: SystemRegistry;
469
- plugins: PluginRegistry;
470
- fixedTimestep: number;
471
-
472
- readonly physics: Physics;
473
- readonly input: Input;
474
- readonly loader: Loader;
475
- readonly renderer: Renderer;
476
- readonly ticker: Ticker;
477
-
478
- start(): void;
479
- stop(): void;
480
- destroy(): void;
481
- }
482
-
483
- // ---------------------------------------------------------------------------
484
- // Engine core
540
+ // Host and plugins
485
541
  // ---------------------------------------------------------------------------
486
542
 
487
- export class Vector2 {
488
- constructor(x?: number, y?: number);
489
- x: number;
490
- y: number;
491
- add(v: Vector2): Vector2;
492
- sub(v: Vector2): Vector2;
493
- scale(s: number): Vector2;
494
- distance(v: Vector2): number;
495
- normalize(): Vector2;
496
- clone(): Vector2;
497
- static distance(a: Vector2, b: Vector2): number;
498
- }
499
-
500
- export class Component {
501
- gameObject: GameObject | null;
502
- kernel: DopamineKernel | null;
503
- onAttach(): void;
504
- onDetach(): void;
505
- update(dt: number): void;
506
- render(ctx: CanvasRenderingContext2D): void;
507
- }
508
-
509
- export interface BoxBounds {
510
- left: number;
511
- right: number;
512
- top: number;
513
- bottom: number;
514
- }
515
-
516
- export interface CircleBounds {
517
- x: number;
518
- y: number;
519
- radius: number;
520
- }
543
+ /** The plugin API version this build accepts. */
544
+ export const HOST_API: 3;
521
545
 
522
- /** A box collider returns edges, a circle collider returns centre and radius. */
523
- export type Bounds = BoxBounds | CircleBounds;
546
+ export type PartName = 'ui' | 'particles' | 'sound' | 'haptics';
524
547
 
525
- export class Collider extends Component {
526
- constructor(type?: 'box' | 'circle', width?: number, height?: number, radius?: number);
527
- type: 'box' | 'circle';
528
- width: number;
529
- height: number;
530
- radius: number;
531
- tag: string | null;
532
- getBounds(): Bounds;
533
- }
548
+ /** A part is a value, a factory, or `false` for none. A factory returning null means the default. */
549
+ export type PartOption<T> = T | false | null | ((env: HostEnv) => T | null | undefined);
534
550
 
535
- export class Sprite extends Component {
536
- constructor(image: HTMLImageElement | HTMLCanvasElement);
537
- setFrame(x: number, y: number, w: number, h: number): void;
538
- setTexture(image: HTMLImageElement | HTMLCanvasElement): void;
551
+ export interface HostEnv {
552
+ hasDom: boolean;
553
+ reducedMotion: boolean;
539
554
  }
540
555
 
541
- export class Animator extends Component {
542
- addAnimation(name: string, frames: unknown[], fps?: number, loop?: boolean): void;
543
- play(name: string): void;
556
+ export interface PluginStorage {
557
+ getItem(key: string): string | null | Promise<string | null>;
558
+ setItem(key: string, value: string): void | Promise<void>;
559
+ removeItem(key: string): void | Promise<void>;
544
560
  }
545
561
 
546
- export class GameObject {
547
- constructor(x?: number, y?: number);
548
- x: number;
549
- y: number;
550
- rotation: number;
551
- scale: { x: number; y: number };
552
- components: Component[];
553
- children: GameObject[];
554
- parent: GameObject | null;
555
- kernel: DopamineKernel | null;
556
- tag?: string;
557
- addChild(child: GameObject): GameObject;
558
- addComponent<T extends Component>(component: T): T;
559
- getComponent<T extends Component>(type: new (...args: any[]) => T): T | undefined;
560
- update(dt: number): void;
561
- render(ctx: CanvasRenderingContext2D): void;
562
- }
563
-
564
- export class Scene {
565
- gameObjects: GameObject[];
566
- kernel: DopamineKernel | null;
567
- onEnter(): void;
568
- onExit(): void;
569
- add(gameObject: GameObject): GameObject;
570
- remove(gameObject: GameObject): void;
571
- update(dt: number): void;
572
- render(ctx: CanvasRenderingContext2D): void;
573
- }
574
-
575
- export class Renderer {
576
- constructor(options?: Record<string, unknown>);
577
- canvas: HTMLCanvasElement;
578
- ctx: CanvasRenderingContext2D;
579
- clear(): void;
580
- resize(width: number, height: number): void;
562
+ export interface Logger {
563
+ debug(...args: unknown[]): void;
564
+ info(...args: unknown[]): void;
565
+ warn(...args: unknown[]): void;
566
+ error(...args: unknown[]): void;
581
567
  }
582
568
 
583
- export class Ticker {
584
- add(callback: (dt: number) => void): void;
585
- remove(callback: (dt: number) => void): void;
586
- /** Cancels any pending frame first, so restarting cannot double-step. */
587
- start(): void;
588
- stop(): void;
589
- running: boolean;
590
- callbacks: Set<(dt: number) => void>;
591
- }
592
-
593
- export class Loader {
594
- init(kernel: DopamineKernel): void;
595
- destroy(): void;
596
- loadImage(key: string, url: string): Promise<HTMLImageElement>;
597
- get(key: string): HTMLImageElement | undefined;
598
- }
599
-
600
- export class Input {
601
- init(kernel: DopamineKernel): void;
602
- destroy(): void;
603
- isKeyDown(key: string): boolean;
604
- isMouseButtonDown(button?: number): boolean;
605
- mouse: { x: number; y: number };
606
- }
607
-
608
- /** Payload of `collision_enter` and `collision_exit` on the kernel event bus. */
609
- export interface CollisionEvent {
610
- a: Collider;
611
- b: Collider;
612
- }
613
-
614
- export class Physics {
615
- init(kernel: DopamineKernel): void;
616
- fixedUpdate(dt: number): void;
617
- destroy(): void;
618
- add(collider: Collider): void;
619
- /** Emits `collision_exit` for each pair the collider was overlapping in. */
620
- remove(collider: Collider): void;
621
- /**
622
- * Emits `collision_enter` once when a pair starts to overlap and
623
- * `collision_exit` once when it stops. `onCollisionEnter` on a component
624
- * runs on every step while the pair overlaps.
625
- */
626
- step(): void;
627
- /** Every collider that overlaps `source`. With a tag, only colliders carrying it. */
628
- checkOverlap(source: Collider, targetTag?: string): Collider[];
629
- addBody(body: Collider): void;
630
- removeBody(body: Collider): void;
631
- checkCollision(a: Collider, b: Collider): boolean;
632
- /** Not implemented. Always null. */
633
- raycast(origin: Vector2, direction: Vector2, distance: number): null;
634
- /** Not implemented. */
635
- setGravity(x: number, y: number): void;
636
- }
637
-
638
- export class Director {
639
- constructor(game: Game);
640
- run(scene: Scene): void;
641
- }
642
-
643
- export class Game {
644
- constructor(config?: KernelConfig);
645
- kernel: DopamineKernel;
646
- scene: Scene | null;
647
- start(): void;
648
- stop(): void;
649
- setScene(newScene: Scene): void;
650
- destroy(): void;
651
- }
652
-
653
- export class TextureGenerator {
654
- static createGround(width: number, height: number, color?: string): HTMLCanvasElement;
655
- static createCharacterSheet(colorBody: string, colorDetail: string): HTMLCanvasElement;
656
- }
657
-
658
- export class ParticleEmitter extends Component {
659
- constructor(particleSystem: ParticleSystem);
660
- play(effectName: string, options?: Record<string, unknown>): void;
569
+ /** The host bus as a plugin sees it. */
570
+ export interface PluginEvents {
571
+ /** Removed by the host when the plugin is disposed, even if the plugin forgets. */
572
+ on(event: string, callback: (data: any) => void): () => void;
573
+ off(event: string, callback: (data: any) => void): void;
574
+ /** The event name must start with `<plugin name>:`. */
575
+ emit(event: string, data?: unknown): void;
661
576
  }
662
577
 
663
- export class ScreenShake extends Component {
664
- shake(intensity?: number, duration?: number): void;
578
+ export interface PluginContext {
579
+ progress: RewardSystem;
580
+ /** Live getters. Read them at call time, never keep them. */
581
+ parts: Readonly<Parts>;
582
+ events: PluginEvents;
583
+ /** Keys are prefixed with `dopamine_plugin_<name>:`. */
584
+ storage: PluginStorage;
585
+ clock: Clock;
586
+ log: Logger;
587
+ env: HostEnv;
588
+ /** The handle another plugin passed to `expose`, or null. */
589
+ plugin(name: string): unknown | null;
590
+ expose(handle: unknown): void;
665
591
  }
666
592
 
667
- /** Deprecated singletons kept for v1 compatibility. Prefer kernel.<system>. */
668
- export const GlobalLoader: Loader;
669
- export const GlobalInput: Input;
670
- export const GlobalPhysics: Physics;
671
-
672
- // ---------------------------------------------------------------------------
673
- // Interfaces
674
- // ---------------------------------------------------------------------------
675
-
676
- export const ISystem: Record<string, unknown>;
677
- export const System: Record<string, unknown>;
678
- export const IPhysicsSystem: Record<string, unknown>;
679
- export const IAudioSystem: Record<string, unknown>;
680
- export const IParticleSystem: Record<string, unknown>;
593
+ export type Disposer = () => void;
681
594
 
682
- // ---------------------------------------------------------------------------
683
- // Facade
684
- // ---------------------------------------------------------------------------
685
-
686
- export interface DopamineConfig {
687
- data?: DataServiceConfig;
688
- rewards?: RewardSystemConfig;
689
- sound?: SoundManagerConfig;
690
- particles?: ParticleSystemConfig;
691
- }
692
-
693
- export interface DopamineSubsystems {
694
- rewardSystem: RewardSystem;
695
- gameUI: GameUI;
696
- particleSystem: ParticleSystem;
697
- soundManager: SoundManager;
595
+ export interface DopaminePlugin {
596
+ name: string;
597
+ version: string;
598
+ api: 3;
599
+ /** Plugins that must already be installed. */
600
+ after?: string[];
601
+ /** Parts that must be set. */
602
+ requires?: PartName[];
603
+ install(context: PluginContext): Disposer | void | Promise<Disposer | void>;
604
+ }
605
+
606
+ export interface DopamineOptions {
607
+ progress?: RewardSystem | ((env: HostEnv) => RewardSystem | null) | null;
608
+ ui?: PartOption<RewardUILike>;
609
+ particles?: PartOption<ParticleRenderer>;
610
+ sound?: PartOption<SoundPlayer>;
611
+ haptics?: PartOption<Haptics>;
612
+ storage?: StorageLike;
613
+ clock?: Clock;
614
+ /** Passed to the default progress object. See `RewardSystemConfig`. */
615
+ streakDays?: 'any' | 'record';
616
+ /** Passed to the default progress object. See `RewardSystemConfig`. */
617
+ builtinAchievements?: boolean;
618
+ plugins?: DopaminePlugin[];
619
+ log?: Partial<Logger>;
620
+ }
621
+
622
+ export interface Dopamine {
623
+ progress: RewardSystem;
624
+ /** Getters only. */
625
+ parts: Readonly<Parts>;
626
+ /** The progress emitter. Plugin events are `name:event`. */
627
+ events: EventEmitter;
628
+ /** Resolves with the host once plugins are installed and progress is loaded. */
629
+ ready: Promise<Dopamine>;
630
+ /** Install a plugin later. Returns its disposer. */
631
+ use(plugin: DopaminePlugin): Disposer;
632
+ /** Disposes plugins in reverse, then the parts, then clears the bus. */
633
+ dispose(): void;
698
634
  }
699
635
 
700
636
  /**
701
- * Wires DataService, RewardSystem, SoundManager, ParticleSystem and GameUI
702
- * together and binds the UI to reward events.
637
+ * Builds the feedback layer from parts and installs plugins on it. A sync
638
+ * caller gets a usable host at once. Plugins that are refused throw here; an
639
+ * async install that fails rejects `ready`.
703
640
  */
704
- export default class Dopamine {
705
- constructor(config?: DopamineConfig);
706
- config: DopamineConfig;
707
- dataService: DataService;
708
- rewardSystem: RewardSystem;
709
- soundManager: SoundManager;
710
- particleSystem: ParticleSystem;
711
- gameUI: GameUI;
712
- init(): Promise<DopamineSubsystems>;
713
- /** Removes the overlay and canvas, closes audio, detaches from reward events. */
714
- destroy(): void;
715
- }
641
+ export function createDopamine(options?: DopamineOptions): Dopamine;