dopaminejs 2.3.1 → 2.4.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.
package/dist/dopamine.js CHANGED
@@ -1,1404 +1,858 @@
1
- import { Animator as j, Collider as X, Component as J, Director as V, DopamineKernel as W, EventBus as K, Game as Y, GameObject as Q, GlobalInput as Z, GlobalLoader as tt, GlobalPhysics as et, Input as st, Loader as it, ParticleEmitter as at, Physics as nt, PluginRegistry as rt, Renderer as ot, Scene as lt, ScreenShake as ct, Sprite as ht, SystemRegistry as dt, Ticker as ut, Vector2 as pt } from "./engine.js";
2
- class T {
3
- constructor() {
4
- this.listeners = /* @__PURE__ */ new Map();
5
- }
6
- /**
7
- * Subscribe to an event
8
- * @param {string} event - Event name
9
- * @param {Function} callback - Callback function
10
- * @returns {Function} Unsubscribe function
11
- */
12
- on(t, e) {
13
- return this.listeners.has(t) || this.listeners.set(t, /* @__PURE__ */ new Set()), this.listeners.get(t).add(e), () => this.off(t, e);
14
- }
15
- /**
16
- * Unsubscribe from an event
17
- * @param {string} event - Event name
18
- * @param {Function} callback - Callback function
19
- */
20
- off(t, e) {
21
- this.listeners.has(t) && this.listeners.get(t).delete(e);
22
- }
23
- /**
24
- * Emit an event
25
- * @param {string} event - Event name
26
- * @param {*} data - Event data
27
- */
28
- emit(t, e) {
29
- this.listeners.has(t) && this.listeners.get(t).forEach((s) => {
30
- try {
31
- s(e);
32
- } catch (i) {
33
- console.error(`Error in listener for event '${t}':`, i);
34
- }
35
- });
36
- }
37
- /**
38
- * Clear all listeners
39
- */
40
- clear() {
41
- this.listeners.clear();
42
- }
43
- }
44
- const E = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), y = (r) => typeof r == "string" && r.length > 0 && !E.has(r), f = (r, t) => Object.prototype.hasOwnProperty.call(r, t), m = (r) => r !== null && typeof r == "object" && !Array.isArray(r), v = (r, t, e = 0) => {
45
- const s = Number(r);
46
- return Number.isInteger(s) && s >= e ? s : t;
1
+ import { C as e, S as t, _ as n, a as r, b as i, c as a, d as o, f as s, g as c, h as l, i as u, l as d, m as f, n as p, o as m, p as h, r as g, s as _, t as v, u as y, v as b, x, y as S } from "./ScreenShake-CLvO1wx4.js";
2
+ //#region src/dopamine/core/EventEmitter.js
3
+ var C = class {
4
+ constructor() {
5
+ this.listeners = /* @__PURE__ */ new Map();
6
+ }
7
+ on(e, t) {
8
+ return this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set()), this.listeners.get(e).add(t), () => this.off(e, t);
9
+ }
10
+ off(e, t) {
11
+ this.listeners.has(e) && this.listeners.get(e).delete(t);
12
+ }
13
+ emit(e, t) {
14
+ this.listeners.has(e) && this.listeners.get(e).forEach((n) => {
15
+ try {
16
+ n(t);
17
+ } catch (t) {
18
+ console.error(`Error in listener for event '${e}':`, t);
19
+ }
20
+ });
21
+ }
22
+ clear() {
23
+ this.listeners.clear();
24
+ }
25
+ }, w = /* @__PURE__ */ new Set([
26
+ "__proto__",
27
+ "constructor",
28
+ "prototype"
29
+ ]), T = (e) => typeof e == "string" && e.length > 0 && !w.has(e), E = (e, t) => Object.prototype.hasOwnProperty.call(e, t), D = (e) => typeof e == "object" && !!e && !Array.isArray(e), O = (e, t, n = 0) => {
30
+ let r = Number(e);
31
+ return Number.isInteger(r) && r >= n ? r : t;
32
+ }, k = class extends C {
33
+ constructor(e, t = {}) {
34
+ super(), this.dataService = e, this.player = null, this.achievements = {
35
+ ...this._initAchievements(),
36
+ ...t.achievements || {}
37
+ }, this.events = t.events || t.kernel?.events || null, this._batchDepth = 0, this._pendingSave = !1;
38
+ }
39
+ _publish(e, t) {
40
+ this.emit(e, t), this.events && this.events.emit(e, t);
41
+ }
42
+ async _batch(e) {
43
+ this._batchDepth++;
44
+ try {
45
+ return await e();
46
+ } finally {
47
+ this._batchDepth--, this._batchDepth === 0 && this._pendingSave && (this._pendingSave = !1, await this._write());
48
+ }
49
+ }
50
+ async init() {
51
+ let e = await this.dataService.load("player", null);
52
+ this.player = this._migrate(e);
53
+ let t = this._updateDailyStreak();
54
+ return await this.save(), t && this._publishStreak(), this.player;
55
+ }
56
+ _requirePlayer() {
57
+ if (!this.player) throw Error("[DopamineJS] RewardSystem.init() must be awaited before use");
58
+ }
59
+ _publishStreak() {
60
+ let { current: e, longest: t } = this.player.streak;
61
+ this._publish("streak_updated", {
62
+ current: e,
63
+ longest: t
64
+ });
65
+ }
66
+ _getDefaultPlayer() {
67
+ return {
68
+ name: "Player",
69
+ xp: 0,
70
+ level: 1,
71
+ totalGamesPlayed: 0,
72
+ createdAt: Date.now(),
73
+ lastPlayedAt: Date.now(),
74
+ streak: {
75
+ current: 1,
76
+ longest: 1,
77
+ lastPlayDate: this._getTodayDateString()
78
+ },
79
+ achievements: {},
80
+ stats: {}
81
+ };
82
+ }
83
+ _migrate(e) {
84
+ let t = this._getDefaultPlayer();
85
+ if (!D(e)) return t;
86
+ let n = Number(e.xp), r = Number.isFinite(n) && n >= 0 ? n : 0, i = this._calculateLevel(r), a = D(e.streak) ? e.streak : {}, o = O(a.current, 1, 1), s = typeof a.lastPlayDate == "string" && /^\d{4}-\d{2}-\d{2}$/.test(a.lastPlayDate) ? a.lastPlayDate : t.streak.lastPlayDate;
87
+ return {
88
+ ...t,
89
+ ...e,
90
+ name: typeof e.name == "string" ? e.name : t.name,
91
+ xp: r,
92
+ level: Math.max(i, O(e.level, i, 1)),
93
+ totalGamesPlayed: O(e.totalGamesPlayed, 0),
94
+ createdAt: Number.isFinite(e.createdAt) ? e.createdAt : t.createdAt,
95
+ lastPlayedAt: Number.isFinite(e.lastPlayedAt) ? e.lastPlayedAt : t.lastPlayedAt,
96
+ streak: {
97
+ current: o,
98
+ longest: Math.max(o, O(a.longest, o, 1)),
99
+ lastPlayDate: s
100
+ },
101
+ achievements: this._migrateAchievements(e.achievements),
102
+ stats: this._migrateStats(e.stats)
103
+ };
104
+ }
105
+ _migrateAchievements(e) {
106
+ let t = {};
107
+ if (!D(e)) return t;
108
+ for (let n of Object.keys(e)) {
109
+ let r = e[n];
110
+ T(n) && D(r) && (t[n] = {
111
+ unlockedAt: Number.isFinite(r.unlockedAt) ? r.unlockedAt : Date.now(),
112
+ seen: r.seen === !0
113
+ });
114
+ }
115
+ return t;
116
+ }
117
+ _migrateStats(e) {
118
+ let t = {};
119
+ if (!D(e)) return t;
120
+ for (let n of Object.keys(e)) {
121
+ let r = e[n];
122
+ if (!T(n) || !D(r)) continue;
123
+ let i = {};
124
+ for (let e of Object.keys(r)) T(e) && Number.isFinite(r[e]) && (i[e] = r[e]);
125
+ i.totalPlays = O(r.totalPlays, 0), i.highScore = Number.isFinite(r.highScore) ? r.highScore : 0, t[n] = i;
126
+ }
127
+ return t;
128
+ }
129
+ async save() {
130
+ if (this.player) {
131
+ if (this._batchDepth > 0) {
132
+ this._pendingSave = !0;
133
+ return;
134
+ }
135
+ await this._write();
136
+ }
137
+ }
138
+ async _write() {
139
+ this.player.lastPlayedAt = Date.now(), await this.dataService.save("player", this.player) === !1 && this._publish("save_failed", { key: "player" });
140
+ }
141
+ async addXP(e, t = "") {
142
+ if (!Number.isFinite(e)) throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);
143
+ this._requirePlayer();
144
+ let n = this.player.level;
145
+ e = Math.max(e, -this.player.xp), this.player.xp += e;
146
+ let r = Math.max(n, this._calculateLevel(this.player.xp)), i = r > n;
147
+ i && (this.player.level = r), await this.save();
148
+ let a = this.player.xp;
149
+ return this._publish("xp_gained", {
150
+ amount: e,
151
+ reason: t,
152
+ leveledUp: i,
153
+ newLevel: r,
154
+ total: a
155
+ }), i && this._publish("level_up", {
156
+ oldLevel: n,
157
+ newLevel: r,
158
+ totalXP: a
159
+ }), {
160
+ leveledUp: i,
161
+ newLevel: r,
162
+ xpGained: e
163
+ };
164
+ }
165
+ _calculateLevel(e) {
166
+ if (!(e > 0)) return 1;
167
+ let t = Math.floor((1 + Math.sqrt(1 + 4 * e / 50)) / 2);
168
+ return Math.max(1, t);
169
+ }
170
+ getXPForNextLevel() {
171
+ this._requirePlayer();
172
+ let e = this.player.level + 1, t = 50 * e * (e - 1), n = 50 * this.player.level * (this.player.level - 1), r = t - n, i = r > 0 ? Math.max(0, Math.min(1, (this.player.xp - n) / r)) : 0;
173
+ return {
174
+ total: t,
175
+ needed: Math.max(0, t - this.player.xp),
176
+ progress: i
177
+ };
178
+ }
179
+ async recordGame(e, t = {}) {
180
+ if (this._requirePlayer(), !T(e)) throw TypeError(`[DopamineJS] recordGame expects a game name, received ${String(e)}`);
181
+ if (!D(t)) throw TypeError("[DopamineJS] recordGame expects a result object");
182
+ if (t.score !== void 0 && !Number.isFinite(t.score)) throw TypeError(`[DopamineJS] recordGame expects a finite score, received ${String(t.score)}`);
183
+ return this._batch(() => this._recordGame(e, t));
184
+ }
185
+ async _recordGame(e, t) {
186
+ this._updateDailyStreak() && this._publishStreak(), E(this.player.stats, e) || (this.player.stats[e] = {
187
+ totalPlays: 0,
188
+ highScore: 0
189
+ });
190
+ let n = this.player.stats[e];
191
+ n.totalPlays++, this.player.totalGamesPlayed++, t.score !== void 0 && t.score > n.highScore && (n.highScore = t.score, this._publish("new_high_score", {
192
+ gameName: e,
193
+ score: t.score
194
+ })), Object.keys(t).forEach((e) => {
195
+ if (e !== "score" && T(e)) {
196
+ let r = E(n, e) && Number.isFinite(n[e]) ? n[e] : 0;
197
+ n[e] = r + (Number.isFinite(t[e]) ? t[e] : 0);
198
+ }
199
+ });
200
+ let r = 10;
201
+ t.score && (r += Math.max(0, Math.floor(t.score / 5))), r = Math.floor(r * this.getStreakMultiplier()), await this.addXP(r, `Played ${e}`), await this.checkAchievements(e, t), await this.save();
202
+ }
203
+ async checkAchievements(e, t) {
204
+ let n = [];
205
+ for (let [r, i] of Object.entries(this.achievements)) {
206
+ if (E(this.player.achievements, r)) continue;
207
+ let a = !1;
208
+ try {
209
+ a = i.check(this.player, e, t);
210
+ } catch (e) {
211
+ console.error(`[DopamineJS] Achievement "${r}" check threw:`, e);
212
+ continue;
213
+ }
214
+ a && await this.unlockAchievement(r) && n.push(i);
215
+ }
216
+ return n;
217
+ }
218
+ async unlockAchievement(e) {
219
+ if (this._requirePlayer(), !T(e) || !E(this.achievements, e) || E(this.player.achievements, e)) return !1;
220
+ let t = this.achievements[e];
221
+ return t ? (this.player.achievements[e] = {
222
+ unlockedAt: Date.now(),
223
+ seen: !1
224
+ }, await this.addXP(Number.isFinite(t.xp) ? t.xp : 0, `Achievement: ${t.name}`), this._publish("achievement_unlocked", {
225
+ ...t,
226
+ id: e
227
+ }), await this.save(), !0) : !1;
228
+ }
229
+ getUnlockedAchievements() {
230
+ return Object.entries(this.player.achievements).map(([e, t]) => ({
231
+ ...this.achievements[e],
232
+ id: e,
233
+ ...t
234
+ }));
235
+ }
236
+ getUnseenAchievements() {
237
+ return this.getUnlockedAchievements().filter((e) => !e.seen);
238
+ }
239
+ async markAchievementsSeen(e) {
240
+ for (let t of e) E(this.player.achievements, t) && (this.player.achievements[t].seen = !0);
241
+ await this.save();
242
+ }
243
+ _updateDailyStreak() {
244
+ let e = this._getTodayDateString(), t = this.player.streak.lastPlayDate;
245
+ return t !== e && (t === this._getYesterdayDateString() ? (this.player.streak.current++, this.player.streak.current > this.player.streak.longest && (this.player.streak.longest = this.player.streak.current)) : this.player.streak.current = 1, this.player.streak.lastPlayDate = e, !0);
246
+ }
247
+ getStreakMultiplier() {
248
+ let e = this.player.streak.current;
249
+ return e >= 7 ? 2 : e >= 5 ? 1.5 : e >= 3 ? 1.25 : 1;
250
+ }
251
+ _toLocalDateString(e) {
252
+ return `${e.getFullYear()}-${String(e.getMonth() + 1).padStart(2, "0")}-${String(e.getDate()).padStart(2, "0")}`;
253
+ }
254
+ _getTodayDateString() {
255
+ return this._toLocalDateString(/* @__PURE__ */ new Date());
256
+ }
257
+ _getYesterdayDateString() {
258
+ let e = /* @__PURE__ */ new Date();
259
+ return e.setDate(e.getDate() - 1), this._toLocalDateString(e);
260
+ }
261
+ _initAchievements() {
262
+ return {
263
+ first_game: {
264
+ name: "First Steps",
265
+ description: "Play your first game",
266
+ icon: "🎮",
267
+ xp: 50,
268
+ check: (e) => e.totalGamesPlayed >= 1
269
+ },
270
+ level_5: {
271
+ name: "Rising Star",
272
+ description: "Reach level 5",
273
+ icon: "⭐",
274
+ xp: 100,
275
+ check: (e) => e.level >= 5
276
+ },
277
+ level_10: {
278
+ name: "Expert Player",
279
+ description: "Reach level 10",
280
+ icon: "🏆",
281
+ xp: 250,
282
+ check: (e) => e.level >= 10
283
+ },
284
+ streak_3: {
285
+ name: "Dedicated",
286
+ description: "Play 3 days in a row",
287
+ icon: "🔥",
288
+ xp: 100,
289
+ check: (e) => e.streak.current >= 3
290
+ },
291
+ streak_7: {
292
+ name: "Unstoppable",
293
+ description: "Play 7 days in a row",
294
+ icon: "💥",
295
+ xp: 300,
296
+ check: (e) => e.streak.current >= 7
297
+ }
298
+ };
299
+ }
47
300
  };
48
- class D extends T {
49
- /**
50
- * @param {Object} dataService - Persistence, see DataService
51
- * @param {Object} [config]
52
- * @param {Object} [config.achievements] - Extra achievement definitions
53
- * @param {Object} [config.events] - Kernel EventBus to mirror events onto
54
- * @param {Object} [config.kernel] - Kernel; its `events` bus is used if present
55
- */
56
- constructor(t, e = {}) {
57
- super(), this.dataService = t, this.player = null, this.achievements = { ...this._initAchievements(), ...e.achievements || {} }, this.events = e.events || e.kernel?.events || null, this._batchDepth = 0, this._pendingSave = !1;
58
- }
59
- /**
60
- * Emit locally, and mirror onto the kernel bus when one is attached.
61
- * @private
62
- */
63
- _publish(t, e) {
64
- this.emit(t, e), this.events && this.events.emit(t, e);
65
- }
66
- /**
67
- * Run `fn` with saves collapsed into a single write at the end.
68
- *
69
- * Nested batches are counted, so an inner operation that batches on its
70
- * own still results in exactly one write for the outermost call.
71
- *
72
- * @param {Function} fn
73
- * @private
74
- */
75
- async _batch(t) {
76
- this._batchDepth++;
77
- try {
78
- return await t();
79
- } finally {
80
- this._batchDepth--, this._batchDepth === 0 && this._pendingSave && (this._pendingSave = !1, await this._write());
81
- }
82
- }
83
- /**
84
- * Initialize the reward system for current player
85
- * @returns {Promise<Object>} Player data
86
- */
87
- async init() {
88
- const t = await this.dataService.load("player", null);
89
- this.player = this._migrate(t);
90
- const e = this._updateDailyStreak();
91
- return await this.save(), e && this._publishStreak(), this.player;
92
- }
93
- /**
94
- * @private
95
- */
96
- _requirePlayer() {
97
- if (!this.player)
98
- throw new Error("[DopamineJS] RewardSystem.init() must be awaited before use");
99
- }
100
- /**
101
- * @private
102
- */
103
- _publishStreak() {
104
- const { current: t, longest: e } = this.player.streak;
105
- this._publish("streak_updated", { current: t, longest: e });
106
- }
107
- /**
108
- * Get default player data structure
109
- */
110
- _getDefaultPlayer() {
111
- return {
112
- name: "Player",
113
- xp: 0,
114
- level: 1,
115
- totalGamesPlayed: 0,
116
- createdAt: Date.now(),
117
- lastPlayedAt: Date.now(),
118
- streak: {
119
- current: 1,
120
- longest: 1,
121
- lastPlayDate: this._getTodayDateString()
122
- },
123
- achievements: {},
124
- // achievement_id: { unlockedAt: timestamp, seen: boolean }
125
- stats: {
126
- // Dynamic stats object, games will add their own keys
127
- }
128
- };
129
- }
130
- /**
131
- * Merge a persisted player record onto the current default shape.
132
- *
133
- * Saves written by older versions are missing whatever fields were added
134
- * since. Without this the first property access on a new field throws
135
- * before the game has drawn a frame.
136
- *
137
- * @param {Object|null} saved - Previously persisted player, if any
138
- * @returns {Object} Player object guaranteed to have every field
139
- * @private
140
- */
141
- _migrate(t) {
142
- const e = this._getDefaultPlayer();
143
- if (!m(t))
144
- return e;
145
- const s = Number(t.xp), i = Number.isFinite(s) && s >= 0 ? s : 0, n = this._calculateLevel(i), a = m(t.streak) ? t.streak : {}, o = v(a.current, 1, 1), l = typeof a.lastPlayDate == "string" && /^\d{4}-\d{2}-\d{2}$/.test(a.lastPlayDate) ? a.lastPlayDate : e.streak.lastPlayDate;
146
- return {
147
- ...e,
148
- ...t,
149
- name: typeof t.name == "string" ? t.name : e.name,
150
- xp: i,
151
- // A level above the curve is kept: older versions banked levels
152
- // at half the XP and those players keep what they earned.
153
- level: Math.max(n, v(t.level, n, 1)),
154
- totalGamesPlayed: v(t.totalGamesPlayed, 0),
155
- createdAt: Number.isFinite(t.createdAt) ? t.createdAt : e.createdAt,
156
- lastPlayedAt: Number.isFinite(t.lastPlayedAt) ? t.lastPlayedAt : e.lastPlayedAt,
157
- streak: {
158
- current: o,
159
- longest: Math.max(o, v(a.longest, o, 1)),
160
- lastPlayDate: l
161
- },
162
- achievements: this._migrateAchievements(t.achievements),
163
- stats: this._migrateStats(t.stats)
164
- };
165
- }
166
- /**
167
- * @private
168
- */
169
- _migrateAchievements(t) {
170
- const e = {};
171
- if (!m(t)) return e;
172
- for (const s of Object.keys(t)) {
173
- const i = t[s];
174
- !y(s) || !m(i) || (e[s] = {
175
- unlockedAt: Number.isFinite(i.unlockedAt) ? i.unlockedAt : Date.now(),
176
- seen: i.seen === !0
177
- });
178
- }
179
- return e;
180
- }
181
- /**
182
- * @private
183
- */
184
- _migrateStats(t) {
185
- const e = {};
186
- if (!m(t)) return e;
187
- for (const s of Object.keys(t)) {
188
- const i = t[s];
189
- if (!y(s) || !m(i)) continue;
190
- const n = {};
191
- for (const a of Object.keys(i))
192
- y(a) && Number.isFinite(i[a]) && (n[a] = i[a]);
193
- n.totalPlays = v(i.totalPlays, 0), n.highScore = Number.isFinite(i.highScore) ? i.highScore : 0, e[s] = n;
194
- }
195
- return e;
196
- }
197
- /**
198
- * Save player data
199
- */
200
- async save() {
201
- if (this.player) {
202
- if (this._batchDepth > 0) {
203
- this._pendingSave = !0;
204
- return;
205
- }
206
- await this._write();
207
- }
208
- }
209
- /**
210
- * The actual persistence call. Bypasses batching.
211
- * @private
212
- */
213
- async _write() {
214
- this.player.lastPlayedAt = Date.now(), await this.dataService.save("player", this.player) === !1 && this._publish("save_failed", { key: "player" });
215
- }
216
- /**
217
- * Add XP and handle level ups
218
- * @param {number} amount - XP to add
219
- * @param {string} reason - Why XP was awarded (for notifications)
220
- * @returns {Object} { leveledUp: boolean, newLevel: number, xpGained: number }
221
- */
222
- async addXP(t, e = "") {
223
- if (!Number.isFinite(t))
224
- throw new TypeError(`[DopamineJS] addXP expects a finite number, received ${t}`);
225
- this._requirePlayer();
226
- const s = this.player.level;
227
- t = Math.max(t, -this.player.xp), this.player.xp += t;
228
- const i = Math.max(s, this._calculateLevel(this.player.xp)), n = i > s;
229
- n && (this.player.level = i), await this.save();
230
- const a = this.player.xp;
231
- return this._publish("xp_gained", { amount: t, reason: e, leveledUp: n, newLevel: i, total: a }), n && this._publish("level_up", { oldLevel: s, newLevel: i, totalXP: a }), { leveledUp: n, newLevel: i, xpGained: t };
232
- }
233
- /**
234
- * Calculate level from XP (exponential curve)
235
- */
236
- _calculateLevel(t) {
237
- if (!(t > 0)) return 1;
238
- const e = Math.floor((1 + Math.sqrt(1 + 4 * t / 50)) / 2);
239
- return Math.max(1, e);
240
- }
241
- /**
242
- * Get XP needed for next level
243
- */
244
- getXPForNextLevel() {
245
- this._requirePlayer();
246
- const t = this.player.level + 1, e = 50 * t * (t - 1), s = 50 * this.player.level * (this.player.level - 1), i = e - s, n = i > 0 ? Math.max(0, Math.min(1, (this.player.xp - s) / i)) : 0;
247
- return {
248
- total: e,
249
- needed: Math.max(0, e - this.player.xp),
250
- progress: n
251
- };
252
- }
253
- /**
254
- * Record game result and award XP
255
- * @param {string} gameName - Unique ID for the game
256
- * @param {Object} result - Game-specific result data
257
- */
258
- async recordGame(t, e = {}) {
259
- if (this._requirePlayer(), !y(t))
260
- throw new TypeError(`[DopamineJS] recordGame expects a game name, received ${String(t)}`);
261
- if (!m(e))
262
- throw new TypeError("[DopamineJS] recordGame expects a result object");
263
- if (e.score !== void 0 && !Number.isFinite(e.score))
264
- throw new TypeError(`[DopamineJS] recordGame expects a finite score, received ${String(e.score)}`);
265
- return this._batch(() => this._recordGame(t, e));
266
- }
267
- /**
268
- * @private
269
- */
270
- async _recordGame(t, e) {
271
- this._updateDailyStreak() && this._publishStreak(), f(this.player.stats, t) || (this.player.stats[t] = { totalPlays: 0, highScore: 0 });
272
- const s = this.player.stats[t];
273
- s.totalPlays++, this.player.totalGamesPlayed++, e.score !== void 0 && e.score > s.highScore && (s.highScore = e.score, this._publish("new_high_score", { gameName: t, score: e.score })), Object.keys(e).forEach((n) => {
274
- if (n !== "score" && y(n)) {
275
- const a = f(s, n) && Number.isFinite(s[n]) ? s[n] : 0;
276
- s[n] = a + (Number.isFinite(e[n]) ? e[n] : 0);
277
- }
278
- });
279
- let i = 10;
280
- e.score && (i += Math.max(0, Math.floor(e.score / 5))), i = Math.floor(i * this.getStreakMultiplier()), await this.addXP(i, `Played ${t}`), await this.checkAchievements(t, e), await this.save();
281
- }
282
- /**
283
- * Check and unlock achievements
284
- */
285
- async checkAchievements(t, e) {
286
- const s = [];
287
- for (const [i, n] of Object.entries(this.achievements)) {
288
- if (f(this.player.achievements, i)) continue;
289
- let a = !1;
290
- try {
291
- a = n.check(this.player, t, e);
292
- } catch (o) {
293
- console.error(`[DopamineJS] Achievement "${i}" check threw:`, o);
294
- continue;
295
- }
296
- a && await this.unlockAchievement(i) && s.push(n);
297
- }
298
- return s;
299
- }
300
- /**
301
- * Unlock an achievement
302
- */
303
- async unlockAchievement(t) {
304
- if (this._requirePlayer(), !y(t) || !f(this.achievements, t) || f(this.player.achievements, t)) return !1;
305
- const e = this.achievements[t];
306
- return e ? (this.player.achievements[t] = {
307
- unlockedAt: Date.now(),
308
- seen: !1
309
- }, await this.addXP(
310
- Number.isFinite(e.xp) ? e.xp : 0,
311
- `Achievement: ${e.name}`
312
- ), this._publish("achievement_unlocked", { ...e, id: t }), await this.save(), !0) : !1;
313
- }
314
- /**
315
- * Get all unlocked achievements
316
- */
317
- getUnlockedAchievements() {
318
- return Object.entries(this.player.achievements).map(([t, e]) => ({
319
- ...this.achievements[t],
320
- id: t,
321
- ...e
322
- }));
323
- }
324
- /**
325
- * Get achievements user hasn't seen the notification for yet
326
- */
327
- getUnseenAchievements() {
328
- return this.getUnlockedAchievements().filter((t) => !t.seen);
329
- }
330
- /**
331
- * Mark achievements as seen
332
- */
333
- async markAchievementsSeen(t) {
334
- for (const e of t)
335
- f(this.player.achievements, e) && (this.player.achievements[e].seen = !0);
336
- await this.save();
337
- }
338
- /**
339
- * Update daily streak
340
- * @returns {boolean} True when the calendar day changed
341
- */
342
- _updateDailyStreak() {
343
- const t = this._getTodayDateString(), e = this.player.streak.lastPlayDate;
344
- if (e === t)
345
- return !1;
346
- const s = this._getYesterdayDateString();
347
- return e === s ? (this.player.streak.current++, this.player.streak.current > this.player.streak.longest && (this.player.streak.longest = this.player.streak.current)) : this.player.streak.current = 1, this.player.streak.lastPlayDate = t, !0;
348
- }
349
- /**
350
- * Get streak multiplier for XP
351
- */
352
- getStreakMultiplier() {
353
- const t = this.player.streak.current;
354
- return t >= 7 ? 2 : t >= 5 ? 1.5 : t >= 3 ? 1.25 : 1;
355
- }
356
- /**
357
- * Format a Date as a YYYY-MM-DD string in the player's local timezone.
358
- *
359
- * Deliberately not toISOString(), which formats in UTC. For anyone east or
360
- * west of Greenwich that shifts the calendar day for part of every day and
361
- * makes streaks reset or double-count.
362
- *
363
- * @param {Date} date
364
- * @returns {string}
365
- * @private
366
- */
367
- _toLocalDateString(t) {
368
- const e = t.getFullYear(), s = String(t.getMonth() + 1).padStart(2, "0"), i = String(t.getDate()).padStart(2, "0");
369
- return `${e}-${s}-${i}`;
370
- }
371
- /**
372
- * Get today's local date as YYYY-MM-DD string
373
- */
374
- _getTodayDateString() {
375
- return this._toLocalDateString(/* @__PURE__ */ new Date());
376
- }
377
- /**
378
- * Get yesterday's local date as YYYY-MM-DD string
379
- */
380
- _getYesterdayDateString() {
381
- const t = /* @__PURE__ */ new Date();
382
- return t.setDate(t.getDate() - 1), this._toLocalDateString(t);
383
- }
384
- /**
385
- * Initialize achievement definitions
386
- * Can be extended by games
387
- */
388
- _initAchievements() {
389
- return {
390
- // Universal achievements
391
- first_game: {
392
- name: "First Steps",
393
- description: "Play your first game",
394
- icon: "🎮",
395
- xp: 50,
396
- check: (t) => t.totalGamesPlayed >= 1
397
- },
398
- level_5: {
399
- name: "Rising Star",
400
- description: "Reach level 5",
401
- icon: "⭐",
402
- xp: 100,
403
- check: (t) => t.level >= 5
404
- },
405
- level_10: {
406
- name: "Expert Player",
407
- description: "Reach level 10",
408
- icon: "🏆",
409
- xp: 250,
410
- check: (t) => t.level >= 10
411
- },
412
- streak_3: {
413
- name: "Dedicated",
414
- description: "Play 3 days in a row",
415
- icon: "🔥",
416
- xp: 100,
417
- check: (t) => t.streak.current >= 3
418
- },
419
- streak_7: {
420
- name: "Unstoppable",
421
- description: "Play 7 days in a row",
422
- icon: "💥",
423
- xp: 300,
424
- check: (t) => t.streak.current >= 7
425
- }
426
- };
427
- }
428
- }
429
- function P() {
430
- const r = /* @__PURE__ */ new Map();
431
- return {
432
- getItem: (t) => r.has(t) ? r.get(t) : null,
433
- setItem: (t, e) => {
434
- r.set(t, String(e));
435
- },
436
- removeItem: (t) => {
437
- r.delete(t);
438
- },
439
- clear: () => {
440
- r.clear();
441
- }
442
- };
443
- }
301
+ //#endregion
302
+ //#region src/dopamine/utils/storage.js
444
303
  function A() {
445
- try {
446
- if (typeof localStorage > "u")
447
- return P();
448
- const r = "__dopamine_probe__";
449
- return localStorage.setItem(r, "1"), localStorage.removeItem(r), localStorage;
450
- } catch {
451
- return P();
452
- }
453
- }
454
- class I {
455
- constructor(t = {}) {
456
- this.storage = t.storage || A(), this.prefix = t.prefix || "dopamine_", this._tail = null;
457
- }
458
- /**
459
- * Run a write after any write still in flight.
460
- *
461
- * Promise storage can finish two overlapping writes in either order, and
462
- * the older value would win. Synchronous storage never has one in flight,
463
- * so it still writes before this returns.
464
- * @private
465
- */
466
- _write(t) {
467
- const e = this._tail ? this._tail.then(t) : t();
468
- if (typeof e?.then == "function") {
469
- const s = Promise.resolve(e).catch(() => {
470
- }).then(() => {
471
- this._tail === s && (this._tail = null);
472
- });
473
- this._tail = s;
474
- }
475
- return e;
476
- }
477
- /**
478
- * Save data to local storage
479
- * @param {string} key
480
- * @param {any} data
481
- */
482
- async save(t, e) {
483
- try {
484
- const s = JSON.stringify(e);
485
- return await this._write(() => this.storage.setItem(this.prefix + t, s)), !0;
486
- } catch (s) {
487
- return console.error("Error saving data:", s), !1;
488
- }
489
- }
490
- /**
491
- * Load data from local storage
492
- * @param {string} key
493
- * @param {any} defaultValue
494
- */
495
- async load(t, e = null) {
496
- try {
497
- await this._tail;
498
- const s = await this.storage.getItem(this.prefix + t);
499
- return s ? JSON.parse(s) : e;
500
- } catch (s) {
501
- return console.error("Error loading data:", s), e;
502
- }
503
- }
504
- /**
505
- * Clear specific data
506
- * @param {string} key
507
- */
508
- async clear(t) {
509
- await this._write(() => this.storage.removeItem(this.prefix + t));
510
- }
511
- }
512
- const M = "game-ui-overlay";
513
- class L {
514
- constructor(t) {
515
- this.particleSystem = t, this.container = null, this.xpBar = null, this.levelDisplay = null, this.streakDisplay = null, this._timers = /* @__PURE__ */ new Set(), this._detached = [], this.init();
516
- }
517
- /**
518
- * Initialize UI overlay
519
- */
520
- init() {
521
- this.container = document.createElement("div"), this.container.className = "game-ui-overlay", document.getElementById(M) || (this.container.id = M), this.container.innerHTML = `
522
- <div class="game-ui-top-bar">
523
- <div class="level-badge">
524
- <span class="level-label">LVL</span>
525
- <span class="level-number">1</span>
526
- </div>
527
-
528
- <div class="xp-container">
529
- <div class="xp-bar-bg">
530
- <div class="xp-bar-fill" style="width: 0%"></div>
531
- </div>
532
- <div class="xp-text">0 / 100 XP</div>
533
- </div>
534
-
535
- <div class="streak-badge">
536
- <span class="streak-icon">🔥</span>
537
- <span class="streak-number">1</span>
538
- </div>
539
- </div>
540
- `, this.liveRegion = document.createElement("div"), this.liveRegion.className = "dopamine-live-region", this.liveRegion.setAttribute("aria-live", "polite"), this.liveRegion.setAttribute("role", "status"), Object.assign(this.liveRegion.style, {
541
- position: "absolute",
542
- width: "1px",
543
- height: "1px",
544
- overflow: "hidden",
545
- clipPath: "inset(50%)",
546
- whiteSpace: "nowrap"
547
- }), this.container.appendChild(this.liveRegion), document.body.appendChild(this.container), this.levelBadge = this.container.querySelector(".level-badge"), this.streakBadge = this.container.querySelector(".streak-badge"), this.xpBar = this.container.querySelector(".xp-bar-fill"), this.xpText = this.container.querySelector(".xp-text"), this.levelDisplay = this.container.querySelector(".level-number"), this.streakDisplay = this.container.querySelector(".streak-number");
548
- }
549
- /**
550
- * setTimeout that destroy() can cancel.
551
- * @private
552
- */
553
- _defer(t, e) {
554
- const s = setTimeout(() => {
555
- this._timers.delete(s), t();
556
- }, e);
557
- return this._timers.add(s), s;
558
- }
559
- /**
560
- * Append a transient element and remember it for cleanup.
561
- * @private
562
- */
563
- _mount(t) {
564
- return document.body.appendChild(t), this._detached.push(t), t;
565
- }
566
- /**
567
- * Repeat a popup as text for assistive technology.
568
- * @private
569
- */
570
- _announce(t) {
571
- this.liveRegion && (this.liveRegion.textContent = t);
572
- }
573
- /**
574
- * Replay a CSS animation by clearing it for one tick.
575
- * @private
576
- */
577
- _replayAnimation(t, e) {
578
- t && (t.style.animation = "none", this._defer(() => {
579
- t.style.animation = e;
580
- }, 10));
581
- }
582
- /**
583
- * Update XP bar
584
- * @param {number} current - XP held right now
585
- * @param {number} needed - XP still required for the next level
586
- * @param {number} total - XP total that marks the next level
587
- * @param {number} [progress] - Position within the current level, 0 to 1.
588
- * Without it the bar falls back to current / total, which is lifetime
589
- * XP and starts every level after the first partly full.
590
- */
591
- updateXP(t, e, s, i) {
592
- const n = Number.isFinite(i) ? i : s > 0 ? t / s : 0;
593
- this.xpBar.style.width = `${Math.max(0, Math.min(100, n * 100))}%`, this.xpText.textContent = `${t} / ${s} XP`, this._replayAnimation(this.xpBar, "xp-pulse 0.3s ease-out");
594
- }
595
- /**
596
- * Update level display
597
- */
598
- updateLevel(t) {
599
- this.levelDisplay.textContent = t, this._replayAnimation(this.levelBadge, "level-pulse 0.5s ease-out");
600
- }
601
- /**
602
- * Update streak display
603
- */
604
- updateStreak(t) {
605
- this.streakDisplay.textContent = t, t >= 7 ? this.streakBadge.style.background = "linear-gradient(135deg, #ff6b00 0%, #ff4400 100%)" : t >= 3 ? this.streakBadge.style.background = "linear-gradient(135deg, #ff8800 0%, #ff6b00 100%)" : this.streakBadge.style.background = "";
606
- }
607
- /**
608
- * Show achievement unlocked popup
609
- *
610
- * `icon` is rendered as HTML by design (documented in ARCHITECTURE.md, so
611
- * games can pass an <img> or inline SVG). Every other field is game state
612
- * and could carry a player-supplied or server-supplied string, so it goes
613
- * in as text.
614
- */
615
- showAchievement(t) {
616
- const e = document.createElement("div");
617
- e.className = "achievement-popup", e.innerHTML = `
618
- <div class="achievement-shine"></div>
619
- <div class="achievement-content">
620
- <div class="achievement-icon"></div>
621
- <div class="achievement-info">
622
- <div class="achievement-title">Achievement Unlocked!</div>
623
- <div class="achievement-name"></div>
624
- <div class="achievement-desc"></div>
625
- <div class="achievement-xp"></div>
626
- </div>
627
- </div>
628
- `, e.querySelector(".achievement-icon").innerHTML = t.icon ?? "", e.querySelector(".achievement-name").textContent = t.name ?? "", e.querySelector(".achievement-desc").textContent = t.description ?? "", e.querySelector(".achievement-xp").textContent = `+${t.xp ?? 0} XP`, this._mount(e), this._announce(`Achievement unlocked: ${t.name ?? ""}`), this._defer(() => {
629
- const s = e.getBoundingClientRect();
630
- this.particleSystem.confetti(s.left + s.width / 2, s.top + s.height / 2, 40);
631
- }, 300), this._defer(() => {
632
- e.style.animation = "slideOut 0.3s ease-in forwards", this._defer(() => this._remove(e), 300);
633
- }, 4e3);
634
- }
635
- /**
636
- * Show level up screen
637
- */
638
- showLevelUp(t, e) {
639
- const s = document.createElement("div");
640
- s.className = "level-up-overlay", s.innerHTML = `
641
- <div class="level-up-content">
642
- <div class="level-up-title">LEVEL UP!</div>
643
- <div class="level-up-number"></div>
644
- <div class="level-up-subtitle">Amazing progress!</div>
645
- </div>
646
- `, s.querySelector(".level-up-number").textContent = e, this._mount(s), this._announce(`Level up: ${e}`), this._defer(() => {
647
- for (let i = 0; i < 5; i++)
648
- this._defer(() => {
649
- const n = Math.random() * window.innerWidth, a = Math.random() * window.innerHeight * 0.6;
650
- this.particleSystem.confetti(n, a, 30);
651
- }, i * 200);
652
- }, 300), this._defer(() => {
653
- s.style.opacity = "0", this._defer(() => this._remove(s), 500);
654
- }, 2500);
655
- }
656
- /**
657
- * Show floating text (e.g., "+50 XP", "COMBO!")
658
- */
659
- showFloatingText(t, e, s, i = "#ffd700", n = "24px") {
660
- const a = document.createElement("div");
661
- a.className = "floating-text", a.textContent = t, a.style.left = e + "px", a.style.top = s + "px", a.style.color = i, a.style.fontSize = n, this._mount(a), this._defer(() => this._remove(a), 2e3);
662
- }
663
- /**
664
- * Show combo multiplier
665
- */
666
- showCombo(t, e, s) {
667
- this.showFloatingText(`${t}× COMBO!`, e, s, "#ff6b6b", "32px"), this.particleSystem.fire(e, s, 20);
668
- }
669
- /**
670
- * Show "near miss" indicator
671
- */
672
- showNearMiss(t, e) {
673
- this.showFloatingText("CLOSE CALL!", t, e, "#45b7d1", "20px"), this.particleSystem.sparkle(t, e, 15, "#45b7d1");
674
- }
675
- /**
676
- * Show lucky moment (random multiplier)
677
- */
678
- showLuckyMoment(t, e, s) {
679
- this.showFloatingText(`LUCKY ${t}×!`, e, s, "#ffd700", "36px"), this.particleSystem.starBurst(e, s, 12), this.particleSystem.confetti(e, s, 25);
680
- }
681
- /**
682
- * Show generic notification
683
- */
684
- showNotification(t, e = "normal") {
685
- const s = window.innerWidth / 2, i = window.innerHeight / 3;
686
- e === "legendary" ? (this.showFloatingText(t, s, i, "#ffd700", "36px"), this.particleSystem.starBurst(s, i, 12), this.particleSystem.confetti(s, i, 25)) : e === "rare" ? (this.showFloatingText(t, s, i, "#ff6b6b", "32px"), this.particleSystem.fire(s, i, 20)) : this.showFloatingText(t, s, i, "#fff", "24px"), this._announce(t);
687
- }
688
- /**
689
- * Show Game Over Summary
690
- *
691
- * @param {Object} data
692
- * @param {number|string} data.score - Final score
693
- * @param {Object} [data.metrics] - Label/value pairs listed under the score
694
- * @param {Function} [data.onReplay] - Replay button handler (default: reload)
695
- * @param {Function} [data.onExit] - Exit button handler (button hidden if omitted)
696
- */
697
- showSummary(t) {
698
- const e = document.createElement("div");
699
- e.className = "message-box", e.style.display = "flex", e.style.position = "absolute", e.style.top = "50%", e.style.left = "50%", e.style.transform = "translate(-50%, -50%)", e.style.zIndex = "1000";
700
- const s = document.createElement("h1");
701
- s.textContent = "Game Over";
702
- const i = document.createElement("div");
703
- i.className = "summary-score", i.style.cssText = "font-size: 3rem; font-weight: bold; color: #e06020; margin: 10px 0;", i.textContent = t.score;
704
- const n = document.createElement("div");
705
- n.className = "summary-metrics", n.style.cssText = "width: 100%; margin-bottom: 20px;";
706
- for (const [o, l] of Object.entries(t.metrics || {})) {
707
- const h = document.createElement("div");
708
- h.style.cssText = "display:flex;justify-content:space-between;width:100%";
709
- const d = document.createElement("span");
710
- d.textContent = `${o}:`;
711
- const u = document.createElement("strong");
712
- u.textContent = l, h.append(d, u), n.appendChild(h);
713
- }
714
- e.append(s, i, n);
715
- const a = document.createElement("button");
716
- if (a.className = "btn", a.textContent = "Play Again", a.addEventListener("click", t.onReplay || (() => window.location.reload())), e.appendChild(a), t.onExit) {
717
- const o = document.createElement("button");
718
- o.className = "btn", o.textContent = "Exit", o.style.cssText = "margin-top: 10px; background: #543847;", o.addEventListener("click", t.onExit), e.appendChild(o);
719
- }
720
- return this._mount(e), e;
721
- }
722
- /**
723
- * @private
724
- */
725
- _remove(t) {
726
- t.remove();
727
- const e = this._detached.indexOf(t);
728
- e > -1 && this._detached.splice(e, 1);
729
- }
730
- /**
731
- * Tear down the overlay, any transient popups, and all pending timers.
732
- */
733
- destroy() {
734
- for (const t of this._timers)
735
- clearTimeout(t);
736
- this._timers.clear();
737
- for (const t of this._detached)
738
- t.remove();
739
- this._detached = [], this.container?.remove(), this.container = null, this.liveRegion = null, this.xpBar = null, this.xpText = null, this.levelBadge = null, this.streakBadge = null, this.levelDisplay = null, this.streakDisplay = null;
740
- }
741
- }
742
- class z {
743
- constructor(t = {}) {
744
- this.container = t.container ? typeof t.container == "string" ? document.querySelector(t.container) : t.container : document.body, this.container || (console.warn(`[DopamineJS] Particle container '${t.container}' not found. Using document.body.`), this.container = document.body), this.maxParticles = Number.isFinite(t.maxParticles) ? Math.max(0, Math.floor(t.maxParticles)) : 5e3, this._reducedMotion = t.respectReducedMotion !== !1 && typeof window.matchMedia == "function" ? window.matchMedia("(prefers-reduced-motion: reduce)") : null, this.canvasId = t.canvasId || "dopamine-particle-canvas", this.canvas = document.createElement("canvas"), this.canvas.classList.add("dopamine-particle-canvas"), document.getElementById(this.canvasId) || (this.canvas.id = this.canvasId), this.canvas.style.pointerEvents = "none", this.canvas.style.zIndex = t.zIndex || "9999", this.container === document.body ? (this.canvas.style.position = "fixed", this.canvas.style.top = "0", this.canvas.style.left = "0") : (this.canvas.style.position = "absolute", this.canvas.style.top = "0", this.canvas.style.left = "0", window.getComputedStyle(this.container).position === "static" && (this.container.style.position = "relative")), this.container.appendChild(this.canvas), this.ctx = this.canvas.getContext("2d"), this.particles = [], this.pool = [], this.sprites = /* @__PURE__ */ new Map(), this.customEffects = /* @__PURE__ */ new Map(), this.isAnimating = !1, this._onResize = () => this._resize(), this._resizeObserver = null, this._frameHandle = null, this._lastFrameTime = null, this._resize(), window.ResizeObserver && this.container !== document.body ? (this._resizeObserver = new ResizeObserver(this._onResize), this._resizeObserver.observe(this.container)) : window.addEventListener("resize", this._onResize);
745
- }
746
- _resize() {
747
- const t = this.container === document.body ? window.innerWidth : this.container.clientWidth, e = this.container === document.body ? window.innerHeight : this.container.clientHeight, s = window.devicePixelRatio || 1;
748
- this.width = t, this.height = e, this.canvas.width = Math.round(t * s), this.canvas.height = Math.round(e * s), this.canvas.style.width = `${t}px`, this.canvas.style.height = `${e}px`, this.ctx.setTransform(s, 0, 0, s, 0, 0);
749
- }
750
- /**
751
- * Register a custom sprite image
752
- * @param {string} key
753
- * @param {string} url
754
- */
755
- registerSprite(t, e) {
756
- const s = new Image();
757
- s.src = e, this.sprites.set(t, s);
758
- }
759
- /**
760
- * Register a custom effect
761
- * @param {string} name
762
- * @param {Function} callback - (x, y, ...args) => void
763
- */
764
- registerEffect(t, e) {
765
- this.customEffects.set(t, e);
766
- }
767
- /**
768
- * Play a registered effect
769
- */
770
- play(t, e, s, ...i) {
771
- const n = this.customEffects.get(t);
772
- n ? n(e, s, ...i) : console.warn(`[DopamineJS] Effect '${t}' not found.`);
773
- }
774
- /**
775
- * Emit particles with custom config
776
- * @param {Object} config
777
- */
778
- emit(t) {
779
- const {
780
- x: e,
781
- y: s,
782
- count: i = 10,
783
- speed: n = 5,
784
- gravity: a = 0.1,
785
- decay: o = 0.02,
786
- life: l = 1,
787
- color: h = "#ffd700",
788
- sprite: d = null,
789
- spread: u = Math.PI * 2,
790
- angle: p = 0,
791
- size: g = 5,
792
- type: C = null
793
- } = t, x = this._allowed(i);
794
- for (let w = 0; w < x; w++) {
795
- const c = this._getParticle(), S = p + (Math.random() - 0.5) * u, b = Math.random() * n;
796
- c.x = e, c.y = s, c.vx = Math.cos(S) * b, c.vy = Math.sin(S) * b, c.life = l, c.decay = o * (0.8 + Math.random() * 0.4), c.gravity = a, c.color = Array.isArray(h) ? h[Math.floor(Math.random() * h.length)] : h, c.size = g * (0.8 + Math.random() * 0.4), c.sprite = d, c.type = C, c.rotation = Math.random() * Math.PI * 2, c.rotationSpeed = (Math.random() - 0.5) * 0.2, this.particles.push(c);
797
- }
798
- x > 0 && this._startAnimation();
799
- }
800
- /**
801
- * How many of `count` particles may be created right now.
802
- * @private
803
- */
804
- _allowed(t) {
805
- if (this._reducedMotion?.matches || !Number.isFinite(t)) return 0;
806
- const e = this.maxParticles - this.particles.length;
807
- return Math.max(0, Math.min(Math.floor(t), e));
808
- }
809
- _getParticle() {
810
- return this.pool.length > 0 ? this.pool.pop() : {};
811
- }
812
- _recycleParticle(t) {
813
- this.pool.push(t);
814
- }
815
- // --- Built-in Effects ---
816
- confetti(t, e, s = 50) {
817
- const i = ["#ff6b6b", "#4ecdc4", "#45b7d1", "#f7dc6f", "#c06c84", "#6c5ce7"];
818
- this.emit({
819
- x: t,
820
- y: e,
821
- count: s,
822
- color: i,
823
- speed: 10,
824
- gravity: 0.3,
825
- decay: 0.015,
826
- size: 8,
827
- spread: Math.PI * 2
828
- });
829
- }
830
- coinShower(t, e, s = 10) {
831
- this.emit({
832
- x: t,
833
- y: e,
834
- count: s,
835
- color: "#ffd700",
836
- speed: 4,
837
- gravity: 0.4,
838
- decay: 0.012,
839
- size: 12,
840
- angle: -Math.PI / 2,
841
- // Upwards initially
842
- spread: Math.PI / 2
843
- });
844
- }
845
- sparkle(t, e, s = 20, i = "#ffd700") {
846
- this.emit({
847
- x: t,
848
- y: e,
849
- count: s,
850
- color: i,
851
- speed: 3,
852
- gravity: -0.05,
853
- // Float up
854
- decay: 0.03,
855
- size: 3
856
- });
857
- }
858
- fire(t, e, s = 15) {
859
- const i = ["#ff6b00", "#ff8800", "#ffaa00", "#ff4400"];
860
- this.emit({
861
- x: t,
862
- y: e,
863
- count: s,
864
- color: i,
865
- speed: 3,
866
- gravity: -0.2,
867
- decay: 0.04,
868
- size: 5,
869
- angle: -Math.PI / 2,
870
- spread: Math.PI / 4
871
- });
872
- }
873
- starBurst(t, e, s = 8) {
874
- const i = this._allowed(s);
875
- for (let n = 0; n < i; n++) {
876
- const a = this._getParticle(), o = Math.PI * 2 / i * n, l = 4;
877
- a.x = t, a.y = e, a.vx = Math.cos(o) * l, a.vy = Math.sin(o) * l, a.life = 1, a.decay = 0.03, a.gravity = 0, a.color = "#ffffff", a.size = 15, a.sprite = null, a.type = "star", a.rotation = o, a.rotationSpeed = 0, this.particles.push(a);
878
- }
879
- i > 0 && this._startAnimation();
880
- }
881
- _startAnimation() {
882
- this.isAnimating || (this.isAnimating = !0, this._lastFrameTime = null, this._animate());
883
- }
884
- /**
885
- * @param {number} [time] - requestAnimationFrame timestamp
886
- */
887
- _animate(t) {
888
- this._frameHandle = null, this.ctx.clearRect(0, 0, this.width, this.height);
889
- let e = 1;
890
- Number.isFinite(t) && (this._lastFrameTime !== null && (e = Math.max(0, Math.min(3, (t - this._lastFrameTime) / (1e3 / 60)))), this._lastFrameTime = t);
891
- for (let s = this.particles.length - 1; s >= 0; s--) {
892
- const i = this.particles[s];
893
- if (i.vy += i.gravity * e, i.x += i.vx * e, i.y += i.vy * e, i.life -= i.decay * e, i.rotationSpeed && (i.rotation += i.rotationSpeed * e), i.life <= 0) {
894
- this._recycleParticle(i);
895
- const n = this.particles.pop();
896
- s < this.particles.length && (this.particles[s] = n);
897
- continue;
898
- }
899
- if (this.ctx.save(), this.ctx.globalAlpha = i.life, this.ctx.translate(i.x, i.y), this.ctx.rotate(i.rotation), i.sprite && this.sprites.has(i.sprite)) {
900
- const n = this.sprites.get(i.sprite);
901
- n.complete && this.ctx.drawImage(n, -i.size / 2, -i.size / 2, i.size, i.size);
902
- } else i.type === "star" ? (this.ctx.fillStyle = i.color, this._drawStarPath(0, 0, 5, i.size, i.size / 2), this.ctx.fill()) : (this.ctx.fillStyle = i.color, this.ctx.beginPath(), this.ctx.arc(0, 0, i.size, 0, Math.PI * 2), this.ctx.fill());
903
- this.ctx.restore();
904
- }
905
- this.particles.length > 0 ? this._frameHandle = requestAnimationFrame((s) => this._animate(s)) : this.isAnimating = !1;
906
- }
907
- _drawStarPath(t, e, s, i, n) {
908
- let a = Math.PI / 2 * 3, o = t, l = e;
909
- const h = Math.PI / s;
910
- this.ctx.beginPath(), this.ctx.moveTo(t, e - i);
911
- for (let d = 0; d < s; d++)
912
- o = t + Math.cos(a) * i, l = e + Math.sin(a) * i, this.ctx.lineTo(o, l), a += h, o = t + Math.cos(a) * n, l = e + Math.sin(a) * n, this.ctx.lineTo(o, l), a += h;
913
- this.ctx.lineTo(t, e - i), this.ctx.closePath();
914
- }
915
- clear() {
916
- this.particles.forEach((t) => this._recycleParticle(t)), this.particles = [], this.ctx.clearRect(0, 0, this.width, this.height);
917
- }
918
- /**
919
- * Stop animating, detach resize handling, and remove the canvas.
920
- *
921
- * Without this the resize listener and canvas outlive the instance, which
922
- * matters in any single-page app that mounts and unmounts a game view.
923
- */
924
- destroy() {
925
- this.clear(), this.isAnimating = !1, this._frameHandle !== null && (cancelAnimationFrame(this._frameHandle), this._frameHandle = null), this._resizeObserver && (this._resizeObserver.disconnect(), this._resizeObserver = null), window.removeEventListener("resize", this._onResize), this.canvas.remove(), this.sprites.clear(), this.customEffects.clear(), this.pool = [];
926
- }
304
+ let e = /* @__PURE__ */ new Map();
305
+ return {
306
+ getItem: (t) => e.has(t) ? e.get(t) : null,
307
+ setItem: (t, n) => {
308
+ e.set(t, String(n));
309
+ },
310
+ removeItem: (t) => {
311
+ e.delete(t);
312
+ },
313
+ clear: () => {
314
+ e.clear();
315
+ }
316
+ };
927
317
  }
928
- const k = (r, t) => Object.prototype.hasOwnProperty.call(r, t);
929
- class F {
930
- constructor(t = {}) {
931
- this.audioContext = null, this.storageKey = t.storageKey || "dopamineSoundsMuted", this.storage = t.storage || A(), this.muted = this.storage.getItem(this.storageKey) === "true", this.assets = /* @__PURE__ */ new Map(), this.customSounds = t.customSounds || {}, this.masterGain = null, this._volume = 1, this.setVolume(t.volume ?? 1), this._loading = /* @__PURE__ */ new Map(), this._timers = /* @__PURE__ */ new Set();
932
- }
933
- /**
934
- * setTimeout that destroy() can cancel.
935
- * @private
936
- */
937
- _later(t, e) {
938
- const s = setTimeout(() => {
939
- this._timers.delete(s), t();
940
- }, e);
941
- this._timers.add(s);
942
- }
943
- /**
944
- * Initialize Audio Context (must be called after user interaction)
945
- */
946
- initAudio() {
947
- if (!this.audioContext) {
948
- const t = typeof window < "u" ? window.AudioContext || window.webkitAudioContext : void 0;
949
- if (!t) return !1;
950
- this.audioContext = new t(), this.masterGain = this.audioContext.createGain(), this.masterGain.gain.value = this._volume, this.masterGain.connect(this.audioContext.destination), this.preloadSounds(this.customSounds);
951
- }
952
- return this.audioContext.state === "suspended" && this.audioContext.resume(), !0;
953
- }
954
- /**
955
- * Set master output volume.
956
- * @param {number} value - 0..1
957
- */
958
- setVolume(t) {
959
- return Number.isFinite(t) ? (this._volume = Math.max(0, Math.min(1, t)), this.masterGain && (this.masterGain.gain.value = this._volume), this._volume) : this._volume;
960
- }
961
- /**
962
- * Current master output volume.
963
- * @returns {number}
964
- */
965
- getVolume() {
966
- return this._volume;
967
- }
968
- /**
969
- * Node every sound routes through, so volume and mute apply uniformly.
970
- * @private
971
- */
972
- _output() {
973
- return this.masterGain || this.audioContext.destination;
974
- }
975
- /**
976
- * Toggle mute state
977
- * @returns {boolean} New mute state
978
- */
979
- toggleMute() {
980
- return this.muted = !this.muted, this.storage.setItem(this.storageKey, this.muted), this.muted;
981
- }
982
- /**
983
- * Register a custom sound URL
984
- * @param {string} key - Unique identifier (e.g., 'jump', 'win')
985
- * @param {string} url - Path to audio file
986
- */
987
- registerSound(t, e) {
988
- this.customSounds[t] = e, this.audioContext && this.loadSound(t, e);
989
- }
990
- /**
991
- * Preload multiple sounds
992
- * @param {Object} soundMap - { key: url }
993
- */
994
- async preloadSounds(t) {
995
- const e = Object.entries(t).map(([s, i]) => this.loadSound(s, i));
996
- await Promise.allSettled(e);
997
- }
998
- /**
999
- * Load and decode a sound file
1000
- */
1001
- async loadSound(t, e) {
1002
- if (!this.audioContext) return;
1003
- if (this._loading.has(t))
1004
- return this._loading.get(t);
1005
- const s = this._load(t, e).finally(() => this._loading.delete(t));
1006
- return this._loading.set(t, s), s;
1007
- }
1008
- /**
1009
- * @private
1010
- */
1011
- async _load(t, e) {
1012
- try {
1013
- const s = this.audioContext, i = await fetch(e);
1014
- if (i.ok === !1)
1015
- throw new Error(`HTTP ${i.status}`);
1016
- const n = await i.arrayBuffer(), a = await s.decodeAudioData(n);
1017
- this.audioContext === s && this.assets.set(t, a);
1018
- } catch (s) {
1019
- console.warn(`[DopamineJS] Failed to load sound '${t}':`, s);
1020
- }
1021
- }
1022
- /**
1023
- * Play a sound by key (custom) or fallback to synth
1024
- * @param {string} key - 'jump', 'score', 'success', etc.
1025
- */
1026
- async play(t) {
1027
- if (this.muted || !this.initAudio()) return;
1028
- if (this.assets.has(t)) {
1029
- this._playBuffer(this.assets.get(t));
1030
- return;
1031
- }
1032
- if (k(this.customSounds, t) && !this.assets.has(t)) {
1033
- const s = this.audioContext;
1034
- if (await this.loadSound(t, this.customSounds[t]), this.audioContext !== s) return;
1035
- if (this.assets.has(t)) {
1036
- this._playBuffer(this.assets.get(t));
1037
- return;
1038
- }
1039
- }
1040
- const e = {
1041
- jump: () => this.playJump(!0),
1042
- score: () => this.playScore(!0),
1043
- success: () => this.playSuccess(!0),
1044
- click: () => this.playClick(!0),
1045
- error: () => this.playError(!0),
1046
- gameover: () => this.playGameOver(!0)
1047
- };
1048
- k(e, t) && e[t]();
1049
- }
1050
- _playBuffer(t) {
1051
- const e = this.audioContext.createBufferSource();
1052
- e.buffer = t, e.connect(this._output()), e.start(0);
1053
- }
1054
- /**
1055
- * Play a synthesized tone
1056
- */
1057
- playTone(t, e, s = "sine", i = 0.3) {
1058
- if (this.muted || !this.initAudio()) return;
1059
- const n = this.audioContext.createOscillator(), a = this.audioContext.createGain();
1060
- n.connect(a), a.connect(this._output()), n.frequency.value = t, n.type = s;
1061
- const o = Math.max(1e-4, i);
1062
- a.gain.setValueAtTime(o, this.audioContext.currentTime), a.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + e), n.start(this.audioContext.currentTime), n.stop(this.audioContext.currentTime + e);
1063
- }
1064
- // --- Presets (Synth) ---
1065
- playJump(t = !1) {
1066
- if (!t && this.assets.has("jump")) return this.play("jump");
1067
- this.playTone(400, 0.1, "square", 0.2);
1068
- }
1069
- playScore(t = !1) {
1070
- if (!t && this.assets.has("score")) return this.play("score");
1071
- this.playTone(800, 0.15, "sine", 0.25), this._later(() => this.playTone(1e3, 0.15, "sine", 0.25), 50);
1072
- }
1073
- playGameOver(t = !1) {
1074
- if (!t && this.assets.has("gameover")) return this.play("gameover");
1075
- this.playTone(300, 0.2, "sawtooth", 0.3), this._later(() => this.playTone(200, 0.2, "sawtooth", 0.3), 100), this._later(() => this.playTone(150, 0.3, "sawtooth", 0.3), 200);
1076
- }
1077
- playClick(t = !1) {
1078
- if (!t && this.assets.has("click")) return this.play("click");
1079
- this.playTone(600, 0.05, "sine", 0.1);
1080
- }
1081
- playSuccess(t = !1) {
1082
- if (!t && this.assets.has("success")) return this.play("success");
1083
- this.playTone(600, 0.1, "sine", 0.2), this._later(() => this.playTone(800, 0.2, "sine", 0.2), 100);
1084
- }
1085
- playError(t = !1) {
1086
- if (!t && this.assets.has("error")) return this.play("error");
1087
- this.playTone(200, 0.2, "sawtooth", 0.3);
1088
- }
1089
- /**
1090
- * Cancel queued tones, close the audio context and drop decoded buffers.
1091
- * Browsers cap the number of live AudioContexts per page.
1092
- */
1093
- destroy() {
1094
- for (const t of this._timers)
1095
- clearTimeout(t);
1096
- this._timers.clear(), this.audioContext && this.audioContext.close?.()?.catch?.(() => {
1097
- }), this.audioContext = null, this.masterGain = null, this.assets.clear(), this._loading.clear();
1098
- }
318
+ function j() {
319
+ try {
320
+ if (typeof localStorage > "u") return A();
321
+ let e = "__dopamine_probe__";
322
+ return localStorage.setItem(e, "1"), localStorage.removeItem(e), localStorage;
323
+ } catch {
324
+ return A();
325
+ }
1099
326
  }
1100
- class N {
1101
- constructor(t = {}) {
1102
- this.config = t, this.dataService = new I(t.data || {}), this.rewardSystem = new D(this.dataService, t.rewards || {}), this.soundManager = new F(t.sound || {}), this.particleSystem = new z(t.particles || {}), this.gameUI = new L(this.particleSystem), this._bindEvents();
1103
- }
1104
- async init() {
1105
- return await this.rewardSystem.init(), this._syncUI(), {
1106
- rewardSystem: this.rewardSystem,
1107
- gameUI: this.gameUI,
1108
- particleSystem: this.particleSystem,
1109
- soundManager: this.soundManager
1110
- };
1111
- }
1112
- /**
1113
- * Draw the loaded player. Without this the overlay keeps its placeholder
1114
- * (level 1, 0 XP, streak 1) until the first event arrives.
1115
- * @private
1116
- */
1117
- _syncUI() {
1118
- const { player: t } = this.rewardSystem, { total: e, needed: s, progress: i } = this.rewardSystem.getXPForNextLevel();
1119
- this.gameUI.updateXP(t.xp, s, e, i), this.gameUI.updateLevel(t.level), this.gameUI.updateStreak(t.streak.current);
1120
- }
1121
- _bindEvents() {
1122
- const t = this.rewardSystem;
1123
- this._unsubscribe = [
1124
- t.on("xp_gained", () => {
1125
- const { total: e, needed: s, progress: i } = t.getXPForNextLevel();
1126
- this.gameUI.updateXP(t.player.xp, s, e, i);
1127
- }),
1128
- t.on("level_up", (e) => {
1129
- this.gameUI.updateLevel(e.newLevel), this.gameUI.showLevelUp(e.oldLevel, e.newLevel);
1130
- }),
1131
- t.on("achievement_unlocked", (e) => {
1132
- this.gameUI.showAchievement(e);
1133
- }),
1134
- t.on("streak_updated", (e) => {
1135
- this.gameUI.updateStreak(e.current);
1136
- }),
1137
- t.on("new_high_score", (e) => {
1138
- this.gameUI.showNotification(`New High Score: ${e.score}!`, "legendary"), this.soundManager.playSuccess();
1139
- })
1140
- ];
1141
- }
1142
- /**
1143
- * Remove the overlay and canvas, stop audio, and detach from the reward
1144
- * system. The reward system itself stays usable.
1145
- */
1146
- destroy() {
1147
- for (const t of this._unsubscribe)
1148
- t();
1149
- this._unsubscribe = [], this.gameUI.destroy(), this.particleSystem.destroy(), this.soundManager.destroy();
1150
- }
1151
- }
1152
- const _ = {
1153
- /**
1154
- * Called when system is registered to the kernel
1155
- * @param {DopamineKernel} kernel - The kernel instance
1156
- */
1157
- init(r) {
1158
- },
1159
- /**
1160
- * Called each frame (variable timestep)
1161
- * @param {number} dt - Delta time in seconds
1162
- */
1163
- update(r) {
1164
- },
1165
- /**
1166
- * Called at fixed timestep (for physics)
1167
- * @param {number} dt - Fixed delta time
1168
- */
1169
- fixedUpdate(r) {
1170
- },
1171
- /**
1172
- * Called when system is unregistered
1173
- */
1174
- destroy() {
1175
- }
1176
- };
1177
- class G {
1178
- constructor() {
1179
- this.kernel = null;
1180
- }
1181
- init(t) {
1182
- this.kernel = t;
1183
- }
1184
- update(t) {
1185
- }
1186
- fixedUpdate(t) {
1187
- }
1188
- destroy() {
1189
- }
1190
- }
1191
- const R = {
1192
- ..._,
1193
- /**
1194
- * Add a physics body to the simulation
1195
- * @param {Object} body - Physics body (implementation-specific)
1196
- */
1197
- addBody(r) {
1198
- },
1199
- /**
1200
- * Remove a physics body from the simulation
1201
- * @param {Object} body - Physics body to remove
1202
- */
1203
- removeBody(r) {
1204
- },
1205
- /**
1206
- * Check collision between two bodies
1207
- * @param {Object} a - First body
1208
- * @param {Object} b - Second body
1209
- * @returns {boolean} - True if colliding
1210
- */
1211
- checkCollision(r, t) {
1212
- },
1213
- /**
1214
- * Perform a raycast
1215
- * @param {Object} origin - Ray origin {x, y}
1216
- * @param {Object} direction - Ray direction {x, y}
1217
- * @param {number} distance - Maximum ray distance
1218
- * @returns {Object|null} - Hit result or null
1219
- */
1220
- raycast(r, t, e) {
1221
- },
1222
- /**
1223
- * Set gravity for the physics world
1224
- * @param {number} x - Gravity X component
1225
- * @param {number} y - Gravity Y component
1226
- */
1227
- setGravity(r, t) {
1228
- },
1229
- /**
1230
- * Step the physics simulation
1231
- * @param {number} dt - Delta time
1232
- */
1233
- step(r) {
1234
- }
1235
- }, B = {
1236
- ..._,
1237
- /**
1238
- * Register a sound with a key
1239
- * @param {string} key - Sound identifier
1240
- * @param {string} url - Path to audio file
1241
- */
1242
- registerSound(r, t) {
1243
- },
1244
- /**
1245
- * Preload multiple sounds
1246
- * @param {Object} soundMap - Map of key -> url
1247
- * @returns {Promise<void>}
1248
- */
1249
- preloadSounds(r) {
1250
- },
1251
- /**
1252
- * Play a sound by key
1253
- * @param {string} key - Sound identifier
1254
- * @param {Object} options - Playback options (volume, loop, etc.)
1255
- */
1256
- play(r, t) {
1257
- },
1258
- /**
1259
- * Play a synthesized tone
1260
- * @param {number} frequency - Frequency in Hz
1261
- * @param {number} duration - Duration in seconds
1262
- * @param {string} type - Waveform type ('sine', 'square', etc.)
1263
- * @param {number} volume - Volume (0-1)
1264
- */
1265
- playTone(r, t, e, s) {
1266
- },
1267
- /**
1268
- * Stop a playing sound
1269
- * @param {string} key - Sound identifier
1270
- */
1271
- stop(r) {
1272
- },
1273
- /**
1274
- * Toggle mute state
1275
- * @returns {boolean} - New mute state
1276
- */
1277
- toggleMute() {
1278
- },
1279
- /**
1280
- * Set master volume
1281
- * @param {number} volume - Volume (0-1)
1282
- */
1283
- setVolume(r) {
1284
- }
327
+ //#endregion
328
+ //#region src/dopamine/core/DataService.js
329
+ var M = class {
330
+ constructor(e = {}) {
331
+ this.storage = e.storage || j(), this.prefix = e.prefix || "dopamine_", this._tail = null;
332
+ }
333
+ _write(e) {
334
+ let t = this._tail ? this._tail.then(e) : e();
335
+ if (typeof t?.then == "function") {
336
+ let e = Promise.resolve(t).catch(() => {}).then(() => {
337
+ this._tail === e && (this._tail = null);
338
+ });
339
+ this._tail = e;
340
+ }
341
+ return t;
342
+ }
343
+ async save(e, t) {
344
+ try {
345
+ let n = JSON.stringify(t);
346
+ return await this._write(() => this.storage.setItem(this.prefix + e, n)), !0;
347
+ } catch (e) {
348
+ return console.error("Error saving data:", e), !1;
349
+ }
350
+ }
351
+ async load(e, t = null) {
352
+ try {
353
+ await this._tail;
354
+ let n = await this.storage.getItem(this.prefix + e);
355
+ return n ? JSON.parse(n) : t;
356
+ } catch (e) {
357
+ return console.error("Error loading data:", e), t;
358
+ }
359
+ }
360
+ async clear(e) {
361
+ await this._write(() => this.storage.removeItem(this.prefix + e));
362
+ }
363
+ }, N = "game-ui-overlay", P = class {
364
+ constructor(e) {
365
+ this.particleSystem = e, this.container = null, this.xpBar = null, this.levelDisplay = null, this.streakDisplay = null, this._timers = /* @__PURE__ */ new Set(), this._detached = [], this.init();
366
+ }
367
+ init() {
368
+ this.container = document.createElement("div"), this.container.className = "game-ui-overlay", document.getElementById(N) || (this.container.id = N), this.container.innerHTML = "\n <div class=\"game-ui-top-bar\">\n <div class=\"level-badge\">\n <span class=\"level-label\">LVL</span>\n <span class=\"level-number\">1</span>\n </div>\n\n <div class=\"xp-container\">\n <div class=\"xp-bar-bg\">\n <div class=\"xp-bar-fill\" style=\"width: 0%\"></div>\n </div>\n <div class=\"xp-text\">0 / 100 XP</div>\n </div>\n\n <div class=\"streak-badge\">\n <span class=\"streak-icon\">🔥</span>\n <span class=\"streak-number\">1</span>\n </div>\n </div>\n ", this.liveRegion = document.createElement("div"), this.liveRegion.className = "dopamine-live-region", this.liveRegion.setAttribute("aria-live", "polite"), this.liveRegion.setAttribute("role", "status"), Object.assign(this.liveRegion.style, {
369
+ position: "absolute",
370
+ width: "1px",
371
+ height: "1px",
372
+ overflow: "hidden",
373
+ clipPath: "inset(50%)",
374
+ whiteSpace: "nowrap"
375
+ }), this.container.appendChild(this.liveRegion), document.body.appendChild(this.container), this.levelBadge = this.container.querySelector(".level-badge"), this.streakBadge = this.container.querySelector(".streak-badge"), this.xpBar = this.container.querySelector(".xp-bar-fill"), this.xpText = this.container.querySelector(".xp-text"), this.levelDisplay = this.container.querySelector(".level-number"), this.streakDisplay = this.container.querySelector(".streak-number");
376
+ }
377
+ _defer(e, t) {
378
+ let n = setTimeout(() => {
379
+ this._timers.delete(n), e();
380
+ }, t);
381
+ return this._timers.add(n), n;
382
+ }
383
+ _mount(e) {
384
+ return document.body.appendChild(e), this._detached.push(e), e;
385
+ }
386
+ _announce(e) {
387
+ this.liveRegion && (this.liveRegion.textContent = e);
388
+ }
389
+ _replayAnimation(e, t) {
390
+ e && (e.style.animation = "none", this._defer(() => {
391
+ e.style.animation = t;
392
+ }, 10));
393
+ }
394
+ updateXP(e, t, n, r) {
395
+ let i = Number.isFinite(r) ? r : n > 0 ? e / n : 0;
396
+ this.xpBar.style.width = `${Math.max(0, Math.min(100, i * 100))}%`, this.xpText.textContent = `${e} / ${n} XP`, this._replayAnimation(this.xpBar, "xp-pulse 0.3s ease-out");
397
+ }
398
+ updateLevel(e) {
399
+ this.levelDisplay.textContent = e, this._replayAnimation(this.levelBadge, "level-pulse 0.5s ease-out");
400
+ }
401
+ updateStreak(e) {
402
+ this.streakDisplay.textContent = e, e >= 7 ? this.streakBadge.style.background = "linear-gradient(135deg, #ff6b00 0%, #ff4400 100%)" : e >= 3 ? this.streakBadge.style.background = "linear-gradient(135deg, #ff8800 0%, #ff6b00 100%)" : this.streakBadge.style.background = "";
403
+ }
404
+ showAchievement(e) {
405
+ let t = document.createElement("div");
406
+ t.className = "achievement-popup", t.innerHTML = "\n <div class=\"achievement-shine\"></div>\n <div class=\"achievement-content\">\n <div class=\"achievement-icon\"></div>\n <div class=\"achievement-info\">\n <div class=\"achievement-title\">Achievement Unlocked!</div>\n <div class=\"achievement-name\"></div>\n <div class=\"achievement-desc\"></div>\n <div class=\"achievement-xp\"></div>\n </div>\n </div>\n ", t.querySelector(".achievement-icon").innerHTML = e.icon ?? "", t.querySelector(".achievement-name").textContent = e.name ?? "", t.querySelector(".achievement-desc").textContent = e.description ?? "", t.querySelector(".achievement-xp").textContent = `+${e.xp ?? 0} XP`, this._mount(t), this._announce(`Achievement unlocked: ${e.name ?? ""}`), this._defer(() => {
407
+ let e = t.getBoundingClientRect();
408
+ this.particleSystem.confetti(e.left + e.width / 2, e.top + e.height / 2, 40);
409
+ }, 300), this._defer(() => {
410
+ t.style.animation = "slideOut 0.3s ease-in forwards", this._defer(() => this._remove(t), 300);
411
+ }, 4e3);
412
+ }
413
+ showLevelUp(e, t) {
414
+ let n = document.createElement("div");
415
+ n.className = "level-up-overlay", n.innerHTML = "\n <div class=\"level-up-content\">\n <div class=\"level-up-title\">LEVEL UP!</div>\n <div class=\"level-up-number\"></div>\n <div class=\"level-up-subtitle\">Amazing progress!</div>\n </div>\n ", n.querySelector(".level-up-number").textContent = t, this._mount(n), this._announce(`Level up: ${t}`), this._defer(() => {
416
+ for (let e = 0; e < 5; e++) this._defer(() => {
417
+ let e = Math.random() * window.innerWidth, t = Math.random() * window.innerHeight * .6;
418
+ this.particleSystem.confetti(e, t, 30);
419
+ }, e * 200);
420
+ }, 300), this._defer(() => {
421
+ n.style.opacity = "0", this._defer(() => this._remove(n), 500);
422
+ }, 2500);
423
+ }
424
+ showFloatingText(e, t, n, r = "#ffd700", i = "24px") {
425
+ let a = document.createElement("div");
426
+ a.className = "floating-text", a.textContent = e, a.style.left = t + "px", a.style.top = n + "px", a.style.color = r, a.style.fontSize = i, this._mount(a), this._defer(() => this._remove(a), 2e3);
427
+ }
428
+ showCombo(e, t, n) {
429
+ this.showFloatingText(`${e}× COMBO!`, t, n, "#ff6b6b", "32px"), this.particleSystem.fire(t, n, 20);
430
+ }
431
+ showNearMiss(e, t) {
432
+ this.showFloatingText("CLOSE CALL!", e, t, "#45b7d1", "20px"), this.particleSystem.sparkle(e, t, 15, "#45b7d1");
433
+ }
434
+ showLuckyMoment(e, t, n) {
435
+ this.showFloatingText(`LUCKY ${e}×!`, t, n, "#ffd700", "36px"), this.particleSystem.starBurst(t, n, 12), this.particleSystem.confetti(t, n, 25);
436
+ }
437
+ showNotification(e, t = "normal") {
438
+ let n = window.innerWidth / 2, r = window.innerHeight / 3;
439
+ t === "legendary" ? (this.showFloatingText(e, n, r, "#ffd700", "36px"), this.particleSystem.starBurst(n, r, 12), this.particleSystem.confetti(n, r, 25)) : t === "rare" ? (this.showFloatingText(e, n, r, "#ff6b6b", "32px"), this.particleSystem.fire(n, r, 20)) : this.showFloatingText(e, n, r, "#fff", "24px"), this._announce(e);
440
+ }
441
+ showSummary(e) {
442
+ let t = document.createElement("div");
443
+ t.className = "message-box", t.style.display = "flex", t.style.position = "absolute", t.style.top = "50%", t.style.left = "50%", t.style.transform = "translate(-50%, -50%)", t.style.zIndex = "1000";
444
+ let n = document.createElement("h1");
445
+ n.textContent = "Game Over";
446
+ let r = document.createElement("div");
447
+ r.className = "summary-score", r.style.cssText = "font-size: 3rem; font-weight: bold; color: #e06020; margin: 10px 0;", r.textContent = e.score;
448
+ let i = document.createElement("div");
449
+ i.className = "summary-metrics", i.style.cssText = "width: 100%; margin-bottom: 20px;";
450
+ for (let [t, n] of Object.entries(e.metrics || {})) {
451
+ let e = document.createElement("div");
452
+ e.style.cssText = "display:flex;justify-content:space-between;width:100%";
453
+ let r = document.createElement("span");
454
+ r.textContent = `${t}:`;
455
+ let a = document.createElement("strong");
456
+ a.textContent = n, e.append(r, a), i.appendChild(e);
457
+ }
458
+ t.append(n, r, i);
459
+ let a = document.createElement("button");
460
+ if (a.className = "btn", a.textContent = "Play Again", a.addEventListener("click", e.onReplay || (() => window.location.reload())), t.appendChild(a), e.onExit) {
461
+ let n = document.createElement("button");
462
+ n.className = "btn", n.textContent = "Exit", n.style.cssText = "margin-top: 10px; background: #543847;", n.addEventListener("click", e.onExit), t.appendChild(n);
463
+ }
464
+ return this._mount(t), t;
465
+ }
466
+ _remove(e) {
467
+ e.remove();
468
+ let t = this._detached.indexOf(e);
469
+ t > -1 && this._detached.splice(t, 1);
470
+ }
471
+ destroy() {
472
+ for (let e of this._timers) clearTimeout(e);
473
+ this._timers.clear();
474
+ for (let e of this._detached) e.remove();
475
+ this._detached = [], this.container?.remove(), this.container = null, this.liveRegion = null, this.xpBar = null, this.xpText = null, this.levelBadge = null, this.streakBadge = null, this.levelDisplay = null, this.streakDisplay = null;
476
+ }
477
+ }, F = class {
478
+ constructor(e = {}) {
479
+ this.container = e.container ? typeof e.container == "string" ? document.querySelector(e.container) : e.container : document.body, this.container ||= (console.warn(`[DopamineJS] Particle container '${e.container}' not found. Using document.body.`), document.body), this.maxParticles = Number.isFinite(e.maxParticles) ? Math.max(0, Math.floor(e.maxParticles)) : 5e3, this._reducedMotion = e.respectReducedMotion !== !1 && typeof window.matchMedia == "function" ? window.matchMedia("(prefers-reduced-motion: reduce)") : null, this.canvasId = e.canvasId || "dopamine-particle-canvas", this.canvas = document.createElement("canvas"), this.canvas.classList.add("dopamine-particle-canvas"), document.getElementById(this.canvasId) || (this.canvas.id = this.canvasId), this.canvas.style.pointerEvents = "none", this.canvas.style.zIndex = e.zIndex || "9999", this.container === document.body ? (this.canvas.style.position = "fixed", this.canvas.style.top = "0", this.canvas.style.left = "0") : (this.canvas.style.position = "absolute", this.canvas.style.top = "0", this.canvas.style.left = "0", window.getComputedStyle(this.container).position === "static" && (this.container.style.position = "relative")), this.container.appendChild(this.canvas), this.ctx = this.canvas.getContext("2d"), this.particles = [], this.pool = [], this.sprites = /* @__PURE__ */ new Map(), this.customEffects = /* @__PURE__ */ new Map(), this.isAnimating = !1, this._onResize = () => this._resize(), this._resizeObserver = null, this._frameHandle = null, this._lastFrameTime = null, this._resize(), window.ResizeObserver && this.container !== document.body ? (this._resizeObserver = new ResizeObserver(this._onResize), this._resizeObserver.observe(this.container)) : window.addEventListener("resize", this._onResize);
480
+ }
481
+ _resize() {
482
+ let e = this.container === document.body ? window.innerWidth : this.container.clientWidth, t = this.container === document.body ? window.innerHeight : this.container.clientHeight, n = window.devicePixelRatio || 1;
483
+ this.width = e, this.height = t, this.canvas.width = Math.round(e * n), this.canvas.height = Math.round(t * n), this.canvas.style.width = `${e}px`, this.canvas.style.height = `${t}px`, this.ctx.setTransform(n, 0, 0, n, 0, 0);
484
+ }
485
+ registerSprite(e, t) {
486
+ let n = new Image();
487
+ n.src = t, this.sprites.set(e, n);
488
+ }
489
+ registerEffect(e, t) {
490
+ this.customEffects.set(e, t);
491
+ }
492
+ play(e, t, n, ...r) {
493
+ let i = this.customEffects.get(e);
494
+ i ? i(t, n, ...r) : console.warn(`[DopamineJS] Effect '${e}' not found.`);
495
+ }
496
+ emit(e) {
497
+ let { x: t, y: n, count: r = 10, speed: i = 5, gravity: a = .1, decay: o = .02, life: s = 1, color: c = "#ffd700", sprite: l = null, spread: u = Math.PI * 2, angle: d = 0, size: f = 5, type: p = null } = e, m = this._allowed(r);
498
+ for (let e = 0; e < m; e++) {
499
+ let e = this._getParticle(), r = d + (Math.random() - .5) * u, m = Math.random() * i;
500
+ e.x = t, e.y = n, e.vx = Math.cos(r) * m, e.vy = Math.sin(r) * m, e.life = s, e.decay = o * (.8 + Math.random() * .4), e.gravity = a, e.color = Array.isArray(c) ? c[Math.floor(Math.random() * c.length)] : c, e.size = f * (.8 + Math.random() * .4), e.sprite = l, e.type = p, e.rotation = Math.random() * Math.PI * 2, e.rotationSpeed = (Math.random() - .5) * .2, this.particles.push(e);
501
+ }
502
+ m > 0 && this._startAnimation();
503
+ }
504
+ _allowed(e) {
505
+ if (this._reducedMotion?.matches || !Number.isFinite(e)) return 0;
506
+ let t = this.maxParticles - this.particles.length;
507
+ return Math.max(0, Math.min(Math.floor(e), t));
508
+ }
509
+ _getParticle() {
510
+ return this.pool.length > 0 ? this.pool.pop() : {};
511
+ }
512
+ _recycleParticle(e) {
513
+ this.pool.push(e);
514
+ }
515
+ confetti(e, t, n = 50) {
516
+ this.emit({
517
+ x: e,
518
+ y: t,
519
+ count: n,
520
+ color: [
521
+ "#ff6b6b",
522
+ "#4ecdc4",
523
+ "#45b7d1",
524
+ "#f7dc6f",
525
+ "#c06c84",
526
+ "#6c5ce7"
527
+ ],
528
+ speed: 10,
529
+ gravity: .3,
530
+ decay: .015,
531
+ size: 8,
532
+ spread: Math.PI * 2
533
+ });
534
+ }
535
+ coinShower(e, t, n = 10) {
536
+ this.emit({
537
+ x: e,
538
+ y: t,
539
+ count: n,
540
+ color: "#ffd700",
541
+ speed: 4,
542
+ gravity: .4,
543
+ decay: .012,
544
+ size: 12,
545
+ angle: -Math.PI / 2,
546
+ spread: Math.PI / 2
547
+ });
548
+ }
549
+ sparkle(e, t, n = 20, r = "#ffd700") {
550
+ this.emit({
551
+ x: e,
552
+ y: t,
553
+ count: n,
554
+ color: r,
555
+ speed: 3,
556
+ gravity: -.05,
557
+ decay: .03,
558
+ size: 3
559
+ });
560
+ }
561
+ fire(e, t, n = 15) {
562
+ this.emit({
563
+ x: e,
564
+ y: t,
565
+ count: n,
566
+ color: [
567
+ "#ff6b00",
568
+ "#ff8800",
569
+ "#ffaa00",
570
+ "#ff4400"
571
+ ],
572
+ speed: 3,
573
+ gravity: -.2,
574
+ decay: .04,
575
+ size: 5,
576
+ angle: -Math.PI / 2,
577
+ spread: Math.PI / 4
578
+ });
579
+ }
580
+ starBurst(e, t, n = 8) {
581
+ let r = this._allowed(n);
582
+ for (let n = 0; n < r; n++) {
583
+ let i = this._getParticle(), a = Math.PI * 2 / r * n;
584
+ i.x = e, i.y = t, i.vx = Math.cos(a) * 4, i.vy = Math.sin(a) * 4, i.life = 1, i.decay = .03, i.gravity = 0, i.color = "#ffffff", i.size = 15, i.sprite = null, i.type = "star", i.rotation = a, i.rotationSpeed = 0, this.particles.push(i);
585
+ }
586
+ r > 0 && this._startAnimation();
587
+ }
588
+ _startAnimation() {
589
+ this.isAnimating || (this.isAnimating = !0, this._lastFrameTime = null, this._animate());
590
+ }
591
+ _animate(e) {
592
+ this._frameHandle = null, this.ctx.clearRect(0, 0, this.width, this.height);
593
+ let t = 1;
594
+ Number.isFinite(e) && (this._lastFrameTime !== null && (t = Math.max(0, Math.min(3, (e - this._lastFrameTime) / (1e3 / 60)))), this._lastFrameTime = e);
595
+ for (let e = this.particles.length - 1; e >= 0; e--) {
596
+ let n = this.particles[e];
597
+ if (n.vy += n.gravity * t, n.x += n.vx * t, n.y += n.vy * t, n.life -= n.decay * t, n.rotationSpeed && (n.rotation += n.rotationSpeed * t), n.life <= 0) {
598
+ this._recycleParticle(n);
599
+ let t = this.particles.pop();
600
+ e < this.particles.length && (this.particles[e] = t);
601
+ continue;
602
+ }
603
+ if (this.ctx.save(), this.ctx.globalAlpha = n.life, this.ctx.translate(n.x, n.y), this.ctx.rotate(n.rotation), n.sprite && this.sprites.has(n.sprite)) {
604
+ let e = this.sprites.get(n.sprite);
605
+ e.complete && this.ctx.drawImage(e, -n.size / 2, -n.size / 2, n.size, n.size);
606
+ } else n.type === "star" ? (this.ctx.fillStyle = n.color, this._drawStarPath(0, 0, 5, n.size, n.size / 2), this.ctx.fill()) : (this.ctx.fillStyle = n.color, this.ctx.beginPath(), this.ctx.arc(0, 0, n.size, 0, Math.PI * 2), this.ctx.fill());
607
+ this.ctx.restore();
608
+ }
609
+ this.particles.length > 0 ? this._frameHandle = requestAnimationFrame((e) => this._animate(e)) : this.isAnimating = !1;
610
+ }
611
+ _drawStarPath(e, t, n, r, i) {
612
+ let a = Math.PI / 2 * 3, o = e, s = t, c = Math.PI / n;
613
+ this.ctx.beginPath(), this.ctx.moveTo(e, t - r);
614
+ for (let l = 0; l < n; l++) o = e + Math.cos(a) * r, s = t + Math.sin(a) * r, this.ctx.lineTo(o, s), a += c, o = e + Math.cos(a) * i, s = t + Math.sin(a) * i, this.ctx.lineTo(o, s), a += c;
615
+ this.ctx.lineTo(e, t - r), this.ctx.closePath();
616
+ }
617
+ clear() {
618
+ this.particles.forEach((e) => this._recycleParticle(e)), this.particles = [], this.ctx.clearRect(0, 0, this.width, this.height);
619
+ }
620
+ destroy() {
621
+ this.clear(), this.isAnimating = !1, this._frameHandle !== null && (cancelAnimationFrame(this._frameHandle), this._frameHandle = null), this._resizeObserver &&= (this._resizeObserver.disconnect(), null), window.removeEventListener("resize", this._onResize), this.canvas.remove(), this.sprites.clear(), this.customEffects.clear(), this.pool = [];
622
+ }
623
+ }, I = (e, t) => Object.prototype.hasOwnProperty.call(e, t), L = class {
624
+ constructor(e = {}) {
625
+ this.audioContext = null, this.storageKey = e.storageKey || "dopamineSoundsMuted", this.storage = e.storage || j(), this.muted = this.storage.getItem(this.storageKey) === "true", this.assets = /* @__PURE__ */ new Map(), this.customSounds = e.customSounds || {}, this.masterGain = null, this._volume = 1, this.setVolume(e.volume ?? 1), this._loading = /* @__PURE__ */ new Map(), this._timers = /* @__PURE__ */ new Set();
626
+ }
627
+ _later(e, t) {
628
+ let n = setTimeout(() => {
629
+ this._timers.delete(n), e();
630
+ }, t);
631
+ this._timers.add(n);
632
+ }
633
+ initAudio() {
634
+ if (!this.audioContext) {
635
+ let e = typeof window < "u" ? window.AudioContext || window.webkitAudioContext : void 0;
636
+ if (!e) return !1;
637
+ this.audioContext = new e(), this.masterGain = this.audioContext.createGain(), this.masterGain.gain.value = this._volume, this.masterGain.connect(this.audioContext.destination), this.preloadSounds(this.customSounds);
638
+ }
639
+ return this.audioContext.state === "suspended" && this.audioContext.resume(), !0;
640
+ }
641
+ setVolume(e) {
642
+ return Number.isFinite(e) ? (this._volume = Math.max(0, Math.min(1, e)), this.masterGain && (this.masterGain.gain.value = this._volume), this._volume) : this._volume;
643
+ }
644
+ getVolume() {
645
+ return this._volume;
646
+ }
647
+ _output() {
648
+ return this.masterGain || this.audioContext.destination;
649
+ }
650
+ toggleMute() {
651
+ return this.muted = !this.muted, this.storage.setItem(this.storageKey, this.muted), this.muted;
652
+ }
653
+ registerSound(e, t) {
654
+ this.customSounds[e] = t, this.audioContext && this.loadSound(e, t);
655
+ }
656
+ async preloadSounds(e) {
657
+ let t = Object.entries(e).map(([e, t]) => (this.customSounds[e] = t, this.loadSound(e, t)));
658
+ await Promise.allSettled(t);
659
+ }
660
+ async loadSound(e, t) {
661
+ if (!this.audioContext) return;
662
+ if (this._loading.has(e)) return this._loading.get(e);
663
+ let n = this._load(e, t).finally(() => this._loading.delete(e));
664
+ return this._loading.set(e, n), n;
665
+ }
666
+ async _load(e, t) {
667
+ try {
668
+ let n = this.audioContext, r = await fetch(t);
669
+ if (r.ok === !1) throw Error(`HTTP ${r.status}`);
670
+ let i = await r.arrayBuffer(), a = await n.decodeAudioData(i);
671
+ this.audioContext === n && this.assets.set(e, a);
672
+ } catch (t) {
673
+ console.warn(`[DopamineJS] Failed to load sound '${e}':`, t);
674
+ }
675
+ }
676
+ async play(e) {
677
+ if (this.muted || !this.initAudio()) return;
678
+ if (this.assets.has(e)) {
679
+ this._playBuffer(this.assets.get(e));
680
+ return;
681
+ }
682
+ if (I(this.customSounds, e) && !this.assets.has(e)) {
683
+ let t = this.audioContext;
684
+ if (await this.loadSound(e, this.customSounds[e]), this.audioContext !== t) return;
685
+ if (this.assets.has(e)) {
686
+ this._playBuffer(this.assets.get(e));
687
+ return;
688
+ }
689
+ }
690
+ let t = {
691
+ jump: () => this.playJump(!0),
692
+ score: () => this.playScore(!0),
693
+ success: () => this.playSuccess(!0),
694
+ click: () => this.playClick(!0),
695
+ error: () => this.playError(!0),
696
+ gameover: () => this.playGameOver(!0)
697
+ };
698
+ I(t, e) && t[e]();
699
+ }
700
+ _playBuffer(e) {
701
+ let t = this.audioContext.createBufferSource();
702
+ t.buffer = e, t.connect(this._output()), t.start(0);
703
+ }
704
+ playTone(e, t, n = "sine", r = .3) {
705
+ if (this.muted || !this.initAudio()) return;
706
+ let i = this.audioContext.createOscillator(), a = this.audioContext.createGain();
707
+ i.connect(a), a.connect(this._output()), i.frequency.value = e, i.type = n;
708
+ let o = Math.max(1e-4, r);
709
+ a.gain.setValueAtTime(o, this.audioContext.currentTime), a.gain.exponentialRampToValueAtTime(.01, this.audioContext.currentTime + t), i.start(this.audioContext.currentTime), i.stop(this.audioContext.currentTime + t);
710
+ }
711
+ playJump(e = !1) {
712
+ if (!e && this.assets.has("jump")) return this.play("jump");
713
+ this.playTone(400, .1, "square", .2);
714
+ }
715
+ playScore(e = !1) {
716
+ if (!e && this.assets.has("score")) return this.play("score");
717
+ this.playTone(800, .15, "sine", .25), this._later(() => this.playTone(1e3, .15, "sine", .25), 50);
718
+ }
719
+ playGameOver(e = !1) {
720
+ if (!e && this.assets.has("gameover")) return this.play("gameover");
721
+ this.playTone(300, .2, "sawtooth", .3), this._later(() => this.playTone(200, .2, "sawtooth", .3), 100), this._later(() => this.playTone(150, .3, "sawtooth", .3), 200);
722
+ }
723
+ playClick(e = !1) {
724
+ if (!e && this.assets.has("click")) return this.play("click");
725
+ this.playTone(600, .05, "sine", .1);
726
+ }
727
+ playSuccess(e = !1) {
728
+ if (!e && this.assets.has("success")) return this.play("success");
729
+ this.playTone(600, .1, "sine", .2), this._later(() => this.playTone(800, .2, "sine", .2), 100);
730
+ }
731
+ playError(e = !1) {
732
+ if (!e && this.assets.has("error")) return this.play("error");
733
+ this.playTone(200, .2, "sawtooth", .3);
734
+ }
735
+ destroy() {
736
+ for (let e of this._timers) clearTimeout(e);
737
+ this._timers.clear(), this.audioContext && (this.audioContext.close?.())?.catch?.(() => {}), this.audioContext = null, this.masterGain = null, this.assets.clear(), this._loading.clear();
738
+ }
739
+ }, R = class {
740
+ constructor(e = {}) {
741
+ this.config = e, this.dataService = new M(e.data || {}), this.rewardSystem = new k(this.dataService, e.rewards || {}), this.soundManager = new L(e.sound || {}), this.particleSystem = new F(e.particles || {}), this.gameUI = new P(this.particleSystem), this._bindEvents();
742
+ }
743
+ async init() {
744
+ return await this.rewardSystem.init(), this._syncUI(), {
745
+ rewardSystem: this.rewardSystem,
746
+ gameUI: this.gameUI,
747
+ particleSystem: this.particleSystem,
748
+ soundManager: this.soundManager
749
+ };
750
+ }
751
+ _syncUI() {
752
+ let { player: e } = this.rewardSystem, { total: t, needed: n, progress: r } = this.rewardSystem.getXPForNextLevel();
753
+ this.gameUI.updateXP(e.xp, n, t, r), this.gameUI.updateLevel(e.level), this.gameUI.updateStreak(e.streak.current);
754
+ }
755
+ _bindEvents() {
756
+ let e = this.rewardSystem;
757
+ this._unsubscribe = [
758
+ e.on("xp_gained", () => {
759
+ let { total: t, needed: n, progress: r } = e.getXPForNextLevel();
760
+ this.gameUI.updateXP(e.player.xp, n, t, r);
761
+ }),
762
+ e.on("level_up", (e) => {
763
+ this.gameUI.updateLevel(e.newLevel), this.gameUI.showLevelUp(e.oldLevel, e.newLevel);
764
+ }),
765
+ e.on("achievement_unlocked", (e) => {
766
+ this.gameUI.showAchievement(e);
767
+ }),
768
+ e.on("streak_updated", (e) => {
769
+ this.gameUI.updateStreak(e.current);
770
+ }),
771
+ e.on("new_high_score", (e) => {
772
+ this.gameUI.showNotification(`New High Score: ${e.score}!`, "legendary"), this.soundManager.playSuccess();
773
+ })
774
+ ];
775
+ }
776
+ destroy() {
777
+ for (let e of this._unsubscribe) e();
778
+ this._unsubscribe = [], this.gameUI.destroy(), this.particleSystem.destroy(), this.soundManager.destroy();
779
+ }
780
+ }, z = {
781
+ init(e) {},
782
+ update(e) {},
783
+ fixedUpdate(e) {},
784
+ destroy() {}
785
+ }, B = class {
786
+ constructor() {
787
+ this.kernel = null;
788
+ }
789
+ init(e) {
790
+ this.kernel = e;
791
+ }
792
+ update(e) {}
793
+ fixedUpdate(e) {}
794
+ destroy() {}
795
+ }, V = {
796
+ ...z,
797
+ addBody(e) {},
798
+ removeBody(e) {},
799
+ checkCollision(e, t) {},
800
+ raycast(e, t, n) {},
801
+ setGravity(e, t) {},
802
+ step(e) {}
803
+ }, H = {
804
+ ...z,
805
+ registerSound(e, t) {},
806
+ preloadSounds(e) {},
807
+ play(e, t) {},
808
+ playTone(e, t, n, r) {},
809
+ stop(e) {},
810
+ toggleMute() {},
811
+ setVolume(e) {}
1285
812
  }, U = {
1286
- ..._,
1287
- /**
1288
- * Register a sprite for particles
1289
- * @param {string} key - Sprite identifier
1290
- * @param {string} url - Path to image
1291
- */
1292
- registerSprite(r, t) {
1293
- },
1294
- /**
1295
- * Register a custom effect
1296
- * @param {string} name - Effect name
1297
- * @param {Function} callback - Effect function (x, y, ...args) => void
1298
- */
1299
- registerEffect(r, t) {
1300
- },
1301
- /**
1302
- * Play a registered effect
1303
- * @param {string} name - Effect name
1304
- * @param {number} x - X position
1305
- * @param {number} y - Y position
1306
- * @param {...any} args - Additional arguments
1307
- */
1308
- play(r, t, e, ...s) {
1309
- },
1310
- /**
1311
- * Emit particles with custom configuration
1312
- * @param {Object} config - Particle configuration
1313
- */
1314
- emit(r) {
1315
- },
1316
- /**
1317
- * Clear all particles
1318
- */
1319
- clear() {
1320
- },
1321
- // Built-in effects (optional, but recommended)
1322
- confetti(r, t, e) {
1323
- },
1324
- coinShower(r, t, e) {
1325
- },
1326
- sparkle(r, t, e, s) {
1327
- },
1328
- fire(r, t, e) {
1329
- },
1330
- starBurst(r, t, e) {
1331
- }
813
+ ...z,
814
+ registerSprite(e, t) {},
815
+ registerEffect(e, t) {},
816
+ play(e, t, n, ...r) {},
817
+ emit(e) {},
818
+ clear() {},
819
+ confetti(e, t, n) {},
820
+ coinShower(e, t, n) {},
821
+ sparkle(e, t, n, r) {},
822
+ fire(e, t, n) {},
823
+ starBurst(e, t, n) {}
824
+ }, W = class {
825
+ static createGround(e, t, n = "#333") {
826
+ let r = document.createElement("canvas");
827
+ r.width = e, r.height = t;
828
+ let i = r.getContext("2d");
829
+ i.fillStyle = n, i.fillRect(0, 0, e, t);
830
+ for (let n = 0; n < 1e3; n++) {
831
+ i.fillStyle = Math.random() > .5 ? "#444" : "#222";
832
+ let n = Math.random() * 4 + 2;
833
+ i.fillRect(Math.random() * e, Math.random() * t, n, n);
834
+ }
835
+ i.strokeStyle = "rgba(255,255,255,0.05)", i.lineWidth = 2, i.beginPath();
836
+ for (let n = 0; n <= e; n += 64) i.moveTo(n, 0), i.lineTo(n, t);
837
+ for (let n = 0; n <= t; n += 64) i.moveTo(0, n), i.lineTo(e, n);
838
+ return i.stroke(), r;
839
+ }
840
+ static createCharacterSheet(e, t) {
841
+ let n = document.createElement("canvas");
842
+ n.width = 256, n.height = 64;
843
+ let r = n.getContext("2d");
844
+ for (let n = 0; n < 4; n++) {
845
+ let i = n * 64 + 32, a = n % 2 == 0 ? 0 : -2, o = n === 1 ? 5 : n === 3 ? -5 : 0;
846
+ r.fillStyle = e, r.beginPath(), r.arc(i, 32 + a, 20, 0, Math.PI * 2), r.fill(), r.fillStyle = t, r.beginPath(), r.arc(i - 15, 32 + a + o, 8, 0, Math.PI * 2), r.arc(i + 15, 32 + a - o, 8, 0, Math.PI * 2), r.fill(), r.fillStyle = G(e, -20), r.beginPath(), r.arc(i, 32 + a, 15, 0, Math.PI * 2), r.fill(), t === "#333" && (r.fillStyle = "#000", r.fillRect(i + 10, 32 + a - 5, 25, 6));
847
+ }
848
+ return n;
849
+ }
1332
850
  };
1333
- class $ {
1334
- static createGround(t, e, s = "#333") {
1335
- const i = document.createElement("canvas");
1336
- i.width = t, i.height = e;
1337
- const n = i.getContext("2d");
1338
- n.fillStyle = s, n.fillRect(0, 0, t, e);
1339
- for (let a = 0; a < 1e3; a++) {
1340
- n.fillStyle = Math.random() > 0.5 ? "#444" : "#222";
1341
- const o = Math.random() * 4 + 2;
1342
- n.fillRect(Math.random() * t, Math.random() * e, o, o);
1343
- }
1344
- n.strokeStyle = "rgba(255,255,255,0.05)", n.lineWidth = 2, n.beginPath();
1345
- for (let a = 0; a <= t; a += 64)
1346
- n.moveTo(a, 0), n.lineTo(a, e);
1347
- for (let a = 0; a <= e; a += 64)
1348
- n.moveTo(0, a), n.lineTo(t, a);
1349
- return n.stroke(), i;
1350
- }
1351
- static createCharacterSheet(t, e) {
1352
- const n = document.createElement("canvas");
1353
- n.width = 256, n.height = 64;
1354
- const a = n.getContext("2d");
1355
- for (let o = 0; o < 4; o++) {
1356
- const l = o * 64, h = 0, d = l + 64 / 2, u = h + 64 / 2, p = o % 2 === 0 ? 0 : -2, g = o === 1 ? 5 : o === 3 ? -5 : 0;
1357
- a.fillStyle = t, a.beginPath(), a.arc(d, u + p, 20, 0, Math.PI * 2), a.fill(), a.fillStyle = e, a.beginPath(), a.arc(d - 15, u + p + g, 8, 0, Math.PI * 2), a.arc(d + 15, u + p - g, 8, 0, Math.PI * 2), a.fill(), a.fillStyle = O(t), a.beginPath(), a.arc(d, u + p, 15, 0, Math.PI * 2), a.fill(), e === "#333" && (a.fillStyle = "#000", a.fillRect(d + 10, u + p - 5, 25, 6));
1358
- }
1359
- return n;
1360
- }
851
+ function G(e, t) {
852
+ return e;
1361
853
  }
1362
- function O(r, t) {
1363
- return r;
1364
- }
1365
- export {
1366
- j as Animator,
1367
- X as Collider,
1368
- J as Component,
1369
- I as DataService,
1370
- V as Director,
1371
- W as DopamineKernel,
1372
- K as EventBus,
1373
- T as EventEmitter,
1374
- Y as Game,
1375
- Q as GameObject,
1376
- L as GameUI,
1377
- Z as GlobalInput,
1378
- tt as GlobalLoader,
1379
- et as GlobalPhysics,
1380
- B as IAudioSystem,
1381
- U as IParticleSystem,
1382
- R as IPhysicsSystem,
1383
- _ as ISystem,
1384
- st as Input,
1385
- it as Loader,
1386
- at as ParticleEmitter,
1387
- z as ParticleSystem,
1388
- nt as Physics,
1389
- rt as PluginRegistry,
1390
- ot as Renderer,
1391
- D as RewardSystem,
1392
- lt as Scene,
1393
- ct as ScreenShake,
1394
- F as SoundManager,
1395
- ht as Sprite,
1396
- G as System,
1397
- dt as SystemRegistry,
1398
- $ as TextureGenerator,
1399
- ut as Ticker,
1400
- pt as Vector2,
1401
- P as createMemoryStorage,
1402
- N as default,
1403
- A as resolveStorage
1404
- };
854
+ //#endregion
855
+ //#region src/index.js
856
+ var K = R;
857
+ //#endregion
858
+ export { g as Animator, n as Collider, b as Component, M as DataService, a as Director, y as DopamineKernel, e as EventBus, C as EventEmitter, _ as Game, m as GameObject, P as GameUI, h as GlobalInput, o as GlobalLoader, l as GlobalPhysics, H as IAudioSystem, U as IParticleSystem, V as IPhysicsSystem, z as ISystem, f as Input, s as Loader, p as ParticleEmitter, F as ParticleSystem, c as Physics, x as PluginRegistry, i as Renderer, k as RewardSystem, d as Scene, v as ScreenShake, L as SoundManager, u as Sprite, B as System, t as SystemRegistry, W as TextureGenerator, S as Ticker, r as Vector2, A as createMemoryStorage, K as default, j as resolveStorage };