dopaminejs 2.4.0 → 2.5.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/DataService-BPXCldpo.cjs +1 -0
- package/dist/DataService-CH9_gv_8.js +398 -0
- package/dist/core.cjs +1 -0
- package/dist/core.js +2 -0
- package/dist/dopamine.cjs +7 -7
- package/dist/dopamine.js +164 -387
- package/package.json +6 -1
- package/src/dopamine/audio/SoundManager.js +24 -0
- package/src/dopamine/core/DataService.js +25 -5
- package/src/dopamine/core/RewardSystem.js +50 -2
- package/src/dopamine/effects/ParticleSystem.js +3 -3
- package/src/dopamine/feel/haptics.js +21 -0
- package/src/dopamine/feel/motion.js +9 -0
- package/src/dopamine/ui/GameUI.js +193 -8
- package/src/index.js +4 -0
- package/src/progression.js +13 -0
- package/types/core.d.ts +27 -0
- package/types/index.d.ts +73 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(n=>{try{n(t)}catch(t){console.error(`Error in listener for event '${e}':`,t)}})}clear(){this.listeners.clear()}},t=new Set([`__proto__`,`constructor`,`prototype`]),n=e=>typeof e==`string`&&e.length>0&&!t.has(e),r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i=e=>typeof e==`object`&&!!e&&!Array.isArray(e),a=(e,t,n=0)=>{let r=Number(e);return Number.isInteger(r)&&r>=n?r:t},o=class extends e{constructor(e,t={}){super(),this.dataService=e,this.player=null,this.achievements={...this._initAchievements(),...t.achievements||{}},this.events=t.events||t.kernel?.events||null,this._batchDepth=0,this._pendingSave=!1,this._loadFailed=!1,this._readFailed=!1}get loadFailed(){return this._readFailed}_publish(e,t){this.emit(e,t),this.events&&this.events.emit(e,t)}async _batch(e){this._batchDepth++;try{return await e()}finally{this._batchDepth--,this._batchDepth===0&&this._pendingSave&&(this._pendingSave=!1,await this._write())}}async init(){let e=await this._readSaved();this._loadFailed&&this.player||(this.player=this._migrate(e));let t=this._updateDailyStreak();return await this.save(),t&&this._publishStreak(),this.player}async _readSaved(){this._loadFailed=!0;try{let e=await this.dataService.load(`player`,null,{strict:!0});return this._loadFailed=!1,this._readFailed=!1,e}catch(e){if(e?.code===`DOPAMINE_CORRUPT`){let t=await this.dataService.save(`player_corrupt`,e.raw);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}return this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null}}_requirePlayer(){if(!this.player)throw Error(`[DopamineJS] RewardSystem.init() must be awaited before use`)}_publishStreak(){let{current:e,longest:t}=this.player.streak;this._publish(`streak_updated`,{current:e,longest:t})}_getDefaultPlayer(){return{name:`Player`,xp:0,level:1,totalGamesPlayed:0,createdAt:Date.now(),lastPlayedAt:Date.now(),streak:{current:1,longest:1,lastPlayDate:this._getTodayDateString()},achievements:{},stats:{}}}_migrate(e){let t=this._getDefaultPlayer();if(!i(e))return t;let n=Number(e.xp),r=Number.isFinite(n)&&n>=0?n:0,o=this._calculateLevel(r),s=i(e.streak)?e.streak:{},c=a(s.current,1,1),l=typeof s.lastPlayDate==`string`&&/^\d{4}-\d{2}-\d{2}$/.test(s.lastPlayDate)?s.lastPlayDate:t.streak.lastPlayDate;return{...t,...e,name:typeof e.name==`string`?e.name:t.name,xp:r,level:Math.max(o,a(e.level,o,1)),totalGamesPlayed:a(e.totalGamesPlayed,0),createdAt:Number.isFinite(e.createdAt)?e.createdAt:t.createdAt,lastPlayedAt:Number.isFinite(e.lastPlayedAt)?e.lastPlayedAt:t.lastPlayedAt,streak:{current:c,longest:Math.max(c,a(s.longest,c,1)),lastPlayDate:l},achievements:this._migrateAchievements(e.achievements),stats:this._migrateStats(e.stats)}}_migrateAchievements(e){let t={};if(!i(e))return t;for(let r of Object.keys(e)){let a=e[r];n(r)&&i(a)&&(t[r]={unlockedAt:Number.isFinite(a.unlockedAt)?a.unlockedAt:Date.now(),seen:a.seen===!0})}return t}_migrateStats(e){let t={};if(!i(e))return t;for(let r of Object.keys(e)){let o=e[r];if(!n(r)||!i(o))continue;let s={};for(let e of Object.keys(o))n(e)&&Number.isFinite(o[e])&&(s[e]=o[e]);s.totalPlays=a(o.totalPlays,0),s.highScore=Number.isFinite(o.highScore)?o.highScore:0,t[r]=s}return t}async save(){if(this.player){if(this._batchDepth>0){this._pendingSave=!0;return}await this._write()}}async _write(){this._loadFailed||(this.player.lastPlayedAt=Date.now(),await this.dataService.save(`player`,this.player)===!1&&this._publish(`save_failed`,{key:`player`}))}async addXP(e,t=``){if(!Number.isFinite(e))throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);this._requirePlayer();let n=this.player.level;e=Math.max(e,-this.player.xp),this.player.xp+=e;let r=Math.max(n,this._calculateLevel(this.player.xp)),i=r>n;i&&(this.player.level=r),await this.save();let a=this.player.xp;return this._publish(`xp_gained`,{amount:e,reason:t,leveledUp:i,newLevel:r,total:a}),i&&this._publish(`level_up`,{oldLevel:n,newLevel:r,totalXP:a}),{leveledUp:i,newLevel:r,xpGained:e}}_calculateLevel(e){if(!(e>0))return 1;let t=Math.floor((1+Math.sqrt(1+4*e/50))/2);return Math.max(1,t)}getXPForNextLevel(){this._requirePlayer();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;return{total:t,needed:Math.max(0,t-this.player.xp),progress:i}}async recordGame(e,t={}){if(this._requirePlayer(),!n(e))throw TypeError(`[DopamineJS] recordGame expects a game name, received ${String(e)}`);if(!i(t))throw TypeError(`[DopamineJS] recordGame expects a result object`);if(t.score!==void 0&&!Number.isFinite(t.score))throw TypeError(`[DopamineJS] recordGame expects a finite score, received ${String(t.score)}`);return this._batch(()=>this._recordGame(e,t))}async _recordGame(e,t){this._updateDailyStreak()&&this._publishStreak(),r(this.player.stats,e)||(this.player.stats[e]={totalPlays:0,highScore:0});let i=this.player.stats[e];i.totalPlays++,this.player.totalGamesPlayed++,t.score!==void 0&&t.score>i.highScore&&(i.highScore=t.score,this._publish(`new_high_score`,{gameName:e,score:t.score})),Object.keys(t).forEach(e=>{if(e!==`score`&&n(e)){let n=r(i,e)&&Number.isFinite(i[e])?i[e]:0;i[e]=n+(Number.isFinite(t[e])?t[e]:0)}});let a=10;t.score&&(a+=Math.max(0,Math.floor(t.score/5))),a=Math.floor(a*this.getStreakMultiplier()),await this.addXP(a,`Played ${e}`),await this.checkAchievements(e,t),await this.save()}async checkAchievements(e,t){let n=[];for(let[i,a]of Object.entries(this.achievements)){if(r(this.player.achievements,i))continue;let o=!1;try{o=a.check(this.player,e,t)}catch(e){console.error(`[DopamineJS] Achievement "${i}" check threw:`,e);continue}o&&await this.unlockAchievement(i)&&n.push(a)}return n}async unlockAchievement(e){if(this._requirePlayer(),!n(e)||!r(this.achievements,e)||r(this.player.achievements,e))return!1;let t=this.achievements[e];return t?(this.player.achievements[e]={unlockedAt:Date.now(),seen:!1},await this.addXP(Number.isFinite(t.xp)?t.xp:0,`Achievement: ${t.name}`),this._publish(`achievement_unlocked`,{...t,id:e}),await this.save(),!0):!1}getUnlockedAchievements(){return Object.entries(this.player.achievements).map(([e,t])=>({...this.achievements[e],id:e,...t}))}getUnseenAchievements(){return this.getUnlockedAchievements().filter(e=>!e.seen)}async markAchievementsSeen(e){for(let t of e)r(this.player.achievements,t)&&(this.player.achievements[t].seen=!0);await this.save()}_updateDailyStreak(){let e=this._getTodayDateString(),t=this.player.streak.lastPlayDate;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)}getStreakMultiplier(){let e=this.player.streak.current;return e>=7?2:e>=5?1.5:e>=3?1.25:1}_toLocalDateString(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}_getTodayDateString(){return this._toLocalDateString(new Date)}_getYesterdayDateString(){let e=new Date;return e.setDate(e.getDate()-1),this._toLocalDateString(e)}_initAchievements(){return{first_game:{name:`First Steps`,description:`Play your first game`,icon:`🎮`,xp:50,check:e=>e.totalGamesPlayed>=1},level_5:{name:`Rising Star`,description:`Reach level 5`,icon:`⭐`,xp:100,check:e=>e.level>=5},level_10:{name:`Expert Player`,description:`Reach level 10`,icon:`🏆`,xp:250,check:e=>e.level>=10},streak_3:{name:`Dedicated`,description:`Play 3 days in a row`,icon:`🔥`,xp:100,check:e=>e.streak.current>=3},streak_7:{name:`Unstoppable`,description:`Play 7 days in a row`,icon:`💥`,xp:300,check:e=>e.streak.current>=7}}}};function s(){let e=new Map;return{getItem:t=>e.has(t)?e.get(t):null,setItem:(t,n)=>{e.set(t,String(n))},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()}}}function c(){try{if(typeof localStorage>`u`)return s();let e=`__dopamine_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return s()}}var l=class{constructor(e={}){this.storage=e.storage||c(),this.prefix=e.prefix||`dopamine_`,this._tail=null}_write(e){let t=this._tail?this._tail.then(e):e();if(typeof t?.then==`function`){let e=Promise.resolve(t).catch(()=>{}).then(()=>{this._tail===e&&(this._tail=null)});this._tail=e}return t}async save(e,t){try{let n=JSON.stringify(t);return await this._write(()=>this.storage.setItem(this.prefix+e,n)),!0}catch(e){return console.error(`Error saving data:`,e),!1}}async load(e,t=null,n={}){let r;try{await this._tail,r=await this.storage.getItem(this.prefix+e)}catch(e){if(n.strict)throw e;return console.error(`Error loading data:`,e),t}if(!r)return t;try{return JSON.parse(r)}catch(i){if(n.strict)throw Object.assign(Error(`[DopamineJS] saved "${e}" is not valid JSON`),{code:`DOPAMINE_CORRUPT`,raw:r});return console.error(`Error loading data:`,i),t}}async clear(e){await this._write(()=>this.storage.removeItem(this.prefix+e))}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return l}});
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
//#region src/dopamine/core/EventEmitter.js
|
|
2
|
+
var e = class {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.listeners = /* @__PURE__ */ new Map();
|
|
5
|
+
}
|
|
6
|
+
on(e, t) {
|
|
7
|
+
return this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set()), this.listeners.get(e).add(t), () => this.off(e, t);
|
|
8
|
+
}
|
|
9
|
+
off(e, t) {
|
|
10
|
+
this.listeners.has(e) && this.listeners.get(e).delete(t);
|
|
11
|
+
}
|
|
12
|
+
emit(e, t) {
|
|
13
|
+
this.listeners.has(e) && this.listeners.get(e).forEach((n) => {
|
|
14
|
+
try {
|
|
15
|
+
n(t);
|
|
16
|
+
} catch (t) {
|
|
17
|
+
console.error(`Error in listener for event '${e}':`, t);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
clear() {
|
|
22
|
+
this.listeners.clear();
|
|
23
|
+
}
|
|
24
|
+
}, t = /* @__PURE__ */ new Set([
|
|
25
|
+
"__proto__",
|
|
26
|
+
"constructor",
|
|
27
|
+
"prototype"
|
|
28
|
+
]), n = (e) => typeof e == "string" && e.length > 0 && !t.has(e), r = (e, t) => Object.prototype.hasOwnProperty.call(e, t), i = (e) => typeof e == "object" && !!e && !Array.isArray(e), a = (e, t, n = 0) => {
|
|
29
|
+
let r = Number(e);
|
|
30
|
+
return Number.isInteger(r) && r >= n ? r : t;
|
|
31
|
+
}, o = class extends e {
|
|
32
|
+
constructor(e, t = {}) {
|
|
33
|
+
super(), this.dataService = e, this.player = null, this.achievements = {
|
|
34
|
+
...this._initAchievements(),
|
|
35
|
+
...t.achievements || {}
|
|
36
|
+
}, this.events = t.events || t.kernel?.events || null, this._batchDepth = 0, this._pendingSave = !1, this._loadFailed = !1, this._readFailed = !1;
|
|
37
|
+
}
|
|
38
|
+
get loadFailed() {
|
|
39
|
+
return this._readFailed;
|
|
40
|
+
}
|
|
41
|
+
_publish(e, t) {
|
|
42
|
+
this.emit(e, t), this.events && this.events.emit(e, t);
|
|
43
|
+
}
|
|
44
|
+
async _batch(e) {
|
|
45
|
+
this._batchDepth++;
|
|
46
|
+
try {
|
|
47
|
+
return await e();
|
|
48
|
+
} finally {
|
|
49
|
+
this._batchDepth--, this._batchDepth === 0 && this._pendingSave && (this._pendingSave = !1, await this._write());
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async init() {
|
|
53
|
+
let e = await this._readSaved();
|
|
54
|
+
this._loadFailed && this.player || (this.player = this._migrate(e));
|
|
55
|
+
let t = this._updateDailyStreak();
|
|
56
|
+
return await this.save(), t && this._publishStreak(), this.player;
|
|
57
|
+
}
|
|
58
|
+
async _readSaved() {
|
|
59
|
+
this._loadFailed = !0;
|
|
60
|
+
try {
|
|
61
|
+
let e = await this.dataService.load("player", null, { strict: !0 });
|
|
62
|
+
return this._loadFailed = !1, this._readFailed = !1, e;
|
|
63
|
+
} catch (e) {
|
|
64
|
+
if (e?.code === "DOPAMINE_CORRUPT") {
|
|
65
|
+
let t = await this.dataService.save("player_corrupt", e.raw);
|
|
66
|
+
return t && (this._loadFailed = !1), this._readFailed = !t, this._publish("load_failed", {
|
|
67
|
+
key: "player",
|
|
68
|
+
reason: "corrupt",
|
|
69
|
+
backedUp: t
|
|
70
|
+
}), null;
|
|
71
|
+
}
|
|
72
|
+
return this._readFailed = !0, this._publish("load_failed", {
|
|
73
|
+
key: "player",
|
|
74
|
+
reason: "read",
|
|
75
|
+
error: e
|
|
76
|
+
}), null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
_requirePlayer() {
|
|
80
|
+
if (!this.player) throw Error("[DopamineJS] RewardSystem.init() must be awaited before use");
|
|
81
|
+
}
|
|
82
|
+
_publishStreak() {
|
|
83
|
+
let { current: e, longest: t } = this.player.streak;
|
|
84
|
+
this._publish("streak_updated", {
|
|
85
|
+
current: e,
|
|
86
|
+
longest: t
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
_getDefaultPlayer() {
|
|
90
|
+
return {
|
|
91
|
+
name: "Player",
|
|
92
|
+
xp: 0,
|
|
93
|
+
level: 1,
|
|
94
|
+
totalGamesPlayed: 0,
|
|
95
|
+
createdAt: Date.now(),
|
|
96
|
+
lastPlayedAt: Date.now(),
|
|
97
|
+
streak: {
|
|
98
|
+
current: 1,
|
|
99
|
+
longest: 1,
|
|
100
|
+
lastPlayDate: this._getTodayDateString()
|
|
101
|
+
},
|
|
102
|
+
achievements: {},
|
|
103
|
+
stats: {}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
_migrate(e) {
|
|
107
|
+
let t = this._getDefaultPlayer();
|
|
108
|
+
if (!i(e)) return t;
|
|
109
|
+
let n = Number(e.xp), r = Number.isFinite(n) && n >= 0 ? n : 0, o = this._calculateLevel(r), s = i(e.streak) ? e.streak : {}, c = a(s.current, 1, 1), l = typeof s.lastPlayDate == "string" && /^\d{4}-\d{2}-\d{2}$/.test(s.lastPlayDate) ? s.lastPlayDate : t.streak.lastPlayDate;
|
|
110
|
+
return {
|
|
111
|
+
...t,
|
|
112
|
+
...e,
|
|
113
|
+
name: typeof e.name == "string" ? e.name : t.name,
|
|
114
|
+
xp: r,
|
|
115
|
+
level: Math.max(o, a(e.level, o, 1)),
|
|
116
|
+
totalGamesPlayed: a(e.totalGamesPlayed, 0),
|
|
117
|
+
createdAt: Number.isFinite(e.createdAt) ? e.createdAt : t.createdAt,
|
|
118
|
+
lastPlayedAt: Number.isFinite(e.lastPlayedAt) ? e.lastPlayedAt : t.lastPlayedAt,
|
|
119
|
+
streak: {
|
|
120
|
+
current: c,
|
|
121
|
+
longest: Math.max(c, a(s.longest, c, 1)),
|
|
122
|
+
lastPlayDate: l
|
|
123
|
+
},
|
|
124
|
+
achievements: this._migrateAchievements(e.achievements),
|
|
125
|
+
stats: this._migrateStats(e.stats)
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
_migrateAchievements(e) {
|
|
129
|
+
let t = {};
|
|
130
|
+
if (!i(e)) return t;
|
|
131
|
+
for (let r of Object.keys(e)) {
|
|
132
|
+
let a = e[r];
|
|
133
|
+
n(r) && i(a) && (t[r] = {
|
|
134
|
+
unlockedAt: Number.isFinite(a.unlockedAt) ? a.unlockedAt : Date.now(),
|
|
135
|
+
seen: a.seen === !0
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
return t;
|
|
139
|
+
}
|
|
140
|
+
_migrateStats(e) {
|
|
141
|
+
let t = {};
|
|
142
|
+
if (!i(e)) return t;
|
|
143
|
+
for (let r of Object.keys(e)) {
|
|
144
|
+
let o = e[r];
|
|
145
|
+
if (!n(r) || !i(o)) continue;
|
|
146
|
+
let s = {};
|
|
147
|
+
for (let e of Object.keys(o)) n(e) && Number.isFinite(o[e]) && (s[e] = o[e]);
|
|
148
|
+
s.totalPlays = a(o.totalPlays, 0), s.highScore = Number.isFinite(o.highScore) ? o.highScore : 0, t[r] = s;
|
|
149
|
+
}
|
|
150
|
+
return t;
|
|
151
|
+
}
|
|
152
|
+
async save() {
|
|
153
|
+
if (this.player) {
|
|
154
|
+
if (this._batchDepth > 0) {
|
|
155
|
+
this._pendingSave = !0;
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
await this._write();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async _write() {
|
|
162
|
+
this._loadFailed || (this.player.lastPlayedAt = Date.now(), await this.dataService.save("player", this.player) === !1 && this._publish("save_failed", { key: "player" }));
|
|
163
|
+
}
|
|
164
|
+
async addXP(e, t = "") {
|
|
165
|
+
if (!Number.isFinite(e)) throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);
|
|
166
|
+
this._requirePlayer();
|
|
167
|
+
let n = this.player.level;
|
|
168
|
+
e = Math.max(e, -this.player.xp), this.player.xp += e;
|
|
169
|
+
let r = Math.max(n, this._calculateLevel(this.player.xp)), i = r > n;
|
|
170
|
+
i && (this.player.level = r), await this.save();
|
|
171
|
+
let a = this.player.xp;
|
|
172
|
+
return this._publish("xp_gained", {
|
|
173
|
+
amount: e,
|
|
174
|
+
reason: t,
|
|
175
|
+
leveledUp: i,
|
|
176
|
+
newLevel: r,
|
|
177
|
+
total: a
|
|
178
|
+
}), i && this._publish("level_up", {
|
|
179
|
+
oldLevel: n,
|
|
180
|
+
newLevel: r,
|
|
181
|
+
totalXP: a
|
|
182
|
+
}), {
|
|
183
|
+
leveledUp: i,
|
|
184
|
+
newLevel: r,
|
|
185
|
+
xpGained: e
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
_calculateLevel(e) {
|
|
189
|
+
if (!(e > 0)) return 1;
|
|
190
|
+
let t = Math.floor((1 + Math.sqrt(1 + 4 * e / 50)) / 2);
|
|
191
|
+
return Math.max(1, t);
|
|
192
|
+
}
|
|
193
|
+
getXPForNextLevel() {
|
|
194
|
+
this._requirePlayer();
|
|
195
|
+
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;
|
|
196
|
+
return {
|
|
197
|
+
total: t,
|
|
198
|
+
needed: Math.max(0, t - this.player.xp),
|
|
199
|
+
progress: i
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
async recordGame(e, t = {}) {
|
|
203
|
+
if (this._requirePlayer(), !n(e)) throw TypeError(`[DopamineJS] recordGame expects a game name, received ${String(e)}`);
|
|
204
|
+
if (!i(t)) throw TypeError("[DopamineJS] recordGame expects a result object");
|
|
205
|
+
if (t.score !== void 0 && !Number.isFinite(t.score)) throw TypeError(`[DopamineJS] recordGame expects a finite score, received ${String(t.score)}`);
|
|
206
|
+
return this._batch(() => this._recordGame(e, t));
|
|
207
|
+
}
|
|
208
|
+
async _recordGame(e, t) {
|
|
209
|
+
this._updateDailyStreak() && this._publishStreak(), r(this.player.stats, e) || (this.player.stats[e] = {
|
|
210
|
+
totalPlays: 0,
|
|
211
|
+
highScore: 0
|
|
212
|
+
});
|
|
213
|
+
let i = this.player.stats[e];
|
|
214
|
+
i.totalPlays++, this.player.totalGamesPlayed++, t.score !== void 0 && t.score > i.highScore && (i.highScore = t.score, this._publish("new_high_score", {
|
|
215
|
+
gameName: e,
|
|
216
|
+
score: t.score
|
|
217
|
+
})), Object.keys(t).forEach((e) => {
|
|
218
|
+
if (e !== "score" && n(e)) {
|
|
219
|
+
let n = r(i, e) && Number.isFinite(i[e]) ? i[e] : 0;
|
|
220
|
+
i[e] = n + (Number.isFinite(t[e]) ? t[e] : 0);
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
let a = 10;
|
|
224
|
+
t.score && (a += Math.max(0, Math.floor(t.score / 5))), a = Math.floor(a * this.getStreakMultiplier()), await this.addXP(a, `Played ${e}`), await this.checkAchievements(e, t), await this.save();
|
|
225
|
+
}
|
|
226
|
+
async checkAchievements(e, t) {
|
|
227
|
+
let n = [];
|
|
228
|
+
for (let [i, a] of Object.entries(this.achievements)) {
|
|
229
|
+
if (r(this.player.achievements, i)) continue;
|
|
230
|
+
let o = !1;
|
|
231
|
+
try {
|
|
232
|
+
o = a.check(this.player, e, t);
|
|
233
|
+
} catch (e) {
|
|
234
|
+
console.error(`[DopamineJS] Achievement "${i}" check threw:`, e);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
o && await this.unlockAchievement(i) && n.push(a);
|
|
238
|
+
}
|
|
239
|
+
return n;
|
|
240
|
+
}
|
|
241
|
+
async unlockAchievement(e) {
|
|
242
|
+
if (this._requirePlayer(), !n(e) || !r(this.achievements, e) || r(this.player.achievements, e)) return !1;
|
|
243
|
+
let t = this.achievements[e];
|
|
244
|
+
return t ? (this.player.achievements[e] = {
|
|
245
|
+
unlockedAt: Date.now(),
|
|
246
|
+
seen: !1
|
|
247
|
+
}, await this.addXP(Number.isFinite(t.xp) ? t.xp : 0, `Achievement: ${t.name}`), this._publish("achievement_unlocked", {
|
|
248
|
+
...t,
|
|
249
|
+
id: e
|
|
250
|
+
}), await this.save(), !0) : !1;
|
|
251
|
+
}
|
|
252
|
+
getUnlockedAchievements() {
|
|
253
|
+
return Object.entries(this.player.achievements).map(([e, t]) => ({
|
|
254
|
+
...this.achievements[e],
|
|
255
|
+
id: e,
|
|
256
|
+
...t
|
|
257
|
+
}));
|
|
258
|
+
}
|
|
259
|
+
getUnseenAchievements() {
|
|
260
|
+
return this.getUnlockedAchievements().filter((e) => !e.seen);
|
|
261
|
+
}
|
|
262
|
+
async markAchievementsSeen(e) {
|
|
263
|
+
for (let t of e) r(this.player.achievements, t) && (this.player.achievements[t].seen = !0);
|
|
264
|
+
await this.save();
|
|
265
|
+
}
|
|
266
|
+
_updateDailyStreak() {
|
|
267
|
+
let e = this._getTodayDateString(), t = this.player.streak.lastPlayDate;
|
|
268
|
+
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);
|
|
269
|
+
}
|
|
270
|
+
getStreakMultiplier() {
|
|
271
|
+
let e = this.player.streak.current;
|
|
272
|
+
return e >= 7 ? 2 : e >= 5 ? 1.5 : e >= 3 ? 1.25 : 1;
|
|
273
|
+
}
|
|
274
|
+
_toLocalDateString(e) {
|
|
275
|
+
return `${e.getFullYear()}-${String(e.getMonth() + 1).padStart(2, "0")}-${String(e.getDate()).padStart(2, "0")}`;
|
|
276
|
+
}
|
|
277
|
+
_getTodayDateString() {
|
|
278
|
+
return this._toLocalDateString(/* @__PURE__ */ new Date());
|
|
279
|
+
}
|
|
280
|
+
_getYesterdayDateString() {
|
|
281
|
+
let e = /* @__PURE__ */ new Date();
|
|
282
|
+
return e.setDate(e.getDate() - 1), this._toLocalDateString(e);
|
|
283
|
+
}
|
|
284
|
+
_initAchievements() {
|
|
285
|
+
return {
|
|
286
|
+
first_game: {
|
|
287
|
+
name: "First Steps",
|
|
288
|
+
description: "Play your first game",
|
|
289
|
+
icon: "🎮",
|
|
290
|
+
xp: 50,
|
|
291
|
+
check: (e) => e.totalGamesPlayed >= 1
|
|
292
|
+
},
|
|
293
|
+
level_5: {
|
|
294
|
+
name: "Rising Star",
|
|
295
|
+
description: "Reach level 5",
|
|
296
|
+
icon: "⭐",
|
|
297
|
+
xp: 100,
|
|
298
|
+
check: (e) => e.level >= 5
|
|
299
|
+
},
|
|
300
|
+
level_10: {
|
|
301
|
+
name: "Expert Player",
|
|
302
|
+
description: "Reach level 10",
|
|
303
|
+
icon: "🏆",
|
|
304
|
+
xp: 250,
|
|
305
|
+
check: (e) => e.level >= 10
|
|
306
|
+
},
|
|
307
|
+
streak_3: {
|
|
308
|
+
name: "Dedicated",
|
|
309
|
+
description: "Play 3 days in a row",
|
|
310
|
+
icon: "🔥",
|
|
311
|
+
xp: 100,
|
|
312
|
+
check: (e) => e.streak.current >= 3
|
|
313
|
+
},
|
|
314
|
+
streak_7: {
|
|
315
|
+
name: "Unstoppable",
|
|
316
|
+
description: "Play 7 days in a row",
|
|
317
|
+
icon: "💥",
|
|
318
|
+
xp: 300,
|
|
319
|
+
check: (e) => e.streak.current >= 7
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
//#endregion
|
|
325
|
+
//#region src/dopamine/utils/storage.js
|
|
326
|
+
function s() {
|
|
327
|
+
let e = /* @__PURE__ */ new Map();
|
|
328
|
+
return {
|
|
329
|
+
getItem: (t) => e.has(t) ? e.get(t) : null,
|
|
330
|
+
setItem: (t, n) => {
|
|
331
|
+
e.set(t, String(n));
|
|
332
|
+
},
|
|
333
|
+
removeItem: (t) => {
|
|
334
|
+
e.delete(t);
|
|
335
|
+
},
|
|
336
|
+
clear: () => {
|
|
337
|
+
e.clear();
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
function c() {
|
|
342
|
+
try {
|
|
343
|
+
if (typeof localStorage > "u") return s();
|
|
344
|
+
let e = "__dopamine_probe__";
|
|
345
|
+
return localStorage.setItem(e, "1"), localStorage.removeItem(e), localStorage;
|
|
346
|
+
} catch {
|
|
347
|
+
return s();
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
//#endregion
|
|
351
|
+
//#region src/dopamine/core/DataService.js
|
|
352
|
+
var l = class {
|
|
353
|
+
constructor(e = {}) {
|
|
354
|
+
this.storage = e.storage || c(), this.prefix = e.prefix || "dopamine_", this._tail = null;
|
|
355
|
+
}
|
|
356
|
+
_write(e) {
|
|
357
|
+
let t = this._tail ? this._tail.then(e) : e();
|
|
358
|
+
if (typeof t?.then == "function") {
|
|
359
|
+
let e = Promise.resolve(t).catch(() => {}).then(() => {
|
|
360
|
+
this._tail === e && (this._tail = null);
|
|
361
|
+
});
|
|
362
|
+
this._tail = e;
|
|
363
|
+
}
|
|
364
|
+
return t;
|
|
365
|
+
}
|
|
366
|
+
async save(e, t) {
|
|
367
|
+
try {
|
|
368
|
+
let n = JSON.stringify(t);
|
|
369
|
+
return await this._write(() => this.storage.setItem(this.prefix + e, n)), !0;
|
|
370
|
+
} catch (e) {
|
|
371
|
+
return console.error("Error saving data:", e), !1;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
async load(e, t = null, n = {}) {
|
|
375
|
+
let r;
|
|
376
|
+
try {
|
|
377
|
+
await this._tail, r = await this.storage.getItem(this.prefix + e);
|
|
378
|
+
} catch (e) {
|
|
379
|
+
if (n.strict) throw e;
|
|
380
|
+
return console.error("Error loading data:", e), t;
|
|
381
|
+
}
|
|
382
|
+
if (!r) return t;
|
|
383
|
+
try {
|
|
384
|
+
return JSON.parse(r);
|
|
385
|
+
} catch (i) {
|
|
386
|
+
if (n.strict) throw Object.assign(/* @__PURE__ */ Error(`[DopamineJS] saved "${e}" is not valid JSON`), {
|
|
387
|
+
code: "DOPAMINE_CORRUPT",
|
|
388
|
+
raw: r
|
|
389
|
+
});
|
|
390
|
+
return console.error("Error loading data:", i), t;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
async clear(e) {
|
|
394
|
+
await this._write(() => this.storage.removeItem(this.prefix + e));
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
//#endregion
|
|
398
|
+
export { e as a, o as i, s as n, c as r, l as t };
|
package/dist/core.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-BPXCldpo.cjs");exports.DataService=e.t,exports.EventEmitter=e.a,exports.RewardSystem=e.i,exports.createMemoryStorage=e.n,exports.resolveStorage=e.r;
|
package/dist/core.js
ADDED
package/dist/dopamine.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("./ScreenShake-9jgNXPS6.cjs");var
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("./DataService-BPXCldpo.cjs"),t=require("./ScreenShake-9jgNXPS6.cjs");var n=`game-ui-overlay`,r={levelUp:`LEVEL UP!`,achievementUnlocked:`Achievement Unlocked!`,nearMiss:`CLOSE CALL!`},i=`🔥`,a=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o=(e,t)=>typeof e==`object`&&e&&a(e,t)?e[t]:void 0,s=`http://www.w3.org/2000/svg`,c=new Set([`svg`,`g`,`path`,`circle`,`ellipse`,`rect`,`line`,`polyline`,`polygon`,`text`,`tspan`,`title`,`desc`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`]),l=new Set(`viewBox.width.height.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.d.points.transform.fill.fill-opacity.fill-rule.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-opacity.opacity.offset.stop-color.stop-opacity.gradientUnits.gradientTransform.clip-path.mask.clip-rule.font-size.font-family.font-weight.text-anchor.id.aria-hidden.aria-label.role`.split(`.`)),u=new Set([`fill`,`stroke`,`clip-path`,`mask`]),d=new Set([`transform`,`gradientTransform`]),f=/^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/,p=/^[#a-zA-Z0-9(),.%\s-]+$/,m=/^[a-zA-Z0-9(),.\s-]+$/,h=/^[A-Za-z][\w.:-]*$/,g=0;function _(e,t){if(e.nodeType!==1||e.namespaceURI!==s||!c.has(e.localName))return;let n=e.getAttribute(`id`);n&&h.test(n)&&t.add(n);for(let n of Array.from(e.childNodes))_(n,t)}function v(e,t,n){if(t.includes(`\\`))return null;let r=t.trim();if(e===`id`)return h.test(r)?n.prefix+r:null;if(u.has(e)){let e=f.exec(r);return e?n.ids.has(e[1])?`url(#${n.prefix}${e[1]})`:null:p.test(r)&&!/url/i.test(r)?r:null}return d.has(e)?m.test(r)&&!/url/i.test(r)?r:null:t.includes(`(`)?e===`stop-color`&&p.test(r)&&!/url/i.test(r)?r:null:t}function y(e,t){if(e.nodeType===3||e.nodeType===4)return document.createTextNode(e.data);if(e.nodeType!==1||e.namespaceURI!==s||!c.has(e.localName))return null;let n=document.createElementNS(s,e.localName);for(let r of Array.from(e.attributes)){if(r.namespaceURI!==null||!l.has(r.name))continue;let e=v(r.name,r.value,t);e!==null&&n.setAttribute(r.name,e)}for(let r of Array.from(e.childNodes)){let e=y(r,t);e&&n.appendChild(e)}return n}function b(e){let t,n=/^\s*<svg[\s>]/.test(e)&&!/^\s*<svg\b[^>]*\sxmlns\s*=/.test(e)?e.replace(/^(\s*<svg)/,`$1 xmlns="${s}"`):e;try{t=new DOMParser().parseFromString(n,`image/svg+xml`)}catch{return null}let r=t.documentElement;if(!r||r.localName!==`svg`||t.getElementsByTagName(`parsererror`).length>0)return null;let i=new Set;return _(r,i),y(r,{ids:i,prefix:`dj-icon-${++g}-`})}var x=class{constructor(e,t={}){this.particleSystem=e;let n=o(t,`text`);this.text={...r};for(let e of Object.keys(r)){let t=o(n,e);typeof t==`string`&&(this.text[e]=t)}this.safeIcons=o(t,`safeIcons`)===!0,this._streakIcon=o(o(t,`icons`),`streak`)??i,this.container=null,this.xpBar=null,this.levelDisplay=null,this.streakDisplay=null,this._timers=new Set,this._detached=[],this.init()}init(){this.container=document.createElement(`div`),this.container.className=`game-ui-overlay`,document.getElementById(n)||(this.container.id=n),this.container.innerHTML=`
|
|
2
2
|
<div class="game-ui-top-bar">
|
|
3
3
|
<div class="level-badge">
|
|
4
4
|
<span class="level-label">LVL</span>
|
|
@@ -13,25 +13,25 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
13
13
|
</div>
|
|
14
14
|
|
|
15
15
|
<div class="streak-badge">
|
|
16
|
-
<span class="streak-icon"
|
|
16
|
+
<span class="streak-icon"></span>
|
|
17
17
|
<span class="streak-number">1</span>
|
|
18
18
|
</div>
|
|
19
19
|
</div>
|
|
20
|
-
`,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,{position:`absolute`,width:`1px`,height:`1px`,overflow:`hidden`,clipPath:`inset(50%)`,whiteSpace:`nowrap`}),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`)}_defer(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);return this._timers.add(n),n}_mount(e){return document.body.appendChild(e),this._detached.push(e),e}_announce(e){this.liveRegion&&(this.liveRegion.textContent=e)}_replayAnimation(e,t){e&&(e.style.animation=`none`,this._defer(()=>{e.style.animation=t},10))}updateXP(e,t,n,r){let i=Number.isFinite(r)?r:n>0?e/n:0;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`)}updateLevel(e){this.levelDisplay.textContent=e,this._replayAnimation(this.levelBadge,`level-pulse 0.5s ease-out`)}updateStreak(e){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=``}showAchievement(e){let t=document.createElement(`div`);t.className=`achievement-popup`,t.innerHTML=`
|
|
20
|
+
`,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,{position:`absolute`,width:`1px`,height:`1px`,overflow:`hidden`,clipPath:`inset(50%)`,whiteSpace:`nowrap`}),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`),this._setIcon(this.container.querySelector(`.streak-icon`),this._streakIcon)}_setIcon(e,t){if(e.textContent=``,typeof Node<`u`&&t instanceof Node)e.appendChild(t);else if(typeof t!=`string`)return;else if(!this.safeIcons)e.innerHTML=t;else{let n=b(t);n?e.appendChild(n):e.textContent=t}}_defer(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);return this._timers.add(n),n}_mount(e){return document.body.appendChild(e),this._detached.push(e),e}_announce(e){this.liveRegion&&(this.liveRegion.textContent=e)}_replayAnimation(e,t){e&&(e.style.animation=`none`,this._defer(()=>{e.style.animation=t},10))}updateXP(e,t,n,r){let i=Number.isFinite(r)?r:n>0?e/n:0;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`)}updateLevel(e){this.levelDisplay.textContent=e,this._replayAnimation(this.levelBadge,`level-pulse 0.5s ease-out`)}updateStreak(e){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=``}showAchievement(e){let t=document.createElement(`div`);t.className=`achievement-popup`,t.innerHTML=`
|
|
21
21
|
<div class="achievement-shine"></div>
|
|
22
22
|
<div class="achievement-content">
|
|
23
23
|
<div class="achievement-icon"></div>
|
|
24
24
|
<div class="achievement-info">
|
|
25
|
-
<div class="achievement-title"
|
|
25
|
+
<div class="achievement-title"></div>
|
|
26
26
|
<div class="achievement-name"></div>
|
|
27
27
|
<div class="achievement-desc"></div>
|
|
28
28
|
<div class="achievement-xp"></div>
|
|
29
29
|
</div>
|
|
30
30
|
</div>
|
|
31
|
-
`,t.querySelector(`.achievement-
|
|
31
|
+
`,t.querySelector(`.achievement-title`).textContent=this.text.achievementUnlocked,this._setIcon(t.querySelector(`.achievement-icon`),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(()=>{let e=t.getBoundingClientRect();this.particleSystem.confetti(e.left+e.width/2,e.top+e.height/2,40)},300),this._defer(()=>{t.style.animation=`slideOut 0.3s ease-in forwards`,this._defer(()=>this._remove(t),300)},4e3)}showLevelUp(e,t){let n=document.createElement(`div`);n.className=`level-up-overlay`,n.innerHTML=`
|
|
32
32
|
<div class="level-up-content">
|
|
33
|
-
<div class="level-up-title"
|
|
33
|
+
<div class="level-up-title"></div>
|
|
34
34
|
<div class="level-up-number"></div>
|
|
35
35
|
<div class="level-up-subtitle">Amazing progress!</div>
|
|
36
36
|
</div>
|
|
37
|
-
`,n.querySelector(`.level-up-number`).textContent=t,this._mount(n),this._announce(`Level up: ${t}`),this._defer(()=>{for(let e=0;e<5;e++)this._defer(()=>{let e=Math.random()*window.innerWidth,t=Math.random()*window.innerHeight*.6;this.particleSystem.confetti(e,t,30)},e*200)},300),this._defer(()=>{n.style.opacity=`0`,this._defer(()=>this._remove(n),500)},2500)}showFloatingText(e,t,n,r=`#ffd700`,i=`24px`){let a=document.createElement(`div`);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)}showCombo(e,t,n){this.showFloatingText(`${e}× COMBO!`,t,n,`#ff6b6b`,`32px`),this.particleSystem.fire(t,n,20)}showNearMiss(e,t){this.showFloatingText(`CLOSE CALL!`,e,t,`#45b7d1`,`20px`),this.particleSystem.sparkle(e,t,15,`#45b7d1`)}showLuckyMoment(e,t,n){this.showFloatingText(`LUCKY ${e}×!`,t,n,`#ffd700`,`36px`),this.particleSystem.starBurst(t,n,12),this.particleSystem.confetti(t,n,25)}showNotification(e,t=`normal`){let n=window.innerWidth/2,r=window.innerHeight/3;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)}showSummary(e){let t=document.createElement(`div`);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`;let n=document.createElement(`h1`);n.textContent=`Game Over`;let r=document.createElement(`div`);r.className=`summary-score`,r.style.cssText=`font-size: 3rem; font-weight: bold; color: #e06020; margin: 10px 0;`,r.textContent=e.score;let i=document.createElement(`div`);i.className=`summary-metrics`,i.style.cssText=`width: 100%; margin-bottom: 20px;`;for(let[t,n]of Object.entries(e.metrics||{})){let e=document.createElement(`div`);e.style.cssText=`display:flex;justify-content:space-between;width:100%`;let r=document.createElement(`span`);r.textContent=`${t}:`;let a=document.createElement(`strong`);a.textContent=n,e.append(r,a),i.appendChild(e)}t.append(n,r,i);let a=document.createElement(`button`);if(a.className=`btn`,a.textContent=`Play Again`,a.addEventListener(`click`,e.onReplay||(()=>window.location.reload())),t.appendChild(a),e.onExit){let n=document.createElement(`button`);n.className=`btn`,n.textContent=`Exit`,n.style.cssText=`margin-top: 10px; background: #543847;`,n.addEventListener(`click`,e.onExit),t.appendChild(n)}return this._mount(t),t}_remove(e){e.remove();let t=this._detached.indexOf(e);t>-1&&this._detached.splice(t,1)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear();for(let e of this._detached)e.remove();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}},p=class{constructor(e={}){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=new Map,this.customEffects=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)}_resize(){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;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)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){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);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;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)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;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)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];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){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t);continue}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)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}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());this.ctx.restore()}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);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;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){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=[]}},m=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),h=class{constructor(e={}){this.audioContext=null,this.storageKey=e.storageKey||`dopamineSoundsMuted`,this.storage=e.storage||l(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=e.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(e.volume??1),this._loading=new Map,this._timers=new Set}_later(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}initAudio(){if(!this.audioContext){let e=typeof window<`u`?window.AudioContext||window.webkitAudioContext:void 0;if(!e)return!1;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)}return this.audioContext.state===`suspended`&&this.audioContext.resume(),!0}setVolume(e){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}getVolume(){return this._volume}_output(){return this.masterGain||this.audioContext.destination}toggleMute(){return this.muted=!this.muted,this.storage.setItem(this.storageKey,this.muted),this.muted}registerSound(e,t){this.customSounds[e]=t,this.audioContext&&this.loadSound(e,t)}async preloadSounds(e){let t=Object.entries(e).map(([e,t])=>(this.customSounds[e]=t,this.loadSound(e,t)));await Promise.allSettled(t)}async loadSound(e,t){if(!this.audioContext)return;if(this._loading.has(e))return this._loading.get(e);let n=this._load(e,t).finally(()=>this._loading.delete(e));return this._loading.set(e,n),n}async _load(e,t){try{let n=this.audioContext,r=await fetch(t);if(r.ok===!1)throw Error(`HTTP ${r.status}`);let i=await r.arrayBuffer(),a=await n.decodeAudioData(i);this.audioContext===n&&this.assets.set(e,a)}catch(t){console.warn(`[DopamineJS] Failed to load sound '${e}':`,t)}}async play(e){if(this.muted||!this.initAudio())return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}if(m(this.customSounds,e)&&!this.assets.has(e)){let t=this.audioContext;if(await this.loadSound(e,this.customSounds[e]),this.audioContext!==t)return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}}let t={jump:()=>this.playJump(!0),score:()=>this.playScore(!0),success:()=>this.playSuccess(!0),click:()=>this.playClick(!0),error:()=>this.playError(!0),gameover:()=>this.playGameOver(!0)};m(t,e)&&t[e]()}_playBuffer(e){let t=this.audioContext.createBufferSource();t.buffer=e,t.connect(this._output()),t.start(0)}playTone(e,t,n=`sine`,r=.3){if(this.muted||!this.initAudio())return;let i=this.audioContext.createOscillator(),a=this.audioContext.createGain();i.connect(a),a.connect(this._output()),i.frequency.value=e,i.type=n;let o=Math.max(1e-4,r);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)}playJump(e=!1){if(!e&&this.assets.has(`jump`))return this.play(`jump`);this.playTone(400,.1,`square`,.2)}playScore(e=!1){if(!e&&this.assets.has(`score`))return this.play(`score`);this.playTone(800,.15,`sine`,.25),this._later(()=>this.playTone(1e3,.15,`sine`,.25),50)}playGameOver(e=!1){if(!e&&this.assets.has(`gameover`))return this.play(`gameover`);this.playTone(300,.2,`sawtooth`,.3),this._later(()=>this.playTone(200,.2,`sawtooth`,.3),100),this._later(()=>this.playTone(150,.3,`sawtooth`,.3),200)}playClick(e=!1){if(!e&&this.assets.has(`click`))return this.play(`click`);this.playTone(600,.05,`sine`,.1)}playSuccess(e=!1){if(!e&&this.assets.has(`success`))return this.play(`success`);this.playTone(600,.1,`sine`,.2),this._later(()=>this.playTone(800,.2,`sine`,.2),100)}playError(e=!1){if(!e&&this.assets.has(`error`))return this.play(`error`);this.playTone(200,.2,`sawtooth`,.3)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear(),this.audioContext&&(this.audioContext.close?.())?.catch?.(()=>{}),this.audioContext=null,this.masterGain=null,this.assets.clear(),this._loading.clear()}},g=class{constructor(e={}){this.config=e,this.dataService=new u(e.data||{}),this.rewardSystem=new s(this.dataService,e.rewards||{}),this.soundManager=new h(e.sound||{}),this.particleSystem=new p(e.particles||{}),this.gameUI=new f(this.particleSystem),this._bindEvents()}async init(){return await this.rewardSystem.init(),this._syncUI(),{rewardSystem:this.rewardSystem,gameUI:this.gameUI,particleSystem:this.particleSystem,soundManager:this.soundManager}}_syncUI(){let{player:e}=this.rewardSystem,{total:t,needed:n,progress:r}=this.rewardSystem.getXPForNextLevel();this.gameUI.updateXP(e.xp,n,t,r),this.gameUI.updateLevel(e.level),this.gameUI.updateStreak(e.streak.current)}_bindEvents(){let e=this.rewardSystem;this._unsubscribe=[e.on(`xp_gained`,()=>{let{total:t,needed:n,progress:r}=e.getXPForNextLevel();this.gameUI.updateXP(e.player.xp,n,t,r)}),e.on(`level_up`,e=>{this.gameUI.updateLevel(e.newLevel),this.gameUI.showLevelUp(e.oldLevel,e.newLevel)}),e.on(`achievement_unlocked`,e=>{this.gameUI.showAchievement(e)}),e.on(`streak_updated`,e=>{this.gameUI.updateStreak(e.current)}),e.on(`new_high_score`,e=>{this.gameUI.showNotification(`New High Score: ${e.score}!`,`legendary`),this.soundManager.playSuccess()})]}destroy(){for(let e of this._unsubscribe)e();this._unsubscribe=[],this.gameUI.destroy(),this.particleSystem.destroy(),this.soundManager.destroy()}},_={init(e){},update(e){},fixedUpdate(e){},destroy(){}},v=class{constructor(){this.kernel=null}init(e){this.kernel=e}update(e){}fixedUpdate(e){}destroy(){}},y={..._,addBody(e){},removeBody(e){},checkCollision(e,t){},raycast(e,t,n){},setGravity(e,t){},step(e){}},b={..._,registerSound(e,t){},preloadSounds(e){},play(e,t){},playTone(e,t,n,r){},stop(e){},toggleMute(){},setVolume(e){}},x={..._,registerSprite(e,t){},registerEffect(e,t){},play(e,t,n,...r){},emit(e){},clear(){},confetti(e,t,n){},coinShower(e,t,n){},sparkle(e,t,n,r){},fire(e,t,n){},starBurst(e,t,n){}},S=class{static createGround(e,t,n=`#333`){let r=document.createElement(`canvas`);r.width=e,r.height=t;let i=r.getContext(`2d`);i.fillStyle=n,i.fillRect(0,0,e,t);for(let n=0;n<1e3;n++){i.fillStyle=Math.random()>.5?`#444`:`#222`;let n=Math.random()*4+2;i.fillRect(Math.random()*e,Math.random()*t,n,n)}i.strokeStyle=`rgba(255,255,255,0.05)`,i.lineWidth=2,i.beginPath();for(let n=0;n<=e;n+=64)i.moveTo(n,0),i.lineTo(n,t);for(let n=0;n<=t;n+=64)i.moveTo(0,n),i.lineTo(e,n);return i.stroke(),r}static createCharacterSheet(e,t){let n=document.createElement(`canvas`);n.width=256,n.height=64;let r=n.getContext(`2d`);for(let n=0;n<4;n++){let i=n*64+32,a=n%2==0?0:-2,o=n===1?5:n===3?-5:0;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=C(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))}return n}};function C(e,t){return e}var w=g;exports.Animator=e.r,exports.Collider=e._,exports.Component=e.v,exports.DataService=u,exports.Director=e.c,exports.DopamineKernel=e.u,exports.EventBus=e.C,exports.EventEmitter=t,exports.Game=e.s,exports.GameObject=e.o,exports.GameUI=f,exports.GlobalInput=e.p,exports.GlobalLoader=e.d,exports.GlobalPhysics=e.h,exports.IAudioSystem=b,exports.IParticleSystem=x,exports.IPhysicsSystem=y,exports.ISystem=_,exports.Input=e.m,exports.Loader=e.f,exports.ParticleEmitter=e.n,exports.ParticleSystem=p,exports.Physics=e.g,exports.PluginRegistry=e.x,exports.Renderer=e.b,exports.RewardSystem=s,exports.Scene=e.l,exports.ScreenShake=e.t,exports.SoundManager=h,exports.Sprite=e.i,exports.System=v,exports.SystemRegistry=e.S,exports.TextureGenerator=S,exports.Ticker=e.y,exports.Vector2=e.a,exports.createMemoryStorage=c,exports.default=w,exports.resolveStorage=l;
|
|
37
|
+
`,n.querySelector(`.level-up-title`).textContent=this.text.levelUp,n.querySelector(`.level-up-number`).textContent=t,this._mount(n),this._announce(`Level up: ${t}`),this._defer(()=>{for(let e=0;e<5;e++)this._defer(()=>{let e=Math.random()*window.innerWidth,t=Math.random()*window.innerHeight*.6;this.particleSystem.confetti(e,t,30)},e*200)},300),this._defer(()=>{n.style.opacity=`0`,this._defer(()=>this._remove(n),500)},2500)}showFloatingText(e,t,n,r=`#ffd700`,i=`24px`){let a=document.createElement(`div`);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)}showCombo(e,t,n){this.showFloatingText(`${e}× COMBO!`,t,n,`#ff6b6b`,`32px`),this.particleSystem.fire(t,n,20)}showNearMiss(e,t){this.showFloatingText(this.text.nearMiss,e,t,`#45b7d1`,`20px`),this.particleSystem.sparkle(e,t,15,`#45b7d1`)}showLuckyMoment(e,t,n){this.showFloatingText(`LUCKY ${e}×!`,t,n,`#ffd700`,`36px`),this.particleSystem.starBurst(t,n,12),this.particleSystem.confetti(t,n,25)}showNotification(e,t=`normal`){let n=window.innerWidth/2,r=window.innerHeight/3;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)}showSummary(e){let t=document.createElement(`div`);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`;let n=document.createElement(`h1`);n.textContent=`Game Over`;let r=document.createElement(`div`);r.className=`summary-score`,r.style.cssText=`font-size: 3rem; font-weight: bold; color: #e06020; margin: 10px 0;`,r.textContent=e.score;let i=document.createElement(`div`);i.className=`summary-metrics`,i.style.cssText=`width: 100%; margin-bottom: 20px;`;for(let[t,n]of Object.entries(e.metrics||{})){let e=document.createElement(`div`);e.style.cssText=`display:flex;justify-content:space-between;width:100%`;let r=document.createElement(`span`);r.textContent=`${t}:`;let a=document.createElement(`strong`);a.textContent=n,e.append(r,a),i.appendChild(e)}t.append(n,r,i);let a=document.createElement(`button`);if(a.className=`btn`,a.textContent=`Play Again`,a.addEventListener(`click`,e.onReplay||(()=>window.location.reload())),t.appendChild(a),e.onExit){let n=document.createElement(`button`);n.className=`btn`,n.textContent=`Exit`,n.style.cssText=`margin-top: 10px; background: #543847;`,n.addEventListener(`click`,e.onExit),t.appendChild(n)}return this._mount(t),t}_remove(e){e.remove();let t=this._detached.indexOf(e);t>-1&&this._detached.splice(t,1)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear();for(let e of this._detached)e.remove();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,this._streakIcon=null}},S=Object.freeze({matches:!1});function C(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||S}var w=class{constructor(e={}){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?null:C(window),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=new Map,this.customEffects=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)}_resize(){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;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)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){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);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;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)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;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)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];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){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t);continue}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)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}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());this.ctx.restore()}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);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;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){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=[]}},T=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),E=class{constructor(t={}){this.audioContext=null,this.storageKey=t.storageKey||`dopamineSoundsMuted`,this.storage=t.storage||e.r(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=t.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(t.volume??1),this._loading=new Map,this._timers=new Set,this._unlocks=new Set}unlockOn(e,t=[`pointerup`,`touchend`,`keydown`]){let n=()=>{for(let n of t)e.removeEventListener(n,r);this._unlocks.delete(n)},r=()=>{n(),this.initAudio()};for(let n of t)e.addEventListener(n,r);return this._unlocks.add(n),n}_later(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}initAudio(){if(!this.audioContext){let e=typeof window<`u`?window.AudioContext||window.webkitAudioContext:void 0;if(!e)return!1;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)}return this.audioContext.state===`suspended`&&this.audioContext.resume(),!0}setVolume(e){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}getVolume(){return this._volume}_output(){return this.masterGain||this.audioContext.destination}toggleMute(){return this.muted=!this.muted,this.storage.setItem(this.storageKey,this.muted),this.muted}registerSound(e,t){this.customSounds[e]=t,this.audioContext&&this.loadSound(e,t)}async preloadSounds(e){let t=Object.entries(e).map(([e,t])=>(this.customSounds[e]=t,this.loadSound(e,t)));await Promise.allSettled(t)}async loadSound(e,t){if(!this.audioContext)return;if(this._loading.has(e))return this._loading.get(e);let n=this._load(e,t).finally(()=>this._loading.delete(e));return this._loading.set(e,n),n}async _load(e,t){try{let n=this.audioContext,r=await fetch(t);if(r.ok===!1)throw Error(`HTTP ${r.status}`);let i=await r.arrayBuffer(),a=await n.decodeAudioData(i);this.audioContext===n&&this.assets.set(e,a)}catch(t){console.warn(`[DopamineJS] Failed to load sound '${e}':`,t)}}async play(e){if(this.muted||!this.initAudio())return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}if(T(this.customSounds,e)&&!this.assets.has(e)){let t=this.audioContext;if(await this.loadSound(e,this.customSounds[e]),this.audioContext!==t)return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}}let t={jump:()=>this.playJump(!0),score:()=>this.playScore(!0),success:()=>this.playSuccess(!0),click:()=>this.playClick(!0),error:()=>this.playError(!0),gameover:()=>this.playGameOver(!0)};T(t,e)&&t[e]()}_playBuffer(e){let t=this.audioContext.createBufferSource();t.buffer=e,t.connect(this._output()),t.start(0)}playTone(e,t,n=`sine`,r=.3){if(this.muted||!this.initAudio())return;let i=this.audioContext.createOscillator(),a=this.audioContext.createGain();i.connect(a),a.connect(this._output()),i.frequency.value=e,i.type=n;let o=Math.max(1e-4,r);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)}playJump(e=!1){if(!e&&this.assets.has(`jump`))return this.play(`jump`);this.playTone(400,.1,`square`,.2)}playScore(e=!1){if(!e&&this.assets.has(`score`))return this.play(`score`);this.playTone(800,.15,`sine`,.25),this._later(()=>this.playTone(1e3,.15,`sine`,.25),50)}playGameOver(e=!1){if(!e&&this.assets.has(`gameover`))return this.play(`gameover`);this.playTone(300,.2,`sawtooth`,.3),this._later(()=>this.playTone(200,.2,`sawtooth`,.3),100),this._later(()=>this.playTone(150,.3,`sawtooth`,.3),200)}playClick(e=!1){if(!e&&this.assets.has(`click`))return this.play(`click`);this.playTone(600,.05,`sine`,.1)}playSuccess(e=!1){if(!e&&this.assets.has(`success`))return this.play(`success`);this.playTone(600,.1,`sine`,.2),this._later(()=>this.playTone(800,.2,`sine`,.2),100)}playError(e=!1){if(!e&&this.assets.has(`error`))return this.play(`error`);this.playTone(200,.2,`sawtooth`,.3)}destroy(){for(let e of[...this._unlocks])e();for(let e of this._timers)clearTimeout(e);this._timers.clear(),this.audioContext&&(this.audioContext.close?.())?.catch?.(()=>{}),this.audioContext=null,this.masterGain=null,this.assets.clear(),this._loading.clear()}},D=class{constructor(t={}){this.config=t,this.dataService=new e.t(t.data||{}),this.rewardSystem=new e.i(this.dataService,t.rewards||{}),this.soundManager=new E(t.sound||{}),this.particleSystem=new w(t.particles||{}),this.gameUI=new x(this.particleSystem),this._bindEvents()}async init(){return await this.rewardSystem.init(),this._syncUI(),{rewardSystem:this.rewardSystem,gameUI:this.gameUI,particleSystem:this.particleSystem,soundManager:this.soundManager}}_syncUI(){let{player:e}=this.rewardSystem,{total:t,needed:n,progress:r}=this.rewardSystem.getXPForNextLevel();this.gameUI.updateXP(e.xp,n,t,r),this.gameUI.updateLevel(e.level),this.gameUI.updateStreak(e.streak.current)}_bindEvents(){let e=this.rewardSystem;this._unsubscribe=[e.on(`xp_gained`,()=>{let{total:t,needed:n,progress:r}=e.getXPForNextLevel();this.gameUI.updateXP(e.player.xp,n,t,r)}),e.on(`level_up`,e=>{this.gameUI.updateLevel(e.newLevel),this.gameUI.showLevelUp(e.oldLevel,e.newLevel)}),e.on(`achievement_unlocked`,e=>{this.gameUI.showAchievement(e)}),e.on(`streak_updated`,e=>{this.gameUI.updateStreak(e.current)}),e.on(`new_high_score`,e=>{this.gameUI.showNotification(`New High Score: ${e.score}!`,`legendary`),this.soundManager.playSuccess()})]}destroy(){for(let e of this._unsubscribe)e();this._unsubscribe=[],this.gameUI.destroy(),this.particleSystem.destroy(),this.soundManager.destroy()}},O={init(e){},update(e){},fixedUpdate(e){},destroy(){}},k=class{constructor(){this.kernel=null}init(e){this.kernel=e}update(e){}fixedUpdate(e){}destroy(){}},A={...O,addBody(e){},removeBody(e){},checkCollision(e,t){},raycast(e,t,n){},setGravity(e,t){},step(e){}},j={...O,registerSound(e,t){},preloadSounds(e){},play(e,t){},playTone(e,t,n,r){},stop(e){},toggleMute(){},setVolume(e){}},M={...O,registerSprite(e,t){},registerEffect(e,t){},play(e,t,n,...r){},emit(e){},clear(){},confetti(e,t,n){},coinShower(e,t,n){},sparkle(e,t,n,r){},fire(e,t,n){},starBurst(e,t,n){}};function N({nav:e=globalThis.navigator,enabled:t=!0}={}){let n=!!t,r=t=>{if(n)try{e.vibrate(t)}catch{}};return{tap:()=>r(10),double:()=>r([10,40,10]),setEnabled(e){n=!!e}}}var P=class{static createGround(e,t,n=`#333`){let r=document.createElement(`canvas`);r.width=e,r.height=t;let i=r.getContext(`2d`);i.fillStyle=n,i.fillRect(0,0,e,t);for(let n=0;n<1e3;n++){i.fillStyle=Math.random()>.5?`#444`:`#222`;let n=Math.random()*4+2;i.fillRect(Math.random()*e,Math.random()*t,n,n)}i.strokeStyle=`rgba(255,255,255,0.05)`,i.lineWidth=2,i.beginPath();for(let n=0;n<=e;n+=64)i.moveTo(n,0),i.lineTo(n,t);for(let n=0;n<=t;n+=64)i.moveTo(0,n),i.lineTo(e,n);return i.stroke(),r}static createCharacterSheet(e,t){let n=document.createElement(`canvas`);n.width=256,n.height=64;let r=n.getContext(`2d`);for(let n=0;n<4;n++){let i=n*64+32,a=n%2==0?0:-2,o=n===1?5:n===3?-5:0;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=F(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))}return n}};function F(e,t){return e}var I=D;exports.Animator=t.r,exports.Collider=t._,exports.Component=t.v,exports.DataService=e.t,exports.Director=t.c,exports.DopamineKernel=t.u,exports.EventBus=t.C,exports.EventEmitter=e.a,exports.Game=t.s,exports.GameObject=t.o,exports.GameUI=x,exports.GlobalInput=t.p,exports.GlobalLoader=t.d,exports.GlobalPhysics=t.h,exports.IAudioSystem=j,exports.IParticleSystem=M,exports.IPhysicsSystem=A,exports.ISystem=O,exports.Input=t.m,exports.Loader=t.f,exports.ParticleEmitter=t.n,exports.ParticleSystem=w,exports.Physics=t.g,exports.PluginRegistry=t.x,exports.Renderer=t.b,exports.RewardSystem=e.i,exports.Scene=t.l,exports.ScreenShake=t.t,exports.SoundManager=E,exports.Sprite=t.i,exports.System=k,exports.SystemRegistry=t.S,exports.TextureGenerator=P,exports.Ticker=t.y,exports.Vector2=t.a,exports.createHaptics=N,exports.createMemoryStorage=e.n,exports.default=I,exports.prefersReducedMotion=C,exports.resolveStorage=e.r;
|