/* GENERATED from walk-engine/engine.js (8f3d663) — do not edit here; edit walk-engine and run its sync.sh. */ /* ===================================================================== Engine: tiles, movement, zones, dialogue, spaced review, speech, saving. ===================================================================== */ const $=id=>document.getElementById(id); let C=null,CH=null; // current chapter content (C) and its registry entry (CH) let state=null,Z=null,ZID='ship',MAP=[],MW=0,MH=0,NPCS=[]; /* 다시 보기: a finished chapter played again in its own save (SK(): ~replay; KEY('replay') keeps it over a reload), mode 'plain', or 'listen' (듣기: each line read aloud, its text hidden until tapped). The real save, its 일지 and the play counts stay as they were; word levels only go up (award and a missed review never lower one). */ let RP=null;const SK=()=>CH.save+(RP?'~replay':''); const has=w=>!!state&&state.badges.includes(w); const now=()=>Date.now(); /* ---------- spaced review: each word has a level 0..5 and a due time ---------- */ /* GAME.srs (optional, 점심 방송): gap:[…ms] the wait after reaching each level (default below). beats:[…] a word is also due again after that many story beats (talks that move the story: a flag, a word, an item, a scene change), whichever comes first, so a fast player and a slow one both get their reviews within one chapter. Beats count game-wide (KEY('beats')). shared:1 one review record for the whole game (KEY('lv')), and words learned in other chapters (their saves' badges) come back here when due: in the notebook, class time and the end-of-chapter round, asked with their own chapter's BANK sentences. */ const GAP=[0,5*60e3,30*60e3,4*3600e3,24*3600e3,3*24*3600e3]; const SRS=()=>G.srs||{},gapAt=b=>(SRS().gap||GAP)[b]; let beatsN=null;const beats=()=>beatsN??(beatsN=+(store.get(KEY('beats'))||0)); function beat(){if(!SRS().beats)return;beatsN=beats()+1;store.set(KEY('beats'),String(beatsN))} const lv=w=>state.lv[w]||{b:0,due:0}; const dueL=L=>L.due<=now()||(L.beat!=null&&beats()>=L.beat); let carrySet=new Set(),carryQs=null; // words learned in other chapters (shared), and their BANK questions (made once, on demand) const known=w=>has(w)||(!!SRS().shared&&carrySet.has(w)&&!C.WORDS.includes(w)); let talkN=0;const askedIn={}; // conversations opened so far, and the one each word was last asked in const isDue=w=>known(w)&&dueL(lv(w))&&!(askedIn[w]>=talkN-1); // never in the conversation right after it was asked (타이밍, then 타이밍 again) function spaced(b){const bg=SRS().beats;return {b,due:now()+gapAt(b),beat:bg&&bg[b]!=null?beats()+bg[b]:null}} function grade(w,ok,held){ // held: right, but with a hint (쓰기 문제): asked again later at the same level let L={...lv(w)};const wr=L.wr; // wr: the word's own 쓰기 rung (the ladder), kept whatever happens to its level if(!ok)L=RP?L:{b:0,due:now(),beat:null}; // 다시 보기 never lowers a word else if(dueL(L))L=spaced(held?L.b:Math.min(5,L.b+1)); // a right answer before the word is due doesn't level it up (asking again and again can't max a word) if(wr!=null)L.wr=wr;state.lv[w]=L;save();return L.b; } let carryDs=null; function carryBank(){ // other chapters' BANK questions by word, and their DICT entries (a carried word taps to the sense you learned) if(carryQs)return carryQs;carryQs={};carryDs={}; for(const ch of CHAPTERS)if(ch!==CH)try{const c=ch.make();(c.BANK||[]).forEach(q=>{if(q.w&&!q.scene&&!q.gram)(carryQs[q.w]=carryQs[q.w]||[]).push(q)}); (c.WORDS||[]).forEach(w=>{if(c.DICT&&c.DICT[w])carryDs[w]=c.DICT[w]})}catch(e){} return carryQs; } const carryDict=w=>{if(!SRS().shared||!carrySet.has(w))return null;carryBank();return carryDs[w]||null}; function refreshCarry(){ // other chapters' saves: their words, and their levels merged into the shared record (the higher level wins) carrySet=new Set();carryQs=null;if(!SRS().shared)return; let all={};try{all=JSON.parse(store.get(KEY('lv'))||'{}')||{}}catch(e){} const take=(w,L)=>{const A=all[w];if(!A||L.b>A.b||(L.b===A.b&&L.due>A.due)){const wr=A&&A.wr!=null?A.wr:L.wr;all[w]={...L};if(wr!=null)all[w].wr=wr}}; // the shared record's 쓰기 rung is the latest for(const ch of CHAPTERS){let sv=null;try{sv=ch===CH?state:JSON.parse(store.get(ch.save)||'null')}catch(e){}if(!sv)continue; if(ch!==CH)(sv.badges||[]).forEach(w=>carrySet.add(w));Object.entries(sv.lv||{}).forEach(([w,L])=>take(w,L))} state.lv=all;store.set(KEY('lv'),JSON.stringify(all)); } const carryWords=()=>[...carrySet].filter(w=>!C.WORDS.includes(w)&&(carryBank()[w]||[]).length); const dueWords=()=>[...C.WORDS,...(SRS().shared?carryWords():[])].filter(isDue); const carryDue=()=>SRS().shared?carryWords().filter(isDue).sort((a,b)=>lv(a).b-lv(b).b):[]; // other chapters' words that are due, weakest first const freshQ=(w,qs)=>{const last=(state.lastAsk||{})[w],o=qs.length>1?qs.filter(q=>q.ask!==last):qs,q=o[Math.random()*o.length|0];if(q)(state.lastAsk=state.lastAsk||{})[w]=q.ask;return q}; // a word's example sentence: not the one it was asked with last time, when it has another /* goal:'R' on a word's DICT entry = recognition only: review asks it only as a meaning question (kind:'meaning'), never a blank to fill or by sound. reg:1 on a question = a register choice (which reply fits this listener): it never comes back in review and never counts as remembering the word (its result goes to state.reg). */ const isR=w=>((C.DICT||{})[w]||carryDict(w)||{}).goal==='R'; const reviewable=q=>!!q&&!q.reg&&(!isR(q.w)||q.kind==='meaning'); const carryQ=w=>freshQ(w,(carryBank()[w]||[]).filter(reviewable)); /* ---------- practice while time passes (opt-in content) ---------- classTime(CLASS,parts): a stretch of time passing (classes between the bells, a shift, a journey). Each part narrates a beat, then someone says one of its lines with a word you've learned, graded like a review: a due word of this chapter (weakest first), else a due word from another chapter (srs.shared: its own BANK sentence, after TERM.carry), else any of yours at random. CLASS={part:{say, lines:[{w, who, ask, opts}]}}. Use it as a step that expands when it's reached, so words taught just before count: {expand:()=>classTime(CLASS,['국어','영어'])}. wrapUp(): the end of a chapter: one more go at this chapter's words not yet ★ (weakest first) and due words from other chapters, at most four, in BANK sentences, after TERM.wrap, so a word taught late isn't left at one review. {expand:()=>wrapUp()} in DONE. */ function classTime(CLASS,parts){ const out=[],used=new Set();let said=0; for(const k of parts){const c=CLASS[k];if(!c)continue;out.push({who:'…',say:c.say}); const ok=c.lines.filter(l=>has(l.w)&&!used.has(l.w)&&reviewable(l)),due=ok.filter(l=>isDue(l.w)); if(due.length){const lo=Math.min(...due.map(l=>lv(l.w).b)),p=due.filter(l=>lv(l.w).b===lo),l=p[Math.random()*p.length|0];used.add(l.w);out.push({...l,review:true});continue} const cw=carryDue().find(w=>!used.has(w)),q=cw&&carryQ(cw); if(q){used.add(cw);if(!said)out.push({who:'…',say:TERM.carry});said=1;out.push({...q,who:'…',review:true});continue} // TERM.carry once per stretch, not before every earlier word if(ok.length){const l=ok[Math.random()*ok.length|0];used.add(l.w);out.push({...l,review:true})}} return out; } function wrapUp(){ const bank=w=>(C.BANK||[]).filter(q=>q.w===w&&!q.scene&&!q.gram&&reviewable(q)); const said=w=>(C.REVIEW||[]).filter(r=>r.w===w&&r.who!=='나'&&reviewable(r)),pick=a=>a[Math.random()*a.length|0]; const nameOf=r=>{const b=[].concat(r.by)[0];return (C.NPC[b]&&C.NPC[b].name)||b}; const metBy=r=>[].concat(r.by).some(b=>metIds().includes(b)); const now_=r=>(!r.when||r.when())&&[].concat(r.by).every(b=>{const n=C.NPC[b];return !n||!n.hide||!n.hide()}); // its moment holds and its speaker is still here (no one speaks after they've died or gone, no "look out!" after the danger) const line=w=>{const R=said(w).filter(now_),f=R.filter(r=>unheard(r)&&metBy(r)),h=R.filter(r=>!unheard(r)),P=f.length?f:h.length?h:R;if(P.length){const r=pick(P),q={...r,who:nameOf(r),review:true};delete q.by;delete q.pre;delete q.when;return q} // a line with it from someone in this chapter, under their name: one you haven't heard yet from someone you've met first (a word-for-word repeat felt stale), else one you heard — only lines whose moment holds (`when`) from someone still here — else the generic sentence const b=bank(w);return b.length?{...pick(b),who:'…',review:true}:null}; const qs=C.WORDS.filter(w=>has(w)&&lv(w).b<3&&(said(w).length||bank(w).length)).sort((a,b)=>lv(a).b-lv(b).b).slice(0,4).map(line).filter(Boolean); carryDue().slice(0,Math.max(0,4-qs.length)).forEach(w=>{const q=carryQ(w);if(q)qs.push({...q,who:'…',review:true})}); return qs.length?[{who:'…',say:TERM.wrap,black:1,wrapStart:1},...qs]:[]; // over a black screen: these are memories of people who aren't here } function nextDue(){const t=C.WORDS.filter(has).map(w=>lv(w).due).filter(d=>d>now());return t.length?Math.min(...t):null} const unit=(n,k)=>G.ui&&G.ui.unit?G.ui.unit(n,k):n+T(k); // GAME.ui.unit(n,'분'): a number and its unit in the game's language (3ぷん) const qt=w=>G.ui&&G.ui.quote?G.ui.quote(w):`"${w}"`; // a word quoted in a message (「水」) function fmtWait(ms){const m=Math.ceil(ms/60e3);return m<60?unit(m,'분'):m<1440?unit(Math.round(m/60),'시간'):unit(Math.round(m/1440),'일')} /* ---------- settings ---------- */ /* Per-game settings come from src/game.js (`var GAME={…}`), so one engine serves 성실호, 형제 and 점심 방송. */ const G=typeof GAME!=='undefined'?GAME:{}; const KEY=k=>(G.prefix||'walk')+'-'+k; /* GAME.ui: a game in another language (ことばのむら) gives the engine's own Korean text in its language, keyed by the Korean; GAME.lang/voice: the speech language and the voice to prefer */ const T=k=>(G.ui&&k in G.ui)?G.ui[k]:k; const TERM_BASE=Object.assign({allWords:n=>[`단어 ${n}개를 다 모았어요!`,`이제 ${TERM.name}에서 복습하면 ★가 생겨요.`],name:'복습 노트',empty:'아직 노트가 비어 있어요.',idle:'지금은 복습할 단어가 없어요.',next:'다음 복습',due:(n,k)=>`복습할 단어가 ${n}개 있어요.`+(k(typeof C!=='undefined'&&C&&C.term&&k in C.term)?C.term[k]:o[k]}); // a chapter's term:{name,…} overrides the game's (one 교시 reviews on paper, the next on a laptop) const LOGNAME=G.log||LOGNAME; const store={get:k=>{try{return localStorage.getItem(k)}catch(e){return null}},set:(k,v)=>{try{localStorage.setItem(k,v)}catch(e){}}}; let soundOn=store.get(KEY('sound'))!=='0'; /* 듣기 문제 (START menu): review may ask a word by sound alone. On by default; ?listen=0 in the URL turns it off and saves that (the playtest tools do, since testers can't hear) */ let writeOn=!G.noWrite&&(store.get(KEY('write'))==='1'||store.get(KEY('write'))==='step'),writeStep=store.get(KEY('write'))==='step'; {const q=new URLSearchParams(location.search).get('write');if(q==='0'||q==='1'||q==='step'){writeOn=q!=='0';writeStep=q==='step';store.set(KEY('write'),q)}} // 쓰기 문제 (START): off until the player turns it on; ?write=0/1; ?write=step (prototype): the 쓰기 ladder let listenOn=store.get(KEY('listen'))!=='0';{const q=new URLSearchParams(location.search).get('listen');if(q==='0'||q==='1'){listenOn=q==='1';store.set(KEY('listen'),q)}} /* ?en=1: a link for testers without Korean: each line's English shows under it, as if its ? were already open (questions still have none, as for everyone). Remembered in this browser; ?en=0 turns it off. Not in the menus, so learners read Korean first. */ const enQ=new URLSearchParams(location.search).get('en');let enAll=store.get(KEY('enAll'))==='1'; if(enQ==='0'||enQ==='1'){enAll=enQ==='1';store.set(KEY('enAll'),enQ)} let readOn=store.get(KEY('read'))==='1'; /* ---------- sound ---------- */ let AC=null; const SFX={move:[[1040,.04,0]],ok:[[880,.07,0],[1320,.12,.07]],no:[[240,.12,0],[180,.18,.1]],badge:[[660,.09,0],[880,.09,.09],[1100,.09,.18],[1320,.25,.27]],star:[[1320,.07,0],[1760,.07,.07],[2200,.2,.14]],door:[[300,.1,0,'square',.07],[220,.16,.08,'square',.07]],item:[[990,.06,0],[1480,.14,.06]],lock:[[160,.08,0],[160,.08,.12]], /* the school bell: the Westminster chime Korean schools ring (딩동댕동), soft sine tones that ring on */ bell:[659.3,523.3,587.3,392,392,587.3,659.3,523.3].flatMap((fq,i)=>[[fq,1.5,i*.5,'sine',.07],[fq*2,.4,i*.5,'sine',.012]])}; const SFXON={}; function sfx(k){ if(!soundOn)return; if(k==='bell')duckMusic(5200,.05); // the bell rings over the music: it dips almost to nothing while the chime plays (user, 2026-10-25) if(k==='door')duckMusic(350,.5); // a door: the music dips by half for a moment, so the low knock is heard over it try{AC=AC||new (window.AudioContext||window.webkitAudioContext)();const t0=AC.currentTime; (SFXON[k]||[]).forEach(g=>{g.gain.cancelScheduledValues(t0);g.gain.setTargetAtTime(.0001,t0,.05)}); /* a sound started again cuts the last one short */ SFXON[k]=SFX[k].map(([fq,d,st,type,vol])=>{const o=AC.createOscillator(),gn=AC.createGain();o.type=type||'square';o.frequency.value=fq;gn.gain.setValueAtTime(0,t0);gn.gain.setValueAtTime(vol||.035,t0+st);gn.gain.exponentialRampToValueAtTime(.0001,t0+st+d);o.connect(gn).connect(AC.destination);o.start(t0+st);o.stop(t0+st+d+.02);return gn})}catch(e){} } /* ---------- speech (Korean voice, if this device has one) ---------- */ const TTS='speechSynthesis' in window; let koVoice=null; function pickVoice(){if(!TTS)return;const vs=speechSynthesis.getVoices();koVoice=vs.find(v=>new RegExp('^'+(G.lang||'ko').slice(0,2),'i').test(v.lang)&&(G.voice||/google|yuna|sora|heami|neural/i).test(v.name))||vs.find(v=>new RegExp('^'+(G.lang||'ko').slice(0,2),'i').test(v.lang))||null;updateRead()} const canSpeak=()=>!!koVoice; const plain=t=>t.replace(/\{([^|}]+)\|[^}]+\}/g,'$1'); function speak(t){ if(!canSpeak())return; try{speechSynthesis.cancel();const u=new SpeechSynthesisUtterance(plain(t).replace(/___/g,T('뭐')));u.lang=G.lang||'ko-KR';u.voice=koVoice;u.rate=.92;speechSynthesis.speak(u)}catch(e){} } /* ---------- canvas + tiles ---------- */ const cv=$('cv'),g=cv.getContext('2d');g.imageSmoothingEnabled=false; const TS=16,VW=11,VH=10; const r=(x,y,w,h,c)=>{g.fillStyle=c;g.fillRect(x,y,w,h)}; const hash=(x,y)=>{let h=x*374761393+y*668265263;h=(h^(h>>13))*1274126177;return ((h^(h>>16))>>>0)%100}; const at=(x,y)=>(x<0||y<0||x>=MW||y>=MH)?null:MAP[y][x]; const same=(x,y)=>at(x,y)===at(x,y); const front=(x,y)=>at(x,y+1)!==at(x,y); let CAM={x:0,y:0}; function stars(X,Y,x,y,t,depth){ // parallax: the stars drift slower than the walls as the camera moves r(X,Y,16,16,'#05080D'); const ox=CAM.x*depth,oy=CAM.y*depth; for(let i=0;i<3;i++){ const sx=((x*16+i*37+hash(x+i,y)*7-ox)%160+160)%160,sy=((y*16+i*53+hash(y+i,x)*3-oy)%160+160)%160; const px=(sx%16),py=(sy%16);const tw=(hash(x*3+i,y)+Math.floor(t/600))%9===0; r(X+px,Y+py,1,1,tw?'#FFFFFF':i===0?'#8FA3B8':'#C8D3DE'); } } function deck(X,Y,x,y){r(X,Y,16,16,'#C9CDC4');r(X,Y,16,1,'#B6BBB1');r(X,Y,1,16,'#B6BBB1');if(hash(x,y)<12){r(X+5,Y+6,2,2,'#B9BDB3')}} function plate(X,Y,x,y){r(X,Y,16,16,'#6E7680');r(X,Y,16,1,'#5D646D');r(X,Y,1,16,'#5D646D');r(X+2,Y+2,1,1,'#88909A');r(X+13,Y+13,1,1,'#88909A');if((x+y)%5===0)r(X+4,Y+8,8,1,'#636B74')} function lawn(X,Y,x,y){r(X,Y,16,16,'#8DC46A');const h=hash(x,y);if(h<55){r(X+(h%11)+2,Y+(h%7)+3,1,2,'#77B058');r(X+(h%11)+4,Y+(h%7)+4,1,1,'#77B058')}if(h%6===0)r(X+(h*3%12)+2,Y+(h*7%12)+2,1,1,'#B4DE8A')} function screenGlow(X,Y,t,c,seed){const on=(Math.floor(t/400)+seed)%5!==0;r(X,Y,6,4,on?c:'#24303A')} const TILES={ /* ship */ hull:(X,Y,x,y,t)=>{r(X,Y,16,16,'#868C84');r(X,Y,16,1,'#9CA299');if(front(x,y)&&at(x,y+1)){r(X,Y+10,16,6,'#ABB0A6');r(X,Y+10,16,1,'#C2C6BC');if(x%4===1)r(X+6,Y+12,4,2,(Math.floor(t/700)+x)%3?'#E8962A':'#7A5420')}else{r(X+3,Y+4,1,1,'#6F756E');r(X+12,Y+4,1,1,'#6F756E')}}, deck:(X,Y,x,y)=>deck(X,Y,x,y), grate:(X,Y,x,y,t)=>{r(X,Y,16,16,'#575E5A');for(let i=1;i<16;i+=3)r(X+i,Y,1,16,'#474D4A');if(x%4===0){const on=(Math.floor(t/180)-x/4)%6===0;r(X+7,Y+7,2,2,on?'#FFD08A':'#B8701A')}}, window:(X,Y,x,y,t)=>{stars(X,Y,x,y,t,.35);r(X,Y,16,2,'#868C84');r(X,Y+14,16,2,'#ABB0A6');if(x%3===0)r(X,Y,1,16,'#6F756E');if(x>=9&&x<=13){const c=['#3E8E6A','#4E9E6E','#C9A64A'];r(X,Y+9,16,5,c[(x)%3]);r(X,Y+9,16,1,'#9FD7E8')}}, console:(X,Y,x,y,t)=>{deck(X,Y,x,y);r(X+1,Y+3,14,11,'#2B3238');r(X+1,Y+3,14,2,'#3C454C');screenGlow(X+3,Y+6,t,x%2?'#69CFD8':'#E8962A',x);r(X+10,Y+7,3,1,'#5F6B72');r(X+10,Y+9,3,1,'#5F6B72')}, hydro:(X,Y,x,y,t)=>{deck(X,Y,x,y);r(X+1,Y+5,14,9,'#5E655F');r(X+2,Y+6,12,2,'#3A6E8A');const h=hash(x,y);for(let i=0;i<3;i++){const px=X+3+i*4,ph=4+((h+i)%3);r(px,Y+6-ph+2,2,ph,'#3F8F4A');r(px-1,Y+6-ph+2,4,2,'#5DB866');if((h+i)%4===0)r(px,Y+6-ph+1,2,2,'#D9544B')}r(X+1,Y,14,1,'#C77DDB')}, bunk:(X,Y,x,y)=>{deck(X,Y,x,y);r(X+1,Y+1,14,14,'#5E655F');r(X+2,Y+2,12,4,'#ECEDE6');r(X+2,Y+6,12,8,'#C9873A');r(X+2,Y+6,12,1,'#E3A65A')}, terminal:(X,Y,x,y,t)=>{(Z.base==='plate'?plate:deck)(X,Y,x,y);r(X+3,Y+1,10,14,'#2B3238');r(X+4,Y+2,8,6,'#0F141A');const due=state&&dueWords().length>0; if(due){const on=Math.floor(t/350)%2;r(X+5,Y+3,6,4,on?'#69CFD8':'#2C5D63')}else{r(X+5,Y+4,4,1,'#3C6E6E');r(X+5,Y+6,6,1,'#3C6E6E')}r(X+5,Y+10,6,1,'#5F6B72');r(X+5,Y+12,6,1,'#5F6B72')}, pipes:(X,Y,x,y,t)=>{deck(X,Y,x,y);r(X+2,Y,4,16,'#6E7570');r(X+9,Y,4,16,'#6E7570');r(X+2,Y,1,16,'#899089');r(X+9,Y,1,16,'#899089');r(X+1,Y+6,6,3,'#4F5652');r(X+8,Y+10,6,3,'#4F5652');r(X+3,Y+7,2,1,'#D2533F')}, engine:(X,Y,x,y,t)=>{deck(X,Y,x,y);const ox=x-3,oy=y-11; // 4x2 block, drawn piece by piece r(X,Y,16,16,'#30363B');if(oy===0)r(X,Y,16,2,'#454C52');if(ox===0)r(X,Y,2,16,'#454C52');if(ox===3)r(X+14,Y,2,16,'#252A2E'); const fixed=state&&state.f.fixed;const pulse=fixed?(Math.sin(t/260)+1)/2:0; if(ox===1||ox===2){const c=fixed?`rgba(105,207,216,${.55+pulse*.45})`:((Math.floor(t/120)%7===0)?'#D2533F':'#3B2422');r(X+(ox===1?6:0),Y+(oy===0?8:0),10,8,c)} if(oy===1&&(ox===0||ox===3))r(X+5,Y+4,6,3,fixed?'#E8962A':'#4A3A2A')}, airlock:(X,Y,x,y)=>{r(X,Y,16,16,'#3A4046');for(let i=-16;i<16;i+=6){g.save();g.beginPath();g.rect(X,Y,16,16);g.clip();g.fillStyle='#E8B73A';g.beginPath();g.moveTo(X+i,Y+16);g.lineTo(X+i+3,Y+16);g.lineTo(X+i+19,Y);g.lineTo(X+i+16,Y);g.fill();g.restore()}r(X+2,Y+3,12,10,'#2B3136');r(X+7,Y+3,2,10,'#1E2327')}, /* dock */ ring:(X,Y,x,y,t)=>{r(X,Y,16,16,'#3F4650');r(X,Y,16,1,'#4E5661');if(front(x,y)&&at(x,y+1)){r(X,Y+9,16,7,'#555D68');r(X,Y+9,16,1,'#6B7480');if(x%2===0)r(X+3,Y+11,10,2,(Math.floor(t/900)+x)%4?'#9FD7E8':'#4B6B78')}}, plate:(X,Y,x,y)=>plate(X,Y,x,y), planetWin:(X,Y,x,y,t)=>{stars(X,Y,x,y,t,.15);const P=Z.planet; g.save();g.beginPath();g.rect(X,Y,16,16);g.clip(); const cx=P.cx-CAM.x,cy=P.cy+Math.sin(t/4000)*2-CAM.y*.0; g.fillStyle='#2E7A68';g.beginPath();g.arc(cx,cy+170,P.r,0,Math.PI*2);g.fill(); g.fillStyle='#4E9E6E';g.beginPath();g.arc(cx-40,cy+190,60,0,Math.PI*2);g.fill(); g.fillStyle='#C9A64A';g.beginPath();g.arc(cx+60,cy+200,40,0,Math.PI*2);g.fill(); g.strokeStyle='rgba(159,215,232,.7)';g.lineWidth=2;g.beginPath();g.arc(cx,cy+170,P.r,Math.PI*1.05,Math.PI*1.95);g.stroke(); g.restore(); if(y===1)r(X,Y,16,2,'#3F4650');if(y===2)r(X,Y+14,16,2,'#555D68');if(x%4===0)r(X,Y,1,16,'#2E343C')}, crate:(X,Y,x,y)=>{plate(X,Y,x,y);r(X+1,Y+2,14,13,'#9C6A34');r(X+1,Y+2,14,2,'#B9844A');r(X+1,Y+8,14,1,'#7A5026');r(X+7,Y+2,2,13,'#7A5026');r(X+3,Y+5,3,1,'#E8962A')}, stall:(X,Y,x,y)=>{plate(X,Y,x,y);r(X,Y+4,16,11,'#6A3A2E');r(X,Y+4,16,3,'#A04E3A');if(y===4){for(let i=0;i<4;i++)r(X+i*4,Y,4,4,i%2?'#E8962A':'#F1E6D0')}else{r(X+3,Y+1,4,4,'#D9544B');r(X+9,Y+2,3,3,'#69CFD8')}}, lift:(X,Y,x,y,t)=>{(Z.outdoor?TILES.stone:plate)(X,Y,x,y);const p=(Math.sin(t/300)+1)/2;g.strokeStyle=`rgba(105,207,216,${.4+p*.6})`;g.lineWidth=2;g.strokeRect(X+2,Y+2,12,12);r(X+6,Y+6,4,4,'#69CFD8')}, /* city */ tree:(X,Y,x,y)=>{lawn(X,Y,x,y);r(X+6,Y+11,4,5,'#7A5530');r(X+2,Y+1,12,11,'#2F8466');r(X+1,Y+3,14,7,'#2F8466');r(X+4,Y+2,5,3,'#4FA67E');r(X+3,Y+5,2,2,'#4FA67E');r(X+2,Y+10,12,1,'#246A52')}, lawn:(X,Y,x,y)=>lawn(X,Y,x,y), stone:(X,Y,x,y)=>{r(X,Y,16,16,'#E5D2B5');r(X,Y+7,16,1,'#D2BD9C');r(X+((y%2)?4:11),Y,1,7,'#D2BD9C');r(X+((y%2)?10:2),Y+8,1,8,'#D2BD9C')}, dome:(X,Y,x,y,t)=>{lawn(X,Y,x,y);const L=at(x-1,y)!=='O',T=at(x,y-1)!=='O'; if(T){g.fillStyle='#7FD3D8';g.beginPath();g.arc(X+(L?16:0),Y+9,9,Math.PI,0);g.fill();g.fillStyle='#BDEFF0';g.fillRect(X+(L?12:1),Y+3,2,4);r(X+(L?15:0),Y,1,2,'#E8962A')} else{r(X+(L?4:0),Y,L?12:12,16,'#E9DCC7');r(X+(L?4:0),Y,L?12:12,2,'#5EB9C1');if(L)r(X+8,Y+6,4,6,'#5EB9C1');else r(X+4,Y+6,4,6,'#5EB9C1')}}, cable:(X,Y,x,y,t)=>{TILES.stone(X,Y,x,y);r(X+1,Y,14,16,'#9AA3AD');r(X+1,Y,14,2,'#B9C1C9');if(x===11){r(X+6,Y,4,16,'#5D646D')}else{r(X+3,Y+5,10,6,'#6E7680')} if(x===11&&y===1){const p=(Math.sin(t/200)+1)/2;r(X+7,Y-16,2,16,`rgba(159,215,232,${.6+p*.4})`)}}, police:(X,Y,x,y)=>{r(X,Y,16,16,'#8C98AE');r(X,Y+15,16,1,'#6F7B91');if(at(x,y-1)!=='P'){r(X,Y,16,4,'#3E4C6A')}if(front(x,y)){if(x===4){r(X+3,Y+3,10,13,'#3E4C6A');r(X+4,Y+4,8,12,'#556483')}else if(x%2===0){r(X+3,Y+4,10,7,'#3E4C6A');r(X+4,Y+5,8,5,'#CFE3F5')}}}, cafe:(X,Y,x,y)=>{r(X,Y,16,16,'#F1D4CC');r(X,Y+15,16,1,'#D8B4AA');if(at(x,y-1)!=='C')r(X,Y,16,3,'#B85A5A');if(front(x,y)){for(let i=0;i<4;i++)r(X+i*4,Y,4,5,i%2?'#F7F1E6':'#2F8F8A');if(x===19){r(X+4,Y+6,8,10,'#6B4A2B')}else{r(X+3,Y+7,10,6,'#6B4A2B');r(X+4,Y+8,8,4,'#F7D98C')}}}, flowers:(X,Y,x,y)=>{lawn(X,Y,x,y);[[3,4,'#E86D8A'],[10,3,'#F7D154'],[6,10,'#FFFFFF'],[12,11,'#E86D8A']].forEach(([a,b,c])=>{r(X+a,Y+b,2,2,c);r(X+a,Y+b+2,1,2,'#3E8E3A')})}, pond:(X,Y,x,y,t)=>{r(X,Y,16,16,'#4AA3C8');const o=Math.floor(t/400+x)%4;r(X+o*3,Y+4,5,1,'#9FD7E8');r(X+((o+2)%4)*3,Y+10,5,1,'#9FD7E8');if(at(x,y-1)!=='~')r(X,Y,16,2,'#3A86A8')}, bench:(X,Y,x,y)=>{lawn(X,Y,x,y);r(X+1,Y+5,14,2,'#9A6A3C');r(X+1,Y+8,14,3,'#B68350');r(X+2,Y+11,2,4,'#6E4A28');r(X+12,Y+11,2,4,'#6E4A28')}, }; /* the floor layer (opt-in): an object stands on its legend's floor, else on its zone's floor, so object tiles draw only the object and look right in any room; a walkable tile is a floor itself unless its legend names one */ function tile(x,y,X,Y,t){const c=at(x,y);const L=c!=null&&Z.legend[c];const fn=L&&TILES[L.tile]; const fl=L&&(L.floor||(!L.walk&&Z.floor));if(fl&&fl!==L.tile&&TILES[fl])TILES[fl](X,Y,x,y,t); if(fn)fn(X,Y,x,y,t);else r(X,Y,16,16,Z.outdoor?'#2F8466':'#1A1F24')} /* ---------- sprites: pixel-art grids ---------- A sprite is an array of equal-length strings; each char is a palette key ('.' = transparent). drawArt draws it with its feet on the tile's bottom edge, so tall sprites (16×24, 16×32) grow upward. */ function shade(hex,k){const n=parseInt(hex.slice(1),16);const f=c=>Math.max(0,Math.min(255,Math.round(c*k)));return '#'+[(n>>16)&255,(n>>8)&255,n&255].map(c=>f(c).toString(16).padStart(2,'0')).join('')} /* art transforms: draw a picture once, upright, and turn it to fit (a view out of an east or west window, a chair turned around). rows = an array of equal-length strings of palette keys. rot turns clockwise by quarter turns (q: 1, 2, 3, or -1 = counter-clockwise). */ const ART={ rot:(rows,q=1)=>{q=((q%4)+4)%4;let a=rows;for(let i=0;i=0;y--)row+=a[y][x];o.push(row)}a=o}return a}, flipH:rows=>rows.map(r=>[...r].reverse().join('')), flipV:rows=>rows.slice().reverse(), /* draw rows top-down from (X,Y), no bottom-alignment: for pieces of tiles */ put:(rows,pal,X,Y)=>{for(let y=0;yi{rows[y]=rows[y].slice(0,x)+ch+rows[y].slice(x+1)}; if(L.coat){for(const y of [4,5])body[y]=body[y].replace(/P/g,'C').replace(/p/g,'c')} if(!L.belt)body=body.map(rw=>rw.replace(/B/g,'C')); if(style==='bob'&&view!=='left'){set(body,0,3,'H');set(body,0,12,'H');if(view==='up')for(let x=4;x<12;x++)set(body,0,x,'H')} if(style==='long'&&view!=='left'){for(const y of [0,1,2]){set(body,y,3,'H');set(body,y,12,'H')}if(view==='down'){set(body,0,4,'H');set(body,0,11,'H')}if(view==='up')for(let x=4;x<12;x++){set(body,0,x,'H');set(body,1,x,'H')}} if(style==='long'&&view==='left'){for(const y of [0,1])for(const x of [9,10])set(body,y,x,'H');set(body,2,10,'H')} if(L.lashes&&view==='down')head=head.map(rw=>rw.replace(/SESSES/,'EESSEE')); if(L.lips)head=head.map(rw=>rw.replace(/M/g,'L')); if(L.beard){if(view==='down'){head[6]='...OSDDDDDDSO...';head[7]='....ODDDDDDO....';body[0]='...OODDDDDDOO...'}else if(view==='left'){head[6]='...ODDDDSHHHO...';head[7]='....ODDDDSO.....'}} if(L.arm){ // mechanical arm on the character's left side if(view==='down'&&dir==='down'){set(body,1,12,'A');set(body,2,12,'A');set(body,3,12,'A')} if(view==='up'){set(body,1,3,'A');set(body,2,3,'A');set(body,3,3,'A')} if(dir==='left'){body=body.map(rw=>rw.replace(/S/g,'A'));set(body,1,7,'A')} } const out=head.concat(body); return crewOn(L)?crewRows(L,out,view):out; } function humanPal(L){ const o='#1B1E2B'; const p={O:o,E:o,H:L.hair,h:L.hairHi||shade(L.hair,.78),S:L.skin,s:shade(L.skin,.85),M:shade(L.skin,.72),W:shade(L.skin,1.12),C:L.shirt,c:shade(L.shirt,.8), P:L.pants,p:shade(L.pants,.8),K:L.shoes||'#2A2A33',B:L.belt||L.shirt,D:L.beard||L.hair,L:L.lips||shade(L.skin,.72),A:L.arm||L.skin,Y:L.cap||L.hair,y:shade(L.cap||L.hair,.8),V:shade(L.cap||'#333333',.55)}; return crewOn(L)?crewPal(L,p):p; } /* ---------- crew style (GAME.lookStyle:'crew' — 성실호): the same base sprite and portrait, set apart from 점심 방송's students by everyday kit instead of a school uniform. Every human gets gloves and boots on the walk sprite; portraits lose the school collar and tie and get eyes with an iris (look.eye, else dark brown). Per look (GAME.looks by name, merged at boot): kit:{piece:colour,…} two pieces from coat, sweater (over a T-shirt: their own colour at the neck), vest, strap (shoulder to hip), pouches (a belt with pouches; a chest pocket in the portrait) · uniform:1 (collar band, seams, insignia) · onePiece:1 (trousers match the top) · jaw: square|round|pointed|long · fullBeard:1 (a short fringe under the chin) · visor:1 (a band across the eyes). Walk-sprite eyes stay the base 1-px eyes: at 16 px any colour there reads as goggles. look.school:1 opts one look out. ---------- */ const crewOn=L=>G.lookStyle==='crew'&&!L.school&&!L.art&&!L.draw; const JAWS={square:{26:10.5,27:10.5,28:10.5,29:10.5,30:10.5,31:10,32:9},round:{26:10.5,27:10.5,28:10.5,29:10,30:9.5,31:8.5,32:7,33:4.5}, pointed:{26:9,27:8,28:7,29:6,30:5,31:4,32:3,33:1.5},long:{26:9.5,27:9.5,28:9,29:8.5,30:8,31:7,32:6,33:5,34:3.5,35:1.5}}; function jawCut(L,g){const J=JAWS[L.jaw];if(!J)return;const neck=shade(L.skin,.85); // re-cut the face below the cheeks; a cut below the chin shows the neck, never a hole for(let y=26;y<=35;y++)for(let x=0;x<48;x++){const c=g[y][x],hw=J[y];if(c!==L.skin&&c!==null&&!(y>=33&&c===neck))continue; if(hw!=null&&Math.abs(x-23.5)<=hw){if(c!==L.skin)g[y][x]=L.skin}else if(c===L.skin)g[y][x]=(y>=31&&x>=20&&x<=27)?neck:null}} function crewPal(L,p){const k=L.kit||{},c0='#8A6A4A',sw=k.sweater||c0; Object.assign(p,{F:k.coat||k.vest||c0,X:sw,x:shade(sw,.75),Q:k.strap||c0,T:'#4A3A2E',t:'#7A5F45',N:shade(L.shirt,1.5),n:shade(L.shirt,.6),I:'#E3B74A',U:'#D8CFAE',G:'#3A3F4A',Z:'#3A6F8A'}); if(L.onePiece){p.P=shade(L.shirt,.88);p.p=shade(L.shirt,.7);p.B='#2E3440'} return p; } function crewRows(L,rows,view){ const R=rows.map(r=>[...r]),set=(y,x,ch,only)=>{if(R[y]&&R[y][x]!==undefined&&(!only||only.includes(R[y][x])))R[y][x]=ch}; if(L.visor){if(view==='down')for(const x of [5,6,7,8,9,10])set(5,x,'Z');if(view==='left')for(const x of [3,4,5])set(5,x,'Z')} if(L.uniform){ if(view==='left'){set(8,7,'N','C');set(8,8,'N','C');set(10,5,'I','C')} else{for(const x of [6,7,8,9])set(8,x,'N','C');set(9,3,'n','C');set(9,12,'n','C');if(view==='down')set(10,10,'I','Cc');set(11,7,'U','B');set(11,8,'U','B')} } for(const piece of Object.keys(L.kit||{})){ if(piece==='vest'){if(view==='left'){for(let y=8;y<=10;y++)for(const x of [5,6,7])set(y,x,'F','Cc')}else for(let y=8;y<=10;y++)for(const x of [5,6,9,10])set(y,x,'F','Cc')} if(piece==='strap'){const pts=view==='down'?[[8,5],[9,6],[9,7],[10,8],[10,9],[11,10]]:view==='up'?[[8,10],[9,9],[9,8],[10,7],[10,6],[11,5]]:[[8,8],[9,7],[10,6],[11,5]];for(const [y,x] of pts)set(y,x,'Q','CcFXxB')} if(piece==='coat'){const side=view==='left'?[5,10]:[3,4,11,12];for(let y=8;y<=10;y++)for(const x of side)set(y,x,'F','Cc');for(const y of [12,13])for(const x of (view==='left'?[5,10]:[4,11]))set(y,x,'F','Pp')} if(piece==='sweater'){for(let y=8;y<=10;y++)for(let x=0;x<16;x++)if(!(y===8&&x>=6&&x<=9&&view!=='up'))set(y,x,'X','Cc');for(let x=0;x<16;x++)set(11,x,'x','B')} if(piece==='pouches'){for(const x of (view==='left'?[5,6,7,8,9]:[5,6,7,8,9,10]))set(11,x,'T','BCcXx');if(view!=='left')set(11,7,'U','T');for(const x of (view==='left'?[6]:[5,10])){set(11,x,'t','T');set(12,x,'t','Pp')}} } for(let y=8;y<16;y++)for(let x=0;x<16;x++)set(y,x,'G','S'); // gloves for(let x=0;x<16;x++)set(14,x,'K','P'); // boots return R.map(r=>r.join('')); } function crewPortrait(L,face,p){ const D='#1B1E2B',sh=L.shirt,shS=shade(sh,.82),px=(x,y,c)=>{if(p[y]&&x>=0&&x<48)p[y][x]=c},rect=(x,y,w,h,c)=>{for(let j=y;jr.slice());for(let y=0;y<48;y++)for(let x=0;x<48;x++)if(!q[y][x]&&[[1,0],[-1,0],[0,1],[0,-1]].some(([dx,dy])=>{const c=q[y+dy]&&q[y+dy][x+dx];return c&&c!==D}))p[y][x]=D; // edge anything painted out past the outline return p; } /* GAME.looks: per-name additions to a chapter's looks (kit, uniform, jaw, eye, fullBeard, visor, colour fixes), merged at boot into every NPC (and the follower) with that name whose look is a plain object; dynamic looks (getters) and custom sprites keep their own */ function mergeLooks(){ if(!G.looks)return; const fix=n=>{const x=G.looks[n&&n.name];if(!x)return;const d=Object.getOwnPropertyDescriptor(n,'look');if(!d||d.get||!n.look||n.look.art||n.look.draw||!n.look.skin)return;n.look={...n.look,...x}}; Object.values(C.NPC||{}).forEach(fix);if(C.FOLLOW)fix(C.FOLLOW); } /* ---------- talk portraits: a chest-up 48×48 pixel portrait generated from a character's walk look (hair style/colour, skin, uniform, tie, lashes/lips, cap, beard) with an expression and an open/closed mouth — Openbound-style, all our own art ---------- */ function portraitGrid(L,face,open){ const W=48,g=Array.from({length:W},()=>Array(W).fill(null)),O='#1B1E2B'; const px=(x,y,c)=>{if(x>=0&&y>=0&&x{for(let j=y;j{for(let y=Math.ceil(cy-ry);y<=cy+ry;y++)for(let x=Math.ceil(cx-rx);x<=cx+rx;x++) if(y>=y0&&y<=y1&&((x-cx)/rx)**2+((y-cy)/ry)**2<=1)px(x,y,c)}; const sk=L.skin,skS=shade(L.skin,.85),hr=L.hair,hrS=L.hairHi||shade(L.hair,.78),sh=L.shirt,shS=shade(L.shirt,.82),style=L.style||(L.long?'long':'short'); // shoulders + uniform rect(9,40,30,8,sh);rect(12,37,24,4,sh);rect(9,44,4,4,shS);rect(35,44,4,4,shS); for(let i=0;i<5;i++){px(19+i,37+i,'#F4F2EA');px(28-i,37+i,'#F4F2EA')} // collar V if(L.belt){rect(23,39,2,9,L.belt);px(23,47,shade(L.belt,.75));px(24,47,shade(L.belt,.75))} // tie if(L.coat){rect(9,40,6,8,shS);rect(33,40,6,8,shS)} // long hair falls behind the shoulders if(style==='long'){rect(11,12,6,30,hrS);rect(31,12,6,30,hrS)} // neck + head + ears rect(20,31,8,7,skS);oval(24,20,11,13,sk);oval(12.5,22,1.6,2.6,sk);oval(35.5,22,1.6,2.6,sk); rect(14,28,20,1,null);oval(24,20,11,13,sk,8,33); for(let y=26;y<=32;y++)px(13+Math.max(0,y-26),y,null),px(35-Math.max(0,y-26),y,null); // jaw taper if(L.jaw)jawCut(L,g); // a crew look's own jaw oval(24,20,11,13,sk,8,25); // hair const top=()=>{oval(24,15,12,9,hr,0,14)}; if(style==='short'){top();rect(13,13,3,6,hr);rect(32,13,3,6,hr);for(let x=15;x<34;x+=3)rect(x,14,2,2,hr)} if(style==='long'){top();rect(12,12,4,16,hr);rect(32,12,4,16,hr);rect(15,13,18,3,hr)} if(style==='bob'){top();rect(13,13,22,4,hr);rect(12,13,4,16,hr);rect(32,13,4,16,hr);rect(13,28,3,2,hrS);rect(32,28,3,2,hrS)} if(style==='bun'){top();oval(24,4.5,4.5,4,hr);rect(14,13,3,4,hr);rect(31,13,3,4,hr)} if(style==='spiky'){top();for(let k=0;k<6;k++){const x=13+k*4;for(let y=0;y<5;y++){const w=Math.min(4,y+1);rect(x+((4-w)/2|0),4+y,w,1,hr)}}rect(13,13,22,2,hr)} // spikes point up: a 1px tip widening to the head if(style==='bald'){rect(12,17,3,7,hr);rect(33,17,3,7,hr)} if(L.cap){oval(24,12,12,7,L.cap,0,13);rect(12,12,24,2,L.cap);rect(24,13,14,2,shade(L.cap,.75))} // face const eyeY=21,ex=[19,29],D='#1B1E2B',WH='#FFFFFF',brow=hrS; const brows=(dl,dr)=>{rect(ex[0]-1,17+dl,4,1,brow);rect(ex[1]-1,17+dr,4,1,brow)}; if(face==='happy'){brows(0,0);for(const x of ex){px(x-1,eyeY+1,D);px(x,eyeY,D);px(x+1,eyeY,D);px(x+2,eyeY+1,D)}rect(15,25,3,1,'#E9A0A0');rect(30,25,3,1,'#E9A0A0')} else if(face==='surprised'){brows(-2,-2);for(const x of ex){rect(x-1,eyeY-1,4,4,D);px(x,eyeY,WH)}} else if(face==='sad'){px(ex[0]-1,17,brow);rect(ex[0],16,3,1,brow);rect(ex[1]-1,16,3,1,brow);px(ex[1]+2,17,brow);for(const x of ex){rect(x,eyeY+1,2,2,D)}} else if(face==='angry'){rect(ex[0]-1,17,2,1,brow);rect(ex[0]+1,18,2,1,brow);rect(ex[1]-1,18,2,1,brow);rect(ex[1]+1,17,2,1,brow);for(const x of ex)rect(x,eyeY,2,2,D)} else if(face==='think'){brows(0,-1);for(const x of ex){rect(x,eyeY,2,2,D);px(x,eyeY,WH)}} else if(face==='sleep'){brows(1,1);for(const x of ex)rect(x-1,eyeY+1,4,1,D)} // asleep: eyes closed else {brows(0,0);for(const x of ex){rect(x,eyeY,2,3,D);px(x,eyeY,WH)}} if(L.lashes){px(ex[0]-1,eyeY-1,D);px(ex[1]+2,eyeY-1,D)} // mouth const lip=L.lips||shade(L.skin,.68),mo='#5A2230'; if(open){if(face==='surprised'||face==='sleep')rect(22,27,face==='sleep'?3:4,face==='sleep'?3:4,mo);else{rect(21,27,6,3,mo);rect(22,29,4,1,'#D9707F')}} else if(face==='happy'){px(20,27,lip);rect(21,28,6,1,lip);px(27,27,lip)} else if(face==='sad'){px(20,29,lip);rect(21,28,6,1,lip);px(27,29,lip)} else if(face==='surprised')rect(23,27,2,2,mo); else if(face==='think')rect(23,28,4,1,lip); else rect(21,28,6,1,lip); if(L.beard){for(let y=27;y<=32;y++)for(let x=14;x<35;x++)if(g[y][x]===sk&&!(y<=29&&x>=20&&x<=27))px(x,y,L.beard)} // outline everything const out=g.map(r=>r.slice()); for(let y=0;yg[y+dy]&&g[y+dy][x+dx]))out[y][x]=O; return crewOn(L)?crewPortrait(L,face,out):out; } function drawPortrait(cv,L,face,open){ const c=cv.getContext('2d');c.clearRect(0,0,48,48); if(L.art){ // custom sprite: its own down frame, enlarged // custom sprite: a bust — scale it to fill the width and show the top (head and shoulders), cut at the frame's bottom const all=(L.art.down||[]),w=all[0]?.length||16,k=Math.max(1,Math.floor(48/w)),rows=all.slice(0,Math.min(all.length,Math.ceil(48/k))); const top=Math.max(0,48-rows.length*k); rows.forEach((r,y)=>[...r].forEach((ch,x)=>{const col=L.art.pal[ch];if(col&&ch!=='.'){c.fillStyle=col;c.fillRect(24-w*k/2+x*k|0,top+y*k,k,k)}}));return} const g=portraitGrid(L,face,open); for(let y=0;y<48;y++)for(let x=0;x<48;x++)if(g[y][x]){c.fillStyle=g[y][x];c.fillRect(x,y,1,1)} } function lookFor(who){ // speaker name → look: an NPC of this chapter with that name if(!who||who==='…')return null; const ok=L=>L&&(L.art||(L.skin&&L.hair&&L.shirt))?L:null; // humans and custom sprites get a portrait; simple robots (kind:'andy') don't // the character you're talking to first (names like '1학년 학생' are shared), then one in this room, then anyone in the chapter if(dlg&&dlg.npc&&dlg.npc.name===who&&ok(dlg.npc.look))return dlg.npc.look; for(const n of live())if(n.name===who&&ok(n.look))return n.look; for(const n of Object.values(C.NPC||{}))if(n.name===who&&ok(n.look))return n.look; if(C.FOLLOW&&C.FOLLOW.name===who)return ok(C.FOLLOW.look); return null; } function faceFor(s,text){ // expression for a line: explicit face, else a guess from the punctuation if(s.face)return s.face; {const n=dlg&&dlg.npc;if(n&&n.sleep&&(!s.who||s.who===n.name))return 'sleep'} // someone asleep (NPC sleep:1) talks in their sleep with their eyes shut, review lines and replies too if(s.ask||/^…|…$/.test(text))return 'think'; if(/[?!]{2}|!\?/.test(text))return 'surprised'; if(/!$/.test(text.trim()))return 'happy'; return 'idle'; } let portraitAnim=null; function setPortrait(s,text){ clearInterval(portraitAnim);const cv=$('face');if(!cv)return;const L=s.look||lookFor(s.who||dlg.name); // a line can bring its speaker's look (two people with the same name) $('dlg').classList.toggle('hasface',!!L);if(!L){cv.hidden=true;return} cv.hidden=false;const face=faceFor(s,text);let open=false;drawPortrait(cv,L,face,false); portraitAnim=setInterval(()=>{if(!typing||typing.finished){clearInterval(portraitAnim);drawPortrait(cv,L,face,false);return} open=!open;drawPortrait(cv,L,face,open)},130); } const palCache=new WeakMap(); /* props an NPC can hold (NPC hold:'phone', or a function of the story). A chapter adds its own in C.PROPS. Drawn over the hands of a standing character; facing away, the prop is hidden behind them. */ const PROPS={ phone:(X,Y,dir)=>{if(dir==='up')return;const x=dir==='left'?X+3:dir==='right'?X+10:X+6;r(x,Y+9,3,5,'#23262D');r(x+1,Y+10,1,3,'#8FD3EA')}, }; function drawChar(L,X,Y,dir,step){ if(L.draw){L.draw(L,X,Y,dir,step);return} // look.draw(look,X,Y,dir,step): a game that keeps its own character drawing (단어 마을) if(L.art){drawCustom(L,X,Y,dir,step);return} let pal=palCache.get(L);if(!pal){pal=humanPal(L);palCache.set(L,pal)} shadow(X,Y);drawArt(humanArt(L,dir,step),pal,X,Y,dir==='right'); } /* custom sprites: look.art = {pal:{key:color}, down:[rows], up:[rows], left:[rows], walk?:{down:[[rows],[rows]],…}} — any height ≤ 32 */ /* how far above a 16px head the quest marker must sit for a taller custom sprite */ function artLift(L){const A=L&&L.art;if(!A)return 0;const rows=A.down||A.left||A.up;return Math.max(0,rows.length-16)} /* sitting: chair = a look whose art draws under the sitter. The sitter keeps its top art.keep rows (default 12: head to belt; 14 adds the lap of someone facing the camera) and sinks art.drop px (default 2; facing a table, enough for the lap to meet it). art.lift raises the whole seat, sitter included (a stool pulled up to the table in the row above). The chair's bottom art.back rows (backrest and legs of a chair facing away from the camera) draw again over the sitter. Chair art is bottom-aligned in the tile like every sprite, so it never reaches into the next row. */ function drawSeated(L,X,Y,dir,chair){ const view=dir==='right'?'left':dir,A=L.art; const rows=A?(A[view]||A.down):humanArt(L,dir,0); let pal=A?A.pal:palCache.get(L);if(!pal){pal=humanPal(L);palCache.set(L,pal)} const C=chair&&chair.art,cr=C&&(C.down||C.up),cx=C?X+Math.floor((16-cr[0].length)/2):0,d=C&&C.drop!=null?C.drop:2,k=C&&C.keep||12; if(C&&C.lift)Y-=C.lift; /* lift: the whole seat sits higher, e.g. pulled up to the edge of the table above */ if(C)drawArt(cr,C.pal,cx,Y,false);else shadow(X,Y); drawArt(rows.slice(0,k),pal,X+Math.floor((16-rows[0].length)/2),Y-16+k+d,dir==='right'); if(C&&C.back)drawArt(cr.slice(-C.back),C.pal,cx,Y,false); } function drawCustom(L,X,Y,dir,step){ const A=L.art,view=dir==='right'?'left':dir; const rows=(step&&A.walk&&A.walk[view]&&A.walk[view][step-1])||A[view]||A.down; shadow(X,Y,rows[0].length>16?12:8);drawArt(rows,A.pal,X+Math.floor((16-rows[0].length)/2),Y,dir==='right'); } function drawAndy(L,X,Y,dir,step,t){ const ol='#1B1E2B'; g.fillStyle='rgba(0,0,0,.22)';g.fillRect(X+3,Y+14,10,2); r(X+5,Y+11,2,4,ol);r(X+9,Y+11,2,4,ol); r(X+3,Y+6,10,7,ol);r(X+4,Y+7,8,5,L.body);r(X+6,Y+8,4,2,'#5F6B72'); r(X+3,Y+0,10,7,ol);r(X+4,Y+1,8,5,L.body); if(dir!=='up'){const blink=Math.floor(t/1700)%8===0;const vx=dir==='left'?X+4:dir==='right'?X+6:X+5;r(vx,Y+3,6,blink?1:2,L.visor)} r(X+7,Y-2,2,2,ol);r(X+7,Y-3,2,1,Math.floor(t/500)%2?L.visor:'#5F6B72'); } const pet={x:0,y:0,fx:0,fy:0,dir:'down',on:false}; function petArrive(){if(!petOn()||pet.on)return; // the follower appears: drawn the first time, and after a door before the room's greeting turns you petReset();const n=dlg&&dlg.npc;if(n&&n.name===C.FOLLOW.name){const [x,y]=npcPos(n);pet.x=pet.fx=x;pet.y=pet.fy=y;pet.dir=n.dir} // joining you in a talk ("앞장서"): from where they stood, not from your square else{const [dx,dy]=D[player.dir],b=[[-dx,-dy],[dy,dx],[-dy,-dx]].map(([ax,ay])=>[player.x+ax,player.y+ay]).find(([x,y])=>walkable(x,y)&&!npcAt(x,y));if(b){pet.x=pet.fx=b[0];pet.y=pet.fy=b[1]}} // after a door: one step behind you (or beside), not hidden on your square until you move pet.on=true} const petOn=()=>!!(C.FOLLOW&&C.FOLLOW.when()); function petReset(){pet.x=pet.fx=player.x;pet.y=pet.fy=player.y;pet.dir=player.dir} function someoneAt(x,y){const n=npcAt(x,y);return !!(n&&n.look)||petOn()&&pet.on&&pet.x===x&&pet.y===y} // a person (not an object stand-in) or the follower on that tile function marker(X,Y,t,st){ if(!st)return; if(Y+CAM.y<11){X+=11;Y=11-CAM.y} // no room above them on the map (the top row: no camera can show a marker there): it sits beside their head and moves with them, so it never jumps while the camera scrolls if(G.marker){G.marker(X,Y,t,st);return} // a game's own ! ? ★ (GAME.marker(X,Y,t,state)) const bob=Math.round(Math.sin(t/220)*1.5); if(st==='todo'){r(X+6,Y-9+bob,4,8,'#1B1E2B');r(X+7,Y-8+bob,2,4,'#E8962A');r(X+7,Y-3+bob,2,1,'#E8962A')} else if(st==='review'){const y=Y-10+bob;r(X+5,y,6,9,'#1B1E2B');r(X+6,y+1,4,7,'#69CFD8');r(X+7,y+2,2,1,'#0F141A');r(X+8,y+3,1,1,'#0F141A');r(X+7,y+4,1,1,'#0F141A');r(X+7,y+6,1,1,'#0F141A')} else if(st==='side'){const y=Y-9,k='#1B1E2B',w='#C9D1CD';r(X+4,y,8,1,k);r(X+3,y+1,1,4,k);r(X+12,y+1,1,4,k);r(X+4,y+5,8,1,k);r(X+4,y+1,8,4,w);r(X+5,y+2,6,1,'#93A09A');r(X+5,y+3,4,1,'#93A09A');r(X+6,y+5,2,1,w);r(X+6,y+6,1,1,w);r(X+5,y+6,1,1,k);r(X+7,y+6,1,1,k);r(X+6,y+7,1,1,k)} // someone with something new to say, off the story path: a still grey speech bubble, quieter than ! and ? else if(st==='wait'){const y=Y-5+bob;[5,7,9].forEach((dx,i)=>r(X+dx,y,1,1,Math.floor(t/300)%3===i?'#FFFFFF':'#93A09A'))} else{const y=Y-9+bob;r(X+7,y,2,2,'#E8962A');r(X+4,y+2,8,2,'#E8962A');r(X+5,y+4,6,1,'#E8962A');r(X+5,y+5,2,2,'#E8962A');r(X+9,y+5,2,2,'#E8962A');r(X+7,y+2,2,2,'#F6D9A6')} } function status(n){ if(n.status){const v=n.status();if(v!==undefined)return v} if(C.REVIEW&&reviewLines(n).length){const own=usual(n);return (n.script&&n.script())||!own||own.some(moves)?null:'review'} // anyone with a line for a due word, badge or not, when the talk would be the review if(!n.badge)return null; if(!n.badge.every(has))return 'todo'; if(!C.REVIEW&&n.badge.some(isDue))return n.script&&n.script()?null:'review'; // a ? only when talking reviews (their script lines come first and skip it) return n.badge.every(w=>lv(w).b>=3)&&!(state.starDone||{})[npcId(n)]?'star':null; // ★: all their words mastered — shown a while, then it fades for good (starFade) } /* the ★ over someone whose words you've all mastered: on screen for STAR_MS, or until you talk to them, then it fades out and stays gone */ const STAR_MS=18000,STAR_FADE=2000,starAcc={};let starT=0,starDt=0; function starFade(n){const id=npcId(n),a=starAcc[id]=(starAcc[id]||0)+starDt,al=ame?{...base,...me}:base; // a chapter's PLAYER object = the uniform; the player's choices = hair, skin, face const player={x:0,y:0,dir:'down',moving:false,t:0,fx:0,fy:0,step:0,look:myLook()}; let held=null,warping=false,lockMsgAt=0,pressN=0,petTurn=-1; // pressN counts new presses (not key repeats): facing the follower takes one press, swapping with them a new one function npcPos(n){return n.pos?n.pos():n.at||[n.x,n.y]} // n.at: where a move: step left them const sitting=n=>typeof n.sit==='function'?n.sit():!!n.sit; // NPC sit: true | fn → drawn seated (on n.chair, a look, if given), and doesn't turn to talk /* step sit:{npc} sits the player on that NPC's tile (a chair), facing its dir; sit:{x,y,dir,chair} anywhere. The first arrow key stands them up. The saved position stays where they stood, so a reload never puts them inside the chair. */ function sitDown(o){ const n=o.npc?C.NPC[o.npc]:null,[x,y]=n?npcPos(n):[o.x,o.y]; const go=()=>Object.assign(player,{x,y,dir:o.dir||(n&&(n.home||n.dir))||player.dir,moving:false,t:0,sit:{npc:n,chair:o.chair||(n&&n.look)||null}}); if(Math.abs(player.x-x)+Math.abs(player.y-y)>1){$('fade').classList.add('on');setTimeout(()=>{go();if(!(dlg&&dlg.black))$('fade').classList.remove('on')},230)} // from further off: a cut, not a jump (inside a black time cut the screen stays black) else go(); } const live=()=>NPCS.filter(n=>!n.hide||!n.hide()); const npcAt=(x,y)=>live().find(n=>{const [a,b]=npcPos(n);return a===x&&b===y}); const warpAt=(x,y)=>Z.warps&&Z.warps[x+','+y]; const walkable=(x,y)=>{const c=at(x,y);return c!=null&&!!(Z.legend[c]||{}).walk}; const blocked=(x,y)=>!walkable(x,y)||!!npcAt(x,y); const CREATOR=!!document.getElementById('mePanel'); // 나 꾸미기 only where the page has the panel const panelOpen=()=>(CREATOR&&!$('mePanel').hidden)||!$('startPanel').hidden||!$('panel').hidden||!$('chPanel').hidden||!$('talkPanel').hidden||!$('tapPanel').hidden||(!!$('repPanel')&&!$('repPanel').hidden)||(!!$('setPanel')&&!$('setPanel').hidden); const boxedIn=(px,py)=>Object.values(D).every(([dx,dy])=>{const x=player.x+dx,y=player.y+dy;return x===px&&y===py||blocked(x,y)}); // every other way is shut: a press toward the follower swaps at once (else the turn-first rule reads as a wall) function tryMove(){ if(player.moving||!held||dlg||panelOpen()||warping)return; player.sit=null; const was=player.dir;player.dir=held;const [dx,dy]=D[held];const nx=player.x+dx,ny=player.y+dy; if(petOn()&&pet.x===nx&&pet.y===ny&&!boxedIn(nx,ny)){if(was!==held){petTurn=pressN;return}if(petTurn===pressN)return} // the follower right there: a press turns you to face them (A talks); a NEW press swaps places — holding that first press never swaps by itself (a normal tap lasts a few frames) const w=warpAt(nx,ny);const lock=w&&w.lock&&w.lock(); if(lock){if(performance.now()-lockMsgAt>1500){lockMsgAt=performance.now();sfx('lock');toast(lock)}return} if(blocked(nx,ny))return; player.moving=true;player.t=0;player.fx=player.x;player.fy=player.y;player.x=nx;player.y=ny;player.step=player.step===1?2:1; if(petOn()){const ox=player.fx,oy=player.fy;pet.fx=pet.x;pet.fy=pet.y;if(ox!==pet.x||oy!==pet.y)pet.dir=ox>pet.x?'right':oxpet.y?'down':'up';pet.x=ox;pet.y=oy} } function arrive(){ state.x=player.x;state.y=player.y;state.dir=player.dir;save(); if(C.onStep){C.onStep();updateQuest();save()} // a chapter that counts steps or starts a scene on a square (단어 마을's cartridges) const w=warpAt(player.x,player.y); if(w){goZone(w.to,w.x,w.y,w.dir);return true} showRoom();return false; } function goZone(id,x,y,dir){ warping=true;sfx('door');$('fade').classList.add('on'); setTimeout(()=>{loadZone(id,x,y,dir);updateQuest();save();if(held&&held!==dir)held=null; // turned around by the warp: let go of the held direction petArrive();if(greet()&&dlg.black){warping=false;return} // the room's greeting starts over black (a ride told on the way): the screen stays dark, no flash of the room first $('fade').classList.remove('on');setTimeout(()=>{warping=false;if(!dlg&&!greet())tryMove()},120)},230); } function loadZone(id,x,y,dir){ ZID=id;Z=C.ZONES[id];state.zone=id; MAP=Z.map.map(row=>row.split(''));MW=MAP[0].length;MH=MAP.length; NPCS=Z.npcs.map(k=>C.NPC[k]);NPCS.forEach(n=>{n.home=n.home||n.dir;n.turnAt=performance.now()+2000+Math.random()*3000}); Object.assign(player,{x,y,dir,moving:false,t:0,sit:null});camT=null;camF=null;state.x=x;state.y=y;state.dir=dir; petReset();pet.on=false;ghosts=[]; $('reg').textContent=`${Z.reg} · ${CH.n} ${CH.title}`;fitReg();showRoom(true); } let roomName=''; function showRoom(force){ let nm=Z.name;(Z.rooms||[]).forEach(([a,b,c,d,n])=>{if(player.x>=a&&player.x<=c&&player.y>=b&&player.y<=d)nm=n}); if(nm!==roomName||force){roomName=nm;const z=$('zone');z.textContent=nm;if(!dlg)z.classList.remove('dim');clearTimeout(showRoom.t);showRoom.t=setTimeout(()=>z.classList.add('dim'),1500)} // fades so it never hides a ! marker } function update(dt,t){ if(player.moving){player.t+=dt/(170*(Z.slow||1)); /* Z.slow > 1 = heavy gravity */if(player.t>=1){player.t=0;player.moving=false;if(!arrive())tryMove()}} else tryMove(); if(!dlg)live().forEach(n=>{if(n.still||n.pos||n.walk||sitting(n))return;if(t>n.turnAt){if(chatPair(n)){n.dir=n.home;n.turnAt=t+3000;return} /* mid-conversation: no glancing around */ const ds=['down','left','right',n.home,n.home];n.dir=ds[Math.random()*ds.length|0];n.turnAt=t+2500+Math.random()*3500}}); $('btnA').classList.toggle('ready',!dlg&&!player.moving&&!!facing()); } const dark=document.createElement('canvas');dark.width=cv.width;dark.height=cv.height;const dg=dark.getContext('2d'); /* a scene can point the camera at a tile (step cam:[x,y]); it glides there, and back to the player when the step says cam:null or the conversation ends */ let camT=null,camF=null,camLast=0,talkCy=null,talkAt=0,talkExtra=0; /* during a conversation: the camera y that keeps the player and the speaker above the dialogue box, or null when they already are. It only ever moves further (never back and forth as the box grows and shrinks line to line) until the conversation ends. Near the bottom of a map it may scroll past the edge by as much as the box covers: that strip is behind the box. */ /* canvas px where the plain dialogue box starts (choices and word tiles don't count), with air for one more line; null when no box */ /* ---------- the dialogue box: as tall as its line (typing lays the whole line out first, so it never grows mid-line), its side chosen once per conversation when it opens, as Undertale's dialogue code does (box at the top when you stand low on the screen): at the bottom unless the tallest box (three lines, the most linecheck allows) would cover you or whoever you're talking to, then at the top. The camera doesn't move for talk. A scene's camera cut (step cam:[x,y]) chooses again, for the tile it shows, and frames that tile in the space the tallest box would leave free, so shorter and longer lines don't nudge the view. ---------- */ function boxSpan(){const box=$('dlg'),k=cv.clientHeight/cv.height;if(!dlg||box.hidden||!k)return null; return [box.offsetTop/k,(box.offsetTop+box.offsetHeight)/k]} // canvas px the box covers (choices and tiles included) function boxReserve(){const box=$('dlg'),t=$('txt'),k=cv.clientHeight/cv.height,m=t.style.minHeight; // canvas px of the box with three full lines t.style.minHeight=3*(parseFloat(getComputedStyle(t).lineHeight)||parseFloat(getComputedStyle(t).fontSize)*1.5)+'px';const h=box.offsetHeight/k;t.style.minHeight=m;return h} function freeBand(){const b=boxSpan();if(!b)return [0,VH*TS];const h=Math.max(b[1]-b[0],dlg.boxH||0); // the view's part the tallest box leaves free return dlg.atTop?[b[0]+h+4,VH*TS]:[0,b[1]-h-4]} function placeBox(rows,camY){ const box=$('dlg'),k=cv.clientHeight/cv.height;if(!dlg||!k)return; box.classList.remove('attop');dlg.atTop=false; dlg.boxH=Math.max(box.offsetHeight/k,boxReserve());const h=dlg.boxH+6,cy=camY??CAM.y; const feet=Math.max(...rows)*TS+16-cy; // the lowest feet on screen if(feet>VH*TS-h){box.classList.add('attop');dlg.atTop=true} } function talkRows(){const rows=[player.y],n=dlg&&dlg.npc;if(n&&NPCS.includes(n)&&(!n.hide||!n.hide()))rows.push(npcPos(n)[1]);return rows} function talkLift(){return null} // talk never moves the camera (the box chooses its side instead) /* sing: true | fn on an NPC → three little ♪ rise from above their head, drift and fade, while it's true (a song on air) */ function singNotes(x,y,t,seed){ for(let i=0;i<3;i++){const p=(t/1600+i/3+seed*.13)%1,X=x+Math.round(Math.sin(p*5+i*2)*3)+(i-1)*4,Y=y-Math.round(p*16); g.globalAlpha=p<.2?p/.2:1-(p-.2)/.8; const note=(c,o)=>{r(X+o,Y+o+4,3,2,c);r(X+o+2,Y+o,1,5,c);r(X+o+3,Y+o+1,1,1,c);r(X+o+4,Y+o+2,1,1,c)};note('#2B2E36',1);note('#FFF3C4',0)} // shadow, then the note g.globalAlpha=1} function render(t){ starDt=starT?Math.min(100,t-starT):0;starT=t; const px=player.moving?player.fx+(player.x-player.fx)*player.t:player.x; const py=player.moving?player.fy+(player.y-player.fy)*player.t:player.y; const [fx,fy]=camT||[px,py]; let cx=fx*TS+8-VW*TS/2,cy=fy*TS+8-VH*TS/2; if(dlg)talkAt=t;else if(talkCy!=null&&t-talkAt>700){talkCy=null;talkExtra=0;camF={...CAM}} // glide back, never snap /* held a moment after it ends: a follow-up note (단어 일지) doesn't make it dip and rise */ const cyMap=Math.max(0,Math.min(cy,MH*TS-VH*TS)); // where the camera would be without a conversation (inside the map) if(!camT&&talkCy!=null||!camT&&dlg){const l=dlg?talkLift(cyMap,py):null;if(l!=null)talkCy=Math.max(talkCy??-1e9,l);if(talkCy!=null)cy=Math.max(cyMap,talkCy)} let camLift=false;if(camT&&dlg){const [b0,b1]=freeBand();cy=fy*TS+8-(b0+b1)/2;camLift=true} // a scene's camera target sits in the space above the dialogue box, not behind it cx=Math.max(0,Math.min(cx,MW*TS-VW*TS));cy=Math.max(0,Math.min(cy,MH*TS-VH*TS)); const dt=Math.min(50,t-camLast);camLast=t; if(camT||camF||talkCy!=null){if(!camF)camF={...CAM};const k=1-Math.exp(-dt/(camT?180:260)); /* talk shifts glide a little slower */camF.x+=(cx-camF.x)*k;camF.y+=(cy-camF.y)*k; if(!camT&&Math.abs(cx-camF.x)<.5&&Math.abs(cy-camF.y)<.5)camF=null;else{cx=camF.x;cy=camF.y}} cx=Math.round(cx);cy=Math.round(cy);CAM={x:cx,y:cy}; const x0=Math.floor(cx/TS),y0=Math.floor(cy/TS); for(let y=y0;y<=y0+VH;y++)for(let x=x0;x<=x0+VW;x++)tile(x,y,x*TS-cx,y*TS-cy,t); // the chair the player sits on is drawn with the player const ents=live().filter(n=>!(player.sit&&player.sit.npc===n)).map(n=>{const wk=walkAt(n,t);if(wk){const [wx,wy,wd,wf]=wk;return {y:wy,f:()=>drawChar(n.look,Math.round(wx*TS-cx),Math.round(wy*TS-cy-2),wd,wf)}} const [nx,ny]=npcPos(n);return {y:ny,f:()=>{const X=nx*TS-cx,Y=ny*TS-cy-2; if(n.look)n.kind==='andy'?drawAndy(n.look,X,Y,n.dir,0,t):sitting(n)?drawSeated(n.look,X,Y,n.dir,n.chair):drawChar(n.look,X,Y,n.dir,0); {const h=typeof n.hold==='function'?n.hold():n.hold,p=h&&((C.PROPS||{})[h]||PROPS[h]);if(p)p(X,Y,n.dir,t)} // hold: a prop in their hands if(n.sleep)for(let i=0;i<2;i++){const p=(t/900+i/2)%1,zx=X+11+Math.round(p*4),zy=Y-2-Math.round(p*10),c='#2E3550';g.globalAlpha=1-p*.7;r(zx,zy,4,1,c);r(zx+2,zy+1,1,1,c);r(zx+1,zy+2,1,1,c);r(zx,zy+3,4,1,c);g.globalAlpha=1} // asleep: z's drifting up // no marker over the player standing just above, over the one you're talking to (or whoever a proxy stands for), or when nomark says so const talking=dlg&&(dlg.npc===n||(n.proxy&&dlg.npc===n.proxy())),off=typeof n.nomark==='function'?n.nomark():n.nomark; if(!(player.x===nx&&player.y=ny-1-Math.ceil(artLift(n.look)/TS))&&!talking&&!off){const st=status(n),al=st==='star'?starFade(n):1;if(al>0){g.globalAlpha=al;const by=n.look&&n.markDy==null&&!n.markDx&&someoneAt(nx,ny-1); // someone right above: the mark would sit on their face, so it goes beside this person's head (the free side) by?marker(X+(someoneAt(nx+1,ny)&&!someoneAt(nx-1,ny)?-11:11),Y+13-artLift(n.look),t,st):marker(X+(n.markDx||0),Y-artLift(n.look)+(n.markDy??(n.look?0:7)),t,st);g.globalAlpha=1}}}}}); // no look (a stand-in for an object: a chair, a shelf, embers): the mark sits on its own tile, not over whatever is above it ghosts=ghosts.filter(gh=>{const wk=walkAt(gh,t);if(!wk)return false;const [wx,wy,wd,wf]=wk;ents.push({y:wy,f:()=>drawChar(gh.look,Math.round(wx*TS-cx),Math.round(wy*TS-cy-2),wd,wf)});return true}); const walk=player.moving?(player.t<.5?player.step:0):0; if(petOn()){ petArrive(); const qx=player.moving?pet.fx+(pet.x-pet.fx)*player.t:pet.x,qy=player.moving?pet.fy+(pet.y-pet.fy)*player.t:pet.y; if(player.moving||pet.x!==player.x||pet.y!==player.y)ents.push({y:qy-.01,f:()=>drawChar(C.FOLLOW.look,Math.round(qx*TS-cx),Math.round(qy*TS-cy-2),pet.dir,walk?3-walk:0)}); // not while it shares your square }else pet.on=false; const plook=typeof C.PLAYER==='function'?(C.PLAYER()||myLook()):player.look; // PLAYER may be a function → the look can change mid-chapter (disguises) const overTall=live().some(n=>{const [nx,ny]=npcPos(n);return nx===player.x&&ny===player.y+1&&artLift(n.look)>=6}); // just above someone tall: drawn over their head, never hidden behind them ents.push({y:overTall?py+1.02:py,f:()=>{const X=Math.round(px*TS-cx),Y=Math.round(py*TS-cy-2);player.sit?drawSeated(plook,X,Y,player.dir,player.sit.chair):drawChar(plook,X,Y,player.dir,walk)}}); ents.sort((a,b)=>a.y-b.y).forEach(e=>e.f()); // a legend entry's `front` tile (tree canopies) draws after the characters, unclipped: it overhangs and covers whoever walks behind it for(let y=y0-4;y<=y0+VH;y++)for(let x=x0-4;x<=x0+VW;x++){const c=at(x,y),L=c!=null&&Z.legend[c];if(L&&L.front&&TILES[L.front])TILES[L.front](x*TS-cx,y*TS-cy,x,y,t)} for(const n of live())if(typeof n.sing==='function'?n.sing():n.sing){const [nx,ny]=npcPos(n);singNotes(Math.round(nx*TS-cx)+6,Math.round(ny*TS-cy)-10,t,nx*7+ny)} // someone singing /* lights out in a broken room: everything goes dark except a small circle around the player */ const dk=Z.dark&&Z.dark(); if(dk){ const [a,b,c,d]=dk;dg.clearRect(0,0,dark.width,dark.height); dg.globalCompositeOperation='source-over';dg.fillStyle='rgba(4,6,10,.9)';dg.fillRect(a*TS-cx,b*TS-cy-4,(c-a+1)*TS,(d-b+1)*TS+4); const flick=Math.random()<.04?4:0; const lx=px*TS-cx+8,ly=py*TS-cy+6;const gr=dg.createRadialGradient(lx,ly,6,lx,ly,34-flick); gr.addColorStop(0,'rgba(0,0,0,1)');gr.addColorStop(1,'rgba(0,0,0,0)'); dg.globalCompositeOperation='destination-out';dg.fillStyle=gr;dg.beginPath();dg.arc(lx,ly,34,0,Math.PI*2);dg.fill(); g.drawImage(dark,0,0); if(Math.floor(t/600)%2){r(a*TS-cx+2,b*TS-cy+1,3,2,'#D2533F');r(c*TS-cx+11,b*TS-cy+1,3,2,'#D2533F')} } } /* scripted walks. walk:{npc,from}: the NPC appears at `from` and walks to its own spot (its pos() if it has one) (e.g. the class president going back to her desk). leave:{npc,to}: the NPC (hidden by the same step's flag) walks from its spot to `to` and is gone (out a door, off the map). leave:{follow:1,to}: the same for the follower (C.FOLLOW), whose when() the step's flag ends. */ let walks=[],leaves=[],ghosts=[];const WALK_MS=230; function walkPath([fx,fy],[tx,ty],self){ const k=(x,y)=>x+','+y,prev={[k(fx,fy)]:null},q=[[fx,fy]]; while(q.length){const [x,y]=q.shift();if(x===tx&&y===ty)break; for(const [dx,dy] of Object.values(D)){const a=x+dx,b=y+dy,kk=k(a,b);if(kk in prev)continue; if(!(a===tx&&b===ty)&&(!walkable(a,b)||live().some(o=>o!==self&&npcPos(o)[0]===a&&npcPos(o)[1]===b)))continue;prev[kk]=[x,y];q.push([a,b])}} let end=[tx,ty]; // blocked (someone stands in the doorway)? walk as close as possible, then step in / vanish if(!(k(tx,ty) in prev)){let best=1e9;for(const kk in prev){const [a,b]=kk.split(',').map(Number),d=Math.abs(a-tx)+Math.abs(b-ty);if(d{const n=C.NPC[m.npc];if(!n)return;const from=npcPos(n);n.at=m.to; const path=walkPath(from,m.to,n);if(m.dir)n.home=m.dir;n.walk=path.length>1?{path,t0:performance.now(),end:m.dir||n.dir}:null;if(!n.walk&&m.dir)n.dir=m.dir})} function queueWalks(s){ // one or a list each // arrivals wait for the conversation to close (until then they stand where they start, no pop to the end spot first) [].concat(s.walk||[]).forEach(w=>{const n=C.NPC[w.npc];if(!n)return;walks.push(w);n.walk={path:[w.from],hold:1,end:n.dir}}); // a leave starts at once, on the line that narrates it ("후다닥 나갔어요"), so nobody lingers after the text says they left [].concat(s.leave||[]).forEach(w=>{const n=w.follow?null:C.NPC[w.npc];if(w.follow?!(C.FOLLOW&&pet.on):!n||!NPCS.includes(n))return; // follow:1 — the follower walks off (the step's flag ends FOLLOW.when) const from=w.follow?[pet.x,pet.y]:npcPos(n),g={look:w.follow?C.FOLLOW.look:n.look,from}; const path=walkPath(from,w.to,null);if(path.length>1){g.walk={path,t0:performance.now()};ghosts.push(g)}}); } function startWalks(){ const t0=performance.now(); walks.splice(0).forEach(w=>{const n=C.NPC[w.npc];if(!n)return;n.walk=null;if(n.hide&&n.hide())return; const path=walkPath(w.from,n.pos?n.pos():[n.x,n.y],n);if(path.length>1)n.walk={path,t0,end:n.dir}}); // to where the story puts them now (pos), else their spot leaves.splice(0).forEach(([w,g])=>{const path=walkPath(g.from,w.to,null);if(path.length>1)g.walk={path,t0};else ghosts=ghosts.filter(x=>x!==g)}); } function walkAt(n,t){ // → [x,y,dir,frame] while walking, null when arrived const w=n.walk;if(!w)return null;if(w.hold)return [w.path[0][0],w.path[0][1],w.dir||w.end||n.dir||'down',0];const p=Math.max(0,(t-w.t0)/WALK_MS),i=Math.floor(p); // a frame can be stamped just before the walk began if(i>=w.path.length-1){n.walk=null;if(w.end)n.dir=w.end;return null} const [ax,ay]=w.path[i],[bx,by]=w.path[i+1],f=p-i; const dir=bx>ax?'right':bxay?'down':'up'; return [ax+(bx-ax)*f,ay+(by-ay)*f,dir,f<.5?(i%2?1:2):0]; } let last=performance.now(); function loop(t){const dt=Math.min(50,t-last);last=t;if(Z){update(dt,t);render(t);if(t-musicT>500){musicT=t;updateMusic()}}requestAnimationFrame(loop)} // music follows the room and the story twice a second /* ---------- dialogue ---------- */ let dlg=null,typing=null,pending=null,sel=0; /* ---------- phone screen, 문화 노트 and 문법 노트 (all optional: a game's shell opts in with #phonePanel/#pscr, #notes/#noteCard and #gnotes/#gnoteCard) ---------- Step phone:{app, post, by, when, count, comments:[[name,text],…], time, battery, culture, grammar}: an app on someone's phone fills the game view on that line (the D-pad and A/B stay below): the D-pad scrolls it, A finishes the line and then closes it, B closes it, and its words are tappable. A step's culture:'id' (or a phone's, when it closes) adds a 문화 노트 from globalThis.CULTURE_NOTES (a game's data: {id:{t, lines:[[korean, english, [source numbers]]…], src:[[title, url]…]}}): the culture behind a story moment, every line tied to its sources, read in the journal. A step's grammar:'id' (or a phone's) adds a 문법 노트 from globalThis.GRAMMAR_NOTES ({id:{t, lines:[[korean, english, [source numbers]]…], ex:[[korean, english]…], src:[[title, url]…]}}): the grammar of the line it's on, a few lines and then its examples, every line tied to its sources like a 문화 노트's, read in the journal under its own heading (#gnotesH), after the 문화 노트. Each kind keeps its own seen/read lists; without GRAMMAR_NOTES the 문법 노트 heading and list are taken out of the journal. Attachments: photo:{look,face,caption,mic,old} is an album portrait; capture:{caption,lines:[text,…]} is a static captured screen, with a header and independently tappable/translated lines (glossHTML / lineEn). A capture can also be a chat message's attachment, beside its text, instead of pic. It has no live buttons, counts or login. Chat transcripts retain captures. */ let phoneOpen=false,curPhone=null; /* English on the phone (when the game has lines-en): a ? by each post, comment and caption that has English shows it under the line (the phone's own .tq/.ten); with 영어 자막 on it is already showing */ const pEnQ=t=>lineEn(t)?``:''; const pEn=t=>{const e=lineEn(t);return e?`${e.replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]))}`:''}; const captureHTML=p=>`
${[p.caption,...(p.lines||[])].map(t=>`
${glossHTML(t||'')}${pEnQ(t)}${pEn(t)}
`).join('')}
`; // Only new attachment/card classes use these styles; existing shells keep their presentation. {const st=document.createElement('style');st.textContent=` .pcapture{background:#F0E7D1;color:#263C42;padding:7px;border:1px solid #A3967B;border-radius:4px;font-size:.8rem;line-height:1.45;display:flex;flex-direction:column;gap:5px} .pcapture .pcapture-line:first-child{font:600 .68rem var(--mono,monospace);border-bottom:1px solid #A3967B;padding-bottom:3px} .pcapture .pcapture-line:nth-child(3){color:#405E59;font-size:.72rem} .pcapture .ten{font-size:.74rem;display:block}.pcapture .ten[hidden]{display:none} .pclabel{font:600 .75rem var(--body,sans-serif);color:var(--muted);display:flex;flex-direction:column;gap:3px} .pcbonus-strip{border-top:1px dashed var(--seam);padding-top:10px} .pcard.pcbonus{max-width:240px;margin:0 auto;border-style:dashed;background:var(--hull);font-size:.82rem;padding:9px} .pcard.pcbonus .pcpic{width:96px;max-width:44%;align-self:center} .pcard.pcbonus .pccap{font-size:.9rem}.pcard.pcbonus .pcl{font-size:.78rem} .pcard.pcbonus .pchead{font-size:.66rem}.pcard.pcbonus .pchead>span:nth-child(2){display:none} @media(max-height:500px) and (orientation:landscape){.pcapture{padding:4px;gap:3px;font-size:.74rem}.pcard.pcbonus .pcpic{width:64px}} `;document.head.appendChild(st)} function openPhone(p){ if(!$('phonePanel'))return;curPhone=p; const bars='',bat=p.battery??60; if(p.capture){ $('pscr').innerHTML=`
${p.time||''}
${glossHTML(p.app||'')}
${captureHTML(p.capture)}
`; $('phonePanel').hidden=false;phoneOpen=true;return} if(p.photo){ // an album photo: a pixel picture (a look's portrait, made old) with its caption $('pscr').innerHTML=`
${p.time||'12:30'}LTE${bars}${bat}%
` +`
${p.app||'사진'}●●●
${glossHTML(p.photo.caption||'')}
${p.photo.caption&&lineEn(p.photo.caption)?`
${pEnQ(p.photo.caption)}${pEn(p.photo.caption)}
`:''}
`; const cv=$('pscr').querySelector('canvas');drawPortrait(cv,p.photo.look,p.photo.face||'happy',false); if(p.photo.mic){const c=cv.getContext('2d');const R=(x,y,w,h,col)=>{c.fillStyle=col;c.fillRect(x,y,w,h)};R(33,27,7,7,'#1B1E2B');R(34,28,5,5,'#8A8E96');R(35,29,1,1,'#C9CDD4');R(35,34,3,14,'#1B1E2B');R(36,34,1,14,'#3A3E48')} // a microphone in front $('phonePanel').hidden=false;phoneOpen=true;return} const c=p.comments.map(([n,t])=>`
${n}${pEnQ(t)}${glossHTML(t)}${pEn(t)}
`).join(''); const more=p.count-p.comments.length; $('pscr').innerHTML=`
${p.time||'12:30'}LTE${bars}${bat}%
` +`
${p.app}●●●
${glossHTML(p.post)}${p.by} · ${p.when}${pEnQ(p.post)}${pEn(p.post)}
` +`
${glossHTML('댓글 '+p.count+'개')}
${c}${more>0?`
${glossHTML('댓글 '+more+'개 더 보기')}
`:''}
`; $('phonePanel').hidden=false;phoneOpen=true; } function closePhone(){if(!phoneOpen)return;phoneOpen=false;$('phonePanel').hidden=true;if(curChat)closeChat();if(curSlides){curSlides=null;document.body.classList.remove('chatting')}hideGloss();if(curPhone&&curPhone.culture)unlockCulture(curPhone.culture);if(curPhone&&curPhone.grammar)unlockGrammar(curPhone.grammar);curPhone=null} if($('phonePanel'))$('phonePanel').addEventListener('click',e=>{const q=e.target.closest('.tq');if(q){e.stopPropagation();hintDone('lineQ');const t=q.closest('.pc,.ppost,.pcapen')?.querySelector('.ten')||(q.nextElementSibling&&q.nextElementSibling.classList.contains('ten')?q.nextElementSibling:null);if(t)t.hidden=!t.hidden;q.classList.toggle('on',!!t&&!t.hidden);q.blur();lineQOpened(q,t);return}const g=e.target.closest('.gl');if(g){e.stopPropagation();showGloss(g.dataset.k,g);return}const w=e.target.closest('.w');if(w){e.stopPropagation();showWord(w.textContent,w)}}); /* ---------- phone chat (opt-in; 소리 엽서). A dialogue step chat:{id, room, msgs, reply?, after?, set?, award?} is one exchange in a messenger room, shown on the phone (#phonePanel) with the dialogue box out of the way: - msgs/after: [{id, from, text, time, now?, pic?, caption?}] (time: when it was sent; now: what the phone's clock shows as it arrives, default its time; the chat's own now: the clock when a finished exchange is reopened later) — from is a cast id (C.CAST / GAME.cast: {id:{name, look}}) or 'me' (the player: right-hand bubbles, no portrait). Each message is one press of A. pic: a picture card (C.PICS[pic](canvas) draws it) with a caption. - reply: {id, ask, opts, w, reg?, time?, now?} — a question whose options are whole messages, answered in the reply strip under the thread (the dialogue's own #choices, moved there): a wrong one shows its hint over the thread and never becomes a bubble; the right one is sent. Or {id, choose:[[label, fn]]}: an ungraded reply whose fn waits for the commit. - The commit: the exchange's last step (the last after message, or the sent reply when there's none) runs set/award and the deferred fn once, and records the exchange in the shared record (GAME prefix + '-shared', across chapters): {done, sent, msgs}. Reopening a done exchange shows that transcript, with nothing sent, set or awarded again. A reload before the commit starts the exchange over. - English: a ? on each message with English, keyed 'chat::' in lines-en (short and jamo-only texts need it), else by the text itself. Every message and sent reply also goes to the talk log under the room's name. - Keys: A next message / send the selected reply; ↑/↓ scroll the thread, or move between replies (↑ on the top one scrolls); B closes word help, then a wrong-answer hint (back to the replies); with no reply pending it puts the phone away and ends the talk. */ const SHARED_KEY=KEY('shared');let shared={};try{shared=JSON.parse(store.get(SHARED_KEY)||'{}')||{}}catch(e){shared={}} const saveShared=()=>{if(!RP)store.set(SHARED_KEY,JSON.stringify(shared))}; // a replay's postcard choices and chats don't replace the real ones const chatRoom=r=>({...(G.rooms||{}),...(C.ROOMS||{})})[r]||{t:r}; const chatWho=id=>id==='me'?{name:T('나')}:({...(G.cast||{}),...(C.CAST||{})})[id]||C.NPC[id]||{name:id}; let curChat=null; // {c, msgs:[…shown], home:[parent, next] of #choices} function chatSteps(c){ // a chat step → its dialogue steps const rec=(shared.chats||{})[c.id]; if(rec&&rec.done)return [{chatOpen:c,chatAll:rec.msgs}]; // done before: the transcript, nothing else happens const msg=m=>({chatMsg:m}),list=[...(c.msgs||[]).map(msg)]; if(c.reply)list.push(c.reply.choose?{chatChoose:c.reply.choose,chatReply:c.reply.id,ask:c.reply.ask||'',time:c.reply.time,now:c.reply.now}:{...c.reply,chatReply:c.reply.id,ask:c.reply.ask||''}); list.push(...(c.after||[]).map(msg)); if(!list.length)return []; list[0].chatOpen=c; const last=list[list.length-1]; // the last step commits; a reply waits: its set/award ride on the bubble it sends if(last.chatReply)Object.assign(last,{chatCommit:c,chatSet:c.set,chatAward:c.award});else Object.assign(last,{chatCommit:c,set:c.set,award:c.award}); return list; } function openChat(c,all){ if(!$('phonePanel'))return;curChat={c,msgs:[],sent:null,later:[]};curPhone={chat:1}; const R=chatRoom(c.room),bat=c.battery??72,bars=''; $('pscr').innerHTML=`
${c.time||(c.msgs&&c.msgs[0]&&(c.msgs[0].now||c.msgs[0].time))||''}LTE${bars}${bat}%
` +`
${glossHTML(R.t||c.room)}${R.members?` ${R.members.length}`:''}☰
` +`
`; const ch=$('choices');curChat.home=[ch.parentNode,ch.nextSibling];$('creply').appendChild(ch); // the dialogue's choices become the reply strip $('phonePanel').hidden=false;phoneOpen=true;document.body.classList.add('chatting'); chatFollow(); if(all){all.forEach(m=>chatPush(m,true));setNow(c.now||'')} // reopened later: the transcript keeps its send times, the clock shows c.now (now) if given } /* a reader at the newest message stays there when the phone reflows (rotation, the reply strip, a bubble's English opening); one who scrolled back keeps their place. A scroll that only clamps during a resize isn't the reader moving. */ function chatFollow(){ const L=$('clist');let w=L.clientWidth,h=L.clientHeight;curChat.atEnd=true; L.addEventListener('scroll',()=>{if(L.clientWidth!==w||L.clientHeight!==h)return;if(curChat)curChat.atEnd=L.scrollHeight-L.scrollTop-L.clientHeight<48},{passive:true}); curChat.ro=new ResizeObserver(()=>{w=L.clientWidth;h=L.clientHeight;if(curChat&&curChat.atEnd)L.scrollTop=L.scrollHeight}); curChat.ro.observe(L); } const setNow=t=>{const el=$('pscr')&&$('pscr').querySelector('.pnow');if(el&&t)el.textContent=t}; function closeChat(){ if(!curChat)return;const ch=$('choices');ch.hidden=true;ch.innerHTML=''; const [par,nx]=curChat.home;if(par)par.insertBefore(ch,nx&&nx.parentNode===par?nx:null); curChat.ro&&curChat.ro.disconnect();curChat=null;document.body.classList.remove('chatting'); } function chatPush(m,quiet){ const L=$('clist');if(!L||!curChat)return; const near=L.scrollHeight-L.scrollTop-L.clientHeight<48,mine=m.from==='me',who=chatWho(m.from); const key=curChat.c&&m.id?'chat:'+curChat.c.id+':'+m.id:null,en=(key&&lineEn(key))||lineEn(m.text||''); const esc=x=>String(x).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c])); const row=document.createElement('div');row.className='cm'+(mine?' me':''); row.innerHTML=(mine?'':``) +`
${mine?'':`${esc(T(who.name||''))}`}` +(m.pic?``:'') +(m.capture?captureHTML(m.capture):'') +`${glossHTML(m.text||m.caption||'')}` +(en?`${esc(en)}`:'') +`
`+(m.time?`${esc(m.time)}`:''); L.appendChild(row);curChat.ro&&curChat.ro.observe(row); if(!mine&&who.look){try{drawPortrait(row.querySelector('.cface'),who.look,m.face||'happy',false)}catch(e){}} if(m.pic){const P=(C.PICS||G.pics||{})[m.pic];if(P)try{P(row.querySelector('.cpic'))}catch(e){}} if(!quiet)setNow(m.now||m.time); // the phone's clock: the story's time now (m.now), else the message's send time curChat.msgs.push({from:m.from,text:m.text||m.caption||'',time:m.time,id:m.id,pic:m.pic,...(m.capture?{capture:m.capture}:{})}); if(!quiet)logTalk(chatRoom(curChat.c.room).t+' · '+(mine?T('나'):who.name),m.text||m.caption||'',key&&lineEn(key)?key:undefined); if(near||mine||curChat.msgs.length<=1)L.scrollTop=L.scrollHeight; // new messages don't pull you back down if you scrolled up to read } function chatCommitNow(c){ // the exchange is over: its deferred reply runs and the shared record keeps the transcript if(!curChat||curChat.committed)return;curChat.committed=1; (shared.chats||(shared.chats={}))[c.id]={done:1,sent:curChat.sent,msgs:curChat.msgs,ch:CH.id,t:Date.now()};saveShared(); curChat.later.forEach(fn=>{try{fn()}catch(e){console.error(e)}});curChat.later=[]; } function chatFb(t){const el=$('cfb');if(!el)return;if(!t){el.hidden=true;el.innerHTML='';return}const e=lineEn(t); el.innerHTML=`${glossHTML(t)}`+(e?`${String(e).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]))}`:'');el.hidden=false} // a wrong reply's hint, with its English behind ? like any line function renderChatChoose(s){ const box=$('choices');box.hidden=false; box.innerHTML=s.chatChoose.map(([label],i)=>``).join(''); box.querySelectorAll('.choice').forEach(b=>b.addEventListener('click',e=>{e.stopPropagation();const [label,fn]=s.chatChoose[+b.dataset.i]; box.hidden=true;box.innerHTML='';sfx('ok');if(fn)curChat.later.push(fn);curChat.sent=label; dlg.next='advance';show({chatMsg:{from:'me',text:label,id:s.chatReply+':'+b.dataset.i,time:s.time,now:s.now},fb:1,...(s.chatCommit?{chatCommit:s.chatCommit,set:s.chatSet,award:s.chatAward}:{})})})); sel=-1;choicesAt=performance.now();markSel(); } /* ---------- the postcard (opt-in; 소리 엽서): cards the player makes across the chapters, kept in the shared record ---------- GAME.postcard (the game's shared.js): [{id, ch, place, def, v:{a:{pic, caption, lines:[[who, text]…]}, b:{…}}}] in story order. Optional variant fields: chosen:true = featured, chosen:false (or bonus:true) = small bonus, after the full cards in both the journal and slides. Missing fields keep the original full card. label prints above it; bonusCaption prints below a small card. footer is a separate printed credit, never a voiced transcript line; footerLabel optionally names that row. All printed text uses glossHTML and lineEn. snapshot:1 freezes pic/caption/lines/footer, presentation and voice at recording time. voice is an authored provenance tag (not permission). card:{id,v,provenance:{…}} optionally stores additional JSON provenance, e.g. the earlier consent version used. Records retain the existing {v,ch,t,lines?,voice?,chosen?} shape; old records remain readable. A step card:{id, v} puts version v of that card on the postcard (a toast says so); the choice lives in the shared record, so a later chapter's slideshow and the 일지 see it. In the 일지 (#pcards, when the shell has it) the cards up to this chapter show: one not made (the chapter skipped, entered directly) shows its default version, marked 기본, without counting anything as seen. A step slides:1 plays the postcard on the phone, a card per A (B goes on too; after the last card B puts it away). slides:{kind:'main'|'bonus',at:0,one:true} optionally filters, starts at an index and shows only one card; authored choices can pause between panels without assembling slideAll. With no kind it includes both, main cards first. 처음부터 in a chapter takes its cards and chats out of the shared record. */ const PC=()=>G.postcard||globalThis.POSTCARD||[]; // GAME.postcard, or a POSTCARD the game's shared.js sets const pcIdx=id=>CHAPTERS.findIndex(c=>c.id===id); const PC_FIELDS=['pic','caption','lines','footer','footerLabel','chosen','bonus','label','bonusCaption','voice']; const cardVariant=x=>{const v={...x.e.v[x.k]};for(const k of PC_FIELDS)if(x.record&&Object.hasOwn(x.record,k))v[k]=x.record[k];return v}; const cardBonus=x=>{const v=cardVariant(x);return v.chosen===false||(v.chosen!==true&&!!v.bonus)}; function pcCards(){ // the cards up to this chapter: [{e, v (the version shown), made}] const cur=pcIdx(CH.id),got=shared.postcard||{}; const cs=PC().filter(e=>{const i=pcIdx(e.ch);return i>=0&&(i{const m=got[e.id];return {e,k:m?m.v:e.def,made:!!m,record:m}}).filter(x=>x.e.v[x.k]); return [...cs.filter(x=>!cardBonus(x)),...cs.filter(cardBonus)]; // this chapter's cards once made; earlier chapters' defaults } function putCard(c){const e=PC().find(x=>x.id===c.id);if(!e||!e.v[c.v])return;const v=e.v[c.v],r={v:c.v,ch:CH.id,t:Date.now()}; if(v.snapshot)for(const k of PC_FIELDS)if(Object.hasOwn(v,k))r[k]=JSON.parse(JSON.stringify(v[k])); if(c.provenance)r.provenance=JSON.parse(JSON.stringify(c.provenance)); (shared.postcard||(shared.postcard={}))[c.id]=r;saveShared(); sfx('item');setTimeout(()=>toast(T('엽서에 추가')+': '+plain(e.v[c.v].caption||e.place||'')),200)} function forgetShared(){let n=0;for(const k of ['postcard','chats'])for(const [id,r] of Object.entries(shared[k]||{}))if(r.ch===CH.id){delete shared[k][id];n++}if(n)saveShared()} function cardHTML(x,i,n){ const esc=t=>String(t).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c])),V=cardVariant(x),bonus=cardBonus(x); const en=t=>{const e=lineEn(t);return e?`${esc(e)}`:''}; const label=t=>`
${glossHTML(t)}${en(t)}
`; return `
${V.label?label(V.label):''}
${esc(T(x.e.place||''))}${n?`${i+1}/${n}`:''}${x.made?'':`${T('기본')}`}
` +(V.pic?``:'') +`
${glossHTML(V.caption||'')}${en(V.caption||'')}
` +(V.lines||[]).map(([w,t])=>`
${esc(T(w))}${glossHTML(t)}${en(t)}
`).join('') +(V.footer?`
${V.footerLabel?`${esc(T(V.footerLabel))}`:''}${glossHTML(V.footer)}${en(V.footer)}
`:'') +(bonus&&V.bonusCaption?label(V.bonusCaption):'')+`
`; } function drawCardPics(root){root.querySelectorAll('canvas.pcpic').forEach(cv=>{const P=(C.PICS||G.pics||{})[cv.dataset.pic];if(P)try{P(cv)}catch(e){}})} // a reply option's words, each held for help; an authored {form|key} pin keeps its sense (data-k → showGloss) const choiceWords=t=>t.split(/(\{[^|}]+\|[^}]+\})/).map(x=>{const m=x.match(/^\{([^|}]+)\|([^}]+)\}$/),e=y=>y.replace(/&/g,'&').replace(/${e(m[1])}`:e(x).replace(/[가-힣]+/g,w=>`${w}`)}).join(''); // word help inside the 일지 (postcards, bag descriptions): pins and words, shown above the journal const panelWordTap=e=>{const gl=e.target.closest('.gl'),w=e.target.closest('.w');if(!gl&&!w)return false;e.stopPropagation();document.body.classList.add('talkopen');gl?showGloss(gl.dataset.k,gl):showWord(w.dataset.w||w.textContent,w);return true}; function renderPostcards(){const el=$('pcards');if(!el)return;const cs=pcCards(); const main=cs.filter(x=>!cardBonus(x)),bonus=cs.filter(cardBonus); el.innerHTML=cs.length?main.map(x=>cardHTML(x)).join('')+(bonus.length?`
${bonus.map(x=>cardHTML(x)).join('')}
`:''):`

${T('아직 없어요.')}

`;drawCardPics(el); el.onclick=e=>{const q=e.target.closest('.tq');if(q){e.stopPropagation();const t=q.nextElementSibling;if(t)t.hidden=!t.hidden;lineQOpened(q,t);return}panelWordTap(e)}} let curSlides=null; function slideSteps(opts={}){const cs=pcCards().filter(x=>opts.kind==='bonus'?cardBonus(x):opts.kind==='main'?!cardBonus(x):true),at=opts.at||0; return cs.map((x,i)=>({slide:i,slideAll:cs})).slice(at,opts.one?at+1:undefined).map((s,i)=>({...s,...(i===0?{slideOpen:1}:{})}))} function showSlide(s){ if(!$('phonePanel'))return; if(s.slideOpen||!curSlides){closePhone();curSlides={n:s.slideAll.length};curPhone={slides:1};$('phonePanel').hidden=false;phoneOpen=true;document.body.classList.add('chatting')} $('pscr').innerHTML=`
${glossHTML(T('소리 엽서'))}▶
${cardHTML(s.slideAll[s.slide],s.slide,s.slideAll.length)}
`; drawCardPics($('pscr')); } const CULTURE=globalThis.CULTURE_NOTES||{}; // a game's notes (its own file sets globalThis.CULTURE_NOTES) let cultureSeen=[];try{cultureSeen=JSON.parse(store.get(KEY('culture'))||'[]')}catch(e){} /* A new note shows on the screen for a few seconds as a tappable chip (#noteChip, made here when the shell has a notes section), then fades: tapping it opens the 일지 on that note. Notes seen before this existed count as read. */ let cultureRead;try{cultureRead=JSON.parse(store.get(KEY('cultureRead'))||'null')}catch(e){}if(!Array.isArray(cultureRead))cultureRead=cultureSeen.slice(); const GRAMMAR=globalThis.GRAMMAR_NOTES||{}; // a game's 문법 노트 (its own file sets globalThis.GRAMMAR_NOTES) let grammarSeen=[],grammarRead=[];try{grammarSeen=JSON.parse(store.get(KEY('grammar'))||'[]')}catch(e){}try{grammarRead=JSON.parse(store.get(KEY('grammarRead'))||'[]')}catch(e){} if(!Array.isArray(grammarSeen))grammarSeen=[];if(!Array.isArray(grammarRead))grammarRead=[]; /* the two kinds of note: the chip's name for it, its data, seen/read lists (saved under KEY(key) and KEY(key+'Read')), journal list and card */ const NOTE_KINDS={culture:{name:'문화 노트',data:CULTURE,seen:cultureSeen,read:cultureRead,key:'culture',list:'notes',card:'noteCard'}, grammar:{name:'문법 노트',data:GRAMMAR,seen:grammarSeen,read:grammarRead,key:'grammar',list:'gnotes',card:'gnoteCard'}}; if(!Object.keys(GRAMMAR).length)for(const id of ['gnotesH','gnotes','gnoteCard'])$(id)?.remove(); // a game without 문법 노트 shows no heading for them {const st=document.createElement('style');st.textContent='body:has(#panel:not([hidden])) #noteChip{display:none!important}';document.head.appendChild(st)} // the chip stays out of sight while the 일지 is open (it sat on top of the notes); its own state is unchanged /* starting a chapter over forgets the notes it unlocks (found in its source: culture:'id' / grammar:'id'), so they come back as you replay it; notes from other chapters stay */ function forgetNotes(){const src=String(CH.make),ids=new Set([...src.matchAll(/\b(culture|grammar)\s*:\s*['"]([^'"]+)['"]/g)].map(m=>m[1]+':'+m[2])); for(const [K,N] of Object.entries(NOTE_KINDS)){for(const L of [N.seen,N.read])for(let i=L.length-1;i>=0;i--)if(ids.has(K+':'+L[i]))L.splice(i,1); store.set(KEY(N.key),JSON.stringify(N.seen));store.set(KEY(N.key+'Read'),JSON.stringify(N.read))} renderNotes();noteChip()} let noteLast='culture'; // the kind unlocked last: the chip shows its newest unread note first, then the rest, newest first const unreadNotes=K=>{const N=NOTE_KINDS[K];return N.seen.filter(k=>N.data[k]&&!N.read.includes(k))}; /* fresh: a note was just unlocked — the chip shows it, then fades once it has been on screen CHIP_MS (time under a talk box, where it's hidden, doesn't count); the note stays unread in the 일지. Without fresh the chip only updates or hides: no old note pops back up. */ const CHIP_MS=6000;let chipOn=0,chipTick=null; function noteChip(fresh){const el=$('noteChip');if(!el)return;const K=[noteLast,...Object.keys(NOTE_KINDS)].find(K=>unreadNotes(K).length); if(!K||!fresh&&el.hidden){el.hidden=true;return} const N=NOTE_KINDS[K],un=unreadNotes(K),k=un[un.length-1];el.dataset.kind=K;el.dataset.k=k;el.innerHTML=`📖 ${N.name} · ${N.data[k].t}›`;el.hidden=false; if(!fresh)return;el.style.transition='';el.style.opacity='';chipOn=0;clearInterval(chipTick); chipTick=setInterval(()=>{if(el.hidden){clearInterval(chipTick);return}if(getComputedStyle(el).display!=='none')chipOn+=250; if(chipOn>=CHIP_MS){clearInterval(chipTick);el.style.transition='opacity .8s';el.style.opacity='0';setTimeout(()=>{el.hidden=true;el.style.transition='';el.style.opacity=''},800)}},250)} function readNote(K,k){const N=NOTE_KINDS[K];if(!N.read.includes(k)){N.read.push(k);store.set(KEY(N.key+'Read'),JSON.stringify(N.read))}noteChip()} function unlockNote(K,k){const N=NOTE_KINDS[K]; if(!N.data[k]||N.seen.includes(k))return;N.seen.push(k);store.set(KEY(N.key),JSON.stringify(N.seen));noteLast=K; setTimeout(()=>{sfx('badge');noteChip(true)},350); } const unlockCulture=k=>unlockNote('culture',k),unlockGrammar=k=>unlockNote('grammar',k); function renderNotes(){ for(const N of Object.values(NOTE_KINDS)){if(!$(N.list))continue;const ks=N.seen.filter(k=>N.data[k]); $(N.list).innerHTML=ks.length?ks.map(k=>``).join(''):'

'+T('아직 없어요.')+'

'; $(N.card).hidden=true} } /* a note in its card: the title and ? (English for every line), its lines (each with its source numbers), then a 문법 노트's examples (예문), then the note's sources (출처) as numbered links, the same markup for both kinds; one card is open at a time */ function showNote(K,k){ const N=NOTE_KINDS[K],n=N&&N.data[k],c=n&&$(N.card);if(!c)return;let en=false; for(const M of Object.values(NOTE_KINDS))if(M!==N&&$(M.card))$(M.card).hidden=true; const ko=t=>`${glossHTML(t)}`,eng=e=>en?`${e}`:''; const draw=()=>{c.innerHTML=`
${n.t}
` +`
    ${n.lines.map(([t,e,s])=>`
  1. ${ko(t)}${s?`${s.join(',')}`:''}${eng(e)}
  2. `).join('')}
` +(n.ex&&n.ex.length?`
예문
    ${n.ex.map(([t,e])=>`
  • ${ko(t)}${eng(e)}
  • `).join('')}
`:'') +(n.src?`
출처${n.src.map(([t,u],i)=>`${i+1}. ${t}`).join('')}
`:''); c.querySelector('.enb').addEventListener('click',e=>{e.stopPropagation();en=!en;draw();if(en)noteLineQ(T(N.name)+' · '+n.t,n.lines.map(l=>l[1]).join(' '))})}; draw();c.hidden=false;c.scrollIntoView({block:'nearest'});readNote(K,k); } if(Object.values(NOTE_KINDS).some(N=>$(N.list))){ for(const [K,N] of Object.entries(NOTE_KINDS))if($(N.list)){ $(N.list).addEventListener('click',e=>{const b=e.target.closest('.nb');if(b)showNote(K,b.dataset.k)}); $(N.card).addEventListener('click',e=>{const w=e.target.closest('.w');if(w){e.stopPropagation();document.body.classList.add('talkopen');showWord(w.dataset.w||w.textContent,w)}})} // word help above the journal {const b=document.createElement('button');b.id='noteChip';b.className='notechip';b.type='button';b.hidden=true;$('toast').after(b); b.addEventListener('click',e=>{e.stopPropagation();openPanel();showNote(b.dataset.kind,b.dataset.k)});noteChip()} for(const id of ['closePanel','panel'])$(id).addEventListener('click',e=>{if(id==='closePanel'||e.target.id==='panel')document.body.classList.remove('talkopen')}); } /* a room's greeting: zone greet:'npcId' (or a function returning one, or null) — whoever is there talks to you the moment you walk in, before you can move (찬 at the gym door), so a scene can't be met in the wrong order. Also on loading a save in that room, so a reload in the middle of it starts it over (its flag is only set on its last line). */ function greet(){ const g=typeof Z.greet==='function'?Z.greet():Z.greet,n=g&&C.NPC[g];if(!n||!NPCS.includes(n)||(n.hide&&n.hide())||dlg)return false; const [nx,ny]=npcPos(n),dx=nx-player.x,dy=ny-player.y;held=null; player.dir=Math.abs(dx)>=Math.abs(dy)&&dx?(dx>0?'right':'left'):(dy>0?'down':'up');state.dir=player.dir; // look at them talkWith(n);return true} function openDialog(name,steps,opts={}){ steps=(steps||[]).filter(s=>s&&(!s.when||s.when())); if(!steps.length)return; // nothing to say: never an empty box talkN++;dlg={name,steps:steps.map(s=>({...s})),i:0,cur:null,next:null,missed:new Set(),npc:opts.npc||null,review:!!opts.review,intro:!!opts.intro,snap:opts.snap||JSON.stringify(state)}; $('tag').hidden=!opts.review;$('dlg').hidden=false;$('zone').classList.add('dim');show(dlg.steps[0]);placeBox(talkRows()); // the room label never shows through a box at the top } /* a black line can show a small scene instead of plain black (a lift ride, a launch): step scene:'name' plays the chapter's SCENES[name] (or the game's, GAME.scenes) on the black, in the game's own pixels, until the black lifts (scene:null stops it sooner). A scene is {ms,draw(g,p,t,band)}: p runs 0→1 over ms (the scene eases it), t is ms since it began, band is the [top,bottom] the dialogue box leaves free — keep the subject there. Reduced motion: its last frame, still. */ let sceneRun=null; function playScene(name){ const fade=$('fade'),S=name&&((C.SCENES||{})[name]||(G.scenes||{})[name]);let c=fade.querySelector('canvas');sceneRun=null; if(!S){if(c)c.hidden=true;return} if(!c){c=document.createElement('canvas');c.width=cv.width;c.height=cv.height;c.style.cssText='position:absolute;inset:0;width:100%;height:100%;image-rendering:pixelated';fade.appendChild(c)} c.hidden=false;const g=c.getContext('2d'),ms=S.ms||6000,still=matchMedia('(prefers-reduced-motion: reduce)').matches,me=sceneRun={t0:performance.now(),n:0}; const frame=now=>{if(sceneRun!==me)return;const t=still?ms:now-me.t0;g.clearRect(0,0,c.width,c.height);S.draw(g,Math.min(1,t/ms),t,dlg?freeBand():[0,c.height]); if(!still||me.n++<2)requestAnimationFrame(frame)}; // still: a frame or two more, once the box has its place frame(performance.now()); } function show(s){ readEnd(); // the line before this one: read long enough, its words count as seen if(!s||!dlg){if(dlg)closeDialog();return} // a step that isn't there closes the talk instead of leaving a blank box if(s&&(s.set||s.award||s.give||s.take||s.go)&&dlg)dlg.moved=1; // a story beat (spaced review counts them) if(s&&s.slides&&s.slide===undefined){const more=slideSteps(s.slides);dlg.steps.splice(dlg.i,1,...more);if(!more.length||dlg.i>=dlg.steps.length){closeDialog();return}return show(dlg.steps[dlg.i])} // the postcard on the phone, a card per step if(s&&s.chat&&!s.chatMsg){const more=chatSteps(s.chat);dlg.steps.splice(dlg.i,1,...more);if(!more.length||dlg.i>=dlg.steps.length){closeDialog();return}return show(dlg.steps[dlg.i])} // a phone chat: its messages, reply and commit as steps if(s&&s.expand){const more=says(s.expand()||[]);dlg.steps.splice(dlg.i,1,...more);if(dlg.i>=dlg.steps.length){closeDialog();return}return show(dlg.steps[dlg.i])} // expand:()=>steps, made when it's reached (class time picks words you have by then) dlg.cur=s;hideGloss(); lastLines.push(((s.who||dlg.name||'')+': '+plain(s.say||s.ask||'')).slice(0,300));if(lastLines.length>3)lastLines.shift(); if(s.set){s.set();save()} if(dlg.wrapBlack&&!s.wrapStart&&!s.review&&!s.fb&&s.who!==LOGNAME&&!('black' in s)){$('fade').classList.remove('on');dlg.black=false;dlg.wrapBlack=false;playScene(null)} // the end round's black lifts at the first ordinary line after it (fb: the feedback after an answer is still the question) if(s.wrapStart)dlg.wrapBlack=true; if('black' in s){$('fade').classList.toggle('on',!!s.black);dlg.black=!!s.black;if(!s.black)playScene(null)} // black:1 — the line plays over a black screen (a time cut); black:0 or the end of the talk brings the room back if('scene' in s)playScene(s.scene); // with black:1: a small scene plays on the black (playScene) if(s.walk||s.leave)queueWalks(s); if(s.move)moveNpcs(s); if(s.phone)openPhone(s.phone); if(s.card)putCard(s.card); if(s.chatOpen){closePhone();openChat(s.chatOpen,s.chatAll)} else if(curChat&&!s.chatMsg&&!s.chatReply&&!s.chatFb&&!s.chatAll){closePhone()} else if(curSlides&&s.slide===undefined){closePhone()} if(s.slide!==undefined){showSlide(s);clearInterval(typing?.id);typing=null;$('more').hidden=true;$('choices').hidden=true;if(!dlg.questHold)updateQuest();return} // the talk goes on past the exchange: the phone goes away if(s.culture)unlockCulture(s.culture); if(s.grammar)unlockGrammar(s.grammar); if(s.sit)sitDown(s.sit); [].concat(s.turn||[]).forEach(o=>{const n=C.NPC[o.npc];if(n){n.dir=o.dir;n.turnAt=performance.now()+60000}}); if('cam' in s){camT=s.cam||null;if(camT){const cyc=Math.max(0,Math.min(camT[1]*TS+8-VH*TS/2,MH*TS-VH*TS));placeBox([camT[1]],cyc)}else placeBox(talkRows())} if(s.go){const [z,x,y,d]=s.go;loadZone(z,x,y,d||'down');talkCy=null;talkExtra=0;save();placeBox(talkRows())} // a scene that moves you ("다음 날 아침, 학교") if(s.sfx||/딩동댕동/.test(s.say||''))sfx(s.sfx||'bell'); /* a step can play a sound; the school bell rings on its own */ if(s.give){state.items.push(s.give);save();sfx('item');setTimeout(()=>toast(T('받았어요: ')+s.give),200)} if(s.take){state.items=state.items.filter(i=>!s.take.includes(i));save()} if(s.award)award(s.award); if(s.listen)s=prepListen(s); if(curChat&&(s.chatMsg||s.chatReply||s.chatFb||s.chatAll)){ // inside a chat: bubbles and the reply strip, no dialogue box clearInterval(typing?.id);typing=null;$('more').hidden=true; if(s.chatFb!==undefined)chatFb(s.chatFb);else chatFb(null); if(s.chatMsg){chatPush(s.chatMsg);if(s.chatMsg.from==='me')curChat.sent=s.chatMsg.text;if(readOn&&s.chatMsg.from!=='me')speak(s.chatMsg.text||'')} const L=$('clist'),pin=L&&L.scrollHeight-L.scrollTop-L.clientHeight<48; // at the newest message: stay there when the replies take room const ask=$('cask');if(ask){const q=(s.chatChoose||s.opts)&&s.ask?s.ask:'';ask.innerHTML=q?glossHTML(q):'';ask.hidden=!q} // the reply's situation, above the replies if(s.chatChoose){$('choices').innerHTML='';renderChatChoose(s)}else if(s.chatReply&&s.opts){$('choices').innerHTML='';renderChoices(s)}else{$('choices').hidden=true;$('choices').innerHTML=''} if(pin)requestAnimationFrame(()=>{L.scrollTop=L.scrollHeight}); if(s.chatCommit&&!s.chatReply)chatCommitNow(s.chatCommit); if(!dlg.questHold)updateQuest();return} $('who').textContent=T(s.who||dlg.name); // '나' is the player in every game; GAME.ui names them in its language setEn(s.ask||s.build||s.listen?null:lineEn(s.enKey||s.say||'')); // an open question has no English (it would give the answer away); answered, its whole line has $('choices').hidden=true;$('choices').innerHTML='';$('build').hidden=true;$('more').hidden=true;writeKbOff(); const text=s.say||s.ask||''; // a word-order question needs no instruction: the tiles explain themselves if(!s.build&&!s.ask)logTalk(s.who||dlg.name,text,s.enKey); // a question is logged once, as the line it becomes when answered typeText(text,()=>{markOk(s.hl);if(s.choose)renderPick(s);else if(s.ask)renderAsk(s);else if(s.build)renderBuild(s);else $('more').hidden=false}); setPortrait(s,text); const lhide=RP&&RP.mode==='listen'&&!s.ask&&!s.build&&!s.choose&&canSpeak();$('txt').classList.toggle('lhide',!!lhide);if(lhide)rpCss(); // 듣기: heard first, read on a tap if((readOn||lhide)&&!s.listenOnly)speak(s.listen?'':text); if(s.listen)setTimeout(()=>speak(s.listenLine||s.listen),readOn?1200:150); if(s.take&&!s.set)dlg.questHold=1;else if(s.set)dlg.questHold=0; // handing an item over: keep the old 목표 until the scene moves the story on (or ends) if(!dlg.questHold)updateQuest(); } function prepListen(s){ const w=s.listen;const pool=(C.CONFUSE[w]||[]).slice(0,2); while(pool.length<2){const o=C.WORDS[Math.random()*C.WORDS.length|0];if(o!==w&&!pool.includes(o))pool.push(o)} const again=dlg.npc&&dlg.npc.banmal?`다시 들어 봐. "${w}".`:`다시 들어 보세요. "${w}".`; const out=s.listenLine?{...s,ask:s.ask.replace('___','🔊'),done:s.listenLine,own:1,w,opts:[[w,1],...pool.map(p=>[p,0,again])],listenOnly:1} // someone's review line said aloud: the word is a sound in the text, and the whole line is the answer :{...s,ask:T('잘 들어 보세요. 무슨 단어예요?'),w,opts:[[w,1],...pool.map(p=>[p,0,`"${w}"였어요. 다시 들어 보세요.`])],listenOnly:1}; dlg.cur=out;return out; } /* Every Korean word in a line is tappable: marked glosses ({shown|key}) open the chapter DICT entry, all other words open the game's dictionary (LEX, built from the dialogue by lexicon/extract.py). */ function glossHTML(t){ const esc=x=>x.replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c])); const words=x=>G.wordsHTML?G.wordsHTML(x,esc):esc(x).replace(/[가-힣]+|[ㄱ-ㅎㅏ-ㅣ]{2,}/g,w=>`${w}`); // GAME.wordsHTML: the game's own word spans (data-w: the word to look up) let out='',last=0;const re=/\{([^|}]+)\|([^}]+)\}/g;let m; while((m=re.exec(t))){out+=words(t.slice(last,m.index))+`${esc(m[1])}`;last=re.lastIndex} return out+words(t.slice(last)); } function lexLookup(w){ // word as written → [[lemma,{k,e}],…]; falls back to the longest known prefix (우주선이 → 우주선) const L=window.LEX||{map:{},defs:{}},hit=l=>C.DICT[l]?[l,C.DICT[l]]:carryDict(l)?[l,carryDict(l)]:L.defs[l]?[l,L.defs[l]]:null; let ls=L.map[w]; if(!ls)for(let n=w.length;n>0&&!ls;n--){const pre=w.slice(0,n); // longest known prefix, also as a verb/adjective stem (강해서 → 강하다) const tries=[pre,pre+'다',/[해했]$/.test(pre)?pre.slice(0,-1)+'하다':null].filter(Boolean); if(L.map[pre])ls=L.map[pre];else{const t=tries.find(x=>hit(x));if(t)ls=[t]}} return (ls||[]).map(hit).filter(Boolean); } function popGloss(rows){ // rows: [[headword,{k,e}],…] — Korean first; English only behind the ? button. Stays until ×, A, B or the next line if(!rows.length){hideGloss();toast(T('사전에 없는 말이에요.'));return} const el=$('gloss'); el.innerHTML=rows.map(([h,d])=>`
${h}${d.r&&d.r!==h?`${d.r}`:''}${d.k}${d.reg?`${T('말투')}: ${d.reg}`:''}${d.note?`${T('참고')}: ${d.note}`:''}
`).join('')+''; el.hidden=false;const q=el.querySelector('.q');if(hints.glossQ!==1){q.classList.add('hintq');hintSeen('glossQ',3)} q.addEventListener('click',e=>{e.stopPropagation();hintDone('glossQ');q.classList.remove('hintq');el.querySelectorAll('.en').forEach(x=>x.hidden=!x.hidden)}); } /* English for a whole line, the last aid after tapping words: a game's src/lines-en.json (built in as window.LINES_EN, Korean line as written, without gloss markup → close English). The ? sits by the speaker button only when the line has English; the English shows under the Korean until the next line. Lines made at run time (names, counts) have none. */ const lineEn=t=>{const L=window.LINES_EN;return L&&t?L[plain(t)]||null:null}; function enUI(){let b=$('enBtn');if(b)return b; b=document.createElement('button');b.id='enBtn';b.className='spk enq';b.type='button';b.textContent='?';b.setAttribute('aria-label',T('영어로 보기'));$('spk').before(b); const d=document.createElement('div');d.id='txtEn';d.className='txt-en';d.hidden=true;$('txt').after(d); const a=document.createElement('button');a.id='askBtn';a.className='txt-ask';a.type='button';a.textContent=T('물어보기');a.hidden=true;d.after(a); // 물어보기: this line, explained by an AI tutor a.addEventListener('click',e=>{e.stopPropagation();a.blur();shareText(askText())}); b.addEventListener('click',e=>{e.stopPropagation();hintDone('lineQ');b.classList.remove('hintq');d.hidden=!d.hidden;$('askBtn').hidden=d.hidden;b.classList.toggle('on',!d.hidden);b.blur();if(!d.hidden)noteLineQ(shownText($('txt')),d.textContent,$('who').textContent)}); // blur: A/Enter go on talking, not toggle it again const st=document.createElement('style');st.textContent='.spk.enq{margin-left:auto;font:700 .9rem/1 var(--body,sans-serif)}.spk.enq+.spk{margin-left:0}' +'.txt-en{font-family:var(--body,sans-serif);font-size:.86rem;line-height:1.4;opacity:.8;margin-top:6px;word-break:normal}' +'.txt-ask{display:block;margin:4px 0 0 auto;padding:1px 8px;font:700 .72rem/1.5 var(--body,sans-serif);color:inherit;background:none;border:1px solid currentColor;border-radius:6px;opacity:.6;cursor:pointer}' +'.tl .tq{margin-left:6px;padding:0 5px;font:700 .72rem/1.4 var(--body,sans-serif);color:inherit;background:none;border:1px solid currentColor;border-radius:4px;opacity:.55;cursor:pointer;vertical-align:1px}' +'.tl .ten{display:block;font-weight:400;font-size:.84rem;opacity:.75;margin-top:2px;word-break:normal}'; document.head.appendChild(st);return b} function setEn(en){if(!window.LINES_EN)return;const b=enUI(),d=$('txtEn');b.hidden=!en;b.classList.toggle('on',enAll&&!!en);d.hidden=!(enAll&&en);d.textContent=en||'';$('askBtn').hidden=d.hidden; const h=!!en&&!enAll&&hints.word===1&&hints.lineQ!==1;b.classList.toggle('hintq',h);if(h)hintSeen('lineQ',12)} // after the word hint: the line's ? pulses /* a right answer: the words that filled the blank (or the whole line built from word tiles) take the answer color, and an underline under them fades away (about a second; none with reduced motion). Never moves or covers anything: the line is the feedback. */ function markOk(hl){ if(!hl||!hl.a)return;const el=$('txt'),t=el.textContent,a=hl.a;let k=-1; if(hl.pre){const j=t.indexOf(hl.pre);if(j>=0&&t.substr(j+hl.pre.length,a.length)===a)k=j+hl.pre.length} if(k<0)k=t.lastIndexOf(a);if(k<0)return; okCss();const end=k+a.length,tw=document.createTreeWalker(el,NodeFilter.SHOW_TEXT),parts=[];let pos=0; for(let n;(n=tw.nextNode());){const s0=pos,e0=pos+n.length;pos=e0;if(e0<=k||s0>=end)continue;parts.push([n,Math.max(k,s0)-s0,Math.min(end,e0)-s0])} for(const [n,a0,b0] of parts){let m=n;if(a0>0)m=m.splitText(a0);if(b0-a0'+p.replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]))+'';let i=0; const reduce=matchMedia('(prefers-reduced-motion: reduce)').matches; typing={id:null,finished:false}; const fin=()=>{clearInterval(typing.id);el.innerHTML=glossHTML(text);typing.finished=true;hintWord();readStart();done()}; typing.fin=fin; if(reduce||!p)return fin(); // nothing to type (a word-order question has no line of its own): its tiles come at once, never after a blank box and a tap const seg=(()=>{try{return [...new Intl.Segmenter('ko',{granularity:'grapheme'}).segment(p)].map(x=>x.segment)}catch(e){return Array.from(p)}})(); // whole characters: never half an emoji (it shows as ? for a tick) const esc=x=>x.replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c])); // the whole line is laid out from the start: words never jump down a line const t0=performance.now(); // by elapsed time, not ticks: a phone that slows timers (battery saver) shows more per tick, never a blank box typing.id=setInterval(()=>{const k=Math.min(seg.length,1+Math.floor((performance.now()-t0)/26));if(k===i)return;i=k;el.innerHTML=esc(seg.slice(0,i).join(''))+''+esc(seg.slice(i).join(''))+'';if(i>=seg.length)fin()},26); } let allDicts=null; const otherDict=k=>{if(!allDicts){allDicts={};for(const ch of CHAPTERS)if(ch!==CH)try{Object.assign(allDicts,ch.make().DICT||{})}catch(e){}}return allDicts[k]}; function showGloss(k,el){const d=C.DICT[k]||otherDict(k),rows=d?[[k,d]]:lexLookup(k);if(rows.length){noteTap(rows,el,el&&el.textContent);popGloss(rows)}} // {form|lemma}: this chapter's entry, else another chapter's (a review asked out of its chapter), else the lexicon function showWord(w,el){const rows=lexLookup(w);noteTap(rows,el,w);popGloss(rows);lastWord=(w+(rows.length?' → '+rows.map(([h,d])=>h+': '+d.k).join(' / '):' (사전에 없음)')).slice(0,400)} /* ---------- 찾아본 말: every tap that finds a definition — how many times, and when last (all chapters, one list) ---------- */ const TAPS_KEY=KEY('taps');let taps={},tapSort='t'; try{taps=JSON.parse(store.get(TAPS_KEY)||'{}')||{}}catch(e){taps={}} const tapRows=o=>Object.entries(o).sort((a,b)=>tapSort==='n'?(b[1].n-a[1].n||b[1].t-a[1].t):b[1].t-a[1].t); /* ---------- 영어로 본 문장: every ? that opens a line's English (dialogue box, talk log, phone, postcards, notes): the line, how many times, when last, who said it and in which chapter (all chapters, one list). The 사전 panel lists them under 문장, and 복사 adds them. ---------- */ const LINEQ_KEY=KEY('lineQ');let lineQs={},tapLines=false; try{lineQs=JSON.parse(store.get(LINEQ_KEY)||'{}')||{}}catch(e){lineQs={}} function noteLineQ(t,e,who){ t=String(t||'').replace(/\s+/g,' ').trim();if(!t)return;const r=lineQs[t]||(lineQs[t]={n:0,t:0});r.n++;r.t=Date.now(); if(e){e=String(e).replace(/\s+/g,' ').trim();r.e=e.length>400?e.slice(0,399)+'…':e}if(who)r.w=String(who).trim();if(CH)r.ch=CH.n+' '+CH.title; const ks=Object.keys(lineQs);if(ks.length>500)ks.sort((a,b)=>lineQs[a].t-lineQs[b].t).slice(0,ks.length-500).forEach(k=>delete lineQs[k]); // the oldest go: every game on the site shares one storage store.set(LINEQ_KEY,JSON.stringify(lineQs))} const shownText=el=>{if(!el)return '';const x=el.cloneNode(true);x.querySelectorAll('.tq,.ten,rt,rp').forEach(n=>n.remove());return x.textContent}; // a line as read: no ? or English, no furigana function lineQOpened(q,ten){ // a ? in a list (talk log, phone, chat, postcards) just showed its English: note its line and who said it if(!ten||ten.hidden)return;const c=q.closest('.tt,.pc,.ppost,.pphoto,.cb,#cfb,.pccap,.pcl');if(!c)return; const w=c.closest('.tl')?.querySelector('.tw')||c.querySelector('.pn,.cn,.pcw'); noteLineQ(shownText(c.matches('.txt')?c:c.querySelector('.txt')),ten.textContent,c.closest('.cm.me')?T('나'):w?shownText(w):c.querySelector('.pmeta')?.textContent.split(' · ')[0])} /* ---------- first-time hints, no instruction text: tap a word · the popup's ? (English) · the line's ? (the line in English) ---------- One record for every game on this site, not per game: browsers keep saved data per site, and all the walk games live on stan-stani.github.io, so a player who learned to tap words in one game isn't shown it again in another. Each hint ends for good once the player does the thing (or after a few showings, so a player who never wants it isn't nagged). The tile hint uses it too. */ const HINTS_KEY='walk-hints';let hints={};try{hints=JSON.parse(store.get(HINTS_KEY)||'{}')||{}}catch(e){hints={}} function hintDone(k){if(hints[k]===1)return;hints[k]=1;store.set(HINTS_KEY,JSON.stringify(hints))} function hintSeen(k,max){hints[k+'N']=(hints[k+'N']||0)+1;if(hints[k+'N']>=max)hintDone(k);else store.set(HINTS_KEY,JSON.stringify(hints))} if(Object.keys(taps).length)hintDone('word'); // this game's 찾아본 말 has taps already: they know {const st=document.createElement('style');st.textContent='@keyframes wHint{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}' +'.txt .w.hintw{display:inline-block;animation:wHint 1s ease-in-out infinite;text-decoration:underline dotted;text-underline-offset:3px}' +'@keyframes qHint{0%,100%{box-shadow:0 0 0 0 rgba(242,180,80,0)}50%{box-shadow:0 0 0 4px rgba(242,180,80,.8)}}.hintq{animation:qHint 1.1s ease-in-out infinite}'; document.head.appendChild(st)} function unhintWord(){clearTimeout(hintWord.t);document.querySelectorAll('.hintw').forEach(e=>e.classList.remove('hintw'))} function hintWord(){ // a line has been on the screen 4 s and no word has ever been tapped: its longest word bobs unhintWord();if(hints.word===1)return;const cur=dlg&&dlg.cur; hintWord.t=setTimeout(()=>{if(!dlg||dlg.cur!==cur||hints.word===1||!$('gloss').hidden||phoneOpen)return; const ws=[...$('txt').querySelectorAll('.w')],w=ws.filter(e=>e.textContent.length>=2).sort((a,b)=>b.textContent.length-a.textContent.length)[0]||ws[0]; if(w){w.classList.add('hintw');hintSeen('word',6)}},4000)} function noteTap(rows,el,sw){hintDone('word');unhintWord();const [h,d]=rows[0]||[];if(!h)return;tapSeen(h);const r=taps[h]||(taps[h]={n:0,t:0});r.n++;r.t=Date.now();r.k=d.k;r.e=d.e;if(d.r&&d.r!==h)r.r=d.r; const line=el&&el.closest&&el.closest('.txt')?shownText(el.closest('.txt')).replace(/\s+/g,' ').trim():'';if(line&&sw){r.s=line;r.sw=String(sw)} // the line it was met in: the review computer quotes it (찾아본 말 복습) store.set(TAPS_KEY,JSON.stringify(taps)); if(state&&state.lv&&known(h)&&lv(h).b>0&&!dueL(lv(h))){state.lv[h]={...lv(h),due:now(),beat:null};save()}} // looking up a word you have: it didn't come back by itself, so it's due now (its level stays) /* ---------- 찾아본 말 복습: words you looked up that no chapter teaches ---------- The review computer (terminal) asks them after the due badge words (or alone when only they are due), at most two a round: a word tapped at least twice that isn't any chapter's badge word, quoted in the line you met it in, its 사전 meaning among two others you looked up. Their own record (KEY('looks'): level 0..3 and when due: now, then 4 hours, then a day; at 3 it stops), never badges, ★ or the review levels. GAME.lookReview:false turns it off. */ const LOOKS_KEY=KEY('looks');let looks={};try{looks=JSON.parse(store.get(LOOKS_KEY)||'{}')||{}}catch(e){looks={}} let taughtAll=null; const taught=w=>{if(!taughtAll){taughtAll=new Set();for(const ch of CHAPTERS)try{((ch===CH?C:ch.make()).WORDS||[]).forEach(x=>taughtAll.add(x))}catch(e){}}return taughtAll.has(w)}; const lookDue=()=>G.lookReview===false?[]:Object.entries(taps).filter(([h,r])=>{const L=looks[h]||{b:0,due:0};return r.n>=2&&r.k&&!taught(h)&&!known(h)&&L.b<3&&L.due<=now()&&wordState(h)!=='known'}).sort((a,b)=>b[1].n-a[1].n).map(([h])=>h); function lookQ(h){ const r=taps[h],ks=new Set([r.k]),pick=[]; for(const k of [...shuffle(Object.values(taps).map(o=>o.k)),...shuffle(Object.values((window.LEX||{}).defs||{}).map(d=>d.k))])if(k&&!ks.has(k)&&pick.length<2){ks.add(k);pick.push(k)} let ctx=r.s||'';if(ctx.length>44){const i=Math.max(0,ctx.indexOf(r.sw||h));const a=Math.max(0,Math.min(i-18,ctx.length-44));ctx=(a?'…':'')+ctx.slice(a,a+44)+(a+44String(k).replace(/\s*[.。]$/,''); // a choice is laid out word by word: no full stop left standing alone return {lookup:h,ask:(ctx?`“${ctx}” `:'')+h+T(': 무슨 뜻이에요?'),opts:shuffle([[lab(r.k),1],...pick.map(k=>[lab(k)])]),done:`${h}: ${r.k}`,who:'…',review:true,ok:T('맞아요!')}; } function gradeLook(h,ok){const L=looks[h]||{b:0,due:0}; looks[h]=!ok?{b:0,due:now()}:L.due<=now()?{b:L.b+1,due:now()+gapAt(Math.min(5,L.b+3))}:L;store.set(LOOKS_KEY,JSON.stringify(looks))} function ago(t){const m=Math.floor((Date.now()-t)/60000);if(m<1)return T('방금');if(m<60)return unit(m,'분')+T(' 전');const h=Math.floor(m/60);if(h<24)return unit(h,'시간')+T(' 전');const d=Math.floor(h/24);return d===1?T('어제'):unit(d,'일')+T(' 전')} function openTaps(){ const esc=x=>String(x||'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c])); const rows=tapRows(taps),lines=tapRows(lineQs),n=tapLines?lines.length:rows.length; $('tapCount').textContent=n?unit(n,'개'):''; const gaps=tapLines?gramGaps():[];if(tapPat&&!gaps.some(g=>g.p===tapPat))tapPat=null; const shownLines=tapPat?lines.filter(([t])=>linePats(t).includes(tapPat)):lines; if(tapPat)$('tapCount').textContent=unit(shownLines.length,'개'); // a pattern picked: its lines $('tapList').innerHTML=(gaps.length?`
${T('문법')}`+gaps.map(g=>``).join('')+'
':'') +(tapLines?(shownLines.length?shownLines.map(([t,r])=>`
${esc(t)}${unit(r.n,'번')} · ${ago(r.t)}
${esc([r.w,r.ch].filter(Boolean).join(' · '))}
`).join('') :'

'+T('아직 영어로 본 문장이 없어요.')+'

') :rows.length?rows.map(([h,r])=>`
${esc(h)}${r.r?`${esc(r.r)}`:''}${unit(r.n,'번')} · ${ago(r.t)}
${esc(r.k)}
`).join('') :'

'+T('아직 찾아본 말이 없어요.')+'

'); $('tapList').onclick=e=>{const g=e.target.closest('.tpgp');if(g){e.stopPropagation();tapPat=tapPat===g.dataset.p?null:g.dataset.p;openTaps()}}; // a pattern: only its lines (again: all) if(!$('tapCopy')){const b=document.createElement('button');b.className='btn';b.id='tapCopy';b.textContent=T('복사');b.style.marginLeft='auto';b.addEventListener('click',copyTaps);$('tapSortN').after(b)} if(!$('tapLines')&&(window.LINES_EN||lines.length)){const b=document.createElement('button');b.className='btn';b.id='tapLines';b.textContent=T('문장');b.addEventListener('click',()=>{tapLines=!tapLines;openTaps()});$('tapSortN').after(b) // 문장: the lines whose English was opened, instead of the words const st=document.createElement('style');st.textContent='.tapsort{flex-wrap:wrap}.tapsort .btn{white-space:nowrap}' +'.tpg{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-bottom:10px}.tpgp{font:inherit;font-size:.8rem;padding:2px 9px;border:1px solid currentColor;border-radius:12px;background:none;color:inherit;opacity:.75;cursor:pointer}.tpgp.on{opacity:1;font-weight:700}.tpgp small{opacity:.7}';document.head.appendChild(st)} // a fourth button: longer labels (ことばのむら) wrap the row, never a word if($('tapLines')){$('tapLines').classList.toggle('on',tapLines);$('tapLines').setAttribute('aria-pressed',String(tapLines))} if(!$('tapSend')){const b=document.createElement('button');b.className='btn';b.id='tapSend';b.textContent=T('보내기');b.addEventListener('click',sendTaps);$('tapCopy').after(b)} if(!$('tapAnki')&&ankiOn()){const b=document.createElement('button');b.className='btn';b.id='tapAnki';b.textContent='Anki';b.addEventListener('click',sendAnki);$('tapSend').after(b)} // the app, with AnkiDroid $('tapCopy').hidden=$('tapSend').hidden=!rows.length&&!lines.length;if($('tapAnki'))$('tapAnki').hidden=$('tapCopy').hidden;if($('tapText'))$('tapText').hidden=true; $('tapSortT').classList.toggle('on',tapSort==='t');$('tapSortN').classList.toggle('on',tapSort==='n'); $('tapPanel').hidden=false;document.body.classList.add('talkopen');$('tapList').scrollTop=0; } function closeTaps(){$('tapPanel').hidden=true;document.body.classList.remove('talkopen');backToMenu()} /* 복사: every looked-up word as plain text (word | times | last day | meaning | English), to paste into a chat and practise; then every line whose English was opened with ? (line | times | last time | who | chapter | English) */ function tapsText(){ const p2=x=>String(x).padStart(2,'0'),d=t=>{const x=new Date(t);return x.getFullYear()+'-'+p2(x.getMonth()+1)+'-'+p2(x.getDate())},hm=t=>{const x=new Date(t);return d(t)+' '+p2(x.getHours())+':'+p2(x.getMinutes())}; const cells=a=>a.map(x=>String(x).replace(/\s*\|\s*/g,' / ')).join(' | '),rows=tapRows(taps),lines=tapRows(lineQs); return `${G.title||document.title} · 찾아본 말 ${rows.length}개 (${d(Date.now())})\n단어 | 찾은 횟수 | 마지막으로 찾은 날 | 뜻 | English\n` +rows.map(([h,r])=>cells([h,r.n,d(r.t),r.k||'',r.e||''])).join('\n')+'\n' +(lines.length?`\n영어로 본 문장 ${lines.length}개\n문장 | 본 횟수 | 마지막으로 본 때 | 누가 | 어디서 | English\n`+lines.map(([t,r])=>cells([t,r.n,hm(r.t),r.w||'',r.ch||'',r.e||''])).join('\n')+'\n':''); } function copyTaps(){copyText(tapsText())} function copyText(txt){ const show=()=>{ // no clipboard (some embeds block it): show the text selected, ready for the phone's own copy let ta=$('tapText');if(!ta){ta=document.createElement('textarea');ta.id='tapText';ta.readOnly=true;ta.style.cssText='width:100%;height:9em;font-size:.8rem;margin:6px 0;box-sizing:border-box';$('tapList').before(ta)} ta.hidden=false;ta.value=txt;ta.focus();ta.select();let ok=false;try{ok=document.execCommand('copy')}catch(e){}if(ok)toast(T('복사했어요!'))}; if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(txt).then(()=>toast(T('복사했어요!')),show);else show(); } /* ---------- 보내기 and 물어보기: the 사전, or one line, as a message to an AI tutor (Claude, ChatGPT, Gemini, Grok… whichever app the phone's share sheet offers; the player picks the app and the conversation). A short brief says who's learning what and asks to be quizzed (보내기) or to have the line explained (물어보기); then the data. 보내기 sends what was looked up since the last 보내기 (KEY('sentAt')), everything when nothing is new, and the badge words not yet remembered. No share sheet (a desktop browser): the text is copied. GAME.learner overrides the brief's "Korean (about TOPIK 3)". ---------- */ const LEARNER={ko:'Korean (about TOPIK 3)',ja:'Japanese (a beginner)'},LANGNAME={ko:'Korean',ja:'Japanese'}; const lang2=()=>(G.lang||'ko').slice(0,2); const brief=()=>`I'm learning ${G.learner||LEARNER[lang2()]||lang2()} by playing ${G.title||document.title}, a walk-around story game. `; function shareText(txt,sent){ if(navigator.share)navigator.share({text:txt}).then(()=>{if(sent)sent();toast(T('보냈어요!'))},()=>{}); // cancelled: nothing marked else{copyText(txt);if(sent)sent()}} function sendText(){ const since=+(store.get(KEY('sentAt'))||0),fmt=t=>{const x=new Date(t);return (x.getMonth()+1)+'/'+x.getDate()+' '+String(x.getHours()).padStart(2,'0')+':'+String(x.getMinutes()).padStart(2,'0')}; let words=tapRows(taps).filter(([,r])=>r.t>since),lines=tapRows(lineQs).filter(([,r])=>r.t>since);const all=!words.length&&!lines.length; if(all){words=tapRows(taps);lines=tapRows(lineQs)} words.sort((a,b)=>b[1].n-a[1].n);lines.sort((a,b)=>b[1].n-a[1].n); const weak=state&&state.badges?state.badges.filter(w=>lv(w).b<=1).map(w=>{const d=(C.DICT||{})[w]||carryDict(w);return w+(d&&d.k?` (${d.k})`:'')}):[],L=LANGNAME[lang2()]||lang2(); return brief()+`Please be my tutor: quiz me one question at a time, in ${L}, starting with the words I looked up most and the sentences I needed the English for (use the sentences as context). ` +`Give English only when I ask or get stuck, and correct me briefly.\n\n` +(words.length?`Words I looked up${all||!since?'':' since '+fmt(since)} (word, times: meaning):\n`+words.slice(0,40).map(([h,r])=>`- ${h}${r.r?' ('+r.r+')':''}, ${r.n}: ${r.k||''}${r.s?` — in "${r.s}"`:''}`).join('\n')+'\n\n':'') +(lines.length?`Sentences I opened the English for (Korean / English, who, where):\n`.replace('Korean',L)+lines.slice(0,25).map(([t,r])=>`- ${t} / ${r.e||''}${r.w||r.ch?` (${[r.w,r.ch].filter(Boolean).join(', ')})`:''}`).join('\n')+'\n\n':'') +(weak.length?`Words I'm still learning: ${weak.slice(0,20).join(', ')}\n\n`:'') +((g=>g.length?`Grammar that shows up in the sentences I needed the English for, more than usual in this game (pattern, sentences): ${g.map(x=>x.p+' '+x.k).join(', ')}. Please teach these, using my sentences as examples.\n\n`:'')(gramGaps())) +((ws=>ws.length?`Words I keep looking up although I've read them often (looked up / read): ${ws.join(', ')}\n`:'')(tapRows(taps).filter(([h,r])=>r.n>=2&&(seen[h]||[0])[0]>=8&&wordState(h)!=='known').slice(0,15).map(([h,r])=>`${h} ${r.n}/${seen[h][0]}`))); } /* ---------- 문법: the grammar patterns the lines you opened English for share (LINE_GRAMMAR, from walk-engine/tools/grammar_tags.py, in games that have it). A pattern counts when at least two such lines have it and it is more common in them than in the game's lines as a whole (lift ≥ 1.3, so -(으)ㄹ 때 doesn't top every list just by being everywhere). The 사전's 문장 view lists them above the lines (tap one: only its lines); 보내기 names them for the tutor. ---------- */ const LG=globalThis.LINE_GRAMMAR||null;let tapPat=null; const linePats=t=>LG?(LG.lines[String(t).replace(/\s+/g,' ').trim()]||[]).map(i=>LG.pats[i]):[]; function gramGaps(){ if(!LG)return [];const ls=Object.keys(lineQs),c={}; for(const t of ls)for(const p of linePats(t))c[p]=(c[p]||0)+1; return Object.entries(c).map(([p,k])=>({p,k,lift:(k/ls.length)/(LG.cnt[LG.pats.indexOf(p)]/LG.n)})) .filter(x=>x.k>=2&&x.lift>=1.3).sort((a,b)=>b.k*Math.log(1+b.lift)-a.k*Math.log(1+a.lift)).slice(0,8); } /* ---------- 본 말: every word you read, counted by its dictionary form, across every game in this language (one record on the site, walk-seen-: word → [times read, times looked up, times read since the last lookup]). A line counts once it has stayed on screen long enough to read (a second, plus a tenth of a second a letter). wordState(w): 'known' (a badge word at ★, or read 4 times, the last 3 without looking it up), 'learning' (looked up, read fewer than 3 times since), else 'new'. An estimate: not looking a word up isn't knowing it. 찾아본 말 복습 stops asking a word that's become known; 보내기 names the words still looked up though read often; the chapter list shows about how much of a chapter's words are known (games with LINE_GRAMMAR). ---------- */ const SEEN_KEY='walk-seen-'+lang2();let seen={};try{seen=JSON.parse(store.get(SEEN_KEY)||'{}')||{}}catch(e){seen={}} let seenT=null,reading=null; const saveSeen=()=>{clearTimeout(seenT);seenT=setTimeout(()=>store.set(SEEN_KEY,JSON.stringify(seen)),1500)}; function readStart(){ // a line has typed out: its words, and how long reading it takes const el=$('txt');if(!el)return;const ws=new Set(); el.querySelectorAll('.w').forEach(x=>{const r=lexLookup(x.dataset.w||x.textContent)[0];if(r)ws.add(r[0])}); el.querySelectorAll('.gl').forEach(x=>ws.add(x.dataset.k)); reading={ws:[...ws],at:Date.now(),need:1000+shownText(el).replace(/\s/g,'').length*100}; } function readEnd(){if(!reading)return;const r=reading;reading=null;if(Date.now()-r.at=3)return 'known'; const x=seen[w];if(!x)return 'new'; if(x[1]&&x[2]<3)return 'learning'; return x[0]>=4&&x[2]>=3?'known':'new'; } function chapterKnown(id){ // about how much of a chapter's words (by use) are known; null without the data or before much reading const ws=LG&&LG.chw&&LG.chw[id];if(!ws||Object.keys(seen).length<50)return null;let all=0,k=0; for(const [w,n] of Object.entries(ws)){all+=n;if(wordState(w)==='known')k+=n} return all?Math.round(100*k/all):null; } /* ---------- Anki (the Android app, with AnkiDroid installed: window.WalkAnki): the 사전's Anki button adds every looked-up word and every line whose English was opened that hasn't gone before (KEY('ankiSent')) as AnkiDroid notes, deck "Walk Games::": a word's card shows the line it was met in with the word in bold (or the word alone), a line's card the line; AnkiDroid reads the front aloud; the back has the meaning, the English and where it came from. ---------- */ const ankiOn=()=>{try{return !!(window.WalkAnki&&WalkAnki.available())}catch(e){return false}}; let ankiSent={},ankiPending=null;try{ankiSent=JSON.parse(store.get(KEY('ankiSent'))||'{}')||{}}catch(e){ankiSent={}} function ankiNotes(){ const esc=x=>String(x||'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c])),out=[]; const notes=Object.values(NOTE_KINDS).map(N=>T(N.name)+' · '); // a note card's ? (문화 노트 · …) isn't a line for(const [h,r] of tapRows(taps)){if(ankiSent['w:'+h]||!r.k)continue;const sw=r.sw||h; const front=r.s&&r.s.includes(sw)?esc(r.s).replace(esc(sw),''+esc(sw)+''):''+esc(h)+''; out.push({key:'w:'+h,front,word:esc(h)+(r.r?' ('+esc(r.r)+')':''),meaning:esc(r.k),english:esc(r.e),source:esc(G.title||document.title)})} for(const [t,r] of tapRows(lineQs)){if(ankiSent['l:'+t]||notes.some(n=>t.startsWith(n)))continue; out.push({key:'l:'+t,front:esc(t),word:'',meaning:'',english:esc(r.e),source:esc([G.title||document.title,r.ch,r.w].filter(Boolean).join(' · '))})} return out; } function sendAnki(){const ns=ankiNotes();if(!ns.length){toast(T('새로 보낼 게 없어요.'));return} ankiPending=ns.map(n=>n.key);WalkAnki.add(JSON.stringify({lang:lang2(),deck:G.title||document.title,tag:G.prefix||'',notes:ns.map(({key,...n})=>n)}))} window.__ankiDone=(n,err)=>{ // the app's answer: how many notes went in, or why none did if(n<0||err){toast(T('Anki에 못 넣었어요.')+(err?' ('+err+')':''));ankiPending=null;return} const t=Date.now();(ankiPending||[]).forEach(k=>ankiSent[k]=t);ankiPending=null;store.set(KEY('ankiSent'),JSON.stringify(ankiSent));toast('Anki +'+n)}; function sendTaps(){shareText(sendText(),()=>store.set(KEY('sentAt'),String(Date.now())))} function askText(){ // the line in the dialogue box, its English, who says it, where, and the lines just before it const line=shownText($('txt')).replace(/\s+/g,' ').trim(),en=($('txtEn')&&$('txtEn').textContent)||'',who=$('who').textContent,L=LANGNAME[lang2()]||lang2(); const before=talk.slice(0,-1).slice(-3).filter(([,t])=>plain(t)!==line).map(([w,t])=>`- ${w}: ${plain(t)}`); return brief()+`Please explain this line to me: what it means, its grammar, and its nuance (how it sounds, who would say it to whom). Answer mostly in ${L} at my level, with English where it helps.\n\n` +`${who}${CH?' ('+CH.n+' '+CH.title+')':''}: ${line}\nEnglish: ${en}`+(before.length?`\n\nJust before it:\n${before.join('\n')}`:'')+'\n'; } function hideGloss(){$('gloss').hidden=true} /* ---------- conversation log: every line shown, scrollable, words tappable like in the dialogue box ---------- */ let talk=[]; const talkKey=()=>SK()+'-talk'; function loadTalk(){talk=[];try{talk=JSON.parse(localStorage.getItem(talkKey())||'[]')}catch(e){}} function logTalk(who,text,enKey){ if(!text)return;const last=talk[talk.length-1];if(last&&last[0]===who&&last[1]===text)return; talk.push(enKey?[who,text,enKey]:[who,text]);if(talk.length>150)talk=talk.slice(-150); try{localStorage.setItem(talkKey(),JSON.stringify(talk))}catch(e){} } function openTalk(){ const esc=x=>String(x).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c])); $('talkList').innerHTML=talk.length?talk.map(([w,t,k])=>{const en=lineEn(k||t);return `
${esc(T(w))}${glossHTML(t)}${en?``:''}
`}).join('') :'

'+T('아직 대화가 없어요.')+'

'; $('talkList').onclick=e=>{const q=e.target.closest('.tq');if(q){e.stopPropagation();const t=q.nextElementSibling;t.hidden=!t.hidden;lineQOpened(q,t)}};if(window.LINES_EN)enUI(); // enUI: the ?'s style $('talkPanel').hidden=false;document.body.classList.add('talkopen'); const L=$('talkList');L.scrollTop=L.scrollHeight; } let fromMenu=false; // the talk log / dictionary was opened from the START menu: closing it goes back there, not to the game const backToMenu=()=>{if(fromMenu){fromMenu=false;$('startPanel').hidden=false}}; function closeTalk(){$('talkPanel').hidden=true;document.body.classList.remove('talkopen');hideGloss();backToMenu()} const choiceBtns=()=>[...document.querySelectorAll('#choices .choice')]; const tileBtns=()=>[...document.querySelectorAll('#tiles .tile:not(.used)')]; const choosing=()=>!!dlg&&!$('choices').hidden&&choiceBtns().length>0; const building=()=>!!dlg&&!$('build').hidden; function shuffle(a){for(let i=a.length-1;i>0;i--){const j=Math.random()*(i+1)|0;[a[i],a[j]]=[a[j],a[i]]}return a} function renderChoices(s){ writeKbOff(); // 보기 after a 쓰기 문제: the controls come back const box=$('choices');box.hidden=false; const order=shuffle(s.opts.map((_,i)=>i)); box.innerHTML=order.map(i=>``).join(''); // one inner span: the shells lay .choice out as a flex row, which would space each word span and its punctuation apart let pressT=null,defined=false; // long-press a word on a choice = its definition (doesn't answer) box.querySelectorAll('.choice').forEach(b=>{ b.addEventListener('pointerdown',e=>{const w=e.target.closest('.cw');defined=false;clearTimeout(pressT);if(w)pressT=setTimeout(()=>{defined=true;w.dataset.k?showGloss(w.dataset.k,w):showWord(w.dataset.w||w.textContent,w)},450)}); for(const t of ['pointerup','pointerleave','pointercancel'])b.addEventListener(t,()=>clearTimeout(pressT)); b.addEventListener('click',e=>{e.stopPropagation();if(defined){defined=false;return}choose(s,+b.dataset.i)})}); sel=-1;choicesAt=performance.now();markSel(); // nothing selected: A can't answer by accident } /* the 쓰기 문제's own 한글 keyboard (두벌식), for players without a Korean keyboard: jamo keys that join into syllables as you tap (ㅂ ㅣ → 비, a final consonant moves on when a vowel follows: 비 ㅁ ㅣ → 비미), ⇧ for ㅃㅉㄸㄲㅆㅒㅖ, ⌫ takes back one jamo. 내 자판 switches to the device's own keyboard (remembered); a desktop keyboard with a Korean IME types into the box either way. */ const HG={CHO:'ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ',JUNG:'ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ', JONG:['','ㄱ','ㄲ','ㄳ','ㄴ','ㄵ','ㄶ','ㄷ','ㄹ','ㄺ','ㄻ','ㄼ','ㄽ','ㄾ','ㄿ','ㅀ','ㅁ','ㅂ','ㅄ','ㅅ','ㅆ','ㅇ','ㅈ','ㅊ','ㅋ','ㅌ','ㅍ','ㅎ'], V2:{'ㅗㅏ':'ㅘ','ㅗㅐ':'ㅙ','ㅗㅣ':'ㅚ','ㅜㅓ':'ㅝ','ㅜㅔ':'ㅞ','ㅜㅣ':'ㅟ','ㅡㅣ':'ㅢ'}, F2:{'ㄱㅅ':'ㄳ','ㄴㅈ':'ㄵ','ㄴㅎ':'ㄶ','ㄹㄱ':'ㄺ','ㄹㅁ':'ㄻ','ㄹㅂ':'ㄼ','ㄹㅅ':'ㄽ','ㄹㅌ':'ㄾ','ㄹㅍ':'ㄿ','ㄹㅎ':'ㅀ','ㅂㅅ':'ㅄ'}}; const hgC=j=>HG.CHO.includes(j),hgV=j=>'ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅛㅜㅠㅡㅣ'.includes(j); function hgJoin(seq){ // key jamo → text let out='',c=null,v=null,f=[]; const flush=()=>{if(c&&v){const F=f.length?(f.length>1?HG.F2[f.join('')]:f[0]):'';out+=String.fromCharCode(0xAC00+(HG.CHO.indexOf(c)*21+HG.JUNG.indexOf(v))*28+HG.JONG.indexOf(F))} else out+=(c||'')+(v||'');c=null;v=null;f=[]}; for(const j of seq){ if(hgC(j)){if(!c&&!v)c=j;else if(!v||!c){flush();c=j} else if(!f.length&&!'ㄸㅃㅉ'.includes(j))f=[j];else if(f.length===1&&HG.F2[f[0]+j])f=[f[0],j];else{flush();c=j}} else if(hgV(j)){if(!v){if(c)v=j;else{flush();v=j}} else if(f.length){const k=f.pop();flush();c=k;v=j} else if(c&&HG.V2[v+j])v=HG.V2[v+j];else if(!c&&HG.V2[v+j])v=HG.V2[v+j];else{flush();v=j}} else{flush();out+=j}} flush();return out} function hgKeys(t){ // text → key jamo (to pick up typing from a device keyboard) const V={},F={};for(const [k,x] of Object.entries(HG.V2))V[x]=[...k];for(const [k,x] of Object.entries(HG.F2))F[x]=[...k]; const out=[];for(const ch of t){const n=ch.charCodeAt(0)-0xAC00; if(n>=0&&n<11172){out.push(HG.CHO[Math.floor(n/588)]);const v=HG.JUNG[Math.floor(n%588/28)];out.push(...(V[v]||[v]));const fz=HG.JONG[n%28];if(fz)out.push(...(F[fz]||[fz]))} else out.push(...(V[ch]||F[ch]||[ch]))} return out} let ownKb=store.get(KEY('ownKb'))==='1'; /* the built-in keyboard takes the controls' place (.pad and .startrow: D-pad, A/B, START) while you write, so the question stays in view; they come back when the line changes or the talk ends */ function writeKbOn(el){writeKbOff();el.id='hgPad';el.classList.add('inpad');const pad=document.querySelector('.pad'); if(!pad){$('choices').append(el);el.classList.remove('inpad');return} for(const q of ['.pad','.startrow']){const e=document.querySelector(q);if(e)e.style.display='none'}pad.after(el)} function writeKbOff(){const k=$('hgPad');if(!k)return;k.remove();for(const q of ['.pad','.startrow']){const e=document.querySelector(q);if(e)e.style.display=''}} function hgPad(inp,own,submit,only){ // own: the player chose their device's keyboard; submit: 확인; only: the small keyboard's keys (쓰기 ladder) const box=document.createElement('div');box.className='hgk';let seq=hgKeys(inp.value),shift=false; const SH={'ㅂ':'ㅃ','ㅈ':'ㅉ','ㄷ':'ㄸ','ㄱ':'ㄲ','ㅅ':'ㅆ','ㅐ':'ㅒ','ㅔ':'ㅖ'};let R=[['ㅂ','ㅈ','ㄷ','ㄱ','ㅅ','ㅛ','ㅕ','ㅑ','ㅐ','ㅔ'],['ㅁ','ㄴ','ㅇ','ㄹ','ㅎ','ㅗ','ㅓ','ㅏ','ㅣ'],['⇧','ㅋ','ㅌ','ㅊ','ㅍ','ㅠ','ㅜ','ㅡ','⌫']]; const both=only&&Object.keys(SH).some(k=>only.has(k)&&only.has(SH[k])); if(only)R=R.map(r=>r.flatMap(k=>k==='⌫'?[]:k==='⇧'?[both?k:'']:[only.has(k)?k:only.has(SH[k])?SH[k]:''])); // each key where it sits on the full keyboard, the rest blank: the layout is learned on the way. ㄲ alone takes ㄱ's place; ⇧ only when both are needed const draw=()=>{box.innerHTML=R.map(r=>`
${r.map(k=>k?``:'').join('')}
`).join('') +(only?'
'+(only.has(' ')?'':'')+'
' :'
')}; draw(); box.addEventListener('pointerdown',e=>{if(e.target.closest('.hk'))e.preventDefault()}); // keep the box's caret, no focus jump box.addEventListener('click',e=>{e.stopPropagation();const b=e.target.closest('.hk');if(!b)return;const k=b.dataset.k; if(k==='own'){own();return}if(k==='ok'){submit();return} if(k==='⇧'){shift=!shift;draw();return} if(k==='⌫')seq.pop();else{seq.push(shift&&SH[k]?SH[k]:k);if(shift){shift=false;draw()}} inp.value=hgJoin(seq)}); inp.addEventListener('input',()=>{seq=hgKeys(inp.value)}); // typed on a desktop or device keyboard return box} /* 쓰기 문제: a review question about a word you know well (level SRS().writeAt, default 3 = ★) asks you to write the answer into the blank instead of picking it. 힌트 shows its first syllable (놓○○); 힌트 again gives the usual choices. A right answer after a hint doesn't raise the word's level (grade held); a wrong one counts as a miss and the question comes back as choices. Only for a graded review step whose blank takes the right option (Hangul), never a listening question. START → 쓰기 문제 turns it on (off by default; ?write=0/1). */ const writing=()=>!!dlg&&!$('choices').hidden&&!!$('writeIn'); function writeBase(s){const o=(s.opts||[]).find(x=>x[1]); return writeOn&&!!s.w&&!!(s.review||dlg.review)&&!s.missed&&!s.choices&&!s.listenOnly&&/___/.test(s.ask||'')&&!!o&&/[가-힣]/.test(o[0])} const writeQ=s=>writeBase(s)&&lv(s.w).b>=(SRS().writeAt??3); /* the 쓰기 ladder (?write=step, a prototype). Each word has two records: its level (lv(w).b, did you know it) and its own 쓰기 rung (lv(w).wr, can you write it): 0 syllable tiles (비·밀·번·호 and a decoy or two, tapped in order), 1 a small keyboard (only the word's jamo and a few look-alikes), 2 the full keyboard. Turning 쓰기 on starts every word at the tiles, however well you know it. A clean answer takes the word up a rung; giving up (보기, a spelling that isn't an option, two wrong tiles) takes it down one; a hint or one wrong tile leaves it. A word is written only once you know it (level SRS().writeAt, default 3 = ★); below that it is a choice. The level counts only whether you knew it: a spelling you couldn't finish comes back as choices and holds the level (never a miss), so choices alone master a word. A one-syllable word skips the tiles. */ const WR_NAME=['글자 조각','작은 자판','자판']; function rampNote(s,res){ // res: true clean, false gave up, null neither if(!writeStep||!s.rung||s.ramped||!s.w||!state.lv[s.w])return;s.ramped=1; const L=state.lv[s.w],r0=L.wr||0,r=Math.max(0,Math.min(2,r0+(res===true?1:res===false?-1:0))); if(r===r0)return;L.wr=r;save();setTimeout(()=>toast(`"${s.w}" 쓰기 ${r>r0?'↑':'↓'} ${WR_NAME[r]}`),900)} function writeRung(s){ if(!writeBase(s))return null;const L=lv(s.w); if(!writeStep)return L.b>=(SRS().writeAt??3)?'full':null; if(L.b<(SRS().writeAt??3))return null;const r=L.wr||0; return r>=2?'full':r===1||[...s.opts.find(o=>o[1])[0]].filter(c=>/[가-힣]/.test(c)).length<2?'mini':'syl'} /* a spelling the player couldn't finish (ladder): the question comes back as choices and the word's level holds */ function writeGiveUp(s){s.choices=1;s.hinted=1;rampNote(s,false)} function renderAsk(s){const r=writeRung(s);s.rung=r;if(r==='syl')renderSyl(s);else if(r)renderWrite(s);else renderChoices(s)} /* look-alike jamo for decoys (the small keyboard) and decoy syllables (the tiles) */ const HGLIKE={'ㄱ':'ㅋㄲ','ㅋ':'ㄱ','ㄲ':'ㄱ','ㄷ':'ㅌㄸ','ㅌ':'ㄷ','ㄸ':'ㄷ','ㅂ':'ㅍㅃ','ㅍ':'ㅂ','ㅃ':'ㅂ','ㅈ':'ㅊㅉ','ㅊ':'ㅈ','ㅉ':'ㅈ', 'ㅅ':'ㅆ','ㅆ':'ㅅ','ㄴ':'ㄹ','ㄹ':'ㄴ','ㅇ':'ㅎ','ㅎ':'ㅇ','ㅁ':'ㅂ','ㅏ':'ㅓ','ㅓ':'ㅗㅏ','ㅗ':'ㅓㅜ','ㅜ':'ㅗㅡ','ㅡ':'ㅜ','ㅣ':'ㅡ', 'ㅐ':'ㅔ','ㅔ':'ㅐ','ㅑ':'ㅕ','ㅕ':'ㅑ','ㅛ':'ㅠ','ㅠ':'ㅛ','ㅒ':'ㅖ','ㅖ':'ㅒ'}; function sylDecoys(ans,opts,n){ // syllables from the wrong options first, then the answer's own syllables with one jamo swapped const have=new Set(ans),out=[]; for(const o of shuffle(opts.filter(o=>!o[1]).map(o=>o[0])))for(const c of o)if(/[가-힣]/.test(c)&&!have.has(c)&&!out.includes(c))out.push(c); shuffle(out);out.length=Math.min(out.length,Math.ceil(n/2)); for(let k=0;out.lengtho[1])[0],ans=[...right].filter(c=>/[가-힣]/.test(c)); const tiles=shuffle([...ans,...sylDecoys(ans,s.opts,ans.length>3?3:2)]);let got=0,bad=0; const shown=()=>{let n=0;return [...right].map(c=>/[가-힣]/.test(c)?(n++${shown()}`+tiles.map((t,i)=>``).join('') +''; box.querySelectorAll('.sy').forEach(b=>b.addEventListener('click',e=>{e.stopPropagation();if(!b.classList.contains('choice'))return; if(b.dataset.t!==ans[got]){sfx('no');b.classList.remove('bad');void b.offsetWidth;b.classList.add('bad'); if(++bad>=2){writeGiveUp(s);renderChoices(s)}return} // one slip is allowed; two and it's choices sfx('move');got++;b.classList.remove('choice','sel');b.classList.add('used');b.disabled=true;$('sylQ').textContent=shown(); if(got===ans.length){rampNote(s,bad?null:true);choose(s,s.opts.findIndex(o=>o[1]));return} sel=Math.min(Math.max(sel,0),choiceBtns().length-1);markSel()})); box.querySelector('.wqhb').addEventListener('click',e=>{e.stopPropagation();writeGiveUp(s);renderChoices(s)}); box.addEventListener('click',e=>e.stopPropagation()); if(firstTime('sylQ'))setTimeout(()=>toast('글자를 순서대로 눌러요.'),300); sel=-1;choicesAt=performance.now();markSel(); } const writeNorm=t=>String(t).replace(/[\s.,!?~…"'“”‘’·]/g,''); const writeHint=a=>{let n=0;return [...a].map(c=>/[가-힣]/.test(c)?(n++?'○':c):c).join('')}; function writeUI(){if($('writeCss'))return;const st=document.createElement('style');st.id='writeCss'; st.textContent='.choices .wqh{flex:1 1 100%;font:600 .9rem/1.3 var(--body,sans-serif);opacity:.8;letter-spacing:.12em}' +'.choices .wq{flex:1 1 100%;display:flex;gap:6px;min-width:0}' +'.choices .wqin{flex:1;min-width:0;font:600 1.05rem/1.3 var(--body,sans-serif);padding:6px 9px;border-radius:5px;border:1px solid var(--glass-edge,#888);background:var(--glass-2,#fff);color:var(--glass-ink,#111)}' +'.choices .wqok,.choices .wqhb{font:600 .95rem/1 var(--body,sans-serif);padding:6px 11px;border-radius:5px;border:1px solid var(--glass-edge,#888);background:var(--glass-2,#eee);color:var(--glass-ink,#111);cursor:pointer}' +'.choices .wqhb{opacity:.85}' +'.choices .wqkb{flex:0 0 auto;font:600 .8rem/1 var(--body,sans-serif);padding:5px 9px;border-radius:5px;border:1px solid var(--glass-edge,#888);background:none;color:inherit;opacity:.75;cursor:pointer}' +'.choices .syls{letter-spacing:.3em;font-size:1.25rem;opacity:1}.choices .sy{flex:0 0 auto;min-width:44px;font-size:1.2rem}.choices .sy.used{opacity:.25}' +'.choices .sy.bad{animation:wqshake .3s}@keyframes wqshake{25%{transform:translateX(-4px)}75%{transform:translateX(4px)}}' +'.hgk{display:flex;flex-direction:column;gap:4px;margin-top:2px;user-select:none;-webkit-user-select:none;flex:1 1 100%}' +'.hgk .hgr{display:flex;gap:3px;justify-content:center}' +'.hgk .hk{flex:1 1 0;min-width:0;max-width:40px;height:34px;padding:0;font:600 1.05rem/1 var(--body,sans-serif);border-radius:5px;border:1px solid var(--glass-edge,#888);background:var(--glass-2,#eee);color:var(--glass-ink,#111);cursor:pointer;touch-action:manipulation}' +'.hgk .hk:active{filter:brightness(1.3)}.hgk .hkw{max-width:52px;font-size:.95rem}.hgk .hk.on{outline:2px solid var(--amber,#E8962A)}' +'.hgk .hkx{visibility:hidden}.hgk .hksp{max-width:none;flex:3 1 0;font-size:.85rem}.hgk .hkown{flex:1.4 1 0;max-width:none;font-size:.8rem}.hgk .hkok{flex:1.4 1 0;max-width:none;font-size:.9rem;background:var(--amber,#E8962A);color:var(--amber-ink,#1B1E2B);border-color:transparent}' +'.hgk.inpad{width:100%;max-width:560px;margin:10px auto 0;padding:8px 6px;gap:7px;box-sizing:border-box;border-radius:12px;background:var(--glass,#1B1E24)}' +'.hgk.inpad .hgr{gap:5px}.hgk.inpad .hk{max-width:none;height:50px;font-size:1.3rem}.hgk.inpad .hkw,.hgk.inpad .hkown,.hgk.inpad .hksp,.hgk.inpad .hkok{font-size:1rem}'; document.head.appendChild(st)} function miniKeys(a){ // the word's own jamo plus three look-alikes it doesn't use const k=new Set(hgKeys(a).filter(j=>j!==' '||a.includes(' ')));const pool=shuffle([...new Set([...k].flatMap(j=>[...(HGLIKE[j]||'')]))].filter(j=>!k.has(j)&&!'ㄲㄸㅃㅉㅆㅒㅖ'.includes(j))); // no doubled decoys: ⇧ only for a word that needs it for(const j of pool.slice(0,3))k.add(j);return k} function renderWrite(s){ const mini=s.rung==='mini'; writeUI();const box=$('choices');box.hidden=false;const right=s.opts.find(o=>o[1])[0],keep=$('writeIn')?$('writeIn').value:''; box.innerHTML=(s.hint1?`
힌트: ${writeHint(right)}
`:'') +`
` +`${ownKb&&!mini?'':''}
` // the built-in keyboard has its own 확인 +(ownKb&&!mini?'':''); const inp=$('writeIn');inp.value=keep;inp.inputMode=ownKb&&!mini?'text':'none'; // the built-in keyboard: no device keyboard over it if(mini)writeKbOn(hgPad(inp,null,()=>submit(),miniKeys(right))); // the small keyboard: always the built-in one else if(!ownKb)writeKbOn(hgPad(inp,()=>{ownKb=true;store.set(KEY('ownKb'),'1');renderWrite(s);$('writeIn').focus()},()=>submit()));else writeKbOff(); box.querySelector('.wqkb')?.addEventListener('click',e=>{e.stopPropagation();ownKb=false;store.set(KEY('ownKb'),'0');renderWrite(s)}); const submit=()=>{const v=writeNorm(inp.value);if(!v)return;inp.blur(); const i=s.opts.findIndex(o=>writeNorm(o[0])===v);if(i>=0){if(s.opts[i][1])rampNote(s,s.hint1?null:true);choose(s,i);return} // right, or a wrong option you wrote (its explanation) sfx('no');if(writeStep)writeGiveUp(s);else{s.missed=true;if(s.w){dlg.missed.add(s.w);askedIn[s.w]=talkN}} dlg.next=s;show({who:s.who==='나'?'…':s.who,say:T('아니에요. 보기에서 골라 봐요.'),fb:1})}; inp.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.isComposing){e.preventDefault();submit()}}); box.querySelector('.wqok')?.addEventListener('click',e=>{e.stopPropagation();submit()}); box.querySelector('.wqhb').addEventListener('click',e=>{e.stopPropagation();s.hinted=1; if(!s.hint1){s.hint1=1;renderWrite(s);$('writeIn').focus()}else{if(writeStep)writeGiveUp(s);s.choices=1;renderChoices(s)}}); // 보기: the usual choices box.addEventListener('click',e=>e.stopPropagation()); if(mini?firstTime('miniQ'):firstTime('writeQ'))setTimeout(()=>toast(mini?'이 단어는 써 봐요. 필요한 키만 있어요.':'★ 단어는 직접 써 봐요. 모르면 힌트!'),300); setTimeout(()=>{if($('writeIn')===inp)inp.focus()},60); // with the built-in keyboard: a caret, no device keyboard (inputmode none) } /* a plain choice (not a quiz): each button closes the conversation and runs its action, e.g. going on to the next chapter */ function renderPick(s){ const box=$('choices');box.hidden=false; box.innerHTML=s.choose.map(([label],i)=>``).join(''); box.querySelectorAll('.choice').forEach(b=>b.addEventListener('click',e=>{e.stopPropagation();const fn=s.choose[+b.dataset.i][1]; box.hidden=true;box.innerHTML='';sfx('ok');closeDialog();if(fn)setTimeout(fn,150)})); sel=-1;choicesAt=performance.now();markSel(); } /* the gate at the end of a chapter: "go on to the next one?" (nothing after the last chapter) */ function nextChapterAsk(line){ const i=CHAPTERS.findIndex(c=>c.id===CH.id),nx=CHAPTERS[i+1];if(!nx)return line; const ro=(w=>{const c=w.charCodeAt(w.length-1)-0xAC00,b=c>=0&&c<11172?c%28:0;return b===0||b===8?'로':'으로'})(nx.n); // 2교시로, 2장으로 return {steps:[{say:(line?line+' ':'')+nx.n+ro+' 갈까요?',choose:[[nx.n+ro+' 가요',()=>{boot(nx.id);sfx('door')}],[T('아직이요'),null]]}]}; } function markSel(){const bs=choosing()?choiceBtns():tileBtns();bs.forEach((b,i)=>b.classList.toggle('sel',i===sel));bs[sel]?.focus({preventScroll:true});bs[sel]?.scrollIntoView({block:'nearest'})} function moveSel(d){if(performance.now()-choicesAt<450)return; // keys still held from walking don't move a fresh question's selection const n=(choosing()?choiceBtns():tileBtns()).length;if(!n)return;sel=sel<0?(d>0?0:n-1):(sel+d+n)%n;markSel();sfx('move')} let choicesAt=0,lastA=0; function confirmSel(){const t=performance.now();if(t-choicesAt<450)return; if(choosing()||(building()&&!dlg.cur.got)){const quick=lastA>choicesAt&&t-lastA<500;lastA=t;if(quick)return} // mashing A through talk never answers: in a question (or word tiles before the first is placed), presses under 0.5 s apart do nothing (pause, then A picks) if(sel<0){sel=0;markSel();return} // nothing selected: A selects the first one (never does nothing); A again picks it const b=(choosing()?choiceBtns():tileBtns())[sel];if(b)b.click()} function renderBuild(s){ s.got=0;$('build').hidden=false; $('slots').innerHTML='· · ·'; let order;const solved=o=>[s.build,...(s.alts||[])].some(a=>o.every((v,i)=>s.build[v]===a[i])); do order=shuffle(s.build.map((_,i)=>i));while(s.build.length>1&&solved(order)); /* never start already solved (in any right order) */ $('tiles').innerHTML=order.map(i=>``).join(''); $('tiles').querySelectorAll('.tile').forEach(b=>b.addEventListener('click',e=>{e.stopPropagation();pickTile(s,b)})); sel=-1;choicesAt=performance.now();markSel();if(s.hintOK===undefined){s.hintOK=hints.tile!==1&&firstTime('tileHint');hintDone('tile')} // once per player across the games (walk-hints), not per gamehintTile(s,4000); } /* the very first word-order question a player meets (in any of the games): after a pause its first right tile bobs, a hint without instruction text. Never again after that, and never past the first tile: from then on the player knows how tiles work. */ function hintTile(s,ms){ clearTimeout(hintTile.t);$('tiles').querySelectorAll('.hint').forEach(b=>b.classList.remove('hint')); if(!s.hintOK||s.got>0)return; hintTile.t=setTimeout(()=>{if(!(dlg&&dlg.cur===s&&building()))return;const seq=s.seq||[],o=[s.build,...(s.alts||[])].find(o=>seq.every((w,j)=>o[j]===w))||s.build; [...$('tiles').querySelectorAll('.tile:not(.used)')].find(b=>s.build[+b.dataset.i]===o[seq.length])?.classList.add('hint')},ms); } function pickTile(s,b){ const i=+b.dataset.i,seq=s.seq||(s.seq=[]),t=s.build[i]; const fits=o=>seq.every((w,j)=>o[j]===w)&&o[seq.length]===t; // the order so far, plus this tile, is a prefix of a right order if(!fits(s.build)&&!(s.alts||[]).some(fits)){sfx('no');s.missed=true;if(s.w)dlg.missed.add(s.w);b.classList.remove('bad');void b.offsetWidth;b.classList.add('bad');hintTile(s,1200);return} sfx('move');seq.push(t);s.got++;b.classList.add('used');b.classList.remove('sel');hintTile(s,4000); if(s.got===1)$('slots').innerHTML=''; $('slots').insertAdjacentHTML('beforeend',`${s.build[i]}`); if(s.got===s.build.length){ const line=seq.join(' ');sfx('ok'); if(s.review||dlg.review)gradeStep(s); dlg.next='advance';$('build').hidden=true; show({who:s.who||dlg.name,say:line+(/[.!?…]$/.test(line)?'':'.'),hl:{a:line}}); // the assembled line, said whole: getting it right is the praise (no 맞아요 toast) if(readOn)speak(line); }else{sel=Math.min(Math.max(sel,0),tileBtns().length-1);markSel()} // the selection moves on to the next tile: A, A, A builds the line } /* Each rule is explained once per player, then only the toasts speak. */ let explained={};try{explained=JSON.parse(localStorage.getItem(KEY('explained'))||'{}')}catch(e){} function firstTime(k){if(explained[k])return false;explained[k]=1;try{localStorage.setItem(KEY('explained'),JSON.stringify(explained))}catch(e){}return true} function gradeStep(s){ if(s.lookup){gradeLook(s.lookup,!s.missed);return} // 찾아본 말 복습: its own record if(!s.w)return; if(s.reg){const r=(state.reg=state.reg||{})[s.w]||(state.reg[s.w]={ok:0,miss:0});s.missed?r.miss++:r.ok++;save();return} // register judgment, kept apart from remembering the word const before=lv(s.w).b,b=grade(s.w,!s.missed,!!s.hinted); updateHud(); if(s.missed)setTimeout(()=>toast(`${qt(s.w)} ${T('다시 연습해요')}`),250); if(!s.missed&&b>=3&&before<3){setTimeout(()=>{toast('★ '+s.w+T(' 기억했어요!'));sfx('star')},250)} if(s.missed?firstTime('reviewMiss'):firstTime('reviewLevel'))dlg.steps.splice(dlg.i+1,0,{who:LOGNAME,say:s.missed?`${qt(s.w)} ${T('다시 연습해요. 곧 또 나와요.')}`:`${qt(s.w)} ${T('기억 레벨')} ${b}/5${T('.')}`+(b>=3?' ★':'')}); } /* praise after a right answer: a step's own `ok`, else 맞아! from a friend who speaks 반말 (NPC banmal:1), else 맞아요! */ const okWord=s=>s.ok||(dlg.npc&&dlg.npc.banmal?T('맞아!'):T('맞아요!')); /* the asked line with its blank filled, minus a question after it that the answer has just settled ("…" 맞춤법에 맞는 건?) */ function answered(ask,a){const f=ask.replace('___',a),i=ask.indexOf('___')+a.length; const m=f.slice(i).match(/^([^"”]*["”][.!?]?)\s+([^"”]*\?)$/);return m?f.slice(0,i)+m[1]:f} // only a quoted example's question function choose(s,i){ const o=s.opts[i];if(s.w)askedIn[s.w]=talkN; if(s.chatReply&&curChat){ // a reply in a chat: right = sent as a bubble (the commit rides on it when nothing comes after); wrong = a hint over the thread if(o[1]){sfx('ok');if(s.review||dlg.review)gradeStep(s);dlg.next='advance';curChat.sent=String(o[0]); show({chatMsg:{from:'me',text:String(o[0]),id:s.chatReply+':'+i,time:s.time,now:s.now},fb:1,...(s.chatCommit?{chatCommit:s.chatCommit,set:s.chatSet,award:s.chatAward}:{})})} else{sfx('no');s.missed=true;if(s.w){dlg.missed.add(s.w);if(!has(s.w)){(state.miss=state.miss||{})[s.w]=1;save()}} dlg.next=s;show({chatFb:o[2]||T('다시 해 봐요.'),fb:1})} return} if(o[1]){ sfx('ok'); if(s.review||dlg.review)gradeStep(s); dlg.next='advance'; const line=s.done||(s.ask.includes('___')?answered(s.ask,o[0]):o[0]),enKey=!s.done&&s.ask.includes('___')?s.ask:undefined; // the filled line's English is kept under the question as written const quiz=/["“][^"”]*___[^"”]*["”]/.test(s.ask)||s.listenOnly; const hl={a:plain(String(o[0])),pre:s.ask.includes('___')&&!s.done?plain(s.ask.slice(0,s.ask.indexOf('___'))):''}; // the answer glows where it filled the blank if(s.who==='나'&&!s.listenOnly||s.own||s.who==='…'||!quiz){ /* own:1 — the line is the speaker's own words, not a reply to you */ // an ok: that isn't praise ("뭐?", "…") is the other person's reaction, so they say it next const react=s.ok&&!/^(맞아|정답|좋아|딩동댕)/.test(s.ok)?s.ok:null; show({who:s.who||dlg.name,say:line,fb:1,enKey,hl}); // the line with its blank filled is the feedback: no 맞아요 toast (the sound and the talk going on say it was right) if(react)dlg.next={who:s.reactWho||dlg.name,say:react,fb:1}}else show({who:s.who==='나'?dlg.name:s.who,say:okWord(s)+' '+(s.listenOnly?`"${o[0]}"`:line),fb:1,enKey:s.listenOnly?undefined:enKey,hl}); }else{ sfx('no');s.missed=true;if(s.w){dlg.missed.add(s.w);if(!has(s.w)){(state.miss=state.miss||{})[s.w]=1;save()}} dlg.next=s;show({who:s.who==='나'?'…':s.who,say:o[2]||T('다시 해 봐요.'),fb:1}); // after your own line, the hint is narration } } function advance(){ if(!dlg)return; if(typing&&!typing.finished){typing.fin();return} if(dlg.cur.ask||dlg.cur.build||dlg.cur.choose||dlg.cur.chatChoose)return; if(dlg.next){const n=dlg.next;dlg.next=null;if(n!=='advance'){show(n);return}} if(dlg.cur.finale){const p=pending;pending=null;closeDialog();finish(p);return} // a note still waiting (20/20 words!) goes before the ending, not under its fade dlg.i++; if(dlg.i>=dlg.steps.length){if(dlg.intro){state.seenIntro=true;state.introPending=false;save()}closeDialog();return} show(dlg.steps[dlg.i]); } let closedAt=0; /* leave whatever conversation is open without finishing it (처음부터, switching chapters): its black, scene, box, phone and queued walks go with it. Starting over during a review round (it plays over black) once kept the screen black for good. */ function dropTalk(){ walks.length=0;leaves.length=0;ghosts=[];pending=null; if(dlg){dlg=null;camT=null;clearInterval(typing?.id);$('dlg').hidden=true;$('dlg').classList.remove('attop');closePhone();hideGloss();if(TTS)try{speechSynthesis.cancel()}catch(e){}} $('fade').classList.remove('on');playScene(null); } function closeDialog(){ readEnd(); writeKbOff(); const wasBlack=dlg&&dlg.black;if(wasBlack){$('fade').classList.remove('on');playScene(null)} closedAt=performance.now();if(dlg&&dlg.moved){pushBack(dlg.snap);beat()}dlg=null;camT=null;startWalks();clearInterval(typing?.id);$('dlg').hidden=true;$('dlg').classList.remove('attop');closePhone();hideGloss();if(TTS)try{speechSynthesis.cancel()}catch(e){} updateQuest(); if(C.afterTalk)C.afterTalk(); // a chapter's own check after every conversation (단어 마을: the cartridge is complete, every word is ★) if(pending){const c=pending;pending=null;setTimeout(()=>{if(!dlg)openDialog(LOGNAME,c)},400)} } function cancel(){ const over=panelOpen(); // the journal, START, the talk log etc. sit above the phone: B closes them first if(!over&&phoneOpen&&curSlides){if(!$('gloss').hidden){hideGloss();return}if(dlg&&dlg.cur&&dlg.cur.slide(Array.isArray(a)?a:[a]).filter(t=>t!=null&&t!=='').map(t=>typeof t==='string'?{say:t}:t); // a missing line (an NPC with no after:) is no step, not a crash // a line, or a full step (set:, sfx:, …) function allQuestions(){ const out=[...(C.BANK||[])];Object.keys(C.Q).forEach(k=>{if(k!=='cafe')out.push(...C.Q[k])});return out; } /* In-character review (opt-in): a chapter's C.REVIEW lists lines people say that use a word you've learned — {w, by:'npcId'|'이름'|[…], ask, opts, pre?:[lines before it], when?:()=>bool, who?:'나'}. Whoever has a line for a word that is due asks it in their own voice (a friend, a teacher, a passer-by), and the answer grades the word as any review does. A chapter without C.REVIEW keeps the narrator's review of the person's own badge words. */ const npcId=n=>Object.keys(C.NPC).find(k=>C.NPC[k]===n); const metIds=()=>state.met||(state.met=[]),met=n=>!!n.badge||metIds().includes(npcId(n)); // someone you've talked to (a teacher always counts) function linesFor(n){ // their lines for words you have, true right now (when), due or not if(!C.REVIEW||(n.badge&&!n.badge.every(has)))return []; // someone still teaching teaches first if(!met(n))return []; // the first talk with anyone is their own (an introduction, a cameo), never a review const id=npcId(n); return C.REVIEW.filter(r=>[].concat(r.by).some(b=>b===id||b===n.name)&&known(r.w)&&(!r.when||r.when())); // known: this chapter's word you have, or one from another chapter (srs.shared) } const revAt={}; // when each person last asked a review: at most one per story beat (re-talking isn't a quiz machine) const cooling=n=>{const r=revAt[npcId(n)];return !!r&&(SRS().beats?r.b===beats():talkN-r.t<3)}; const cooledLine=r=>{const h=(state.heardB||{})[rKey(r)];return h==null||beats()-h>=3}; // a line just heard as plain talk isn't asked for a few beats const reviewLines=n=>cooling(n)?[]:linesFor(n).filter(r=>isDue(r.w)&&cooledLine(r)&&reviewable(r)); /* Spaced review decides when a line is a question, not whether you hear it: with nothing of theirs due, a person says one of their lines you haven't heard yet, the word filled in, as ordinary talk (state.heard keeps which), then their usual chatter. */ const rKey=r=>r.w+'|'+r.ask,heard=()=>state.heard||(state.heard=[]),unheard=r=>!heard().includes(rKey(r)); function hear(r){if(unheard(r)){heard().push(rKey(r));save()}} function sayLine(n){ const L=linesFor(n).filter(unheard);if(!L.length)return null; const r=L[Math.random()*L.length|0],ok=(r.opts||[]).find(o=>o[1]);hear(r);(state.heardB||(state.heardB={}))[rKey(r)]=beats(); if(r.plain)return [...says(r.pre||[]),{...(r.who?{who:r.who}:{}),say:r.plain}]; // plain: the line said when nothing is due, for a row that can't be filled in (a meaning question about an R word) return [...says(r.pre||[]),{...(r.who?{who:r.who}:{}),say:answered(r.ask,ok?ok[0]:r.w),enKey:r.ask}]; // its English is kept under the question as written } const usual=n=>n.badge?(n.badge.every(has)?says(n.after):null):(n.again&&metIds().includes(npcId(n))?says(typeof n.again==='function'?n.again():n.again):n.talk()); // again: what they say once you've met (no second introduction) // what they'd say anyway (null: still teaching) const moves=s=>['set','give','take','award','go','walk','leave','move','phone','culture','grammar','sit','choose','finale'].some(k=>k in s); function reviewPick(n){ const L=reviewLines(n);if(!L.length)return null; const rank=r=>lv(r.w).b*2+((n.badge||[]).includes(r.w)?0:1); // the weakest word first; their own word before someone else's const lo=Math.min(...L.map(rank)),best0=L.filter(r=>rank(r)===lo),fresh=best0.filter(unheard),best=fresh.length?fresh:best0,r=best[Math.random()*best.length|0];hear(r);revAt[npcId(n)]={b:beats(),t:talkN+1}; // a line you haven't heard first const q={...r,review:true};delete q.by;delete q.pre;delete q.when; if(q.who!=='나'&&!isR(q.w)&&canSpeak()&&soundOn&&listenOn&&Math.random()<.35){const ok=(q.opts||[]).find(o=>o[1]);q.listen=q.w;q.listenLine=answered(q.ask,ok?ok[0]:q.w)} // they say it aloud (the answer as it fits the line: 주워, not 줍다); you pick the word you heard return [...says(r.pre||[]),q]; } function reviewFor(words){ // pick a question for the weakest of these words const ws=[...words].sort((a,b)=>(isDue(b)-isDue(a))||(lv(a).b-lv(b).b)); const w=ws[0]; let pool=allQuestions().filter(q=>q.w===w&&reviewable(q)); if(!pool.length&&SRS().shared)pool=(carryBank()[w]||[]).filter(reviewable); // a word from another chapter: its own chapter's sentences if(C.REVIEW){const g=(C.BANK||[]).filter(q=>q.w===w&&!q.scene&&reviewable(q));if(g.length)pool=g} // with in-character review, the notebook asks the generic example sentences, not lines from someone's scene const gen=pool.filter(q=>!q.scene),all=gen.length?gen:pool; // scene:1 quotes its own scene: never asked in review (it would play the scene before it happens) const own=all.filter(q=>!q.gram),qs=own.length?own:all; // gram:1 tests a pattern, not the word: no star for the word from it if(!qs.length)return null; // nothing it can be asked with (a recognition word with no meaning question): no review, not a blank box const narr={review:true,who:'…',ok:T('맞아요!')}; /* asked by the narrator: the sentences are generic examples, not in the NPC's voice */ if(!isR(w)&&canSpeak()&&soundOn&&listenOn&&Math.random()<.35)return {listen:w,...narr}; // a muted phone (or 듣기 문제 off) can't answer a listening question return {...freshQ(w,qs),...narr}; } function terminal(){ const due=dueWords(),lk=lookDue(); if(!state.badges.length&&!due.length&&!lk.length)return [{who:TERM.name,say:TERM.empty}]; // empty only when there's nothing at all: earlier chapters' due words count (srs.shared) if(!due.length&&!lk.length){const n=nextDue();return [{who:TERM.name,say:TERM.idle+(n?` ${TERM.next}: ${fmtWait(n-now())} 후.`:'')}]} const size=Number.isInteger(TERM.batchSize)&&TERM.batchSize>0?TERM.batchSize:4,pick=shuffle(due.slice()).slice(0,size),steps=[]; // term.batchSize: positive integer, default 4 if(pick.length){steps.push({who:TERM.name,say:TERM.due(due.length,pick.length)});pick.forEach(w=>steps.push(reviewFor([w])))} // due(n,k): n words due, k asked this round if(lk.length){steps.push({who:TERM.name,say:T('찾아본 말도 볼까요?')});lk.slice(0,pick.length>=size?1:2).forEach(h=>steps.push(lookQ(h)))} // 찾아본 말 복습 steps.push({who:TERM.name,say:TERM.end}); return steps; } function facing(){ const [dx,dy]=D[player.dir];const tx=player.x+dx,ty=player.y+dy; let n=npcAt(tx,ty); if(!n&&(Z.legend[at(tx,ty)]||{}).over)n=npcAt(tx+dx,ty+dy); if(n)return {n}; if(petOn()&&pet.x===tx&&pet.y===ty&&!(pet.x===player.x&&pet.y===player.y))return {pet:1}; const key=tx+','+ty; {const L=Z.legend[at(tx,ty)];if(L&&(L.tile==='terminal'||L.term))return {term:1}} // the review computer: the 'terminal' tile, or any tile marked term:1 (a laptop, …) if(Z.spots&&Z.spots[key])return {spot:Z.spots[key]}; const w=warpAt(tx,ty);if(w&&w.lock&&w.lock())return {spot:w.lock()}; /* things: a line for every tile of a kind (Z.things[char] = text | [variants, picked by position] | fn(x,y) → either) */ const th=Z.things&&Z.things[at(tx,ty)],tv=typeof th==='function'?th(tx,ty):th; if(tv)return {spot:Array.isArray(tv)?tv[(tx*7+ty*13)%tv.length]:tv}; // tv may also be {steps:[…]} (a conversation) return null; } /* {chat:'id'} on someone who is answering another: [opener, answerer] when both are here, so either one plays the whole exchange */ function chatPair(n){ const L=live(),o=n.chat?C.NPC[n.chat]:L.find(m=>m.chat&&C.NPC[m.chat]===n); return o&&L.includes(o)&&!(o.badge&&o.badge.length)?(n.chat?[o,n]:[n,o]):null; } /* a conversation with n, as when you press A facing them (also a room's greeting) */ function talkWith(n){ const snap=JSON.stringify(state); // the save from before this talk (a script may change flags as it starts): 한 단계 뒤로 puts it back if(n.proxy){const p=n.proxy();if(p)n=p} const pair=chatPair(n); // two people talking to each other: they keep facing each other, and the one who started speaks first if(!pair&&!n.pos&&!sitting(n)&&!n.fixed){n.dir=OPP[player.dir];n.turnAt=performance.now()+6000} // fixed: furniture (a chair) never turns to face you let steps=n.script?n.script():null,isReview=false,extra=null; if(!steps&&C.REVIEW){const own=usual(n),rv=own&&!own.some(moves)?reviewPick(n):null; // a talk that moves the story goes first; the review waits for the next talk if(rv){const q=rv[rv.length-1],stems=[q.w.replace(/다$/,''),q.w.replace(/하다$/,'')].filter(x=>x),gives=t=>stems.some(x=>(t.say||'').includes(x)); // their usual line goes first, unless it says the very word they're about to ask (흥정해 → 흥정하다) steps=[...(n.badge?own.filter(t=>!gives(t)):[]),...rv];isReview=true} else{const sl=own&&!own.some(moves)?sayLine(n):null;if(sl&&pair){extra=sl;steps=own||n.talk()}else steps=sl?[...(n.badge?own:[]),...sl]:own||n.talk()}} // in a pair the extra line comes after their exchange: in place of the opener, the friend answered a line nobody said if(!steps){ if(n.badge&&n.badge.every(has)){const due=n.badge.some(isDue);steps=due?[...says(n.after),reviewFor(n.badge)]:says(n.after);isReview=due} // a review question only when one of their words is due else steps=n.talk(); } {const id=npcId(n);if(id&&!metIds().includes(id)){metIds().push(id);save()}if(id&&status(n)==='star')starAcc[id]=Math.max(starAcc[id]||0,STAR_MS)} // met: from now on they can review and chat; a ★ over them starts to fade once you've talked if(pair&&isReview&&!n.pos&&!sitting(n)&&!n.fixed){n.dir=OPP[player.dir];n.turnAt=performance.now()+6000} // a review question is for you: the one asking turns to you (and back to their friend after, as after any talk) if(pair&&!isReview){const said=m=>(m===n?steps:(m.script&&m.script())||m.talk()).map(s=>s.who?s:{...s,who:m.name,look:m.look});steps=[...said(pair[0]),...said(pair[1]),...(extra||[]).map(s=>s.who?s:{...s,who:n.name,look:n.look})]; for(const m of pair){const id=npcId(m);if(id&&!metIds().includes(id)){metIds().push(id);save()}}} // both of them spoke: both count as met, so either can ask a review next time (not only the one you faced) openDialog(n.name,steps,{npc:n,review:isReview,snap}); } function interact(){ if(phoneOpen&&curChat){if(!$('gloss').hidden){hideGloss();return}if(choosing()){confirmSel();return}if(dlg)advance();return} if(phoneOpen&&curSlides){if(!$('gloss').hidden){hideGloss();return}if(dlg)advance();else closePhone();return} // the postcard: A is the next card // a chat: A is the next message, or sends the reply if(phoneOpen){if(!$('gloss').hidden){hideGloss();return}if(typing&&!typing.finished){typing.fin();return}closePhone();if(dlg&&dlg.cur&&dlg.cur.phone&&!(dlg.cur.say||'').trim())advance();return} // A finishes the line, then puts the phone away (a step that is only the phone goes on: no empty box left behind) if(!$('gloss').hidden){hideGloss();return} // A closes the definition first, without advancing if(panelOpen())return; if(choosing()||building()){confirmSel();return} if(dlg){advance();return} if(performance.now()-closedAt<650)return; // the tap that closed a talk, doubled, doesn't reopen it if(player.moving||warping)return; const F=facing();if(!F)return; if(F.n){talkWith(F.n);return} if(F.pet){openDialog(C.FOLLOW.name,C.FOLLOW.talk());return} if(F.term){openDialog(TERM.name,terminal(),{review:true});return} if(F.spot){openDialog('…',F.spot.steps||says(F.spot))} } function award(words){ const nw=words.filter(w=>!has(w));if(!nw.length)return; state.badges.push(...nw); const perfect=nw.filter(w=>!dlg.missed.has(w)&&!(state.miss&&state.miss[w]));if(state.miss)nw.forEach(w=>delete state.miss[w]); // state.miss: a word missed in a talk left early (B) still counts as missed const L0=SRS().start??2; // srs.start: the level of a word answered right every time it was taught (★ is level 3) nw.forEach(w=>{const L=perfect.includes(w)?spaced(L0):{b:0,due:now()};if(!RP||!state.lv[w]||L.b>state.lv[w].b)state.lv[w]=L}); // 다시 보기: only ever up save();updateHud();sfx('badge'); toast((G.gotToast||T('일지에 추가'))+': '+nw.join(', ')); // GAME.gotToast: the game's word for it (단어 마을: 배지 획득) const note=perfect.length===nw.length ?{who:LOGNAME,say:G.ui&&G.ui.awardPerfect?G.ui.awardPerfect(nw,L0):`한 번도 안 틀렸어요! "${nw.join('", "')}" 기억 레벨 ${L0}/5.`} :{who:LOGNAME,say:G.ui&&G.ui.awardMissed?G.ui.awardMissed(nw):`일지에 적었어요. 틀린 단어는 곧 다시 나와요. 머리 위의 ?를 찾아요.`}; if(firstTime(perfect.length===nw.length?'awardPerfect':'awardMissed'))dlg.steps.splice(dlg.i+1,0,note); if(state.badges.length>=C.WORDS.length&&!state.f.allWords){state.f.allWords=1;save();const all=TERM.allWords(C.WORDS.length);if(all&&all.length)pending=says(all)} // term.allWords(n): the note when the last word is in ([] = none) } function finish(pre){ if(!state.counted){state.counted=1;save();countPlay('done')} // once per chapter in this browser $('fade').classList.add('on');sfx('star'); setTimeout(()=>{$('fade').classList.remove('on');const nx=nextChapterAsk('');openDialog('…',(pre||[]).map(s=>({who:LOGNAME,...s})).concat(says(C.DONE),nx.steps||[])) /* the ending is narration, then: on to the next chapter? */},900); } let toastT;function toast(t){const el=$('toast');el.textContent=t;el.hidden=false;clearTimeout(toastT);toastT=setTimeout(()=>el.hidden=true,2400)} /* ---------- HUD + log ---------- */ function updateHud(){const n=state.badges.length,st=C.WORDS.filter(w=>has(w)&&lv(w).b>=3).length;$('logBtn').textContent=`${G.hud||'일지'} ${n}/${C.WORDS.length}`+(st?` ★${st}`:'');fitReg()} /* the header label (room · 교시 title): tighten its letter spacing, then its size, before it would be cut off (…) next to a wide 일지 badge */ function fitReg(){const e=$('reg');if(!e)return;e.style.letterSpacing=e.style.fontSize='';const f0=parseFloat(getComputedStyle(e).fontSize); for(const [ls,k] of [['.08em',1],['.03em',1],['.02em',.92],['0',.86]]){if(e.scrollWidth<=e.clientWidth)return;e.style.letterSpacing=ls;e.style.fontSize=k<1?f0*k+'px':''}} addEventListener('resize',()=>fitReg()); /* phones: the first tap goes fullscreen (browsers allow it only from a tap, and only on release for touch), hiding the status and address bars: in landscape they took a third of the height and shrank the game. Tried once per visit: a player who leaves fullscreen stays out until the next load. (iPhone Safari has no fullscreen for pages; nothing happens there.) */ {let fsTried=false;const fs=()=>{if(fsTried||document.fullscreenElement||!matchMedia('(pointer:coarse)').matches||!document.documentElement.requestFullscreen)return; fsTried=true;document.documentElement.requestFullscreen({navigationUI:'hide'}).catch(()=>{})}; addEventListener('pointerup',fs,true);addEventListener('touchend',fs,true)} function updateQuest(){$('questTxt').textContent=C.questText();countStep();$('quest').classList.toggle('late',!!(C.questLate&&C.questLate()))} // questLate: the goal is overdue (shell CSS .quest.late) function updateRead(){$('readBtn').setAttribute('aria-pressed',readOn&&canSpeak()?'true':'false');$('spk').hidden=!canSpeak()} function updateSound(){$('sndBtn').setAttribute('aria-pressed',soundOn?'true':'false')} let logSel=null,showEn=false; function pips(w){const L=lv(w);return `${[1,2,3,4,5].map(i=>``).join('')}`} function openPanel(){ renderNotes();renderPostcards();if($('itemCard'))$('itemCard').hidden=true; const got=C.WORDS.filter(has); $('logCount').textContent=`${got.length}/${C.WORDS.length} · ${T('복습')} ${dueWords().length}`; if(!logSel||!has(logSel))logSel=got[got.length-1]||null; $('wlist').innerHTML=C.WORDS.map(w=>has(w)?``:`
?
`).join(''); $('wlist').querySelectorAll('button.wd').forEach(b=>b.addEventListener('click',()=>{logSel=b.dataset.w;showEn=false;openPanel();speak(logSel)})); if(logSel){const d=C.DICT[logSel],L=lv(logSel); $('card').innerHTML=`
${logSel}${d.r&&d.r!==logSel?`${d.r}`:''}
${d.k}${d.reg?`${T('말투')}: ${d.reg}`:''}${d.note?`${T('참고')}: ${d.note}`:''}${T('예')}: ${G.tappableExamples?glossHTML(d.ex):plain(d.ex)}${d.hj?`${d.hj}`:''} ${T('기억 레벨')} ${L.b}/5 · ${isDue(logSel)?T('지금 복습할 수 있어요'):T('다음 복습: ')+fmtWait(L.due-now())+T(' 후')} ${showEn?`${d.e}${d.reg&&lineEn(d.reg)?' · '+lineEn(d.reg):''}`:''}`; $('cardSpk')?.addEventListener('click',()=>speak(logSel+'. '+plain(d.ex))); $('cardEn')?.addEventListener('click',()=>{showEn=true;openPanel()}); // its own id: it once shared the dialogue's #enBtn, so this handler went onto the line's ? (re-rendering the 일지 on every tap) if(G.tappableExamples)$('card').onclick=e=>{if(e.target.closest('.ex'))panelWordTap(e)}; }else $('card').innerHTML=''+T('아직 단어가 없어요.')+''+T('사람들한테 말을 걸면 일지에 단어가 생겨요.')+''; $('items').innerHTML=state.items.length?state.items.map((i,k)=>`
  • ${String(i).replace(/`).join(''):'
  • '+T('비어 있어요.')+'
  • '; /* tap an item to read it again (the 복숭아 쪽지 that starts it all): its description in the card; an item with a photo (C.PHOTOS) opens it */ $('items').querySelectorAll('li[data-k]').forEach(li=>li.addEventListener('click',()=>{const name=state.items[+li.dataset.k],ph=(C.PHOTOS||{})[name]; if(ph){$('panel').hidden=true;openPhone(ph);return} $('items').querySelectorAll('li').forEach(x=>x.classList.toggle('sel',x===li)); let ic=$('itemCard');if(!ic){ic=document.createElement('div');ic.id='itemCard';ic.className='card';$('items').after(ic);ic.addEventListener('click',panelWordTap)} // right under the bag, not in the word card at the top (out of view) ic.innerHTML=`
    ${String(name).replace(/
    ${glossHTML(String(C.ITEMS[name]||''))}`;ic.hidden=false;ic.scrollIntoView({block:'nearest'})})); $('panel').hidden=false; } /* ---------- saving ---------- */ function fresh(){const st=CH.start;return {v:1,zone:st.zone,x:st.x,y:st.y,dir:st.dir,badges:[],lv:{},items:[],f:{},seenIntro:false}} /* CH.resumeIntro:true opts in: save a pending introduction, mark seen only after the last line is advanced. Reload replays the unfinished introduction; author its effects idempotently. Legacy seenIntro:true saves remain complete unless CH.migrate clears it using a chapter-specific old checkpoint. introPending:false distinguishes native completed saves from legacy ones. B advances a pending intro. Other chapters retain their original intro behavior. */ function beginIntro(){ const resumable=!!CH.resumeIntro; if(resumable){state.introPending=true;state.seenIntro=false}else state.seenIntro=true; save();const ch=CH; setTimeout(()=>{if(CH!==ch)return;if(!(C.INTRO||[]).length){if(resumable){state.seenIntro=true;state.introPending=false;save()}return} openDialog(CH.introWho||G.title||T('이야기'),C.INTRO,{intro:resumable})},300); } function save(){store.set(SK(),JSON.stringify(state));if(SRS().shared)store.set(KEY('lv'),JSON.stringify(state.lv));else if(RP)liftReal()} const higher=(to,from)=>{for(const [w,L] of Object.entries(from||{}))if(!to[w]||to[w].bpad.querySelector(`button[data-d="${d}"]`);let pid=null,cur=null; const dirAt=e=>{const r=pad.getBoundingClientRect(),dx=e.clientX-(r.left+r.width/2),dy=e.clientY-(r.top+r.height/2),dz=r.width/8; if(Math.abs(dx)Math.abs(dy)?(dx>0?'right':'left'):(dy>0?'down':'up')}; const set=d=>{if(d===cur)return;if(cur){btn(cur)?.classList.remove('on');if(held===cur)held=null}cur=d;if(!d)return; btn(d)?.classList.add('on');if(dirPress(d))return;held=d;pressN++;if(dlg)return;tryMove()}; // each new direction is a new press (menus move once, the follower rule counts it) pad.addEventListener('pointerdown',e=>{e.preventDefault();if(pid!==null)return;pid=e.pointerId;try{pad.setPointerCapture(e.pointerId)}catch(_){}set(dirAt(e))}); pad.addEventListener('pointermove',e=>{if(e.pointerId===pid)set(dirAt(e))}); const off=e=>{if(e.pointerId!==pid)return;pid=null;set(null)}; for(const t of ['pointerup','pointercancel','lostpointercapture'])pad.addEventListener(t,off);} $('btnA').addEventListener('pointerdown',e=>{e.preventDefault();interact()}); $('btnB').addEventListener('pointerdown',e=>{e.preventDefault();cancel()}); $('dlg').addEventListener('click',e=>{if($('txt').classList.contains('lhide')&&!e.target.closest('#spk')){$('txt').classList.remove('lhide');return} // 듣기: the first tap shows the line const gl=e.target.closest('.gl');if(gl){e.stopPropagation();showGloss(gl.dataset.k,gl);return}const w=e.target.closest('.txt .w');if(w){e.stopPropagation();showWord(w.dataset.w||w.textContent,w);return}if(e.target.closest('#spk'))return;advance()}); $('spk').addEventListener('click',e=>{e.stopPropagation();if(dlg)speak(dlg.cur.listenLine||dlg.cur.listen||dlg.cur.say||dlg.cur.ask||'')}); $('gloss').addEventListener('click',e=>{if(e.target.closest('.gx'))hideGloss()}); // × closes; A and B close too $('choices').addEventListener('pointerdown',e=>{const b=e.target.closest('.choice');if(b){sel=choiceBtns().indexOf(b);markSel()}}); $('logBtn').addEventListener('click',()=>{showEn=false;openPanel()}); $('talkBtn').addEventListener('click',openTalk); /* 나 꾸미기 panel: pick a look; the walk sprite and talk portrait preview live */ const ME_OPTS={style:[['short',T('짧은 머리')],['long',T('긴 머리')],['bob',T('단발')],['bun',T('올림머리')],['spiky',T('삐죽 머리')],['bald',T('민머리')]], hair:['#1E1B22','#4A3426','#7A4B2A','#C9A15A','#B23A3A','#5A6FA8','#D8D2C4'],skin:['#F6D7BD','#F1C9A5','#E2AE86','#C68A5E','#8E5A3C']}; let meDraft=null,meDone=null; function drawMePreview(){ const L={...CREW_LOOK,...meDraft};drawPortrait($('meFace'),L,'happy',false); const c=$('meWalk').getContext('2d');c.clearRect(0,0,16,24);const rows=humanArt(L,'down',0),pal=humanPal(L); rows.forEach((r,y)=>[...r].forEach((ch,x)=>{const col=pal[ch];if(col&&ch!=='.'){c.fillStyle=col;c.fillRect(x,y,1,1)}})); for(const b of $('meOpts').querySelectorAll('[data-k]'))b.classList.toggle('on',b.dataset.t?!!meDraft[b.dataset.k]&&meDraft[b.dataset.k]!=='0':String(meDraft[b.dataset.k])===b.dataset.v); } function openMe(done){ meDraft={style:'short',hair:'#1E1B22',skin:'#F1C9A5',lashes:0,lips:0,...(me||{})};meDone=done||null; const sw=(k,v,label,bg)=>``; $('meOpts').innerHTML=`
    머리 모양
    ${ME_OPTS.style.map(([v,l])=>sw('style',v,l)).join('')}
    머리 색
    ${ME_OPTS.hair.map((v,i)=>sw('hair',v,'머리 색 '+(i+1),1)).join('')}
    피부
    ${ME_OPTS.skin.map((v,i)=>sw('skin',v,'피부 '+(i+1),1)).join('')}
    얼굴
    `; drawMePreview();$('mePanel').hidden=false; } function closeMe(keep){ if(keep){me={...meDraft};if(me.lashes==='0'||!+me.lashes)delete me.lashes;else me.lashes=1;if(!me.lips||me.lips==='0')delete me.lips; store.set(ME_KEY,JSON.stringify(me));if(typeof C.PLAYER!=='function')player.look=myLook(C.PLAYER||CREW_LOOK);toast(T('반가워요! 👋'))} $('mePanel').hidden=true;const d=meDone;meDone=null;if(d)d(); } if(CREATOR)$('meOpts').addEventListener('click',e=>{const b=e.target.closest('[data-k]');if(!b)return;const k=b.dataset.k,on=meDraft[k]&&meDraft[k]!=='0'; meDraft[k]=b.dataset.t?(on?'0':b.dataset.v):b.dataset.v;drawMePreview()}); // data-t = an on/off toggle if(CREATOR)$('meRandom').addEventListener('click',()=>{const pick=a=>a[Math.random()*a.length|0];meDraft={style:pick(ME_OPTS.style)[0],hair:pick(ME_OPTS.hair),skin:pick(ME_OPTS.skin),lashes:pick(['1','0']),lips:pick(['#C25B6A','0'])};drawMePreview()}); if(CREATOR)$('meOk').addEventListener('click',()=>closeMe(true)); if(CREATOR)$('meBtn').addEventListener('click',()=>openMe()); /* START: everything that isn't the game itself (logs, dictionary, chapters, reading aloud, sound) */ /* 업데이트: build.py stamps globalThis.BUILD {v: a hash of the whole game, t: when that version first appeared} and writes the same to version.json next to the page. START shows when it was updated; reports carry v. A game left open (phones keep tabs for days) checks version.json when the player comes back to it and every 30 minutes; on a newer one it reloads at a calm moment (no talk, no panel, not walking or between rooms, so everything is saved) and says so in a toast. Each new version is tried once per tab (sessionStorage), so a cache still serving the old page right after a push can't loop; ?v= asks for a fresh copy. */ const VER=globalThis.BUILD||{};let newVer=null; async function checkVersion(){ if(!VER.v||location.protocol==='file:'||newVer)return; try{const r=await fetch('version.json?t='+Date.now(),{cache:'no-store'}),j=r.ok?await r.json():{}; let tried=null;try{tried=sessionStorage.getItem(KEY('tried'))}catch(e){} if(j.v&&j.v!==VER.v&&j.v!==tried)newVer=j.v}catch(e){} } function updateNow(){ if(!newVer||!state||dlg||panelOpen()||document.querySelector('.panel:not([hidden])')||warping||player.moving||held)return; try{sessionStorage.setItem(KEY('tried'),newVer)}catch(e){} save();store.set(KEY('updated'),newVer); const u=new URL(location.href);u.searchParams.delete('count');u.searchParams.set('v',newVer);location.replace(u.href); } addEventListener('visibilitychange',()=>{if(!document.hidden)checkVersion()}); setInterval(checkVersion,30*60e3);setTimeout(checkVersion,60e3);setInterval(updateNow,1000); const buildDate=()=>{const d=new Date(VER.t||'');return isNaN(d)?'':d.toLocaleString(G.lang||'ko-KR',{month:'long',day:'numeric',hour:'numeric',minute:'2-digit'})}; if(VER.v){const p=document.createElement('p');p.id='verLine';p.style.cssText='font-size:.72rem;opacity:.55;margin:12px 0 0;text-align:center'; p.textContent=(buildDate()?T('업데이트')+' '+buildDate()+' · ':'')+VER.v;$('startPanel').querySelector('.sheet').append(p) /* 디버그 on or off in any browser or the app: tap the version line 5 times within 2 s (the same switch ?debug=1 / ?debug=0 sets), then a reload */ let n=0,t0=0;p.addEventListener('click',()=>{const t=Date.now();n=t-t0<2000?n+1:1;t0=t;if(n<5)return;n=0; const on=store.get('walk-debug-ok')!=='1';store.set('walk-debug-ok',on?'1':'0');toast(on?'디버그 켬 · 다시 불러와요':'디버그 끔 · 다시 불러와요');setTimeout(()=>location.reload(),900)})} /* 통계: anonymous counts go to the same server: the game opened (each page load), a chapter started (its first time in this browser), each objective reached in it (how far players get; once each, in the order reached), finished, and the first real tap or key in a visit (so the dashboard counts people, not bots that only load the page). No ID and no cookie: the server only keeps the day and a tag that changes every day (people per day). Only from the published site, so the playtests (file://) never count, nor a browser that says it's automated (navigator.webdriver); the server also drops bots by user agent. Opening any game once with ?count=0 leaves that browser out for good (all the games share stan-stani.github.io, so one visit covers them all); ?count=1 puts it back. */ const COUNT_URL='https://seldoncortex.com/api/word-reports/count',countQ=new URLSearchParams(location.search).get('count'); if(countQ==='0'||countQ==='1')store.set('walk-count',countQ); const COUNT_ON=location.hostname==='stan-stani.github.io'&&!navigator.webdriver&&store.get('walk-count')!=='0'; /* the first real tap or key in a visit: a person, not a bot that only loads the page (script-made events aren't trusted) */ {let touched=false;const first=e=>{if(touched||!e.isTrusted||!CH)return;touched=true;countPlay('input')}; addEventListener('keydown',first,true);addEventListener('pointerdown',first,true)} function countPlay(ev,more){if(COUNT_ON)try{navigator.sendBeacon(COUNT_URL,JSON.stringify({game:G.prefix,ev,ch:CH.id,...more}))}catch(e){}} /* a step is the objective's text (numbers as #, so "3/9" doesn't make new steps). Only for a chapter started since steps were counted (state.steps made at its start), so an old save doesn't report its current objective as step 1 */ function countStep(){ if(!Array.isArray(state.steps)||state.steps.length>=40)return; const q=String((C.questText&&C.questText())||'').replace(/\d+/g,'#').trim().slice(0,60); if(!q||state.steps.includes(q))return; state.steps.push(q);save();countPlay('step',{step:q,n:state.steps.length}); } /* 문제 알리기: a report goes to the word-reports inbox on seldoncortex.com. Artifacts can't call other sites, so 보내기 is a plain link that carries the report after the # (never in server logs); the page there posts it once and says thanks. 보내기 stays dim (no link) until the note says something: the page sends as soon as it opens, so a curious tap once sent an empty report. */ const REPORT_URL='https://seldoncortex.com/word-reports/';let lastLines=[],repKind='game',lastWord=''; function reportCtx(){ return {chapter:CH.n+' '+CH.title,place:roomName||Z.name,zone:ZID,pos:player.x+','+player.y,objective:(C.questText&&C.questText())||'', line:dlg&&dlg.cur?lastLines[lastLines.length-1]:'',lines:lastLines.join('\n'),word:lastWord} } function reportHref(){ const r={game:G.prefix,kind:repKind,note:$('repNote').value.trim().slice(0,1000),build:(VER.v||'dev')+' '+CH.id,ctx:reportCtx()}; const b=new TextEncoder().encode(JSON.stringify(r));let bin='';b.forEach(x=>bin+=String.fromCharCode(x)); return REPORT_URL+'#'+btoa(bin).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); } function openReport(){ if(!$('repPanel')){ const P=document.createElement('div');P.className='panel';P.id='repPanel';P.hidden=true; P.innerHTML=``; document.body.append(P); P.addEventListener('click',e=>{if(e.target===P)closeReport()});$('repClose').addEventListener('click',closeReport); $('repGame').addEventListener('click',()=>setRepKind('game'));$('repKo').addEventListener('click',()=>setRepKind('korean')); $('repNote').addEventListener('input',syncSend); $('repSend').addEventListener('click',e=>{if(!$('repNote').value.trim()){e.preventDefault();$('repNote').focus();return} $('repSend').href=reportHref();setTimeout(()=>{closeReport();$('repNote').value='';syncSend();toast(T('고마워요!'))},300)}); } const c=reportCtx();$('repCtx').textContent=[c.chapter+' · '+c.place,c.line||lastLines[lastLines.length-1]||'',c.word?'단어: '+c.word:''].filter(Boolean).join('\n'); setRepKind(repKind);$('repPanel').hidden=false;document.body.classList.add('talkopen');hideGloss(); } function setRepKind(k){repKind=k;$('repGame').classList.toggle('on',k==='game');$('repKo').classList.toggle('on',k==='korean');syncSend()} function syncSend(){const ok=!!$('repNote').value.trim(),a=$('repSend');if(ok)a.href=reportHref();else a.removeAttribute('href');a.setAttribute('aria-disabled',String(!ok));a.style.opacity=ok?'':'.45'} // no note, no link function closeReport(){$('repPanel').hidden=true;document.body.classList.remove('talkopen')} function toggleStart(){const P=$('startPanel');if(P.hidden&&panelOpen())return;P.hidden=!P.hidden;hideGloss();if(!P.hidden)nowCard()} /* a button the engine adds to the START menu goes into the first gap (a lone half-width button before a wide one, e.g. 소리 above 듣기 문제), else after the last lone one, else on a row of its own */ function menuAdd(b){const g=$('startPanel').querySelector('.mgrid');if(!g)return;let col=0; for(const c of g.children){if(c.hidden||getComputedStyle(c).display==='none')continue; if(c.classList.contains('wide')){if(col===1){g.insertBefore(b,c);return}col=0}else col^=1} if(col===0)b.classList.add('wide');g.append(b)} /* 영어 자막: the on/off for ?en=1's English under every line, only for someone who has opened that link (others never see it) */ if(window.LINES_EN&&store.get(KEY('enAll'))!==null){const b=document.createElement('button');b.className='mi toggle';b.id='enAllBtn';b.textContent=T('영어 자막'); const upd=()=>b.setAttribute('aria-pressed',String(enAll));upd();menuAdd(b); b.addEventListener('click',()=>{enAll=!enAll;store.set(KEY('enAll'),enAll?'1':'0');upd();sfx('ok'); const d=$('txtEn');if(d&&d.textContent){d.hidden=!enAll;$('enBtn').classList.toggle('on',enAll)}toast(enAll?T('영어 자막을 켰어요.'):T('영어 자막을 껐어요.'))})} /* ---------- 저장 옮기기 (START): every walk game's progress in this browser as a file, to carry to another browser or the Android app. 내보내기 saves walk-saves-.json (a download; in the app, Downloads/WalkGames, where its own backups go); 가져오기 opens the file picker, says what's in the file, and on a second tap writes it over this browser's saves (keys it doesn't have are left alone) and reloads, so no game still open can save its old state over it. A file, not the clipboard: a big text copy can fail silently on a phone. All the games share stan-stani.github.io, so one file carries all of them; walk-count (left out of 통계) stays this browser's own. Plain JSON: {walkSaves:1, from, t, data:{key: value}}, the format of the app's backups. ---------- */ function savesText(){const data={};for(let i=0;iString(n).padStart(2,'0');return `walk-saves-${x.getFullYear()}${p2(x.getMonth()+1)}${p2(x.getDate())}-${p2(x.getHours())}${p2(x.getMinutes())}${p2(x.getSeconds())}.json`} function openSaves(){ let p=$('savePanel'); if(!p){p=document.createElement('div');p.className='panel';p.id='savePanel';p.hidden=true; p.innerHTML=``; $('tapPanel').after(p); let pending=null;const msg=t=>{$('saveMsg').textContent=t},inBtn=$('saveIn'); const disarm=()=>{pending=null;inBtn.classList.remove('armed');inBtn.textContent=T('가져오기')}; $('saveClose').addEventListener('click',()=>{p.hidden=true;document.body.classList.remove('talkopen');backToMenu()}); p.addEventListener('click',e=>{if(e.target===p)$('saveClose').click()}); $('saveOut').addEventListener('click',()=>{disarm();const txt=savesText(),name=savesName(); if(window.WalkFiles){msg(WalkFiles.save(name,txt)?T('저장했어요')+': Download/WalkGames/'+name:T('저장하지 못했어요.'));return} // the app: Downloads/WalkGames const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([txt],{type:'application/json'}));a.download=name;document.body.append(a);a.click();a.remove(); setTimeout(()=>URL.revokeObjectURL(a.href),10000);msg(T('저장했어요')+': '+name)}); inBtn.addEventListener('click',()=>{ if(!pending){$('saveFile').value='';$('saveFile').click();return} // first: pick the file for(const [k,v] of Object.entries(pending))try{localStorage.setItem(k,v)}catch(err){msg(T('저장할 자리가 모자라요.'));return} store.set=()=>{};location.reload()}); // then: written, and reloaded before anything of the old game is saved over it $('saveFile').addEventListener('change',async()=>{const f=$('saveFile').files[0];if(!f)return; let txt='';try{txt=await f.text()}catch(e){} const data=readSaves(txt);if(!data){disarm();msg(T('저장 파일이 아니에요.')+' ('+f.name+')');return} let when='';try{when=new Date(JSON.parse(txt).t).toLocaleString()}catch(e){} pending=data;inBtn.classList.add('armed');inBtn.textContent=T('한 번 더 누르면 덮어써요'); msg(`${f.name}: ${unit(Object.keys(data).length,'개')}${when?' · '+when:''}`)}); } $('saveMsg').textContent='';p.hidden=false;document.body.classList.add('talkopen'); } /* 가로 화면 (START, phones): fullscreen plus a landscape lock, the only way a page may lock the screen (Android Chrome and Firefox; iPhone Safari can't, and the app's WebView has no fullscreen: it isn't offered there, turning the phone still works). Leaving fullscreen drops the lock; the choice (walk-landscape, every game) comes back with the first tap after the next load. */ const landOK=matchMedia('(pointer:coarse)').matches&&!!document.documentElement.requestFullscreen&&!!(screen.orientation&&screen.orientation.lock)&&!window.WalkFiles; let landOn=false; function landLock(){return (document.fullscreenElement?Promise.resolve():document.documentElement.requestFullscreen({navigationUI:'hide'})) .then(()=>screen.orientation.lock('landscape')).then(()=>{landOn=true;store.set('walk-landscape','1');updLand()})} const updLand=()=>{const b=$('landBtn');if(b)b.setAttribute('aria-pressed',landOn?'true':'false')}; if(landOK){const b=document.createElement('button');b.className='mi toggle';b.id='landBtn';b.textContent=T('가로 화면'); b.addEventListener('click',()=>{if(landOn){try{screen.orientation.unlock()}catch(e){}landOn=false;store.set('walk-landscape','');updLand();return} landLock().catch(()=>{landOn=false;updLand();toast(T('이 브라우저는 화면을 돌릴 수 없어요.'))})}); menuAdd(b);updLand(); document.addEventListener('fullscreenchange',()=>{if(!document.fullscreenElement&&landOn){landOn=false;updLand()}}); if(store.get('walk-landscape')==='1'){const again=()=>{removeEventListener('pointerup',again,true);if(landOn)return; // the first-tap fullscreen above usually asks first (a second request meanwhile is refused): lock once it's in, or ask ourselves let done=false;const go=()=>{if(done)return;done=true;landLock().catch(()=>{})}; if(document.fullscreenElement)go();else{document.addEventListener('fullscreenchange',go,{once:true});setTimeout(go,800)}}; addEventListener('pointerup',again,true)}} {const b=document.createElement('button');b.className='mi';b.id='saveBtn';b.textContent=T('저장 옮기기');b.addEventListener('click',()=>{$('startPanel').hidden=true;openSaves()});menuAdd(b)} {const b=document.createElement('button');b.className='mi';b.id='repBtn';b.textContent=T('문제 알리기');b.addEventListener('click',()=>{$('startPanel').hidden=true;openReport()});menuAdd(b)} $('startBtn').addEventListener('click',toggleStart);$('startClose').addEventListener('click',()=>$('startPanel').hidden=true); $('startPanel').addEventListener('click',e=>{if(e.target.id==='startPanel'){$('startPanel').hidden=true;return} const mi=e.target.closest('.mi');if(mi&&!mi.classList.contains('toggle')){fromMenu=!$('startPanel').hidden&&['talkBtn','tapBtn'].includes(mi.id);$('startPanel').hidden=true}},true); // capture: close the menu before the item opens its panel (the talk log and dictionary go back to it on 닫기) $('tapBtn').addEventListener('click',openTaps);$('tapClose').addEventListener('click',closeTaps); $('tapSortT').addEventListener('click',()=>{tapSort='t';openTaps()});$('tapSortN').addEventListener('click',()=>{tapSort='n';openTaps()}); $('tapPanel').addEventListener('click',e=>{if(e.target.id==='tapPanel'){closeTaps();return}const p=e.target.closest('.tp');if(p){const en=p.querySelector('.tpe');en.hidden=!en.hidden}});$('talkClose').addEventListener('click',closeTalk); $('talkPanel').addEventListener('click',e=>{if(e.target.id==='talkPanel'){closeTalk();return}const gl=e.target.closest('.gl');if(gl){showGloss(gl.dataset.k,gl);return}const w=e.target.closest('.w');if(w)showWord(w.dataset.w||w.textContent,w)}); /* debug (START → 디버그, saved per game): a 건너뛰기 button on every conversation runs it to the end — right answers, finished word orders, every flag / item / word it sets, quietly — and stops at a real decision (a plain choice like "2교시로 갈까요?"). For testing. */ /* only for development: shown off the published site (file://, localhost: the playtests) and in a browser that opened ?debug=1 once (all the games share it; ?debug=0 hides it again), so players never get a skip button */ {const q=new URLSearchParams(location.search).get('debug');if(q==='0'||q==='1')store.set('walk-debug-ok',q)} const debugOK=location.hostname!=='stan-stani.github.io'||store.get('walk-debug-ok')==='1'; let debugOn=debugOK&&store.get(KEY('debug'))==='1'; /* 한 단계 뒤로 (debug: in the 일지, by 처음부터): every talk that moves the story keeps this chapter's save from just before it (the last 12). The button puts the last one back and loads the chapter from it, as the chapter menu would, so nothing is undone by hand and nothing is left half undone. The talk's own story steps are gone; words you met still count (the shared word memory stays). */ const backKey=()=>SK()+'~back'; function backList(){try{return JSON.parse(store.get(backKey())||'[]')||[]}catch(e){return []}} function pushBack(snap){if(!snap)return;const L=backList();L.push({s:snap,b:beats()});store.set(backKey(),JSON.stringify(L.slice(-12)));updBack()} function updBack(){const b=$('backBtn');if(!b)return;const n=backList().length;b.hidden=!debugOn;b.disabled=!n;b.textContent='한 단계 뒤로'+(n?` (${n})`:'')} function stepBack(){const L=backList(),e=L.pop();if(!e)return; store.set(backKey(),JSON.stringify(L));store.set(CH.save,e.s);store.set(KEY('beats'),String(e.b||0));beatsN=null; boot(CH.id);sfx('door');toast('한 단계 뒤로 · '+C.questText())} function skipTalk(){ const snd=soundOn;soundOn=false; for(let n=0;dlg&&n<500;n++){ if(typing&&!typing.finished)typing.fin(); const s=dlg.cur; if(s.choose)break; if(s.ask&&!dlg.next){choose(s,s.opts.findIndex(o=>o[1]));continue} if(s.build&&!dlg.next){for(let i=s.got;i{const grid=document.querySelector('#startPanel .mgrid');if(!grid)return; if(debugOK){const b=document.createElement('button');b.className='mi toggle';b.id='dbgBtn';b.setAttribute('aria-pressed','false');b.textContent=T('디버그');menuAdd(b)} $('spk').insertAdjacentHTML('beforebegin',''); $('resetBtn').insertAdjacentHTML('beforebegin',''); const upd=()=>{$('dbgBtn')?.setAttribute('aria-pressed',debugOn?'true':'false');$('skipBtn').hidden=!debugOn;$('sceneBtn').hidden=!debugOn;updBack()};upd(); $('sceneBtn').addEventListener('click',()=>{$('panel').hidden=true;sceneMenu(CH,true)}); // debug: any chapter's moments, in the replay save $('dbgBtn')?.addEventListener('click',()=>{debugOn=!debugOn;store.set(KEY('debug'),debugOn?'1':'0');upd();sfx('ok');toast(debugOn?'디버그: 대화에 건너뛰기 버튼':'디버그 꺼짐')}); $('skipBtn').addEventListener('click',e=>{e.stopPropagation();skipTalk()}); $('backBtn').addEventListener('click',stepBack); })(); $('sndBtn').addEventListener('click',()=>{soundOn=!soundOn;store.set(KEY('sound'),soundOn?'1':'0');updateSound();sfx('ok');updateMusic()}); /* ---------- music ---------- */ /* A looping track per room (zone music:) or per chapter (MUSIC), a path or a function of the story so far; '' or null is quiet. Only games whose game.js names a music credit (GAME.music) get the 음악 toggle and the credit line in the menu. 소리 off silences music too. Browsers hold audio until the first tap or key, so a blocked start retries then. */ let musicOn=store.get(KEY('music'))!=='0',bgm=null,bgmSrc='',musicT=0,musicVol=+(store.get(KEY('musicVol'))??30); if(!(musicVol>=0&&musicVol<=100))musicVol=30; /* GAME.music: the credit, a string or {by,url} (the credit links there); the playing track's name comes from its file (audio/cafe-alps.m4a → Cafe Alps) */ function creditUI(){const c=$('credit');if(!c||!G.music)return;const M=typeof G.music==='string'?{by:G.music}:G.music; const t=bgmSrc.split('/').pop().replace(/\.\w+$/,'').split(/[-_]/).filter(Boolean).map(w=>w[0].toUpperCase()+w.slice(1)).join(' '); // '' while quiet: no track name c.textContent='음악 · '+(t?t+' — ':'');const a=document.createElement(M.url?'a':'span');a.textContent=M.by; if(M.url){a.href=M.url;a.target='_blank';a.rel='noopener'}c.append(a)} let duck=1,duckEnd=0,duckT=null,duckTo=1; // 1 = full music volume; the bell takes it down to .05 (a door to .5) and back const musicLevel=()=>musicVol/100*duck; function duckMusic(ms,to){const now=performance.now();duckTo=now{const down=performance.now()=1){clearInterval(duckT);duckT=null}},50)} function updateMusic(){ if(!G.music)return; let m=Z?('music' in Z?Z.music:C.MUSIC):null;if(typeof m==='function')m=m();m=(soundOn&&musicOn&&m)||''; if(m===bgmSrc)return;bgmSrc=m;creditUI(); if(bgm){bgm.pause();bgm=null} if(!m)return;bgm=new Audio(m);bgm.loop=true;bgm.volume=musicLevel();bgm.play().catch(()=>{}); } if(G.music){ const b=document.createElement('button');b.className='mi toggle';b.id='musicBtn';b.textContent=T('음악'); const upd=()=>b.setAttribute('aria-pressed',String(musicOn));upd(); b.addEventListener('click',()=>{musicOn=!musicOn;store.set(KEY('music'),musicOn?'1':'0');upd();sfx('ok');updateMusic()}); const v=document.createElement('div');v.className='vol';v.innerHTML='';v.prepend(b); // the 음악 on/off sits beside its volume, under the menu buttons // the volume (Android and desktop: iPhones ignore it, use the side buttons) const r=v.querySelector('input');r.value=musicVol;$('startPanel').querySelector('.mgrid').after(v); r.addEventListener('input',()=>{musicVol=+r.value;store.set(KEY('musicVol'),String(musicVol));if(bgm)bgm.volume=musicLevel(); if(!musicOn&&musicVol>0){musicOn=true;store.set(KEY('music'),'1');upd();updateMusic()}}); // moving the slider while 음악 is off turns it back on const g=document.querySelector('.startsheet .games');if(g){const c=document.createElement('div');c.className='credit';c.id='credit';g.after(c);creditUI()} const wake=()=>{if(bgm&&bgm.paused&&!document.hidden)bgm.play().catch(()=>{})}; addEventListener('pointerdown',wake,true);addEventListener('keydown',wake,true); document.addEventListener('visibilitychange',()=>{if(!bgm)return;if(document.hidden)bgm.pause();else wake()}); } if(!G.noWrite){const b=document.createElement('button');b.className='mi toggle';b.id='writeBtn';b.textContent=writeStep?'쓰기 문제 · 단계별':'쓰기 문제'; // 쓰기 문제 on/off (every game); 단계별 = the ladder (?write=step) const upd=()=>b.setAttribute('aria-pressed',String(writeOn));upd();menuAdd(b); b.addEventListener('click',()=>{writeOn=!writeOn;store.set(KEY('write'),writeOn?(writeStep?'step':'1'):'0');upd();sfx('ok');toast(writeOn?'★ 단어는 직접 써요.':'쓰기 문제를 껐어요. 보기에서 골라요.')})} if($('listenBtn')){const upd=()=>$('listenBtn').setAttribute('aria-pressed',String(listenOn));upd(); // a game's shell may offer the 듣기 문제 toggle $('listenBtn').addEventListener('click',()=>{listenOn=!listenOn;store.set(KEY('listen'),listenOn?'1':'0');upd();sfx('ok');toast(listenOn?T('복습에 듣기 문제가 나와요.'):T('듣기 문제를 껐어요.'))})} $('readBtn').addEventListener('click',()=>{ if(!canSpeak()){toast(T('이 기기에는 한국어 음성이 없어요.'));return} readOn=!readOn;store.set(KEY('read'),readOn?'1':'0');updateRead();toast(readOn?T('대사를 소리 내서 읽어요.'):T('읽기를 껐어요.'));if(readOn&&dlg)speak(dlg.cur.say||dlg.cur.ask||''); }); $('closePanel').addEventListener('click',()=>$('panel').hidden=true); $('panel').addEventListener('click',e=>{if(e.target.id==='panel')$('panel').hidden=true}); let armT; $('resetBtn').addEventListener('click',()=>{ const b=$('resetBtn'); if(!b.classList.contains('armed')){b.classList.add('armed');b.textContent=T('한 번 더 누르면 지워져요');clearTimeout(armT);armT=setTimeout(()=>{b.classList.remove('armed');b.textContent=T('처음부터')},3000);return} b.classList.remove('armed');b.textContent=T('처음부터'); $('chPanel').hidden=true;dropTalk();state=fresh();if(RP)state.counted=1;save();if(!RP){forgetNotes();forgetShared()}store.set(backKey(),'[]');updBack();loadZone(state.zone,state.x,state.y,state.dir);updateHud();updateQuest();$('panel').hidden=true; beginIntro(); // starting over replays the intro, like a first start }); document.addEventListener('contextmenu',e=>e.preventDefault()); document.querySelector('.pad').addEventListener('touchstart',e=>{if(e.cancelable)e.preventDefault()},{passive:false}); const KEYS={ArrowUp:'up',ArrowDown:'down',ArrowLeft:'left',ArrowRight:'right',w:'up',s:'down',a:'left',d:'right'}; addEventListener('keydown',e=>{ if(e.target.closest&&e.target.closest('textarea,input'))return; // typing a note, not playing if(KEYS[e.key]){e.preventDefault();if(dirPress(KEYS[e.key]))return;held=KEYS[e.key];if(!e.repeat)pressN++;return} if(choosing()&&/^[1-4]$/.test(e.key)){const b=choiceBtns()[+e.key-1];if(b){e.preventDefault();b.click()}return} if(building()&&/^[1-9]$/.test(e.key)){const b=[...document.querySelectorAll('#tiles .tile')][+e.key-1];e.preventDefault();if(b&&!b.classList.contains('used'))b.click();return} // N = the Nth tile where it sits (placed tiles leave a gap) if([' ','Enter','z','Z'].includes(e.key)){e.preventDefault();if(!e.repeat)interact();return} if(['x','X','Escape'].includes(e.key)){e.preventDefault();cancel();return} if(['m','M'].includes(e.key)&&!e.repeat){e.preventDefault();toggleStart()} }); addEventListener('keyup',e=>{if(KEYS[e.key]===held)held=null}); /* ---------- chapters (each keeps its own save; old chapters are never overwritten) ---------- */ const BASE_TILES={...TILES}; function boot(id,rp){ window.__labActive=null; // any boot leaves a lab; a lab sets this again right after its own boot CH=CHAPTERS.find(c=>c.id===id)||CHAPTERS[0]; if(RP&&!rp)try{shared=JSON.parse(store.get(SHARED_KEY)||'{}')||{}}catch(e){shared={}} // leaving a replay: the real shared record again RP=rp&&(chapterProgress(CH).done||(rp.force&&debugOK))?{mode:rp.mode||'plain',force:!!rp.force}:null;store.set(KEY('replay'),RP?JSON.stringify({id:CH.id,mode:RP.mode,force:RP.force}):''); if(RP&&rp.at){store.set(SK(),JSON.stringify(rp.at.state));store.set(SK()+'-talk',JSON.stringify(rp.at.talk||[]));store.set(SK()+'~back','[]')} // 장면: that moment, in the replay save if(RP&&RP.mode==='listen'&&!canSpeak()){RP.mode='plain';setTimeout(()=>toast(T('이 기기에는 한국어 음성이 없어요.')),600)} C=CH.make();mergeLooks(); Object.keys(TILES).forEach(k=>{if(!(k in BASE_TILES))delete TILES[k]});Object.assign(TILES,C.TILES||{}); player.look=typeof C.PLAYER==='function'?myLook():myLook(C.PLAYER||CREW_LOOK); // PLAYER as a function = a disguise, drawn at render time // a chapter may put the player in someone else's shoes (5장: Terence) dropTalk();held=null;warping=false;$('panel').hidden=true;$('chPanel').hidden=true;$('toast').hidden=true;logSel=null; store.set(KEY('chapter'),CH.id); loadState();loadTalk(); loadZone(state.zone,state.x,state.y,state.dir); $('chName').textContent=CH.n+(RP?' · '+T('다시 보기'):''); updateHud();updateQuest();updBack(); if(G.onBoot)G.onBoot(CH,C); // the game's own page parts for this chapter (단어 마을: tips, news sources) if(!state.seenIntro){ if(CH.resumeIntro){if(!state.introPending){state.steps=[];if(!RP){countPlay('start');countStep()}}if(me||!CREATOR)beginIntro();else openMe(beginIntro)} else{state.seenIntro=true;state.steps=[];save();if(!RP){countPlay('start');countStep()}const intro=()=>setTimeout(()=>openDialog(CH.introWho||G.title||T('이야기'),C.INTRO),300);if(me||!CREATOR)intro();else openMe(intro)} } // first time ever: make your character first; legacy chapters keep their original seenIntro timing else setTimeout(()=>{if(!dlg&&!panelOpen())greet()},400); // loaded in a room whose greeting hasn't happened (reloaded mid-scene): it starts over if(RP){const m=RP.mode;setTimeout(()=>toast(T('다시 보기')+' · '+T(RP_MODES[m])+': '+T('지금까지 한 건 그대로예요.')),700)} // the mode now: it may have ended by then } const RP_MODES={plain:'보통',listen:'듣기'}; function chapterProgress(c){try{const s=JSON.parse(store.get(c.save)||'null');return s?{got:(s.badges||[]).length,done:!!(s.f&&s.f.done)}:{got:0,done:false}}catch(e){return {got:0,done:false}}} function openChapters(){ $('chList').innerHTML=CHAPTERS.map(c=>{const p=chapterProgress(c); return ``}).join(''); $('chList').querySelectorAll('.chap').forEach(b=>b.addEventListener('click',()=>{const id=b.dataset.id,c=CHAPTERS.find(x=>x.id===id); if(chapterProgress(c).done||c===CH){replayMenu(c);return} // finished: play it as it is, or again (다시 보기); this one: 처음부터 is here $('chPanel').hidden=true;if(id!==CH.id||RP){boot(id);sfx('door')}})); $('chPanel').hidden=false;$('chList').querySelector('.cur')?.focus(); } function replayMenu(c){ // 그대로 보기 = the real save; 다시 보기 = a fresh run in its own save, in one of three modes const done=chapterProgress(c).done; const opts=done?[['',T('그대로 보기')],...Object.entries(RP_MODES).filter(([m])=>m!=='listen'||canSpeak()).map(([m,l])=>[m,T('다시 보기')+' · '+T(l)]),['scenes',T('장면 고르기')]]:[['',T('이어서 하기')]]; $('chList').innerHTML=`
    ${c.n}${c.title}${done?T('지금까지 한 건 그대로예요.'):(c.place||'')}
    ` +opts.map(([m,l])=>``).join('') +``; $('chList').querySelectorAll('.rpo').forEach(b=>b.addEventListener('click',()=>{const m=b.dataset.m;if(m==='back'){openChapters();return} if(m==='scenes'){sceneMenu(c,false);return} if(m==null)return; // 처음부터 has its own handler $('chPanel').hidden=true;const want=m?{mode:m}:null;if(c.id!==CH.id||!!RP!==!!want||(RP&&want&&RP.mode!==want.mode)){boot(c.id,want);sfx('door')}})); if(c===CH&&RESET){RESET.classList.add('mi','rpo','danger');RESET.style.cssText='width:100%;margin-top:14px';$('chList').querySelector('.rpo[data-m="back"]').before(RESET)} // the one red button, beside the chapter it wipes $('chList').querySelector('.rpo')?.focus(); } /* 장면: checkpoints.json next to the game (tools/play.mjs --checkpoints writes it from the walk scripts): per chapter, the moments the 목표 changed with no talk open: [{q: the 목표, zone, state, talk}]. A finished chapter's 장면 고르기 starts 다시 보기 at one of them; with 디버그 on, 장면으로 (in the 일지) does it in any chapter, so a story beat can be tried without playing up to it. */ let cpAll=null;const loadCps=()=>cpAll||(cpAll=fetch('checkpoints.json',{cache:'no-cache'}).then(r=>r.ok?r.json():{}).catch(()=>({}))); let sceneListen=false; function sceneMenu(c,force){ loadCps().then(all=>{const L=(all||{})[c.id]||[]; if(L.length<2){toast(T('장면이 아직 없어요.'));return} // one moment is just the start const esc=x=>String(x).replace(/[&<>"]/g,ch=>({'&':'&','<':'<','>':'>','"':'"'}[ch])); $('chList').innerHTML=(canSpeak()?``:'') +L.map((x,i)=>``).join('') +``; $('scListen')?.addEventListener('click',()=>{sceneListen=!sceneListen;$('scListen').setAttribute('aria-pressed',String(sceneListen))}); $('chList').querySelectorAll('.rpo').forEach(b=>b.addEventListener('click',()=>{const i=b.dataset.i;if(i==='back'){force?($('chPanel').hidden=true):replayMenu(c);return} $('chPanel').hidden=true;boot(c.id,{mode:sceneListen&&canSpeak()?'listen':'plain',at:L[+i],force});sfx('door')})); $('chPanel').hidden=false;$('chList').querySelector('.rpo')?.focus()}); } $('chBtn').addEventListener('click',openChapters); $('chPanel').addEventListener('click',e=>{if(e.target.id==='chPanel')$('chPanel').hidden=true}); $('chClose').addEventListener('click',()=>$('chPanel').hidden=true); /* ---------- START, sorted by how often you reach for it ---------- Built once from the buttons the shell and the engine made (same ids and handlers, so games and tests keep working): the 지금 card on top (the chapter button: where you are and your 목표; tap for the chapter list and 처음부터), three tiles (대화 · 사전 · 일지), the two toggles flipped mid-scene (소리, 읽기) beside 설정, and the rare ones as small links. Every other toggle moves to the 설정 sheet as a switch row, grouped 소리 · 읽기 · 복습 · 화면, with 개발 (디버그, 장면으로, 한 단계 뒤로) only where 디버그 is offered. A switch clicks the original button, so its state and sound stay the button's own. */ let RESET=null; function menuCss(){if($('menuCss'))return;const st=document.createElement('style');st.id='menuCss'; st.textContent='.mgrid.v2{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.mgrid.v2>*{grid-column:auto}' +'.nowcard{grid-column:1/-1!important;display:grid!important;grid-template-columns:auto 1fr auto;gap:10px;align-items:center;text-align:left;background:var(--ink)!important;color:var(--hull)!important;border-color:var(--ink)!important}' +'.nowcard #chName{margin:0;opacity:1;font-size:.8rem;font-weight:700;background:var(--amber,#E8952B);color:var(--ink);border-radius:5px;padding:3px 6px;white-space:nowrap}' +'.nowcard .nci{display:grid;min-width:0}.nowcard .nci b{font-size:1rem}.nowcard .nci small{margin:0;font-size:.78rem;opacity:.75;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.nowcard .ncg{font-size:.8rem;opacity:.8;white-space:nowrap}' +'.mgrid.v2 .tile{padding:16px 4px}.mgrid.v2 .qk{font-size:.95rem;padding:10px 6px}' +'.mlinks{display:flex;flex-wrap:wrap;gap:2px 16px;padding-top:6px;border-top:1px solid color-mix(in srgb,var(--ink) 25%,transparent)}' +'.mlinks .mi{border:none!important;background:none!important;color:var(--ink)!important;padding:6px 0;font-size:.9rem;font-weight:500;text-decoration:underline;text-underline-offset:3px;opacity:.85}' +'.srows{display:grid;gap:4px}.sgrp{font-size:.72rem;letter-spacing:.1em;opacity:.65;margin:10px 2px 0}' +'.srow{display:grid;grid-template-columns:1fr auto;align-items:center;gap:10px;border:2px solid color-mix(in srgb,var(--ink) 18%,transparent);border-radius:8px;padding:8px 10px;font-weight:700}' +'.srow .btn{padding:4px 12px;font-size:.85rem}.srow input[type=range]{width:100%;accent-color:var(--accent,#E8952B)}' +'.sw{width:44px;height:26px;border-radius:999px;border:2px solid var(--ink);background:transparent;position:relative;cursor:pointer;padding:0}' +'.sw::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:var(--ink);transition:left .15s}' +'.sw[aria-checked="true"]{background:var(--ink)}.sw[aria-checked="true"]::after{left:21px;background:var(--hull)}' +'.sw:focus-visible,.nowcard:focus-visible{outline:3px solid var(--amber,#E8952B);outline-offset:2px}' +'.mi.danger{border-color:#b3412f!important;color:#b3412f!important}' +'@media (prefers-reduced-motion:reduce){.sw::after{transition:none}}'; document.head.appendChild(st)} function nowCard(){const t=$('nowTitle'),q=$('nowQuest');if(!t||!CH)return;t.textContent=CH.title||'';q.textContent=C&&C.questText?C.questText():''} function closeSettings(){$('setPanel').hidden=true;$('startPanel').hidden=false;nowCard()} const SET_GROUPS=[['소리',['sndBtn','musicBtn']],['읽기',['readBtn','enAllBtn']],['복습',['listenBtn','writeBtn']],['화면',['landBtn']]]; function reworkMenu(){ const P=$('startPanel'),g=P&&P.querySelector('.mgrid');if(!g||g.classList.contains('v2'))return;menuCss(); const keep={};['chBtn','talkBtn','tapBtn','sndBtn','readBtn','musicBtn','listenBtn','writeBtn','landBtn','enAllBtn','dbgBtn','sceneBtn','backBtn','resetBtn'].forEach(id=>keep[id]=$(id)); // before the grid is emptied: detached buttons can't be found by id const el=id=>keep[id]||$(id); const mk=(id,text,cls)=>{const b=document.createElement('button');b.type='button';b.id=id;b.className=cls;b.textContent=text;return b}; const ch=el('chBtn'),label=[...ch.childNodes].filter(n=>n.nodeType===3).map(n=>n.textContent).join('').trim(); ch.className='mi nowcard';ch.innerHTML=`${CH?CH.n:''}${label} ›`; const log=mk('logTile',G.hud||T('일지'),'mi tile');log.addEventListener('click',()=>{setTimeout(()=>$('logBtn').click(),0)}); const setB=mk('setBtn',T('설정'),'mi qk');setB.addEventListener('click',()=>{setTimeout(()=>{$('setPanel').hidden=false;syncSw()},0)}); const toggles=[...g.querySelectorAll('.mi.toggle')],others=[...g.querySelectorAll('.mi:not(.toggle)')].filter(b=>!['talkBtn','tapBtn','chBtn'].includes(b.id)); const vol=P.querySelector('.vol'); // START g.classList.add('v2');g.innerHTML=''; [ch,el('talkBtn'),el('tapBtn'),log].forEach(b=>{b.classList.remove('wide');if(b!==ch)b.classList.add('tile');g.append(b)}); const quick=['sndBtn','readBtn'].map(el).filter(Boolean);quick.forEach(b=>{b.classList.remove('wide');b.classList.add('qk');g.append(b)});g.append(setB); const links=document.createElement('div');links.className='mlinks';others.forEach(b=>{b.classList.remove('wide');links.append(b)});g.after(links); // 설정 const S=document.createElement('div');S.className='panel';S.id='setPanel';S.hidden=true; S.innerHTML=``; P.after(S);const rows=S.querySelector('#srows'),hold=S.querySelector('#setHold'); const rowFor=b=>{const r=document.createElement('div');r.className='srow';const name=document.createElement('span');name.textContent=b.textContent; const sw=document.createElement('button');sw.type='button';sw.className='sw';sw.setAttribute('role','switch');sw.setAttribute('aria-label',b.textContent);sw.dataset.for=b.id; sw.addEventListener('click',()=>{b.click();syncSw()});r.append(name,sw);if(!quick.includes(b))hold.append(b);return r}; const placed=new Set(); for(const [name,ids] of SET_GROUPS){const bs=ids.map(el).filter(b=>b&&(toggles.includes(b)||quick.includes(b)||b.id==='musicBtn'));if(!bs.length)continue; if(!(bs.length===1&&bs[0].textContent.trim()===T(name)))rows.insertAdjacentHTML('beforeend',`
    ${T(name)}
    `); // no heading that only repeats its one row for(const b of bs){rows.append(rowFor(b));placed.add(b);if(b.id==='musicBtn'&&vol){const r=document.createElement('div');r.className='srow';r.style.gridTemplateColumns='1fr';const i=vol.querySelector('input');r.append(i);rows.append(r);vol.remove()}}} const rest=toggles.filter(b=>!placed.has(b)&&b.id!=='dbgBtn'); if(rest.length){rows.insertAdjacentHTML('beforeend',`
    ${T('기타')}
    `);rest.forEach(b=>rows.append(rowFor(b)))} if(el('dbgBtn')){rows.insertAdjacentHTML('beforeend',`
    ${T('개발')}
    `);rows.append(rowFor(el('dbgBtn'))); for(const id of ['sceneBtn','backBtn']){const b=el(id);if(b){const r=document.createElement('div');r.className='srow dev-'+id;const n=document.createElement('span');n.textContent=b.textContent.replace(/\s*\(\d+\)$/,'');r.append(n,b);rows.append(r)}} loadLabs().then(L=>L.forEach(l=>{const r=document.createElement('div');r.className='srow';const n=document.createElement('span');n.textContent=T('실험')+' · '+l.name; const b=document.createElement('button');b.type='button';b.className='btn';b.textContent=T('시작');b.addEventListener('click',()=>{$('setPanel').hidden=true;startLab(l)});r.append(n,b);rows.append(r)}))} RESET=el('resetBtn');if(RESET)RESET.remove(); S.querySelector('#setClose').addEventListener('click',closeSettings); S.addEventListener('click',e=>{if(e.target===S)closeSettings()}); syncSw();nowCard(); } /* 실험 (labs): a feature tried out before it belongs to the game, in its own file next to the game (labs.json lists them: [{id, name, file}]), never in the build. Only where 디버그 is offered: 설정 · 개발 lists them, ?lab= starts one at load. A lab registers WALK_LABS[id] = {start()} and may wrap engine functions while it runs; taking it out = deleting its file and entry. window.__labActive names the lab that's on: a lab sets it after its own boot, every boot clears it, and the one that was on when the page went away starts again on the next load (a reload keeps you in the lab). */ window.WALK_LABS=window.WALK_LABS||{}; let labsP=null;const loadLabs=()=>labsP||(labsP=fetch('labs.json',{cache:'no-cache'}).then(r=>r.ok?r.json():[]).catch(()=>[])); function startLab(l){ const go=()=>{const L=WALK_LABS[l.id];if(L&&L.start){$('startPanel').hidden=true;L.start()}else toast(T('실험을 못 열었어요.'))}; if(WALK_LABS[l.id])return go(); const sc=document.createElement('script');sc.src=l.file+'?t='+Date.now();sc.onload=go;sc.onerror=()=>toast(T('실험을 못 열었어요.'));document.head.appendChild(sc); } function syncSw(){document.querySelectorAll('#srows .sw').forEach(s=>{const b=$(s.dataset.for);s.setAttribute('aria-checked',String(!!b&&b.getAttribute('aria-pressed')==='true'))}); for(const id of ['sceneBtn','backBtn']){const r=document.querySelector('.dev-'+id),b=$(id);if(r&&b)r.hidden=b.hidden}} reworkMenu(); /* ---------- start ---------- */ function start(){ if(TTS){pickVoice();speechSynthesis.onvoiceschanged=pickVoice} updateSound();updateRead(); const want=new URLSearchParams(location.search).get('ch')||store.get(KEY('chapter')); let rp=null;try{rp=JSON.parse(store.get(KEY('replay'))||'null')}catch(e){} boot(CHAPTERS.some(c=>c.id===want)?want:CHAPTERS[0].id,rp&&rp.id===want?rp:null); // first visit starts at chapter 1; after that, the last chapter played (a replay goes on) const upd=store.get(KEY('updated'));if(upd)store.set(KEY('updated'),''); if(upd&&upd===VER.v)setTimeout(()=>toast('새 버전으로 업데이트했어요.'),1500);else countPlay('open'); // our own reload isn't a new visit if(window.LINES_EN&&(enQ==='0'||enQ==='1'))setTimeout(()=>toast(enAll?'English under every line (tester link).':'영어 자동 보기를 껐어요.'),2600); {const q=new URLSearchParams(location.search).get('lab')||store.get(KEY('lab'));if(q&&debugOK)loadLabs().then(L=>{const l=L.find(x=>x.id===q);if(l)setTimeout(()=>startLab(l),900)})} // ?lab=, or the lab that was on when the page went away: straight into it addEventListener('pagehide',()=>store.set(KEY('lab'),debugOK&&window.__labActive||'')); if(countQ==='0'||countQ==='1')setTimeout(()=>toast(countQ==='0'?'이 브라우저는 이제 통계에서 빠져요.':'이 브라우저도 다시 통계에 들어가요.'),1200); requestAnimationFrame(loop); } window.claude?.hot?.ready?window.claude.hot.ready(start):start();