// UI 主控:渲染单屏 + 处理动作返回的事件(反馈 / 叙事 / 成就)。逻辑全部在 core / game。署名:FmodeCode import * as S from '../game/state.js'; import * as F from '../core/formulas.js'; import * as B from '../core/balance.js'; import { PLANETS } from '../data/planets.js'; import { LIFE, lifeById } from '../data/lives.js'; import { CHAPTER_TEXT, LIFE_CRY, ERA_TEXT, TUTORIAL_LINES, PROLOGUE } from '../data/story.js'; import { ACHIEVEMENTS, achById, achCount } from '../game/achievements.js'; import { $, $$, fmt, fmtTime, icon, esc } from '../util.js'; import { buildSystemSvg, planetSvg, planetPos, fxAt, sparksAt, rippleAt, confetti, globalFlash } from './art.js'; export class Game { constructor(state) { this.s = state; this.now = Date.now() / 1000; this.sheetName = null; this.modalQueue = []; this.modalOpen = false; this.lastSave = Date.now(); this.bind(); } start() { $('#app').hidden = false; document.body.classList.toggle('in-prologue', !this.s.story.prologue); this.buildSystem(); if (!this.s.story.prologue) this.showPrologue(); else this.afterPrologue(false); document.body.classList.toggle('in-prologue', !this.s.story.prologue); this.renderAll(); this.loop(); setInterval(() => this.tickOnce(), 1000); document.addEventListener('visibilitychange', () => { if (!document.hidden) this.onReturn(); }); window.addEventListener('beforeunload', () => this.persist()); setInterval(() => this.persist(), 5000); } // ── 主循环:数字与进度条按帧平滑 ───────────────────── loop() { const paint = () => { this.now = Date.now() / 1000; this.paintStats(); this.frame = requestAnimationFrame(paint); }; paint(); } tickOnce() { const out = S.tick(this.s, this.now, 1); this.handle(out.world, 'tick'); this.handle(out.ui, 'tick', true); this.refreshDynamic(); } onReturn() { const gap = this.now ? (Date.now() / 1000 - this.now) : 0; const off = S.applyOffline(this.s, gap, Date.now() / 1000); if (off) { const sec = fmtTime(off.sec); this.toast(`根系在你离开时仍在生长${sec} · 本源 +${fmt(off.res)}${off.grow > 0 ? ` · 星球改造 +${off.grow.toFixed(1)}%` : ''}`, 'green', 5000); this.handle(off.events, 'offline'); } this.now = Date.now() / 1000; this.renderAll(); } persist() { S.save.write(localStorage, this.s); this.lastSave = Date.now(); } // ── 事件绑定 ─────────────────────────────────────── bind() { $('#tree').addEventListener('pointerdown', (e) => this.onTap(e)); $('#goal').addEventListener('click', () => this.onGoalClick()); $$('.tabbar button').forEach((b) => b.addEventListener('click', () => this.openSheet(b.dataset.nav))); $('#btn-menu').addEventListener('click', () => this.openSheet('menu')); $('#root-chip').addEventListener('click', () => this.openSheet('root')); $('#crystal-chip').addEventListener('click', () => this.openSheet('era')); $('#sheet-x').addEventListener('click', () => this.closeSheet()); $('#sheet-mask').addEventListener('click', (e) => { if (e.target.id === 'sheet-mask') this.closeSheet(); }); $('#btn-explore').addEventListener('click', () => this.doExplore()); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { this.closeSheet(); if (this.modalOpen) this.advanceModal(); } if (e.code === 'Space' && !this.modalOpen && $('#app').hidden === false && !this.sheetName) { e.preventDefault(); this.onTap({ clientX: innerWidth / 2, clientY: innerHeight * 0.8 }); } }); // 星图:事件委托 $('#system').addEventListener('click', (e) => { const g = e.target.closest('[data-planet]'); if (!g) return; const i = +g.dataset.planet; if (F.isPlanetUnlocked(this.s, i)) this.switchPlanet(i); else this.explainLocked(i); }); } // ── 开场故事 ────────────────────────────────────── showPrologue() { this.proIdx = 0; const el = $('#prologue'); el.hidden = false; $('#pro-next').onclick = () => this.proNext(); $('#pro-skip').onclick = () => this.proFinish(); this.proRender(); } proRender() { const p = PROLOGUE[this.proIdx]; $('#pro-bg').style.backgroundImage = `url(assets/${p.art}.webp)`; $('#pro-kicker').textContent = p.kicker; $('#pro-text').textContent = p.text; $('#pro-lines').innerHTML = p.lines.map((l) => `
${esc(l)}
`).join(''); $('#pro-dots').innerHTML = PROLOGUE.map((_, k) => ``).join(''); $('#pro-next').textContent = this.proIdx < PROLOGUE.length - 1 ? '继续' : '让根须苏醒'; const body = $('#pro-body') || $('.pro-body'); body.style.animation = 'none'; void body.offsetWidth; body.style.animation = ''; } proNext() { if (this.proIdx < PROLOGUE.length - 1) { this.proIdx++; this.proRender(); } else this.proFinish(); } proFinish() { this.s.story.prologue = 1; $('#prologue').hidden = true; document.body.classList.remove('in-prologue'); globalFlash(); this.afterPrologue(true); } // ── 引导:每一步只讲一句话,完成即推进 ───────────────── afterPrologue(fresh) { const step = this.s.tutorial.step; if (fresh && step <= 1) { this.introCard = true; this.pushModal({ kicker: '第一章 · 地球', title: CHAPTER_TEXT.earth.intro.title, text: CHAPTER_TEXT.earth.intro.text, sigil: 'earth', choices: [{ text: '让根须扎进土壤', primary: true }], }); } else if (TUTORIAL_LINES[step]) { this.toast(`世界树${esc(TUTORIAL_LINES[step].text)}`, 'green', 6000); } } tutorialHint() { const step = this.s.tutorial.step; const line = TUTORIAL_LINES[step]; if (!line || this.hintShown === step) return; this.hintShown = step; this.toast(`${line.speaker}${esc(line.text)}`, 'green', 5500); } // ── 点击世界树 ───────────────────────────────────── onTap(e) { const out = S.tap(this.s, this.now); const btn = $('#tree').getBoundingClientRect(); const x = (e && e.clientX) || btn.left + btn.width / 2; const y = (e && e.clientY) || btn.top + btn.height / 2; const gain = out.find((o) => o.type === 'tap')?.gain || 0; fxAt(x, y - 10, '+' + fmt(gain)); sparksAt(x, y, 6); rippleAt(x, y); const crown = $('.tree-crown'); crown.style.transform = 'scale(1.12)'; setTimeout(() => { crown.style.transform = ''; }, 120); this.handle(out); this.paintStats(); this.renderGoal(); this.tutorialHint(); } onGoalClick() { const g = F.currentGoal(this.s); if (g.key === 'tut5' || g.key === 'tut6') this.s.tutorial.starOpened = true; if (g.action === 'next') { this.onNextPlanet(g.planet); return; } if (g.action === 'era') { this.openSheet('era'); return; } if (g.action === 'life') this.openSheet('lives'); else if (g.action === 'explore') this.doExplore(); else if (g.action === 'planet') this.openSheet('planet'); else if (g.action === 'root') this.openSheet('root'); else if (g.action === 'star') this.openSheet('star'); else this.pulse('#tree'); this.renderAll(); } pulse(sel) { const e = $(sel); if (!e) return; e.classList.remove('hint'); void e.offsetWidth; e.classList.add('hint'); } // ── 提示 toast ────────────────────────────────────── toast(html, cls = '', ms = 3000, bad = false) { const box = $('#toasts'); const t = document.createElement('div'); t.className = 'toast ' + (cls || ''); t.innerHTML = html; box.appendChild(t); while (box.children.length > 3) box.firstChild.remove(); setTimeout(() => { t.classList.add('out'); setTimeout(() => t.remove(), 320); }, ms); } // ── 核心动作 ─────────────────────────────────────── switchPlanet(i) { if (i === this.s.curPlanet) { this.openSheet('planet'); return; } const out = S.enterPlanet(this.s, i); this.handle(out); this.buildSystem(); this.renderAll(); this.toast(`${PLANETS[i].name}${esc(PLANETS[i].hint)}`, '', 3800); } explainLocked(i) { const P = PLANETS[i]; const prev = PLANETS[i - 1]; const prevDone = this.s.planets[i - 1].rem <= 0; const lvOk = this.s.rootLv >= P.unlockLv; this.openSheet('lock', { i, msg: prevDone && !lvOk ? `需要世界树扎根 ${P.unlockLv} 级(当前 ${this.s.rootLv} 级)` : `先让${prev.name}复苏,并让世界树扎根到 ${P.unlockLv} 级` }); } buyLife(id) { const out = S.buyLife(this.s, id); if (!out.length) return; const btn = $(`.life-btn[data-life="${id}"]`); if (btn) { btn.classList.remove('flash'); void btn.offsetWidth; btn.classList.add('flash'); } this.handle(out); this.renderLives(); this.renderGoal(); this.paintStats(); } buyRootAll() { const n = 8; const out = S.buyRoot(this.s, n); if (out.length) this.toast(`根系生长扎根 ${this.s.rootLv} 级 · 本源 ×${B.rootProdMul(this.s.rootLv).toFixed(1)}`, 'green', 2500); this.handle(out); this.renderAll(); } doExplore() { const i = this.s.curPlanet; const out = S.explore(this.s); if (!out.length) { const p = this.s.planets[i]; if (p.explore >= B.STAR.exploreMax) this.toast('这颗星球已被完全勘探改造只需 3% 的等级即可完成', '', 3000); else this.toast(`勘探需要 ${fmt(S.exploreCostNow(this.s, i))} 本源根须继续生长后再来`, '', 2600); return; } confettiSmall(); this.handle(out); this.renderAll(); } // ── 事件处理(所有动作统一出口)──────────────────────── handle(events, source = 'ui', deferModal = false) { for (const ev of events || []) { switch (ev.type) { case 'tap': break; case 'ach': this.toast(`${icon(ev.ach.icon)}成就解锁 · ${esc(ev.ach.name)}${esc(ev.ach.desc)}`, 'ach', 4200); this.renderNavDots(); break; case 'life': if (ev.first && ev.planet === this.s.curPlanet) { // 生命苏醒卡:同一时刻苏醒的多种生命合并成一张卡;引导期间只弹“引导”的那一株(避免打断教学) const stepNow = this.s.tutorial.step; const tutLife = !(stepNow === 1 || stepNow === 2) && stepNow < 99; // 只有走到“种下第一株生命”那一步之后才需要弹出 if (!tutLife || ev.id === 'moss') { this.lifeModalQueue = (this.lifeModalQueue || []).concat([ev]); if (!this.lifeModalTimer) this.lifeModalTimer = setTimeout(() => this.flushLifeModals(), 1500); } } break; case 'planet-done': this.onPlanetDone(ev.planet); break; case 'heat-good': this.toast(`环境转机${esc(CHAPTER_TEXT[PLANETS[ev.planet].id].heatGood)}`, 'green', 3200); break; case 'heat-bad': this.toast(`环境恶化${esc(CHAPTER_TEXT[PLANETS[ev.planet].id].heatBad)}`, '', 2600, true); break; case 'event-open': this.pushModalEv(ev.ev, ev.crisis ? '危机' : '星海事件'); break; case 'event-done': this.toast(`${esc(ev.choice.effect)}`, 'green', 2600); break; case 'res': fxAt(innerWidth / 2, innerHeight * 0.55, '+' + fmt(ev.amount)); break; case 'progress': this.toast(`${ev.pct > 0 ? '改造推进' : '改造回退'} ${Math.abs(ev.pct)}%`, ev.pct > 0 ? 'green' : '', 2000); break; case 'life-gain': this.toast(`${esc(ev.life.name)} ×${ev.n}生命在根系中苏醒`, 'green', 2400); break; case 'tut': this.tutorialHint(); this.pulseGoal(); break; case 'era': this.onEra(ev); break; case 'curio': this.toast(`星辰洗礼 · ${esc(B.STEM_ELEMENTS.find((e) => e.id === ev.el)?.name)}第 ${ev.stems} 颗基因之种`, 'ach', 3200); break; case 'heal': this.toast('屏障修补完成根系撑过了这一阵风暴', 'green', 2200); break; case 'explore': this.toast(`勘探第 ${ev.level} 层所需生命等级 ×${B.STAR.exploreBoost.toFixed(2)}`, 'green', 2400); break; case 'enter': break; default: break; } } } /** 生命苏醒:集中弹一次(多个生命在同一时刻苏醒时只弹一个“名录”) */ flushLifeModals() { const q = this.lifeModalQueue || []; this.lifeModalQueue = []; this.lifeModalTimer = null; if (!q.length) return; if (q.length === 1) { const ev = q[0]; this.pushModal({ kicker: `${PLANETS[ev.planet].name} · 生命苏醒`, title: lifeById(ev.id).name, text: LIFE_CRY[ev.id] || lifeById(ev.id).lore, sigil: lifeById(ev.id).icon, choices: [{ text: '让它继续生长', primary: true }] }); return; } const title = q.map((ev) => lifeById(ev.id).name).join('、'); const text = q.map((ev) => `「${lifeById(ev.id).name}」——${LIFE_CRY[ev.id] || lifeById(ev.id).lore}`).join('\n\n'); this.pushModal({ kicker: `${PLANETS[q[0].planet].name} · 生命苏醒`, title, text, sigil: lifeById(q[q.length - 1].id).icon, choices: [{ text: '让它们一起生长', primary: true }] }); } pulseGoal() { const g = $('#goal'); g.classList.remove('flash'); void g.offsetWidth; g.classList.add('flash'); } onPlanetDone(i) { const P = PLANETS[i]; const ch = CHAPTER_TEXT[P.id]; confetti(); globalFlash(); const next = PLANETS[i + 1]; this.pushModal({ kicker: `第 ${P.chapterNo} 章 · 星球复苏`, title: ch.clear.title, text: ch.clear.text, sigil: P.sun ? 'sun' : 'check', choices: [{ text: next ? `前往${next.name}` : '回到太阳系', primary: true, next: next ? i + 1 : null, reopen: !!next }], }); this.buildSystem(); } onEra(ev) { confetti(); globalFlash(); if (this.sheetName === 'era') this.closeSheet(); this.pushModal({ kicker: `第 ${ev.eras} 纪元`, title: ERA_TEXT.title, text: ERA_TEXT.text + `\n\n获得时间结晶 ×${ev.reward}(共 ${ev.crystals})。`, sigil: 'hourglass', choices: [{ text: '让新的纪元开始', primary: true }], era: true, }); this.buildSystem(); } onSwitchAfterDone(i) { const out = S.enterPlanet(this.s, i); this.handle(out); this.buildSystem(); if (this.s.planets[i].rem > 0 && !this.s.story['intro' + i]) { this.s.story['intro' + i] = 1; this.pushModal({ kicker: `第 ${PLANETS[i].chapterNo} 章`, title: CHAPTER_TEXT[PLANETS[i].id].intro.title, text: CHAPTER_TEXT[PLANETS[i].id].intro.text, sigil: PLANETS[i].icon || 'planet', choices: [{ text: '开始改造', primary: true }] }); } this.renderAll(); } // ── 弹窗队列 ────────────────────────────────────── pushModal(spec) { this.modalQueue.push(spec); if (!this.modalOpen) this.nextModal(); } pushModalEv(ev, kind) { this.modalQueue.push({ kicker: kind, title: ev.title, text: ev.text, sigil: 'wind', ev, choices: ev.choices.map((c, k) => ({ text: c.text, effect: c.effect, pick: k })), }); if (!this.modalOpen) this.nextModal(); } nextModal() { const m = this.modalQueue.shift(); if (!m) { this.modalOpen = false; $('#modal-mask').hidden = true; this.renderAll(); return; } this.modalOpen = true; this.curModal = m; $('#modal-mask').hidden = false; const sig = m.lifeId ? (lifeById(m.lifeId)?.icon || 'sprout') : (m.sigil || 'star'); $('#modal-art').innerHTML = `${esc(l.lore)}
🔒 ${need} 后苏醒
${esc(l.lore)}
${kindText(l)}${cur ? ` · 已叠 ${stackText(l, cur)}` : ''}
根系越深,本源生长越快。${PLANETS[Math.min(8, i + 1)].name}需要扎根 ${PLANETS[Math.min(8, i + 1)].unlockLv} 级。
本源产出 ×${B.rootProdMul(s.rootLv).toFixed(2)}
${nextL.unlockRoot && s.rootLv < nextL.unlockRoot ? `根系扎根到 ${nextL.unlockRoot} 级` : `星球改造到 ${Math.round(nextL.stage * 100)}%`} 后,它会从根须里苏醒。
${sub}
${done} / ${PLANETS.length} 颗星球重新长出生命
选择一颗基因之种,它会永久改变下一个纪元。
' : `攒够 ${B.CURIO.cost} 颗时间结晶,可以完成一次三选一的星辰洗礼。(当前 ${s.crystals})
`}` : ''; return `已点亮 ${achCount(s)} / ${ACHIEVEMENTS.length}
根系是全太阳系的根:等级越高,所有星球的生长都越快。
`; } sheetPlanet() { const s = this.s, i = s.curPlanet, P = PLANETS[i]; const ch = CHAPTER_TEXT[P.id]; const cs = F.challengeStatus(s, i); const th = cs.threat; const h = s.heat[i]; const pct = 100 - s.planets[i].rem; return `${this.planetDossier(i)}${esc(th.desc)}
${esc(ch.intro.text)}
${esc(P.intro)}
游戏每 5 秒自动保存在本机。导出后可在其他设备导入。
《世界树 · 太阳系》
作者:FmodeCode
操作:点击世界树获得本源 · 空格键也可以
快捷键:Esc 关闭弹层
版本 v3 · 太阳系篇
`; } afterSheetRender(m) { if (m === 'era') { const go = document.getElementById('era-go'); if (go) go.onclick = () => { const out = S.doEra(this.s); this.handle(out); this.renderAll(); }; return; } if (m !== 'menu') return; $('#m-export').onclick = () => { const blob = new Blob([S.save.serialize(this.s)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'worldtree-solaris-save.json'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); this.toast('存档已导出', 'green'); }; $('#m-import').onchange = async (e) => { const f = e.target.files[0]; if (!f) return; const text = await f.text(); const r = S.save.parse(text); if (!r.ok) { this.toast(`导入失败${r.error}`, '', 3000); return; } S.save.write(localStorage, r.data); location.reload(); }; $('#m-reset').onclick = () => { if (!confirm('确定清除存档,从第一根须重新开始吗?')) return; S.save.clear(localStorage); location.reload(); }; } } function iconBox(name, locked) { return `