| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678 |
- // 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(`<b>根系在你离开时仍在生长</b><small>${sec} · 本源 +${fmt(off.res)}${off.grow > 0 ? ` · 星球改造 +${off.grow.toFixed(1)}%` : ''}</small>`, '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) => `<p>${esc(l)}</p>`).join('');
- $('#pro-dots').innerHTML = PROLOGUE.map((_, k) => `<i class="${k === this.proIdx ? 'on' : ''}"></i>`).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(`<b>世界树</b><small>${esc(TUTORIAL_LINES[step].text)}</small>`, '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(`<b>${line.speaker}</b><small>${esc(line.text)}</small>`, '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(`<b>${PLANETS[i].name}</b><small>${esc(PLANETS[i].hint)}</small>`, '', 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(`<b>根系生长</b><small>扎根 ${this.s.rootLv} 级 · 本源 ×${B.rootProdMul(this.s.rootLv).toFixed(1)}</small>`, '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('<b>这颗星球已被完全勘探</b><small>改造只需 3% 的等级即可完成</small>', '', 3000);
- else this.toast(`<b>勘探需要 ${fmt(S.exploreCostNow(this.s, i))} 本源</b><small>根须继续生长后再来</small>`, '', 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(`<span class="ic">${icon(ev.ach.icon)}</span><span><b>成就解锁 · ${esc(ev.ach.name)}</b><small>${esc(ev.ach.desc)}</small></span>`, '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(`<b>环境转机</b><small>${esc(CHAPTER_TEXT[PLANETS[ev.planet].id].heatGood)}</small>`, 'green', 3200); break;
- case 'heat-bad': this.toast(`<b>环境恶化</b><small>${esc(CHAPTER_TEXT[PLANETS[ev.planet].id].heatBad)}</small>`, '', 2600, true); break;
- case 'event-open': this.pushModalEv(ev.ev, ev.crisis ? '危机' : '星海事件'); break;
- case 'event-done': this.toast(`<b>${esc(ev.choice.effect)}</b>`, 'green', 2600); break;
- case 'res': fxAt(innerWidth / 2, innerHeight * 0.55, '+' + fmt(ev.amount)); break;
- case 'progress': this.toast(`<b>${ev.pct > 0 ? '改造推进' : '改造回退'} ${Math.abs(ev.pct)}%</b>`, ev.pct > 0 ? 'green' : '', 2000); break;
- case 'life-gain': this.toast(`<b>${esc(ev.life.name)} ×${ev.n}</b><small>生命在根系中苏醒</small>`, 'green', 2400); break;
- case 'tut': this.tutorialHint(); this.pulseGoal(); break;
- case 'era': this.onEra(ev); break;
- case 'curio': this.toast(`<b>星辰洗礼 · ${esc(B.STEM_ELEMENTS.find((e) => e.id === ev.el)?.name)}</b><small>第 ${ev.stems} 颗基因之种</small>`, 'ach', 3200); break;
- case 'heal': this.toast('<b>屏障修补完成</b><small>根系撑过了这一阵风暴</small>', 'green', 2200); break;
- case 'explore': this.toast(`<b>勘探第 ${ev.level} 层</b><small>所需生命等级 ×${B.STAR.exploreBoost.toFixed(2)}</small>`, '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 = `<div class="sigil">${icon(sig)}</div>`;
- $('#modal-kicker').textContent = m.kicker || '';
- $('#modal-title').textContent = m.lifeId ? lifeById(m.lifeId).name : (m.title || '');
- let text = m.text || '';
- if (m.lifeId) {
- const l = lifeById(m.lifeId);
- text = LIFE_CRY[m.lifeId] || l.lore;
- }
- $('#modal-text').innerHTML = esc(text);
- $('#modal-choices').innerHTML = m.choices.map((c, k) =>
- `<button class="choice ${c.primary ? 'primary' : ''}" data-k="${k}"><b>${esc(c.text)}</b>${c.effect ? `<small>${esc(c.effect)}</small>` : ''}</button>`).join('');
- $$('#modal-choices .choice').forEach((b) => b.addEventListener('click', () => this.chooseModal(+b.dataset.k)));
- const first = $('#modal-choices .choice'); if (first) setTimeout(() => first.focus({ preventScroll: true }), 30);
- }
- chooseModal(k) {
- const m = this.curModal;
- const c = m.choices[k];
- // 只有真实事件卡才把选择写回存档;叙事卡(章节 / 苏醒 / 纪元)只是“继续”按钮
- if (m.ev) {
- const out = S.resolveEvent(this.s, k, this.now);
- this.handle(out);
- }
- this.modalOpen = false; $('#modal-mask').hidden = true;
- if (c && c.next !== undefined && c.next !== null) setTimeout(() => this.onNextPlanet(c.next), 80);
- if (m.era) setTimeout(() => this.renderAll(), 80);
- setTimeout(() => this.nextModal(), 60);
- this.renderAll();
- }
- /** 星球已复苏时:直接进入下一颗(由“前往”按钮触发) */
- onNextPlanet(i) {
- if (F.isPlanetUnlocked(this.s, i)) this.onSwitchAfterDone(i);
- else { this.explainLocked(i); this.renderAll(); }
- }
- advanceModal() { if (this.curModal && this.curModal.choices.length === 1) this.chooseModal(0); }
- // ── 渲染 ──────────────────────────────────────────
- buildSystem() {
- this.systemSig = this.s.planets.map((p) => F.planetStatus(this.s, this.s.planets.indexOf(p))).join(',') + '|' + this.s.rootLv + '|' + this.s.curPlanet + '|' + this.s.planets.map((p) => p.rem <= 0 ? 1 : 0).join('');
- const st = PLANETS.map((P, i) => ({ i, idx: i, state: F.planetStatus(this.s, i), pct: 100 - this.s.planets[i].rem }));
- $('#system').innerHTML = buildSystemSvg(st);
- }
- paintStats() {
- const s = this.s;
- const inc = F.incomeOf(s, this.now);
- $('#res-val').textContent = fmt(s.res);
- $('#res-rate').textContent = '+' + fmt(inc) + '/秒';
- $('#root-lv').textContent = s.rootLv;
- $('#crystal-val').textContent = s.crystals;
- const eb = $('#era-badge');
- if (s.eras > 0) { eb.hidden = false; eb.textContent = `纪元 ${s.eras + 1}`; } else eb.hidden = true;
- const bar = $('#pc-bar'), pct = $('#pc-pct');
- if (bar) {
- const i = s.curPlanet, p = s.planets[i];
- const v = 100 - p.rem;
- bar.style.width = v.toFixed(2) + '%';
- pct.textContent = v.toFixed(1) + '%';
- }
- }
- renderGoal() {
- const g = F.currentGoal(this.s, this.now);
- this.curGoal = g;
- $('#goal-text').textContent = g.text;
- $('#goal-sub').textContent = g.sub || '';
- const tree = $('#tree');
- tree.classList.toggle('hint', ['tut1', 'tut2', 'tut3', 'tut4'].includes(g.key));
- if (g.life) this.hlLife = g.life;
- }
- renderPlanetCard() {
- const s = this.s, i = s.curPlanet, P = PLANETS[i];
- const cleared = s.planets[i].rem <= 0;
- $('#progress-card').classList.toggle('cleared', cleared);
- const h = s.heat[i];
- $('#pc-name').textContent = P.name;
- const env = $('#pc-env');
- const cs = F.challengeStatus(s, i);
- if (h && h.kind === 'bad' && h.until > this.now) { env.textContent = `${P.wave.short}来袭`; env.className = 'pc-env bad'; }
- else if (h && h.kind === 'good' && h.until > this.now) { env.textContent = '环境转机'; env.className = 'pc-env good'; }
- else if (!cs.sat) { env.textContent = `${cs.threat.short}压制中`; env.className = 'pc-env'; }
- else { env.textContent = '生长中'; env.className = 'pc-env'; }
- const rate = F.growRateOf(s, i, this.now);
- $('#pc-note').textContent = cleared ? '星球复苏 · 绿意永续' : rate > 0 ? `+${rate.toFixed(2)}%/秒 · ${cs.sat ? '挑战已攻克' : '挑战压制中'}` : '根系正在寻找第一颗种子';
- const ex = S.exploreCostNow(s, i);
- const bt = $('#btn-explore');
- const exLeft = (s.planets[i].explore || 0) < B.STAR.exploreMax;
- bt.textContent = exLeft ? `勘探 ${fmt(ex)}` : '已勘探';
- bt.disabled = !exLeft || s.res < ex || s.planets[i].rem <= 0;
- }
- renderLives() {
- const s = this.s, i = s.curPlanet;
- const av = F.availableLives(s, i);
- const nextL = F.nextLife(s, i);
- const list = LIFE.filter((l) => l.planet === i);
- $('#lives').innerHTML = list.map((l) => {
- const cur = s.lives[i][l.id];
- const unlocked = av.some((x) => x.id === l.id);
- const cost = S.lifeCostNow(s, l.id);
- const can = unlocked && s.res >= cost;
- if (!unlocked) {
- const pct = (100 - s.planets[i].rem);
- return `<button class="life-btn locked" data-life="${l.id}" aria-label="${l.name}未解锁">${icon(l.icon)}<span class="nm">${l.name}</span><span class="lv">${pct < l.stage * 100 ? `${Math.round(l.stage * 100)}%` : '扎根'}</span></button>`;
- }
- return `<button class="life-btn ${can ? 'buyable' : ''}" data-life="${l.id}" aria-label="${l.name} ${cur || 0}级">${icon(l.icon)}<span class="nm">${l.name}</span><span class="lv">Lv ${cur || 0} · ${fmt(cost)}</span></button>`;
- }).join('');
- if (nextL && this.modalOpen === false) $$('.life-btn').forEach((b) => { if (b.dataset.life === nextL.id && !av.some((x) => x.id === nextL.id)) b.classList.add('next'); });
- $$('.life-btn').forEach((b) => b.addEventListener('click', () => this.onLifeBtn(b.dataset.life)));
- }
- onLifeBtn(id) {
- if (S.lifeAvailable(this.s, id)) this.buyLife(id);
- else {
- const l = lifeById(id);
- const pct = (100 - this.s.planets[this.s.curPlanet].rem);
- if (l.unlockRoot && this.s.rootLv < l.unlockRoot) this.toast(`<b>${l.name}</b><small>根系扎根到 ${l.unlockRoot} 级后才会苏醒</small>`, '', 2600);
- else this.toast(`<b>${l.name}</b><small>星球改造到 ${Math.round(l.stage * 100)}% 后苏醒</small>`, '', 2600);
- }
- }
- renderNavDots() {
- const btn = $('.tabbar [data-nav="ach"]');
- btn.querySelector('.dot')?.remove();
- if (achCount(this.s) > (this.s.seen.ach || 0)) { const d = document.createElement('i'); d.className = 'dot'; btn.appendChild(d); }
- }
- refreshDynamic() {
- this.renderGoal(); this.renderPlanetCard(); this.renderLives(); this.paintStats();
- // 星图只在状态变化时重绘(避免每帧重建 SVG 导致点击目标抖动)
- const sig = this.s.planets.map((p) => F.planetStatus(this.s, this.s.planets.indexOf(p))).join(',') + '|' + this.s.rootLv + '|' + this.s.curPlanet + '|' + this.s.planets.map((p) => p.rem <= 0 ? 1 : 0).join('');
- if (sig !== this.systemSig) { this.systemSig = sig; this.buildSystem(); }
- }
- renderAll() {
- this.buildSystem();
- this.renderGoal(); this.renderPlanetCard(); this.renderLives(); this.paintStats(); this.renderNavDots();
- // 抽屉正文只在“打开抽屉”时由 openSheet 渲染;其余渲染不重建(避免按钮句柄丢失与输入被打断)
- this.tutorialHint();
- }
- // ── 抽屉 ──────────────────────────────────────────
- openSheet(name, arg) {
- if (name === 'star') this.s.tutorial.starOpened = true;
- this.sheetName = name; this.sheetArg = arg;
- $('#sheet-mask').hidden = false;
- setTimeout(() => $('#sheet').focus({ preventScroll: true }), 30);
- if (name === 'ach') this.s.seen.ach = achCount(this.s);
- this.renderNavDots();
- $$('.tabbar button').forEach((b) => b.classList.toggle('on', b.dataset.nav === name));
- this.renderSheetBody();
- this.renderGoal();
- this.afterSheetRender(name);
- }
- closeSheet() {
- if ($('#sheet-mask').hidden) return;
- $('#sheet-mask').hidden = true; this.sheetName = null;
- $$('.tabbar button').forEach((b) => b.classList.remove('on'));
- }
- renderSheetBody() {
- const name = this.sheetName;
- const titles = { lives: '生命', star: '太阳系星图', era: '纪元 · 时间结晶', ach: '成就', root: '世界树根系', menu: '菜单', planet: PLANETS[this.s.curPlanet].name, lock: '尚未抵达' };
- $('#sheet-title').textContent = titles[name] || '';
- const body = $('#sheet-body');
- const foot = $('#sheet-foot');
- foot.innerHTML = '';
- if (name === 'lives') body.innerHTML = this.sheetLives();
- else if (name === 'star') body.innerHTML = this.sheetStar();
- else if (name === 'era') body.innerHTML = this.sheetEra();
- else if (name === 'ach') body.innerHTML = this.sheetAch();
- else if (name === 'root') body.innerHTML = this.sheetRoot();
- else if (name === 'menu') body.innerHTML = this.sheetMenu();
- else if (name === 'planet') body.innerHTML = this.sheetPlanet();
- else if (name === 'lock') body.innerHTML = `<div class="lock-note">${icon('lock')}<div>${esc(this.sheetArg?.msg || '')}</div></div><div class="sec-title">星球档案</div>${this.planetDossier(this.sheetArg?.i ?? 0)}`;
- if (name === 'lives') {
- const i = this.s.curPlanet;
- const cur = F.availableLives(this.s, i).find((l) => this.s.res >= S.lifeCostNow(this.s, l.id));
- if (cur) {
- foot.innerHTML = `<button class="btn primary" id="buy-best" style="width:100%">种下 / 升级「${esc(cur.name)}」· ${fmt(S.lifeCostNow(this.s, cur.id))}</button>`;
- $('#buy-best').onclick = () => this.buyLife(cur.id);
- }
- }
- if (name === 'root') {
- foot.innerHTML = `<button class="btn primary" id="root-buy" style="width:100%">升级根系 · ${fmt(S.rootCostNow(this.s))}</button>`;
- $('#root-buy').onclick = () => this.buyRootAll();
- }
- if (name === 'era') {
- if (S.canCurio(this.s)) {
- const opts = S.curioOptions(this.s);
- foot.innerHTML = `<div class="sec-title" style="margin-top:0">星辰洗礼(${B.CURIO.cost} 结晶 · 三选一)</div><div class="curio-opts">${opts.map((o) => `<button class="curio" data-el="${o.id}">${icon(o.icon)}<b>${o.name}</b><small>${o.desc}</small><span class="own">已有 ${(this.s.stems[o.id] || 0)}</span></button>`).join('')}</div>`;
- $$('#sheet-foot .curio').forEach((b) => b.onclick = () => { const out = S.doCurio(this.s, b.dataset.el); this.handle(out); this.renderAll(); this.paintStats(); });
- }
- return;
- }
- if (name === 'planet') {
- const i = this.s.curPlanet;
- const cs = F.challengeStatus(this.s, i);
- if (!cs.sat && cs.unlockedAll) { /* 挑战详情在正文里 */ }
- const h = this.s.heat[i];
- const canHeal = h.kind === 'bad' && !h.healed && h.until - this.now >= B.STAR.heatBadDur - B.STAR.healWindow && h.until > this.now;
- foot.innerHTML = `${canHeal ? `<button class="btn primary" id="heal-btn" style="width:100%">修补根系屏障 · ${fmt(S.healCostNow(this.s, this.now))}</button>` : ''}`;
- if (canHeal) $('#heal-btn').onclick = () => { const out = S.heal(this.s, this.now); this.handle(out); this.renderAll(); };
- }
- }
- sheetLives() {
- const s = this.s, i = s.curPlanet;
- const P = PLANETS[i];
- const av = F.availableLives(s, i);
- const nextL = F.nextLife(s, i);
- const ls = LIFE.filter((l) => l.planet === i);
- const rows = ls.map((l) => {
- const cur = s.lives[i][l.id];
- const unlocked = av.some((x) => x.id === l.id);
- const cost = S.lifeCostNow(s, l.id);
- if (!unlocked) {
- const need = l.unlockRoot && s.rootLv < l.unlockRoot ? `世界树扎根 ${l.unlockRoot} 级` : `星球改造 ${Math.round(l.stage * 100)}%`;
- return `<div class="card life-card locked">${iconBox(l.icon, true)}<div><h4>${l.name}</h4><p>${esc(l.lore)}</p><p style="color:#8fa2c4;margin-top:4px">🔒 ${need} 后苏醒</p></div><div></div></div>`;
- }
- return `<div class="card life-card">${iconBox(l.icon)}<div><h4>${l.name} <span class="muted small">Lv ${cur || 0}</span></h4><p>${esc(l.lore)}</p><p style="margin-top:4px;color:#9cffc0">${kindText(l)}${cur ? ` · 已叠 ${stackText(l, cur)}` : ''}</p></div><button class="buy" data-buy="${l.id}" ${s.res < cost ? 'disabled' : ''}>${cur ? '升级' : '种下'}<span class="c">${fmt(cost)} 本源</span></button></div>`;
- }).join('');
- $$('.life-card').forEach(() => {});
- setTimeout(() => $$('#sheet-body [data-buy]').forEach((b) => b.onclick = () => this.buyLife(b.dataset.buy)), 0);
- const root = `<div class="card life-card">${iconBox('root')}<div><h4>世界树根系 <span class="muted small">Lv ${s.rootLv}</span></h4><p>根系越深,本源生长越快。${PLANETS[Math.min(8, i + 1)].name}需要扎根 ${PLANETS[Math.min(8, i + 1)].unlockLv} 级。</p><p style="margin-top:4px;color:#9cffc0">本源产出 ×${B.rootProdMul(s.rootLv).toFixed(2)}</p></div><button class="buy" data-root="1" ${s.res < S.rootCostNow(s) ? 'disabled' : ''}>扎根<span class="c">${fmt(S.rootCostNow(s))} 本源</span></button></div>`;
- setTimeout(() => { const b = $('#sheet-body [data-root]'); if (b) b.onclick = () => this.buyRootAll(); }, 0);
- const nextHint = nextL && !av.some((x) => x.id === nextL.id) ? `<div class="card"><b class="small">下一株生命 · ${nextL.name}</b><p class="small muted" style="margin:4px 0 0">${nextL.unlockRoot && s.rootLv < nextL.unlockRoot ? `根系扎根到 ${nextL.unlockRoot} 级` : `星球改造到 ${Math.round(nextL.stage * 100)}%`} 后,它会从根须里苏醒。</p></div>` : '';
- return `<div class="sec-title">${P.name} · 生命</div>${root}${rows}${nextHint}`;
- }
- sheetStar() {
- const s = this.s;
- const rows = PLANETS.map((P, i) => {
- const st = F.planetStatus(s, i);
- const pct = 100 - s.planets[i].rem;
- const sub = st === 'cleared' ? '已复苏 ✓' : st === 'locked' ? `需要:${PLANETS[i - 1].name}复苏 · 扎根 ${P.unlockLv} 级` : `${Math.round(pct)}% · ${i === s.curPlanet ? '当前' : '可前往'}`;
- const go = st === 'cleared' ? '已复苏' : st === 'locked' ? '未解锁' : i === s.curPlanet ? '改造中' : '前往';
- return `<div class="pcard ${st} ${i === s.curPlanet ? 'cur' : ''}" data-go="${i}"><div class="orb" style="background: radial-gradient(circle at 34% 30%, ${P.color2}, ${P.color} 60%, #1a2234)"></div><div><h4>${P.name} <span class="muted small">第 ${P.chapterNo} 章</span></h4><p>${sub}</p></div><span class="go ${st === 'locked' ? 'lock' : ''}">${go} ›</span></div>`;
- }).join('');
- setTimeout(() => $$('#sheet-body [data-go]').forEach((c) => c.onclick = () => { const i = +c.dataset.go; if (F.isPlanetUnlocked(s, i)) { if (i !== s.curPlanet && s.planets[i].rem > 0) { this.closeSheet(); this.switchPlanet(i); } else this.openSheet('planet'); } else this.explainLocked(i); }), 0);
- const done = F.clearedCount(s);
- return `<div class="card"><div class="row"><div class="grow"><b>太阳系复苏进度</b><p class="small muted" style="margin:4px 0 0">${done} / ${PLANETS.length} 颗星球重新长出生命</p></div><b style="font-size:26px;color:var(--green2)">${Math.round(done / PLANETS.length * 100)}%</b></div></div><div class="sec-title">逐星推进</div><div class="planet-list">${rows}</div>`;
- }
- sheetEra() {
- const s = this.s;
- const can = S.canEra(s);
- const cleared = F.clearedCount(s);
- const reward = S.eraPreview(s);
- const stems = B.STEM_ELEMENTS.map((e) => `<div class="kv"><span class="k" style="display:flex;gap:6px;align-items:center">${icon(e.icon)} ${e.name}</span><span class="v">×${s.stems[e.id] || 0}</span></div>`).join('');
- const lock = can ? '' : `<div class="lock-note">${icon('lock')}<div><b>新纪元尚未开启</b><br>必须先让<b>地球复苏</b>${s.planets[0].rem <= 0 ? `,并让世界树扎根到 ${B.ERA.minRootLv} 级(当前 ${s.rootLv} 级)` : '——这是第一个纪元的终章仪式'}。<br>纪元会重置所有星球的改造与生命,但时间结晶与基因之种永久保留。</div></div>`;
- const btn = can ? `<div class="sec-title">星辰洗礼</div>${S.canCurio(s) ? '<p class="small muted">选择一颗基因之种,它会永久改变下一个纪元。</p>' : `<p class="small muted">攒够 ${B.CURIO.cost} 颗时间结晶,可以完成一次三选一的星辰洗礼。(当前 ${s.crystals})</p>`}` : '';
- return `<div class="era-hero"><div class="lbl">当前纪元</div><div class="big">${s.eras + 1}</div><div class="small muted">纪元乘区 ×${F.eraFactor(s).toFixed(2)} · 时间结晶 ${s.crystals}</div></div>
- ${lock}
- <div class="card"><div class="kv"><span class="k">已完成星球</span><span class="v">${cleared} / ${PLANETS.length}</span></div>
- <div class="kv"><span class="k">进入新纪元可得</span><span class="v" style="color:var(--gold)">时间结晶 ×${reward}</span></div>
- <div class="kv"><span class="k">永久加成(每次纪元)</span><span class="v">产出与生长 ×1.25</span></div>
- <div class="kv"><span class="k">时间结晶效果</span><span class="v">产出 +15%/颗 · 基因之种 −4%/颗</span></div></div>
- ${can ? `<button class="btn primary" id="era-go" style="width:100%;margin:6px 0 10px">进入新纪元 · ${s.eras + 2}</button>` : ''}
- <div class="sec-title">基因之种(跨纪元永久)</div><div class="card">${stems}</div>${btn}`;
- }
- sheetAch() {
- const s = this.s;
- const grid = ACHIEVEMENTS.map((a) => `<div class="ach ${s.ach[a.id] ? 'on' : ''}"><div class="ic">${icon(a.icon)}</div><b>${a.name}</b><small>${a.desc}</small></div>`).join('');
- return `<div class="card"><div class="row"><div class="grow"><b>成就</b><p class="small muted" style="margin:4px 0 0">已点亮 ${achCount(s)} / ${ACHIEVEMENTS.length}</p></div><b style="font-size:26px;color:var(--gold)">${Math.round(achCount(s) / ACHIEVEMENTS.length * 100)}%</b></div></div><div class="ach-grid">${grid}</div>`;
- }
- sheetRoot() {
- const s = this.s;
- const P = PLANETS[s.curPlanet];
- const nextP = PLANETS[Math.min(PLANETS.length - 1, s.curPlanet + 1)];
- const rows = [
- ['根系等级', `Lv ${s.rootLv}`],
- ['本源产出乘区', `×${B.rootProdMul(s.rootLv).toFixed(2)}(每级 +${(B.ROOT.prodPer * 100).toFixed(0)}%)`],
- ['点击本源', fmt(F.tapOf(s, this.now))],
- ['自动产出', fmt(F.incomeOf(s, this.now)) + '/秒'],
- ['星辰共鸣', '×' + fmt(F.resonanceMul(s)) + '(此前复苏星球的生命)'],
- ['纪元乘区', `×${F.eraFactor(s).toFixed(2)}`],
- ['下一颗星', `${nextP.name} · 需要扎根 ${nextP.unlockLv} 级`],
- ].map(([k, v]) => `<div class="kv"><span class="k">${k}</span><span class="v">${v}</span></div>`).join('');
- return `<div class="card">${rows}</div><p class="small muted">根系是全太阳系的根:等级越高,所有星球的生长都越快。</p>`;
- }
- 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)}
- <div class="sec-title">环境挑战 · ${th.name}</div>
- <div class="card"><p class="lore">${esc(th.desc)}</p>
- <div class="kv"><span class="k">攻克条件</span><span class="v" style="color:${cs.sat ? 'var(--green2)' : 'var(--red)'}">${th.needText} ${cs.sat ? '✓' : '✗'}</span></div>
- <div class="kv"><span class="k">当前压制</span><span class="v">${cs.sat ? '已攻克' : `改造速度 −${Math.round(B.STAR.attackDef * B.STAR.suppress * 100)}%`}</span></div>
- ${P.wave ? `<div class="kv"><span class="k">环境波动</span><span class="v">${h.kind === 'bad' && h.until > this.now ? `${P.wave.name}来袭` : h.kind === 'good' && h.until > this.now ? '转机' : '平稳'}</span></div>` : ''}</div>
- <div class="sec-title">本章</div><div class="card"><p class="lore">${esc(ch.intro.text)}</p></div>`;
- }
- planetDossier(i) {
- const P = PLANETS[i];
- const pct = 100 - this.s.planets[i].rem;
- return `<div class="card"><div class="row"><div style="width:56px;height:56px;position:relative">${`<svg viewBox="-60 -60 120 120" style="width:56px;height:56px">${planetSvg(i, 34)}</svg>`}</div><div class="grow"><b>${P.name} <span class="muted small">${P.en}</span></b><p class="small muted" style="margin:4px 0 0">${esc(P.intro)}</p></div></div>
- <div class="bar" style="margin-top:10px"><i style="width:${pct.toFixed(1)}%"></i><span>${pct.toFixed(1)}%</span></div></div>`;
- }
- sheetMenu() {
- return `<div class="card"><b>存档</b><p class="small muted" style="margin:6px 0 10px">游戏每 5 秒自动保存在本机。导出后可在其他设备导入。</p>
- <div class="row" style="gap:8px"><button class="btn ghost grow" id="m-export">导出存档</button><label class="btn ghost grow" style="display:inline-flex;align-items:center;justify-content:center;text-align:center">导入<input type="file" id="m-import" accept="application/json,.json" hidden></label></div>
- <button class="btn ghost" id="m-reset" style="width:100%;margin-top:8px;color:var(--red);border-color:rgba(255,122,107,.3)">重新开始(清除存档)</button></div>
- <div class="card"><b>关于</b><p class="small muted" style="margin:6px 0 0;line-height:1.8">《世界树 · 太阳系》<br>作者:FmodeCode<br>操作:点击世界树获得本源 · 空格键也可以<br>快捷键:Esc 关闭弹层</p></div>
- <p class="small muted" style="text-align:center;margin-top:12px">版本 v3 · 太阳系篇</p>`;
- }
- 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('<b>存档已导出</b>', '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(`<b>导入失败</b><small>${r.error}</small>`, '', 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 `<div class="ic">${icon(name)}</div>`; }
- function kindText(l) {
- if (l.kind === 'prod') return `本源产出 +${Math.round(l.per * 100)}%/级`;
- if (l.kind === 'attack') return `星球稳定 +${Math.round(l.per * 100)}%/级(产出与改造更快)`;
- return `产出 +${Math.round(l.per * 100)}% · 稳定 +${Math.round(l.per * 100)}%/级`;
- }
- function stackText(l, n) {
- if (l.kind === 'prod') return `本源 ×${(1 + l.per * n).toFixed(2)}`;
- if (l.kind === 'attack') return `稳定 +${(l.per * n * 100).toFixed(0)}%`;
- return `本源 ×${(1 + l.per * n).toFixed(2)} · 稳定 +${(l.per * n * 100).toFixed(0)}%`;
- }
- function confettiSmall() {
- const layer = document.getElementById('fx');
- for (let k = 0; k < 18; k++) {
- const e = document.createElement('div'); e.className = 'spark';
- e.style.left = (innerWidth / 2 + (Math.random() - 0.5) * 80) + 'px'; e.style.top = innerHeight * 0.6 + 'px';
- e.style.setProperty('--dx', (Math.random() - 0.5) * 120 + 'px'); e.style.setProperty('--dy', (-60 - Math.random() * 80) + 'px');
- layer.appendChild(e); setTimeout(() => e.remove(), 700);
- }
- }
- /** 导出给自动化测试使用:渲染类的小工具 */
- export const __test = { planetPos };
|