dopaminejs 2.5.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 (81) 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 -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-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 +24 -9
  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 +54 -24
  26. package/src/dopamine/core/DopamineError.js +7 -0
  27. package/src/dopamine/core/RewardSystem.js +323 -373
  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 +358 -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 +489 -0
  42. package/types/core.d.ts +9 -1
  43. package/types/games.d.ts +46 -0
  44. package/types/index.d.ts +291 -384
  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,17 +138,22 @@ 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
+ /** 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';
78
149
  }
79
150
 
80
151
  export type RewardEvent =
81
152
  | 'xp_gained'
82
153
  | 'level_up'
83
154
  | 'achievement_unlocked'
84
- | 'new_high_score'
155
+ /** Payload `{ activity, score }`. */
156
+ | 'personal_best'
85
157
  /** Payload `{ current, longest }`. Fires when the day rolls over. */
86
158
  | 'streak_updated'
87
159
  /** Payload `{ key }`. The storage write failed; state lives in memory only. */
@@ -107,10 +179,7 @@ export class EventEmitter {
107
179
  export class RewardSystem extends EventEmitter {
108
180
  constructor(dataService: DataService, config?: RewardSystemConfig);
109
181
 
110
- player: Player | null;
111
182
  achievements: Record<string, AchievementDefinition>;
112
- /** Kernel bus events are mirrored onto, if one was supplied. */
113
- events: EventBus | null;
114
183
  /**
115
184
  * True when the last `init()` could not read the saved player, so nothing
116
185
  * is saved until `init()` is called again and the read works.
@@ -118,6 +187,19 @@ export class RewardSystem extends EventEmitter {
118
187
  readonly loadFailed: boolean;
119
188
 
120
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;
121
203
  save(): Promise<void>;
122
204
 
123
205
  /** @throws TypeError if `amount` is not finite. */
@@ -126,12 +208,13 @@ export class RewardSystem extends EventEmitter {
126
208
 
127
209
  /**
128
210
  * 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.
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.
131
214
  */
132
- recordGame(gameName: string, result?: GameResult): Promise<void>;
215
+ record(activity: string, result?: GameResult): Promise<boolean>;
133
216
 
134
- checkAchievements(gameName: string, result: GameResult): Promise<AchievementDefinition[]>;
217
+ checkAchievements(activity: string, result: GameResult): Promise<AchievementDefinition[]>;
135
218
  unlockAchievement(achievementId: string): Promise<boolean>;
136
219
  getUnlockedAchievements(): Array<AchievementDefinition & UnlockedAchievement & { id: string }>;
137
220
  getUnseenAchievements(): Array<AchievementDefinition & UnlockedAchievement & { id: string }>;
@@ -205,23 +288,13 @@ export function prefersReducedMotion(win?: { matchMedia?: (query: string) => { m
205
288
  // UI
206
289
  // ---------------------------------------------------------------------------
207
290
 
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 {
291
+ export interface RewardUIConfig {
219
292
  /**
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.
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.
225
298
  */
226
299
  safeIcons?: boolean;
227
300
  /** Replaces the built-in popup strings. Rendered as text. */
@@ -230,38 +303,103 @@ export interface GameUIConfig {
230
303
  levelUp?: string;
231
304
  /** Default `Achievement Unlocked!`. */
232
305
  achievementUnlocked?: string;
233
- /** Default `CLOSE CALL!`. */
234
- nearMiss?: string;
235
306
  };
236
307
  icons?: {
237
308
  /**
238
- * A string is HTML (unless `safeIcons` is on), a Node is moved into
239
- * the badge, not copied. Default is a fire emoji.
309
+ * A string follows `safeIcons`, a Node is moved into the badge, not
310
+ * copied. Default is a fire emoji.
240
311
  */
241
312
  streak?: string | Node;
242
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;
243
320
  }
244
321
 
245
- export class GameUI {
246
- constructor(particleSystem: ParticleSystem, config?: GameUIConfig);
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
+ }
247
376
 
248
- container: HTMLElement | null;
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;
383
+ }
384
+
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
+ }
249
391
 
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;
392
+ export class RewardUI implements RewardUILike {
393
+ /** `parts.particles` is read on every call. */
394
+ constructor(parts?: Pick<Parts, 'particles'>, config?: RewardUIConfig);
254
395
 
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;
396
+ readonly root: HTMLElement | null;
263
397
 
264
- /** Removes the overlay, any transient popups, and all pending timers. */
398
+ hud(state: HudState): void;
399
+ popup(popup: Popup): void;
400
+ text(text: FloatingText): void;
401
+
402
+ /** Removes the overlay, any transient popups, the injected styles and all pending timers. */
265
403
  destroy(): void;
266
404
  }
267
405
 
@@ -309,8 +447,10 @@ export class ParticleSystem {
309
447
 
310
448
  registerSprite(key: string, url: string): void;
311
449
  registerEffect(name: string, callback: (x: number, y: number, ...args: unknown[]) => void): void;
312
- 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;
313
452
  emit(config: ParticleConfig): void;
453
+ burst(kind: BurstKind, at?: { x: number; y: number }, opts?: BurstOptions): void;
314
454
 
315
455
  confetti(x: number, y: number, count?: number): void;
316
456
  coinShower(x: number, y: number, count?: number): void;
@@ -336,6 +476,9 @@ export interface SoundManagerConfig {
336
476
  customSounds?: Record<string, string>;
337
477
  }
338
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
+
339
482
  export class SoundManager {
340
483
  constructor(config?: SoundManagerConfig);
341
484
 
@@ -352,17 +495,24 @@ export class SoundManager {
352
495
  toggleMute(): boolean;
353
496
 
354
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;
355
504
  /** Registers every key, then loads the files. Before the audio context exists they load when it is created. */
356
505
  preloadSounds(soundMap: Record<string, string>): Promise<void>;
357
506
  loadSound(key: string, url: string): Promise<void>;
507
+ /** Presets: `xp`, `level_up`, `achievement`, `personal_best`, `click`, `error`. An unknown key is ignored. */
358
508
  play(key: string): Promise<void>;
359
509
  playTone(frequency: number, duration: number, type?: OscillatorType, volume?: number): void;
360
510
 
361
- playJump(force?: boolean): void;
362
- playScore(force?: boolean): void;
363
- playGameOver(force?: boolean): void;
364
511
  playClick(force?: boolean): void;
365
- playSuccess(force?: boolean): void;
512
+ playXP(force?: boolean): void;
513
+ playLevelUp(force?: boolean): void;
514
+ playAchievement(force?: boolean): void;
515
+ playPersonalBest(force?: boolean): void;
366
516
  playError(force?: boolean): void;
367
517
 
368
518
  /** Cancels queued tones, closes the audio context, drops decoded buffers. */
@@ -370,346 +520,103 @@ export class SoundManager {
370
520
  }
371
521
 
372
522
  // ---------------------------------------------------------------------------
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
523
+ // Host and plugins
485
524
  // ---------------------------------------------------------------------------
486
525
 
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
- }
526
+ /** The plugin API version this build accepts. */
527
+ export const HOST_API: 3;
499
528
 
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
- }
529
+ export type PartName = 'ui' | 'particles' | 'sound' | 'haptics';
508
530
 
509
- export interface BoxBounds {
510
- left: number;
511
- right: number;
512
- top: number;
513
- bottom: number;
514
- }
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);
515
533
 
516
- export interface CircleBounds {
517
- x: number;
518
- y: number;
519
- radius: number;
520
- }
521
-
522
- /** A box collider returns edges, a circle collider returns centre and radius. */
523
- export type Bounds = BoxBounds | CircleBounds;
524
-
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;
534
+ export interface HostEnv {
535
+ hasDom: boolean;
536
+ reducedMotion: boolean;
533
537
  }
534
538
 
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;
539
- }
540
-
541
- export class Animator extends Component {
542
- addAnimation(name: string, frames: unknown[], fps?: number, loop?: boolean): void;
543
- play(name: string): void;
544
- }
545
-
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;
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>;
581
543
  }
582
544
 
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>;
545
+ export interface Logger {
546
+ debug(...args: unknown[]): void;
547
+ info(...args: unknown[]): void;
548
+ warn(...args: unknown[]): void;
549
+ error(...args: unknown[]): void;
591
550
  }
592
551
 
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;
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;
661
559
  }
662
560
 
663
- export class ScreenShake extends Component {
664
- 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;
665
574
  }
666
575
 
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>;
576
+ export type Disposer = () => void;
681
577
 
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;
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;
698
615
  }
699
616
 
700
617
  /**
701
- * Wires DataService, RewardSystem, SoundManager, ParticleSystem and GameUI
702
- * 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`.
703
621
  */
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
- }
622
+ export function createDopamine(options?: DopamineOptions): Dopamine;