ahafrog 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. ahafrog/__init__.py +3 -0
  2. ahafrog/cli.py +66 -0
  3. ahafrog/engine/engine.js +709 -0
  4. ahafrog/engine/minigames/simulation.js +263 -0
  5. ahafrog/engine/pixelpack.js +393 -0
  6. ahafrog/engine/player.html +285 -0
  7. ahafrog/engine/shell-stage.html +54 -0
  8. ahafrog/engine/shell.css +316 -0
  9. ahafrog/engine/shell.js +166 -0
  10. ahafrog/engine/template.html +412 -0
  11. ahafrog/generator/__init__.py +1 -0
  12. ahafrog/generator/api.py +282 -0
  13. ahafrog/generator/assembler.py +1583 -0
  14. ahafrog/generator/cancel.py +66 -0
  15. ahafrog/generator/course_assembler.py +566 -0
  16. ahafrog/generator/course_pipeline.py +336 -0
  17. ahafrog/generator/documents.py +368 -0
  18. ahafrog/generator/i18n.py +1064 -0
  19. ahafrog/generator/package_builder.py +161 -0
  20. ahafrog/generator/pipeline.py +2716 -0
  21. ahafrog/generator/prompts.py +2287 -0
  22. ahafrog/generator/sandbox.py +278 -0
  23. ahafrog/generator/sandbox_harness.js +653 -0
  24. ahafrog/generator/structure.py +443 -0
  25. ahafrog/generator/theme_light.py +189 -0
  26. ahafrog/node/engine-state.js +46 -0
  27. ahafrog/node/package.json +13 -0
  28. ahafrog/node/server.js +91 -0
  29. ahafrog/server.py +1326 -0
  30. ahafrog/static/ahafrog.png +0 -0
  31. ahafrog/static/frog/aha.json +1 -0
  32. ahafrog/static/frog/crying.json +1 -0
  33. ahafrog/static/frog/excited.json +1 -0
  34. ahafrog/static/frog/happy.json +1 -0
  35. ahafrog/static/frog/idle.json +1 -0
  36. ahafrog/static/frog/sad.json +1 -0
  37. ahafrog/static/frog/walk_left.json +1 -0
  38. ahafrog/static/frog/walk_right.json +1 -0
  39. ahafrog/static/index.html +469 -0
  40. ahafrog/static/studio.html +2065 -0
  41. ahafrog/static/vendor/lottie_light.min.js +4 -0
  42. ahafrog-0.2.0.dist-info/METADATA +86 -0
  43. ahafrog-0.2.0.dist-info/RECORD +48 -0
  44. ahafrog-0.2.0.dist-info/WHEEL +5 -0
  45. ahafrog-0.2.0.dist-info/entry_points.txt +2 -0
  46. ahafrog-0.2.0.dist-info/licenses/LICENSE +661 -0
  47. ahafrog-0.2.0.dist-info/licenses/LICENSE-AGPL-3.0 +673 -0
  48. ahafrog-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,709 @@
1
+ // =============================================================================
2
+ // AhaFrog — AI Game-Based Learning Studio
3
+ // Created by Yuqi Hang (github.com/yh2072)
4
+ // https://github.com/yh2072/ahafrog
5
+ // =============================================================================
6
+ if(typeof window.BACKGROUNDS==='undefined'||!window.BACKGROUNDS)window.BACKGROUNDS=[];
7
+ if(typeof window.CHAR_DRAW_FNS==='undefined'||!window.CHAR_DRAW_FNS)window.CHAR_DRAW_FNS={};
8
+ (function(){
9
+ var orig=CanvasRenderingContext2D.prototype.arc;
10
+ CanvasRenderingContext2D.prototype.arc=function(x,y,radius,startAngle,endAngle,anticlockwise){
11
+ var r=Number(radius);
12
+ if(!(r>0)||!isFinite(r))r=1e-6;
13
+ return orig.call(this,x,y,r,startAngle,endAngle,anticlockwise);
14
+ };
15
+ })();
16
+ const Audio=(()=>{
17
+ const BASE=GAME.audioBase||'/assets/audio/';
18
+ let bgmEnabled=true,sfxEnabled=true,bgmVolume=0.35,sfxVolume=0.5,currentBGM=null,audioCtxStarted=false;
19
+ const _DEF_SFX={click:'Interface Sounds/Audio/click_003.ogg',select:'Interface Sounds/Audio/select_003.ogg',correct:'Interface Sounds/Audio/confirmation_002.ogg',wrong:'Interface Sounds/Audio/error_004.ogg',drop:'Interface Sounds/Audio/drop_004.ogg',powerUp:'Digital Audio/Audio/highUp.ogg',complete:'Interface Sounds/Audio/confirmation_004.ogg',chapterDone:'Digital Audio/Audio/pepSound2.ogg',maximize:'Interface Sounds/Audio/maximize_009.ogg',levelUp:'Music Jingles/Audio (Retro)/jingles-retro_00.ogg',reward:'Music Jingles/Audio (Retro)/jingles-retro_05.ogg',bookOpen:'RPG Audio/Audio/bookOpen.ogg',bookFlip:'RPG Audio/Audio/bookFlip1.ogg'};
20
+ const _DEF_BGM={title:'Music Loops/Retro/Retro Mystic.ogg',dialog:'Music Loops/Retro/Retro Comedy.ogg',minigame:'Music Loops/Retro/Retro Beat.ogg',victory:'Music Loops/Loops/Cheerful Annoyance.ogg',explore:'Music Loops/Retro/Retro Reggae.ogg'};
21
+ const _ga=GAME.audio||{};
22
+ const SFX_MAP={};for(const k in _DEF_SFX)SFX_MAP[k]=BASE+((_ga.sfx&&_ga.sfx[k])||_DEF_SFX[k]);
23
+ const BGM_MAP={};for(const k in _DEF_BGM)BGM_MAP[k]=BASE+((_ga.bgm&&_ga.bgm[k])||_DEF_BGM[k]);
24
+ if(_ga.bgm)for(const k in _ga.bgm){if(!BGM_MAP[k])BGM_MAP[k]=BASE+_ga.bgm[k]}
25
+ if(_ga.sfx)for(const k in _ga.sfx){if(!SFX_MAP[k])SFX_MAP[k]=BASE+_ga.sfx[k]}
26
+ const cache={};
27
+ function load(url){if(!cache[url]){cache[url]=new window.Audio(url);cache[url].preload='auto'}return cache[url]}
28
+ function playSFX(n){if(!sfxEnabled||!SFX_MAP[n])return;const a=load(SFX_MAP[n]);a.volume=sfxVolume;a.currentTime=0;a.play().catch(()=>{})}
29
+ function playBGM(n,opts){if(!BGM_MAP[n])return;stopBGM();currentBGM=load(BGM_MAP[n]);currentBGM.loop=!(opts&&opts.once);currentBGM.volume=bgmEnabled?bgmVolume:0;currentBGM.currentTime=0;currentBGM.play().catch(()=>{})}
30
+ function stopBGM(){if(currentBGM){currentBGM.pause();currentBGM.currentTime=0;currentBGM=null}}
31
+ function fadeOutBGM(ms){if(!currentBGM)return;const a=currentBGM,s=a.volume,st=Date.now();(function f(){const p=Math.min((Date.now()-st)/ms,1);a.volume=s*(1-p);if(p<1)requestAnimationFrame(f);else{a.pause();a.currentTime=0;if(currentBGM===a)currentBGM=null}})()}
32
+ function toggleBGM(){bgmEnabled=!bgmEnabled;if(currentBGM)currentBGM.volume=bgmEnabled?bgmVolume:0;document.getElementById('btn-bgm').classList.toggle('muted',!bgmEnabled)}
33
+ function toggleSFX(){sfxEnabled=!sfxEnabled;document.getElementById('btn-sfx').classList.toggle('muted',!sfxEnabled)}
34
+ function ensureContext(){if(!audioCtxStarted){audioCtxStarted=true;playBGM('title')}}
35
+ return{playSFX,playBGM,stopBGM,fadeOutBGM,toggleBGM,toggleSFX,ensureContext};
36
+ })();
37
+
38
+ const C=document.getElementById('main');const ctx=C.getContext('2d');
39
+ function px(x,y,c){ctx.fillStyle=c;ctx.fillRect(x,y,1,1)}
40
+ function rect(x,y,w,h,c){ctx.fillStyle=c;ctx.fillRect(x,y,w,h)}
41
+ function gpx(g,x,y,c){g.fillStyle=c;g.fillRect(x,y,1,1)}
42
+ function grect(g,x,y,w,h,c){g.fillStyle=c;g.fillRect(x,y,w,h)}
43
+
44
+ function createIcon(w,h,scale,drawFn){
45
+ const c=document.createElement('canvas');c.width=w;c.height=h;
46
+ c.style.width=(w*scale)+'px';c.style.height=(h*scale)+'px';
47
+ c.style.imageRendering='pixelated';drawFn(c.getContext('2d'),w,h);return c;
48
+ }
49
+ function makeIcon(name,scale){
50
+ if(!ICONS[name]){var fc=document.createElement('canvas');fc.width=1;fc.height=1;fc.style.display='none';return fc;}
51
+ return createIcon(16,16,scale||2,ICONS[name]);
52
+ }
53
+ function makePortrait(name){
54
+ if(!PORTRAITS[name])return document.createElement('canvas');
55
+ return createIcon(32,32,3,PORTRAITS[name]);
56
+ }
57
+
58
+ const TOTAL_CHAPTERS=GAME.totalChapters||8;
59
+ (function(){const bar=document.getElementById('chapter-bar');for(let i=0;i<TOTAL_CHAPTERS;i++){const d=document.createElement('div');d.className='ch-dot';d.id='ch'+i;bar.appendChild(d)}})();
60
+
61
+ const CHAR_W=24,CHAR_H=36,CHAR_SCALE=4;
62
+ function createCharCanvas(drawFn){
63
+ const c=document.createElement('canvas');c.width=CHAR_W;c.height=CHAR_H;
64
+ c.style.width=(CHAR_W*CHAR_SCALE)+'px';c.style.height=(CHAR_H*CHAR_SCALE)+'px';
65
+ c.className='char-sprite';drawFn(c.getContext('2d'));return c;
66
+ }
67
+
68
+ let particles=[];
69
+ function spawnParticles(x,y,type,count){
70
+ const colors=GAME.particleColors||['#ffc0d0','#ff6a9a','#90e0a0','#80b0e0','#ffb0c0','#e0a0ff'];
71
+ for(let i=0;i<count;i++){
72
+ const a=Math.random()*Math.PI*2;const s=Math.random()*3+1;
73
+ particles.push({x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s-(type==='confetti'?2:1),life:1,type,color:colors[Math.floor(Math.random()*colors.length)]});
74
+ }
75
+ }
76
+ const pCanvas=document.getElementById('particles-canvas');const pCtx=pCanvas.getContext('2d');
77
+ function updateParticles(){
78
+ pCtx.clearRect(0,0,768,576);
79
+ particles=particles.filter(p=>{p.x+=p.vx;p.y+=p.vy;p.vy+=0.08;p.life-=0.015;if(p.life<=0)return false;pCtx.globalAlpha=p.life;pCtx.fillStyle=p.color;pCtx.fillRect(p.x,p.y,p.type==='confetti'?4:3,p.type==='confetti'?4:3);return true});
80
+ pCtx.globalAlpha=1;if(particles.length>0)requestAnimationFrame(updateParticles);
81
+ }
82
+ setInterval(()=>{if(particles.length>0)updateParticles()},50);
83
+
84
+ (function(){
85
+ const inp=document.getElementById('player-name-input');
86
+ const stored=localStorage.getItem('edgame_user_name');
87
+ if(stored&&inp){inp.value=stored;inp.placeholder=stored}
88
+ inp.addEventListener('keydown',e=>{if(e.key==='Enter')startGame()});
89
+ async function tryAutoStart(){
90
+ if(!window.auth||!GAME.courseId||!GAME.chunkId)return;
91
+ try{
92
+ await auth.ready();
93
+ const r=await auth.canPlayGame(GAME.courseId,GAME.chunkId);
94
+ if(!r.allowed){
95
+ if(window.authUI){authUI.showPaywall(r.reason,GAME.courseId,GAME.chunkId,r)}
96
+ return;
97
+ }
98
+ }catch(e){}
99
+ }
100
+ document.addEventListener('ahafrog-paywall-unlocked',function(ev){
101
+ if(ev.detail&&ev.detail.courseId===GAME.courseId&&ev.detail.chunkId===GAME.chunkId&&typeof startGame==='function'){startGame()}
102
+ });
103
+ if(window._localeReady){window._localeReady.then(tryAutoStart)}else{tryAutoStart()}
104
+ })();
105
+
106
+ window._goNextGame=function(){
107
+ var url=typeof GAME!=='undefined'&&GAME.nextGameUrl?GAME.nextGameUrl:null;
108
+ if(!url){return;}
109
+ var nextChunkId=(url.match(/(chunk-\d+)/)||[])[1]||null;
110
+ if(!window.auth||!GAME.courseId||!nextChunkId){location.href=url;return;}
111
+ auth.canPlayGame(GAME.courseId,nextChunkId).then(function(r){
112
+ if(r&&r.allowed){location.href=url;return;}
113
+ if(window.authUI){authUI.showPaywall((r&&r.reason)||'login_required',GAME.courseId,nextChunkId,r);}
114
+ else{location.href=url;}
115
+ }).catch(function(){location.href=url;});
116
+ };
117
+
118
+ let currentChapter=0,scriptIndex=0,gameState='title';
119
+ let chapterComplete=new Array(TOTAL_CHAPTERS).fill(false);
120
+ let _gameStartTime=Date.now();
121
+ const _ui=GAME.ui||{};
122
+ let playerName=GAME.defaultPlayerName||_ui.defaultPlayer||'研究员';
123
+ let currentSpeaker=null;let currentChars=[];
124
+ let _lastMiniGameType=null;
125
+
126
+ let totalXP=0,playerLevel=0,_mgScore=null,_minigameClosing=false;
127
+ // XP for finishing an activity that reported no score. Flat and small on
128
+ // purpose: it credits the time spent without pretending to measure it.
129
+ const COMPLETION_XP=20;
130
+ const _chapterStars={};
131
+ const _LV_THRESHOLDS=[0,120,320,600,1000,1500];
132
+ const _LV_NAMES=_ui.levelNames||['✦ 初学者','✦✦ 探索者','✦✦✦ 学者','✧ 专家','✧✧ 大师','✧✧✧ 宗师'];
133
+ function _getLevel(xp){for(let i=_LV_THRESHOLDS.length-1;i>=0;i--)if(xp>=_LV_THRESHOLDS[i])return i;return 0}
134
+ function _getLevelName(lv){return _LV_NAMES[Math.min(lv,_LV_NAMES.length-1)]}
135
+ function _getStars(s){return s>=85?3:s>=55?2:s>=25?1:0}
136
+ function _starsText(n){if(typeof n!=='number')return '';return '★'.repeat(n)+'☆'.repeat(3-n)}
137
+
138
+ function _addXP(amount){
139
+ const oldLv=playerLevel;totalXP+=amount;playerLevel=_getLevel(totalXP);
140
+ _updateXPBar();
141
+ if(playerLevel>oldLv)_showLevelUp(playerLevel);
142
+ }
143
+ function _updateXPBar(){
144
+ const bar=document.getElementById('xp-bar');if(!bar)return;
145
+ bar.style.display='block';
146
+ const cur=_LV_THRESHOLDS[playerLevel]||0;
147
+ const nxt=_LV_THRESHOLDS[playerLevel+1]||cur+100;
148
+ const pct=Math.min(((totalXP-cur)/(nxt-cur))*100,100);
149
+ const fill=document.getElementById('xp-fill');if(fill)fill.style.width=pct+'%';
150
+ const label=document.getElementById('xp-label');
151
+ if(label)label.textContent=(_ui.levelPrefix||'Lv.')+' '+(playerLevel+1)+' '+_getLevelName(playerLevel)+' · '+totalXP+' '+(_ui.xpUnit||'XP');
152
+ }
153
+
154
+ function _showLevelUp(lv){
155
+ Audio.playSFX('levelUp');
156
+ const ov=document.getElementById('level-up-overlay');if(!ov)return;
157
+ const th=GAME.theme||{};
158
+ ov.innerHTML='<div style="text-align:center;animation:levelUpPop 0.5s">'+
159
+ '<div style="font-size:48px;margin-bottom:8px">🎉</div>'+
160
+ '<div style="color:'+(th.highlight||'#ffc0d0')+';font-size:20px;letter-spacing:3px">'+(_ui.levelUp||'等级提升!')+'</div>'+
161
+ '<div style="color:'+(th.accent||'#ff6a9a')+';font-size:32px;margin:8px 0;font-weight:bold">'+(_ui.levelPrefix||'Lv.')+' '+(lv+1)+'</div>'+
162
+ '<div style="color:'+(th.success||'#90e0a0')+';font-size:15px">'+_getLevelName(lv)+'</div></div>';
163
+ ov.style.display='flex';
164
+ spawnParticles(384,250,'confetti',50);
165
+ setTimeout(function(){ov.style.display='none';ov.innerHTML=''},2500);
166
+ }
167
+
168
+ function _showChapterTransition(ch){
169
+ const ov=document.getElementById('chapter-transition');if(!ov)return;
170
+ const th=GAME.theme||{};
171
+ const _chFmt=(_ui.chapterFormat||'Ch.{n}').replace('{n}',ch+1);
172
+ const title=(GAME.chapterTitles&&GAME.chapterTitles[ch])||_chFmt;
173
+ ov.innerHTML='<div style="text-align:center;animation:chapterSlide 0.6s">'+
174
+ '<div style="color:'+(th.muted||'#c080a0')+';font-size:10px;letter-spacing:4px;text-transform:uppercase;margin-bottom:6px">'+_chFmt+'</div>'+
175
+ '<div style="color:'+(th.highlight||'#ffc0d0')+';font-size:22px;letter-spacing:2px;margin-bottom:12px">'+title+'</div>'+
176
+ '<div style="width:40px;height:2px;background:'+(th.accent||'#ff6a9a')+';margin:0 auto 12px;border-radius:1px"></div>'+
177
+ '<div style="color:'+(th.accent||'#ff6a9a')+';font-size:11px">'+(_ui.levelPrefix||'Lv.')+' '+(playerLevel+1)+' '+_getLevelName(playerLevel)+' · '+totalXP+' '+(_ui.xpUnit||'XP')+'</div></div>';
178
+ ov.style.display='flex';
179
+ Audio.playSFX('chapterDone');
180
+ ov.onclick=function(){ov.style.display='none';ov.onclick=null};
181
+ setTimeout(function(){ov.style.display='none';ov.onclick=null},2200);
182
+ }
183
+
184
+ function _showScoreFeedback(score,xpGained,stars){
185
+ const fb=document.getElementById('score-feedback');if(!fb)return;
186
+ const th=GAME.theme||{};
187
+ const starColor=stars===3?(th.success||'#90e0a0'):stars===2?(th.accent||'#ff6a9a'):(th.muted||'#c080a0');
188
+ fb.innerHTML='<div style="animation:scorePop 0.4s">'+
189
+ (typeof stars==='number'
190
+ ? '<div style="font-size:24px;color:'+starColor+';letter-spacing:4px">'+_starsText(stars)+'</div>'
191
+ : '')+
192
+ '<div style="color:'+(th.highlight||'#ffc0d0')+';font-size:13px;margin-top:4px">+'+xpGained+' '+(_ui.xpUnit||'XP')+'</div></div>';
193
+ fb.style.display='block';
194
+ setTimeout(function(){fb.style.animation='scoreFloat 0.5s forwards';
195
+ setTimeout(function(){fb.style.display='none';fb.style.animation='';fb.innerHTML=''},500)},1200);
196
+ }
197
+
198
+ function _updateChapterStars(ch,stars){
199
+ // Nothing was measured, so nothing is recorded. The chapter then stays out
200
+ // of the star totals entirely instead of counting as a zero out of three.
201
+ if(typeof stars!=='number')return;
202
+ _chapterStars[ch]=Math.max(_chapterStars[ch]||0,stars);
203
+ const dot=document.getElementById('ch'+ch);
204
+ if(dot){
205
+ let s=dot.querySelector('.ch-stars');
206
+ if(!s){s=document.createElement('div');s.className='ch-stars';dot.appendChild(s)}
207
+ s.textContent=_starsText(_chapterStars[ch]);
208
+ }
209
+ }
210
+
211
+ const CHAR_NAME_MAP={};
212
+ if(GAME.characters){
213
+ Object.entries(GAME.characters).forEach(([id,info])=>{
214
+ if(id==='player')CHAR_NAME_MAP.player=()=>playerName;
215
+ else CHAR_NAME_MAP[id]=()=>info.name;
216
+ });
217
+ }
218
+ if(!CHAR_NAME_MAP.player)CHAR_NAME_MAP.player=()=>playerName;
219
+
220
+ function personalizeText(text){return (text||'').replace(/\{player\}/g,playerName)}
221
+
222
+ function renderScene(bgIdx,chars){try{ctx.clearRect(0,0,128,96);if(BACKGROUNDS[bgIdx])BACKGROUNDS[bgIdx](ctx);renderCharacters(chars)}catch(e){console.error('renderScene error bg='+bgIdx,e)}}
223
+
224
+ /* Which character is speaking, by the name shown on the tab. CHAR_NAME_MAP
225
+ holds functions rather than strings because the player's own name can
226
+ change in settings mid-game. */
227
+ function _speakerId(displayName){
228
+ for(const[id,fn]of Object.entries(CHAR_NAME_MAP))if(fn()===displayName)return id;
229
+ return null;
230
+ }
231
+
232
+ /* The portrait falls back twice before giving up, so a speaker is shown with
233
+ whatever art the course actually has:
234
+ 1. a pixel-pack Faceset, when the character names a `sprite`
235
+ 2. the course's own PORTRAITS draw function
236
+ 3. the overworld sprite the character is already drawn with, cropped to
237
+ head and shoulders by the frame's overflow
238
+ With none of the three the column is removed (.no-face) rather than left as
239
+ an empty frame — that is what the pack's plain DialogBox sprite looks like. */
240
+ function updateDialogPortrait(displayName){
241
+ const box=document.getElementById('dialog-box');
242
+ const frame=document.getElementById('dialog-portrait');
243
+ const slot=document.getElementById('dialog-portrait-inner');
244
+ if(!box||!frame||!slot)return;
245
+ const id=_speakerId(displayName);
246
+ const info=(id&&typeof GAME!=='undefined'&&GAME.characters)?GAME.characters[id]:null;
247
+ const spriteName=info&&info.sprite;
248
+ slot.innerHTML='';
249
+ const token=++_portraitToken;
250
+ if(spriteName&&window.PixelPack&&PixelPack.ready){
251
+ PixelPack.ready().then(function(available){
252
+ if(token!==_portraitToken)return; // a later line already drew
253
+ if(available&&PixelPack.has('character',spriteName)){
254
+ // The catalogue lists what the pack contains; it cannot know what is
255
+ // actually served. This repository ships the UI frames only, so a
256
+ // listed character is usually NOT on disk -- draw the procedural
257
+ // portrait rather than leaving a broken image in the frame.
258
+ const im=new Image();im.alt='';
259
+ im.onerror=function(){ if(token!==_portraitToken)return;
260
+ slot.innerHTML=''; _portraitFallback(box,slot,id,displayName); };
261
+ im.src=PixelPack.faceUrl('character',spriteName);
262
+ slot.appendChild(im);box.classList.remove('no-face');
263
+ }else _portraitFallback(box,slot,id,displayName);
264
+ });
265
+ return;
266
+ }
267
+ _portraitFallback(box,slot,id,displayName);
268
+ }
269
+
270
+ let _portraitToken=0;
271
+ function _portraitFallback(box,slot,id,displayName){
272
+ if(window.PORTRAITS&&id&&PORTRAITS[id]){
273
+ slot.appendChild(makePortrait(id));box.classList.remove('no-face');return;
274
+ }
275
+ if(window.PORTRAITS&&PORTRAITS[displayName]){
276
+ slot.appendChild(makePortrait(displayName));box.classList.remove('no-face');return;
277
+ }
278
+ if(window.CHAR_DRAW_FNS&&id&&typeof CHAR_DRAW_FNS[id]==='function'){
279
+ slot.appendChild(createCharCanvas(CHAR_DRAW_FNS[id]));box.classList.remove('no-face');return;
280
+ }
281
+ box.classList.add('no-face');
282
+ }
283
+
284
+ let dialogTypingDone=false,dialogLocked=false,currentTypingInterval=null;
285
+ function showDialog(name,text){
286
+ const displayName=personalizeText(name);const displayText=personalizeText(text);
287
+ document.getElementById('dialog-box').style.display='flex';
288
+ document.getElementById('dialog-name').textContent=displayName;
289
+ updateDialogPortrait(displayName);
290
+ const textEl=document.getElementById('dialog-text');textEl.textContent='';
291
+ dialogTypingDone=false;dialogLocked=true;highlightSpeaker(displayName);
292
+ if(currentTypingInterval)clearInterval(currentTypingInterval);
293
+ let i=0;currentTypingInterval=setInterval(()=>{
294
+ if(i<displayText.length){textEl.textContent+=displayText[i];i++}
295
+ else{clearInterval(currentTypingInterval);currentTypingInterval=null;dialogTypingDone=true}
296
+ },18);
297
+ setTimeout(()=>{dialogLocked=false},80);
298
+ }
299
+ function skipTyping(){
300
+ if(currentTypingInterval){clearInterval(currentTypingInterval);currentTypingInterval=null}
301
+ const cmd=SCRIPT[scriptIndex];
302
+ if(cmd&&cmd.type==='dialog')document.getElementById('dialog-text').textContent=personalizeText(cmd.text);
303
+ dialogTypingDone=true;
304
+ }
305
+ function hideDialog(){
306
+ document.getElementById('dialog-box').style.display='none';
307
+ if(currentTypingInterval){clearInterval(currentTypingInterval);currentTypingInterval=null}
308
+ currentSpeaker=null;document.querySelectorAll('.char-wrapper').forEach(w=>w.classList.remove('speaking','silent'));
309
+ }
310
+ function hideCharacters(){document.getElementById('character-layer').innerHTML='';currentChars=[]}
311
+
312
+ function renderCharacters(chars){
313
+ const layer=document.getElementById('character-layer');layer.innerHTML='';
314
+ if(!chars||!chars.length){currentChars=[];return}
315
+ currentChars=chars;
316
+ chars.forEach(c=>{
317
+ const w=document.createElement('div');w.className='char-wrapper';w.dataset.charId=c.id;
318
+ w.style.left=((c.x/128)*768-(CHAR_W*CHAR_SCALE)/2)+'px';
319
+ const nt=document.createElement('div');nt.className='char-name-tag';
320
+ nt.textContent=CHAR_NAME_MAP[c.id]?CHAR_NAME_MAP[c.id]():'';
321
+ w.appendChild(nt);
322
+ if(CHAR_DRAW_FNS&&CHAR_DRAW_FNS[c.id]&&typeof CHAR_DRAW_FNS[c.id]==='function')w.appendChild(createCharCanvas(CHAR_DRAW_FNS[c.id]));
323
+ layer.appendChild(w);
324
+ });
325
+ if(currentSpeaker)highlightSpeaker(currentSpeaker);
326
+ }
327
+
328
+ function highlightSpeaker(n){
329
+ currentSpeaker=n;const ws=document.querySelectorAll('.char-wrapper');if(!ws.length)return;
330
+ let sid=null;for(const[id,fn]of Object.entries(CHAR_NAME_MAP))if(fn()===n){sid=id;break}
331
+ ws.forEach(w=>{w.classList.remove('speaking','silent');if(sid&&w.dataset.charId===sid)w.classList.add('speaking');else if(sid)w.classList.add('silent')});
332
+ }
333
+
334
+ function updateChapterBar(){
335
+ for(let i=0;i<TOTAL_CHAPTERS;i++){
336
+ const d=document.getElementById('ch'+i);d.className='ch-dot';
337
+ if(chapterComplete[i])d.classList.add('done');else if(i===currentChapter)d.classList.add('active');
338
+ }
339
+ updateHearts();
340
+ }
341
+
342
+ /* ── Life hearts ───────────────────────────────────────────────────────────
343
+ The HUD's five hearts are quarter-fillable, so the row is a 20-step meter.
344
+ WHAT it measures is a design decision, not a technical one, and this one
345
+ function is where it is made: today it is how much of the course is behind
346
+ you, because the engine has no damage model — nothing can take a heart away.
347
+ Change this and the HUD changes meaning (lives spent on wrong answers,
348
+ stars earned, minigame score) without touching anything else. */
349
+ function _heartQuarters(){
350
+ if(!TOTAL_CHAPTERS)return 20;
351
+ let done=0;for(let i=0;i<TOTAL_CHAPTERS;i++)if(chapterComplete[i])done++;
352
+ return Math.round((done/TOTAL_CHAPTERS)*20);
353
+ }
354
+
355
+ function updateHearts(){
356
+ const bar=document.getElementById('hp-hearts');
357
+ if(!bar||!window.PixelPack||!PixelPack.ready)return;
358
+ PixelPack.ready().then(function(available){
359
+ // No pack, no art: leave the chapter dots as the whole progress display.
360
+ if(!available){bar.classList.remove('on');return}
361
+ if(!bar.childElementCount){
362
+ for(let i=0;i<5;i++){
363
+ const h=document.createElement('div');h.className='hp-heart';
364
+ h.style.backgroundImage="url('"+(window.PIXELPACK_BASE||'/assets/pixelpack/')+"ui/Receptacle/Heart.png')";
365
+ bar.appendChild(h);
366
+ }
367
+ }
368
+ const q=_heartQuarters();
369
+ Array.prototype.forEach.call(bar.children,function(h,i){
370
+ const frame=Math.max(0,Math.min(4,q-i*4)); // 0 empty … 4 full
371
+ h.style.backgroundPositionX=(-frame*34)+'px';
372
+ });
373
+ bar.classList.add('on');
374
+ const dots=document.getElementById('chapter-bar');
375
+ if(dots)dots.classList.add('under-hearts');
376
+ });
377
+ }
378
+
379
+ function advanceDialog(){
380
+ if(dialogLocked)return;
381
+ if(gameState!=='dialog'){
382
+ if(gameState==='playing'&&!_deferredProcessTimer&&scriptIndex<SCRIPT.length){processScript()}
383
+ return;
384
+ }
385
+ if(!dialogTypingDone){skipTyping();Audio.playSFX('click');return}
386
+ dialogLocked=true;Audio.playSFX('click');scriptIndex++;
387
+ if(scriptIndex<SCRIPT.length)processScript();
388
+ }
389
+
390
+ // -- Created by Yuqi Hang (github.com/yh2072) --
391
+ function processScript(){
392
+ try{
393
+ if(scriptIndex>=SCRIPT.length){console.warn('processScript: scriptIndex',scriptIndex,'beyond SCRIPT length',SCRIPT.length);return}
394
+ const cmd=SCRIPT[scriptIndex];
395
+ if(!cmd){console.error('processScript: null cmd at index',scriptIndex);scriptIndex++;processScript();return}
396
+ if(cmd.type==='bg'){renderScene(cmd.bg,cmd.chars);scriptIndex++;processScript()}
397
+ else if(cmd.type==='chapter'){if(cmd.ch>0)chapterComplete[cmd.ch-1]=true;currentChapter=cmd.ch;updateChapterBar();_reportProgress(Math.min(0.9,(cmd.ch+1)/TOTAL_CHAPTERS));scriptIndex++;if(cmd.ch>0){_showChapterTransition(cmd.ch);_scheduleProcess(2300)}else{processScript()}}
398
+ else if(cmd.type==='dialog'){gameState='dialog';dialogLocked=false;showDialog(cmd.name,cmd.text)}
399
+ else if(cmd.type==='minigame'){hideDialog();hideCharacters();gameState='minigame';Audio.fadeOutBGM(400);setTimeout(()=>Audio.playBGM('minigame'),500);launchMiniGame(cmd.game)}
400
+ else if(cmd.type==='end'){chapterComplete[TOTAL_CHAPTERS-1]=true;updateChapterBar();hideDialog();hideCharacters();Audio.fadeOutBGM(400);setTimeout(()=>Audio.playBGM('victory'),500);showEndScreen()}
401
+ else{console.warn('processScript: unknown cmd type',cmd.type,'at',scriptIndex);scriptIndex++;processScript()}
402
+ }catch(e){
403
+ console.error('processScript error at index',scriptIndex,e);
404
+ scriptIndex++;
405
+ setTimeout(processScript,100);
406
+ }
407
+ }
408
+
409
+ document.getElementById('dialog-click-area').addEventListener('click',advanceDialog);
410
+ document.getElementById('dialog-box').addEventListener('click',advanceDialog);
411
+
412
+ let _stuckCheckTimer=null,_deferredProcessTimer=null;
413
+ function _scheduleProcess(ms){if(_deferredProcessTimer)clearTimeout(_deferredProcessTimer);_deferredProcessTimer=setTimeout(function(){_deferredProcessTimer=null;processScript()},ms)}
414
+ function _checkStuck(){
415
+ if(gameState==='title'||gameState==='dialog'||gameState==='minigame')return;
416
+ if(_deferredProcessTimer)return;
417
+ const dialogBox=document.getElementById('dialog-box');
418
+ const mgOverlay=document.getElementById('mini-game-overlay');
419
+ const chTrans=document.getElementById('chapter-transition');
420
+ const scoreFb=document.getElementById('score-feedback');
421
+ const dialogVisible=dialogBox&&dialogBox.style.display!=='none';
422
+ const mgVisible=mgOverlay&&mgOverlay.style.display!=='none';
423
+ const chVisible=chTrans&&chTrans.style.display!=='none';
424
+ const scoreVisible=scoreFb&&scoreFb.style.display!=='none';
425
+ if(!dialogVisible&&!mgVisible&&!chVisible&&!scoreVisible&&scriptIndex<SCRIPT.length){
426
+ console.warn('Stuck-state detected: gameState='+gameState+' scriptIndex='+scriptIndex+' - auto-recovering');
427
+ gameState='playing';dialogLocked=false;
428
+ processScript();
429
+ }
430
+ }
431
+ document.getElementById('game-container').addEventListener('click',function(){
432
+ if(_stuckCheckTimer)clearTimeout(_stuckCheckTimer);
433
+ _stuckCheckTimer=setTimeout(_checkStuck,500);
434
+ });
435
+
436
+ function startGame(){
437
+ const ni=document.getElementById('player-name-input').value.trim();
438
+ const storedName=localStorage.getItem('edgame_user_name');
439
+ playerName=ni||storedName||GAME.defaultPlayerName||_ui.defaultPlayer||'研究员';
440
+ if(storedName&&!ni)document.getElementById('player-name-input').value=playerName;
441
+ CHAR_NAME_MAP.player=()=>playerName;
442
+ Audio.ensureContext();Audio.playSFX('maximize');Audio.fadeOutBGM(600);
443
+ setTimeout(()=>Audio.playBGM('dialog'),700);
444
+ document.getElementById('title-screen').style.display='none';
445
+ gameState='playing';scriptIndex=0;_gameStartTime=Date.now();
446
+ document.getElementById('game-container').classList.add('playing');
447
+ updateChapterBar();processScript();
448
+ _reportProgress('started');
449
+ if(window.auth&&GAME.courseId&&GAME.chunkId){try{auth.recordGamePlay(GAME.courseId,GAME.chunkId)}catch(e){}}
450
+ if(window.ahafrogAnalytics&&GAME.courseId&&GAME.chunkId){try{ahafrogAnalytics.trackGameStart(GAME.courseId,GAME.chunkId,{player:playerName})}catch(e){}}
451
+ }
452
+ function _reportProgress(status){
453
+ try{
454
+ const chunkId=GAME.chunkId||'';
455
+ if(!chunkId)return;
456
+ const prog=JSON.parse(localStorage.getItem('edgame_progress')||'{}');
457
+ if(status==='started'){prog[chunkId]={progress:0.1,startedAt:new Date().toISOString()}}
458
+ else if(status==='completed'){prog[chunkId]={completed:true,progress:1,completedAt:new Date().toISOString()}}
459
+ else if(typeof status==='number'){prog[chunkId]=prog[chunkId]||{};prog[chunkId].progress=status}
460
+ localStorage.setItem('edgame_progress',JSON.stringify(prog));
461
+ }catch(e){}
462
+ }
463
+
464
+ function showEndScreen(){
465
+ const ov=document.getElementById('mini-game-overlay');ov.style.display='flex';
466
+ const th=GAME.theme||{};const endData=GAME.endScreen||{};
467
+ const iconNames=endData.icons||[];
468
+ const _endTitle=(_ui.endTitle||'✿ 恭喜你,{player}!✿').replace('{player}',playerName);
469
+ const _endSub=(_ui.endSub||'{player},你完成了全部 {total} 章!').replace('{player}',playerName).replace('{total}',TOTAL_CHAPTERS);
470
+ var totalStars=0,maxStars=0;
471
+ for(var k in _chapterStars){totalStars+=_chapterStars[k];maxStars+=3}
472
+ if(!maxStars)maxStars=TOTAL_CHAPTERS*3;
473
+ var avgPct=maxStars>0?Math.round((totalStars/maxStars)*100):0;
474
+ var grade=avgPct>=90?'S':avgPct>=75?'A':avgPct>=60?'B':avgPct>=40?'C':'D';
475
+ var gradeColor=avgPct>=90?(th.success||'#88ce02'):avgPct>=60?(th.accent||'#00e5c8'):(th.muted||'#7878a0');
476
+ var starSummary='';
477
+ for(var ci=0;ci<TOTAL_CHAPTERS;ci++){
478
+ var s=_chapterStars[ci]||0;
479
+ var cTitle=(GAME.chapterTitles&&GAME.chapterTitles[ci])?GAME.chapterTitles[ci]:(_ui.chapterFormat||'Ch.{n}').replace('{n}',ci+1);
480
+ starSummary+='<div style="display:flex;justify-content:space-between;align-items:center;padding:4px 0;border-bottom:1px solid rgba(255,255,255,0.05)">'+
481
+ '<span style="color:'+(th.muted||'#7878a0')+';font-size:11px">'+cTitle+'</span>'+
482
+ '<span style="color:'+(s===3?(th.success||'#88ce02'):s===2?(th.accent||'#00e5c8'):(th.muted||'#7878a0'))+';font-size:12px;letter-spacing:2px">'+_starsText(s)+'</span></div>';
483
+ }
484
+ ov.innerHTML='<div style="text-align:center;max-width:560px;margin:0 auto">'+
485
+ '<div class="mg-title" style="font-size:24px;margin-bottom:8px">'+_endTitle+'</div>'+
486
+ '<div class="mg-instruction" style="font-size:14px;color:'+(th.success||'#90e0a0')+'">'+_endSub+'</div>'+
487
+ '<div style="display:flex;gap:20px;justify-content:center;margin:16px 0;flex-wrap:wrap">'+
488
+ '<div style="text-align:center;padding:12px 20px;background:rgba(255,255,255,0.03);border-radius:12px;border:1px solid '+(th.border||'#26263c')+'">'+
489
+ '<div style="color:'+gradeColor+';font-size:36px;font-weight:bold">'+grade+'</div>'+
490
+ '<div style="color:'+(th.muted||'#7878a0')+';font-size:10px">'+(_ui.grade||'评级')+'</div></div>'+
491
+ '<div style="text-align:center;padding:12px 20px;background:rgba(255,255,255,0.03);border-radius:12px;border:1px solid '+(th.border||'#26263c')+'">'+
492
+ '<div style="color:'+(th.success||'#88ce02')+';font-size:24px;font-weight:bold">'+totalStars+'/'+maxStars+'</div>'+
493
+ '<div style="color:'+(th.muted||'#7878a0')+';font-size:10px">★ '+(_ui.stars||'星级')+'</div></div>'+
494
+ '<div style="text-align:center;padding:12px 20px;background:rgba(255,255,255,0.03);border-radius:12px;border:1px solid '+(th.border||'#26263c')+'">'+
495
+ '<div style="color:'+(th.accent||'#00e5c8')+';font-size:24px;font-weight:bold">'+(_ui.levelPrefix||'Lv.')+' '+(playerLevel+1)+'</div>'+
496
+ '<div style="color:'+(th.muted||'#7878a0')+';font-size:10px">'+_getLevelName(playerLevel)+'</div></div>'+
497
+ '</div>'+
498
+ '<div style="max-width:400px;margin:0 auto 16px;text-align:left">'+starSummary+'</div>'+
499
+ '<div id="end-icons" style="display:flex;gap:8px;justify-content:center;margin:12px 0;flex-wrap:wrap"></div>'+
500
+ '<div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap">'+
501
+ '<button class="mg-btn" style="font-size:14px;padding:12px 32px;background:rgba(136,206,2,0.12);border-color:'+(th.success||'#88ce02')+';color:'+(th.success||'#88ce02')+';border-radius:20px;display:inline-flex;align-items:center;gap:6px" onclick="location.reload()"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.5"/></svg>'+(_ui.playAgain||'再玩一次')+'</button>'+
502
+ (GAME.nextGameUrl?'<button class="mg-btn" style="font-size:14px;padding:12px 32px;background:rgba(0,229,200,0.12);border-color:'+(th.accent||'#00e5c8')+';color:'+(th.accent||'#00e5c8')+';border-radius:20px;display:inline-flex;align-items:center;gap:6px" onclick="window._goNextGame&&window._goNextGame()"><svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="none"><polygon points="5,3 19,12 5,21"/></svg>'+(_ui.nextGame||'下一关')+'</button>':'')+
503
+ (!GAME.nextGameUrl?'<a class="mg-btn" href="../.." style="font-size:14px;padding:12px 32px;border-color:'+(th.border||'#26263c')+';color:'+(th.muted||'#7878a0')+';border-radius:20px;text-decoration:none;pointer-events:auto;display:inline-flex;align-items:center;gap:6px"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>'+(_ui.backToCourse||'返回课程')+'</a>':'')+
504
+ '</div></div>';
505
+ iconNames.forEach(function(n){var el=document.getElementById('end-icons');if(el)el.appendChild(makeIcon(n,3))});
506
+ spawnParticles(384,200,'confetti',60);
507
+ _reportProgress('completed');
508
+ if(window.ahafrogAnalytics&&GAME.courseId&&GAME.chunkId){try{var _elapsed=Date.now()-(_gameStartTime||Date.now());var _avgScore=totalStars&&maxStars?Math.round(totalStars/maxStars*100):0;ahafrogAnalytics.trackGameComplete(GAME.courseId,GAME.chunkId,_avgScore,_elapsed)}catch(e){}}
509
+ if(window.auth&&GAME.courseId&&GAME.chunkId){try{var _elapsed=Date.now()-(_gameStartTime||Date.now());var _avgScore=totalStars&&maxStars?Math.round(totalStars/maxStars*100):0;auth.recordLessonComplete(GAME.courseId,GAME.chunkId,_avgScore,Math.round(_elapsed/1000))}catch(e){}}
510
+ }
511
+
512
+ // -- Created by Yuqi Hang (github.com/yh2072) --
513
+ const MINIGAME_BUILDERS={};
514
+ function registerMinigame(type,builderFn){MINIGAME_BUILDERS[type]=builderFn}
515
+
516
+ function _buildMinigame(type,ov,mgData){
517
+ if(MINIGAME_BUILDERS[type]){
518
+ try{
519
+ MINIGAME_BUILDERS[type](ov,mgData);ov.style.display='flex';
520
+ // Safety delegate: if the sim's #done button fails to attach its own listener,
521
+ // this catches the click and still calls closeMiniGame().
522
+ (function(){var _sd=function(e){
523
+ if(gameState!=='minigame')return;
524
+ var t=e.target&&(e.target.id==='done'||(e.target.closest&&e.target.closest('[id="done"]')));
525
+ if(t){ov.removeEventListener('click',_sd);closeMiniGame();}
526
+ };ov.addEventListener('click',_sd);})();
527
+ }
528
+ catch(e){console.error('Minigame error:',type,e);try{if(GAME.courseId&&GAME.chunkId){fetch('/api/report-minigame-error',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({course_id:GAME.courseId,chunk_id:GAME.chunkId,minigame_type:type,error:String(e)})}).catch(()=>{});}}catch(_){}ov.innerHTML=`<div class="mg-title">⚠ ${type}</div><div class="mg-instruction" style="color:#ff6060">${_ui.loadError||'加载失败'}</div><button class="mg-btn" onclick="closeMiniGame()" style="pointer-events:auto">${_ui.skip||'跳过 →'}</button>`;ov.style.display='flex';}
529
+ } else {
530
+ ov.innerHTML=`<div class="mg-title">小游戏:${type}</div><div class="mg-instruction">该小游戏类型尚未实现。</div><button class="mg-btn" onclick="closeMiniGame()" style="pointer-events:auto">跳过 →</button>`;
531
+ }
532
+ }
533
+
534
+ function _getMiniTutorial(type,data){
535
+ if(type.startsWith('sim_'))return data&&data.subtitle?data.subtitle:null;
536
+ return null;
537
+ }
538
+
539
+ let _mgIsFullscreen=false;
540
+ function _openReportModal(){
541
+ if(!GAME.courseId||!GAME.chunkId)return;
542
+ var overlay=document.createElement('div');
543
+ overlay.id='mg-report-overlay';
544
+ overlay.style.cssText='position:fixed;inset:0;z-index:300;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);backdrop-filter:blur(6px);pointer-events:auto';
545
+ var inner=document.createElement('div');
546
+ inner.style.cssText='background:rgba(28,18,32,0.98);border:1px solid rgba(255,100,150,0.3);border-radius:14px;padding:20px 24px;max-width:360px;width:90%';
547
+ var th=GAME.theme||{};
548
+ inner.innerHTML='<div class="mg-title" style="margin-bottom:12px;color:'+(th.highlight||'#ffc0d0')+'">报错 / Report</div>'+
549
+ '<p style="font-size:12px;color:'+(th.muted||'#c080a0')+';margin-bottom:10px">问题描述(选填)</p>'+
550
+ '<textarea id="mg-report-msg" placeholder="e.g. 画面卡住、题目显示不全…" style="width:100%;min-height:80px;padding:10px;border-radius:8px;border:1px solid rgba(255,255,255,0.15);background:rgba(255,255,255,0.05);color:#e8d8f0;font-size:13px;resize:vertical;box-sizing:border-box" maxlength="1000"></textarea>'+
551
+ '<div style="margin-top:14px;display:flex;gap:10px;justify-content:flex-end">'+
552
+ '<button type="button" id="mg-report-cancel" class="mg-btn" style="pointer-events:auto;padding:8px 16px">取消</button>'+
553
+ '<button type="button" id="mg-report-submit" class="mg-btn" style="pointer-events:auto;padding:8px 20px;border-color:'+(th.success||'#90e0a0')+';color:'+(th.success||'#90e0a0')+'">提交</button></div>';
554
+ overlay.appendChild(inner);
555
+ document.body.appendChild(overlay);
556
+ function closeReportModal(){var o=document.getElementById('mg-report-overlay');if(o)o.remove();}
557
+ document.getElementById('mg-report-cancel').onclick=closeReportModal;
558
+ document.getElementById('mg-report-submit').onclick=function(){
559
+ var msg=(document.getElementById('mg-report-msg').value||'').trim().slice(0,1000);
560
+ var payload={course_id:GAME.courseId,chunk_id:GAME.chunkId,minigame_type:_lastMiniGameType||'',error:'',message:msg};
561
+ fetch('/api/report-minigame-error',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}).then(function(){closeReportModal();if(typeof _ui!=='undefined'&&_ui.reportSubmitted)alert(_ui.reportSubmitted);else alert('已提交,感谢反馈');}).catch(function(){closeReportModal();alert('提交失败,请稍后再试');});
562
+ };
563
+ }
564
+ function _attachSkipButton(){
565
+ if(gameState!=='minigame')return;
566
+ var s=document.getElementById('mg-skip-fixed');
567
+ if(s){s.textContent=_ui.skip||'跳过 →';s.onclick=function(){closeMiniGame()};s.style.display='inline-block';}
568
+ var r=document.getElementById('mg-report-fixed');
569
+ if(r){r.textContent='报错';r.onclick=function(){_openReportModal()};r.style.display='inline-block';}
570
+ }
571
+
572
+ // A sim's subtitle is written by the generator as a three-beat spec --
573
+ // [what you do] - [what you see] - [what you learn] -- and was being printed
574
+ // to the learner verbatim, brackets and dashes included. The brackets are the
575
+ // seam: split on them and the spec becomes the briefing it was always
576
+ // describing. Anything that does not match that shape falls through as prose,
577
+ // so a differently written subtitle still reads correctly.
578
+ function _tutorialBeats(text){
579
+ var m=String(text||'').match(/[\[【][^\]】]+[\]】]/g);
580
+ if(!m||m.length<2)return null;
581
+ return m.map(function(x){return x.replace(/^[\[【]|[\]】]$/g,'').trim()})
582
+ .filter(function(x){return x.length});
583
+ }
584
+ // Generated titles carry a decorative emoji from the pipeline. It is the one
585
+ // thing on this screen the pixel pack has no answer for, so it is dropped at
586
+ // render time -- which also fixes every course already on disk.
587
+ function _noEmoji(s){
588
+ var out=String(s==null?'':s).replace(/[‼-㊙️‍]|[\uD83C-\uDBFF][\uDC00-\uDFFF]/g,'').trim();
589
+ return out||String(s==null?'':s);
590
+ }
591
+ function _esc(s){
592
+ return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
593
+ }
594
+
595
+ // -- Created by Yuqi Hang (github.com/yh2072) --
596
+ function launchMiniGame(type){
597
+ _lastMiniGameType=type;
598
+ // The overlay is a column flexbox, so justify- is its vertical axis and
599
+ // align- the horizontal one. Both were pinned to flex-start, which parked
600
+ // every generated minigame in the top-left corner and let wide ones run
601
+ // out under the audio buttons. flex-start was there to keep tall content
602
+ // reachable back when the overlay scrolled; the host scales content to fit
603
+ // now, so nothing can be clipped and it can simply be centred.
604
+ const ov=document.getElementById('mini-game-overlay');ov.style.display='flex';ov.style.justifyContent='center';ov.style.alignItems='center';
605
+ _mgIsFullscreen=false;
606
+
607
+ const mgData=GAME.minigames[type]||{};
608
+ const tutorialText=mgData._tutorial||_getMiniTutorial(type,mgData);
609
+ if(tutorialText&&!mgData._tutorialSeen){
610
+ mgData._tutorialSeen=true;
611
+ const th=GAME.theme||{};
612
+ var beats=_tutorialBeats(tutorialText);
613
+ // Numbered badges rather than written labels: the beats mean the same
614
+ // thing in every locale this ships in, and a number needs no translating.
615
+ var bodyHtml=beats
616
+ ? '<ol class="mg-beats">'+beats.map(function(b,i){
617
+ return '<li><span class="mg-beat-n">'+(i+1)+'</span><span class="mg-beat-t">'+_esc(b)+'</span></li>';
618
+ }).join('')+'</ol>'
619
+ : '<p class="mg-brief-prose">'+_esc(tutorialText)+'</p>';
620
+ ov.innerHTML='<div class="mg-brief">'+
621
+ '<h2 class="mg-brief-title">'+_esc(_noEmoji(mgData.title||type))+'</h2>'+
622
+ '<div class="mg-brief-body">'+bodyHtml+'</div>'+
623
+ '<button class="mg-cta" id="tut-start" type="button">'+_esc(_ui.start||'开始')+' →</button>'+
624
+ '</div>';
625
+ ov.querySelector('#tut-start').addEventListener('click',function(){_buildMinigame(type,ov,mgData)});
626
+ } else {
627
+ _buildMinigame(type,ov,mgData);
628
+ }
629
+ _attachSkipButton();
630
+ }
631
+
632
+ function closeMiniGame(score){
633
+ if(_minigameClosing)return;_minigameClosing=true;
634
+ try{
635
+ var skip=document.getElementById('mg-skip-fixed');if(skip)skip.style.display='none';
636
+ var reportBtn=document.getElementById('mg-report-fixed');if(reportBtn)reportBtn.style.display='none';
637
+ const ov=document.getElementById('mini-game-overlay');if(!ov){_minigameClosing=false;return;}
638
+ // A minigame reports its result either by passing a score here or by
639
+ // setting _mgScore before closing. Anything else means it measured
640
+ // nothing -- which is not the same as measuring zero.
641
+ //
642
+ // This used to conflate the two: an unreported result arrived as 0, and
643
+ // any 0 from a sim was then rewritten to 70 so that a sim which forgot to
644
+ // score would not look like a failure. That rewrote real failures too, so
645
+ // closing a simulation without touching it paid out 70 points, two stars
646
+ // and 48 XP. An unmeasured score is now null and the result screen says so
647
+ // rather than inventing a number.
648
+ const reported = typeof score==='number' ? score
649
+ : (typeof _mgScore==='number' ? _mgScore : null);
650
+ _mgScore=null;
651
+ const finalScore = reported===null ? null : Math.min(100,Math.max(0,reported));
652
+ const stars = finalScore===null ? null : _getStars(finalScore);
653
+ const xpGained = finalScore===null ? COMPLETION_XP
654
+ : Math.round(finalScore*0.4+stars*10);
655
+ _showMiniGameResult(finalScore,xpGained,stars,ov);
656
+ }catch(e){
657
+ console.error('closeMiniGame error',e);
658
+ _minigameClosing=false;
659
+ _advanceMiniGame(0,0,0);
660
+ }
661
+ }
662
+
663
+ function _showMiniGameResult(finalScore,xpGained,stars,ov){
664
+ const th=GAME.theme||{};
665
+ const starColor=stars===3?(th.success||'#90e0a0'):stars===2?(th.accent||'#ff6a9a'):(th.muted||'#c080a0');
666
+ ov.style.display='flex';ov.style.justifyContent='center';ov.style.alignItems='center';
667
+ // The same paper card as the briefing, so finishing a minigame lands in the
668
+ // furniture the game has been speaking through rather than a glass panel.
669
+ // An activity that measured nothing gets a completion mark, not a score:
670
+ // a fabricated number here is worse than no number, because the player
671
+ // cannot tell it apart from one they earned.
672
+ var scoredHtml = (typeof finalScore==='number')
673
+ ? '<div class="mg-stars" style="color:'+starColor+'">'+_starsText(stars)+'</div>'+
674
+ '<div class="mg-score-big">'+finalScore+'<span class="mg-score-unit">'+_esc(_ui.scoreUnit||'pts')+'</span></div>'
675
+ : '<div class="mg-done-mark">'+_esc(_ui.complete||'Complete')+'</div>';
676
+ ov.innerHTML='<div class="mg-brief mg-result">'+
677
+ scoredHtml+
678
+ '<div class="mg-xp">+'+xpGained+' '+_esc(_ui.xpUnit||'XP')+'</div>'+
679
+ '<div class="mg-actions">'+
680
+ '<button class="mg-cta mg-cta-ghost" id="mg-retry-btn" type="button">\u21ba '+_esc(_ui.retry||'Retry')+'</button>'+
681
+ '<button class="mg-cta" id="mg-continue-btn" type="button">'+_esc(_ui.continue||'Continue \u2192')+'</button>'+
682
+ '</div></div>';
683
+ Audio.playSFX('complete');
684
+ document.getElementById('mg-retry-btn').onclick=function(){_retryMiniGame()};
685
+ document.getElementById('mg-continue-btn').onclick=function(){_advanceMiniGame(finalScore,xpGained,stars)};
686
+ }
687
+
688
+ function _retryMiniGame(){
689
+ _minigameClosing=false;_mgScore=null;
690
+ if(_lastMiniGameType){launchMiniGame(_lastMiniGameType)}
691
+ else{_advanceMiniGame(0,0,0)}
692
+ }
693
+
694
+ function _advanceMiniGame(finalScore,xpGained,stars){
695
+ _minigameClosing=false;
696
+ const ov=document.getElementById('mini-game-overlay');
697
+ if(ov){
698
+ if(_mgIsFullscreen){ov.style.position='';ov.style.width='';ov.style.height='';ov.style.zIndex='';_mgIsFullscreen=false;}
699
+ ov.style.display='none';ov.innerHTML='';
700
+ }
701
+ _addXP(xpGained);
702
+ _updateChapterStars(currentChapter,stars);
703
+ chapterComplete[currentChapter]=true;updateChapterBar();
704
+ Audio.fadeOutBGM(300);setTimeout(function(){Audio.playBGM('dialog')},400);
705
+ _showScoreFeedback(finalScore,xpGained,stars);
706
+ gameState='playing';scriptIndex++;
707
+ for(let i=scriptIndex-1;i>=0;i--)if(SCRIPT[i].type==='bg'){renderCharacters(SCRIPT[i].chars);break}
708
+ _scheduleProcess(1800);
709
+ }