ui.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. // 表现层:DOM 渲染、弹窗、Toast、里世界交互、存档 UI。只读 state,所有写入都经 state.js 的 action。
  2. // 署名:FmodeCode
  3. import * as C from './config.js';
  4. import * as F from './formulas.js';
  5. import * as S from './state.js';
  6. import * as R from './rift.js';
  7. import { CIV_EVENTS, CRISIS_EVENTS } from './events-data.js';
  8. import { fmt, fmtPct, fmtTime, esc } from './util.js';
  9. import { I, lifeIcon, relicIcon } from './icons.js';
  10. import { MarchScene } from './march.js';
  11. const $ = (s, r = document) => r.querySelector(s);
  12. const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));
  13. const BATCH = 12;
  14. export class App {
  15. constructor(state, rift) {
  16. this.s = state;
  17. this.riftRun = rift && rift.run ? rift.run : null;
  18. this.cache = new Map();
  19. this.scene = new MarchScene($('#march'));
  20. this.toasts = [];
  21. this.modalOpen = false;
  22. this.dialog = null; // 当前弹窗类型
  23. this.dialogQueue = [];
  24. this.lastFrame = performance.now();
  25. this.lastSave = 0;
  26. this.lastRender = 0;
  27. this.fps = { n: 0, t: 0, v: 60 };
  28. this.readTune();
  29. this.bindEvents();
  30. this.bindKeys();
  31. this.startLoop();
  32. }
  33. // ───────────── 循环 ─────────────
  34. startLoop() {
  35. let acc = 0;
  36. const STEP = 0.2;
  37. const loop = (ts) => {
  38. const dt = Math.min(0.5, (ts - this.lastFrame) / 1000);
  39. this.lastFrame = ts;
  40. const tsMul = (this.tune && this.tune.ts) || 1;
  41. acc += dt * tsMul; // 手感调节:时间倍率
  42. let guard = 0;
  43. while (acc >= STEP && guard++ < 10) { acc -= STEP; this.step(STEP); }
  44. if (ts - this.lastRender > 100) { this.lastRender = ts; this.renderDynamic(); }
  45. this.fps.n++; this.fps.t += dt;
  46. if (this.fps.t >= 1) { this.fps.v = Math.round(this.fps.n / this.fps.t); this.fps.n = 0; this.fps.t = 0; }
  47. requestAnimationFrame(loop);
  48. };
  49. requestAnimationFrame(loop);
  50. }
  51. step(dt) {
  52. const s = this.s;
  53. const e0 = s.essence;
  54. const out = S.tick(s, this.riftRun ? { run: this.riftRun } : null, dt);
  55. if (this.tune && this.tune.rs !== 1 && s.essence > e0) s.essence = e0 + (s.essence - e0) * this.tune.rs;
  56. this.riftRun = s.planeRun;
  57. // 表现:跳关
  58. if (out.skip) { this.scene.burst(1); this.floatLayer(`跃迁 +${out.skip.k}`); }
  59. for (const e of out.events) {
  60. if (e.quiet) continue;
  61. if (e.type === 'civ') this.pushDialog({ kind: 'civ', civIdx: e.civIdx });
  62. else if (e.type === 'milestone') this.pushDialog({ kind: 'milestone', data: e });
  63. else if (e.type === 'info') this.log(e.title + ':' + e.text, 'info');
  64. else if (e.type === 'ambient') { this.log(e.text + '(' + e.bonus + ')', 'ambient'); this.toast('✦ ' + e.bonus, 'good'); }
  65. }
  66. if (out.crisis) this.pushDialog({ kind: 'crisis' });
  67. if (out.crisisExpire) { const t = S.crisisExpire(s); if (t) this.log(t, 'crisis'); this.toast(t, 'warn'); }
  68. if (out.anchors) this.log(`锚定位面后台采集:${out.anchors.count} 个位面 +${fmt(out.anchors.gain)} 本源`, 'anchor');
  69. if (out.auto) this.autoHarvest();
  70. if (out.floor) this.floatLayer(`${out.floor} 层`);
  71. // 存档
  72. if (performance.now() - this.lastSave > 30000) { this.lastSave = performance.now(); this.saveNow(); }
  73. }
  74. autoHarvest() {
  75. const s = this.s;
  76. s._lastRebSec = s.playSec;
  77. if (s.planeRun) return;
  78. const st = F.computeStats(s);
  79. if ((s.maxLayerRound || 0) < 3) return;
  80. const r = S.rebirth(s);
  81. if (r.event) this.pushDialog({ kind: 'milestone', data: r.event });
  82. this.log(`禅定回溯 #${s.rebirths} · +${fmt(r.gain)} 结晶(本轮深度 ${fmt(r.T, { int: true })})`, 'mile');
  83. this.toast(`禅定回溯:+${fmt(r.gain)} 时间结晶`, 'good');
  84. this.renderStatic();
  85. }
  86. floatLayer(text) {
  87. const el = document.createElement('div');
  88. el.className = 'skip-float';
  89. el.textContent = text;
  90. el.style.left = (18 + Math.random() * 30) + '%';
  91. el.style.top = (28 + Math.random() * 20) + '%';
  92. $('#float-layer').appendChild(el);
  93. setTimeout(() => el.remove(), 1200);
  94. }
  95. // ───────────── 渲染 ─────────────
  96. renderStatic() { this.envEls = false; this.renderTop(); this.renderLeft(); this.renderRight(); this.renderRiftPanel(); this.renderDynamic(); }
  97. renderDynamic() {
  98. const s = this.s;
  99. const st = F.computeStats(s);
  100. this.stats = st;
  101. this.renderTop(st);
  102. this.renderHud(st);
  103. // 资源块
  104. this.setText('#res-essence .num', fmt(s.essence));
  105. this.setText('#res-essence-rate', `${fmt(st.prod)} / 秒${st.frozen ? '(冻结)' : ''}`);
  106. this.setText('#res-crystal .num', fmt(s.crystals));
  107. this.setText('#res-crystal-rate', s.planes.filter((p) => p.explore >= 100).length ? `锚定采集 ${s.planes.filter((p) => p.explore >= 100).length} 处运行中` : '转生结算,永久');
  108. const lf = s.layer;
  109. this.html('#hud-r', `<b>${fmt(Math.max(s.maxLayerRound || 0, Math.floor(s.layer)), { int: true })}</b> 本轮最深<br>时间乘区 <b>×${st.timeMul.toFixed(2)}</b>`);
  110. this.renderEnv(st);
  111. const magic = $('#magic-badge');
  112. if (st.narrSig > 0) {
  113. this.html('#magic-badge', `叙事共鸣 ×${Math.pow(1.3, Math.min(10, st.narrSig)).toFixed(2)}(${st.narrSig} 层)`);
  114. $('#magic-badge').hidden = false;
  115. } else $('#magic-badge').hidden = true;
  116. // 行动条
  117. this.refreshMainline(st);
  118. this.refreshActions();
  119. this.refreshAutoButtons();
  120. // 转生面板
  121. this.refreshRebirth();
  122. // 升级按钮状态(价格变化)
  123. this.refreshUpgradeButtons();
  124. this.refreshLives();
  125. // 主世界 canvas
  126. const chF = C.chapterOf(lf);
  127. this.scene.update({ chapter: chF, layerFloat: lf, layersPerSec: st.layersPerSec, layerSec: st.layerSec });
  128. document.documentElement.style.setProperty('--plane-c', C.PLANES[s.currentPlane].color);
  129. $('.topbar').style.borderTopColor = C.PLANES[s.currentPlane].color;
  130. // 里世界
  131. if (this.riftRun) this.renderRiftLive();
  132. // 手感调节(?speed=&prod=)
  133. const tune = this.tune || { ts: 1, rs: 1 };
  134. const th = $('#tune-hint');
  135. if (th) { const text = (tune.ts !== 1 || tune.rs !== 1) ? `×${tune.ts} 时间 · ×${tune.rs} 产出` : ''; if (th.textContent !== text) th.textContent = text; }
  136. // 引导
  137. this.refreshGuide(st);
  138. }
  139. renderEnv(st) {
  140. if (!this.envEls) {
  141. this.envEls = true;
  142. $('#env-strip').innerHTML = '<span class="env-dot"></span><b></b><span class="env-eff"></span><span class="env-prog"><i></i></span><span class="env-left"></span><span class="env-left" id="tune-hint" style="margin-left:auto;color:#cbd5e1"></span>';
  143. }
  144. const env = st.env;
  145. if (!env) return;
  146. const strip = $('#env-strip');
  147. const D = Math.max(0, (this.s.layer || 0) - st.start);
  148. const prog = (D % 18) / 18;
  149. const fire = st.envFactors && st.envFactors.fire ? ` · 火种 ${Math.floor(this.s._fireAcc || 0)}/10` : '';
  150. const boost = (this.s._fireBoost || 0) > Date.now() / 1000 ? ' · 星火 ×2.5' : '';
  151. const set = (sel, v) => { const e = strip.querySelector(sel); if (e && e.textContent !== v) e.textContent = v; };
  152. const dot = strip.querySelector('.env-dot'); if (dot) dot.style.background = env.color;
  153. set('b', env.name);
  154. set('.env-eff', env.eff);
  155. const bar = strip.querySelector('.env-prog i'); if (bar) bar.style.cssText = `width:${(prog * 100).toFixed(0)}%;background:${env.color}`;
  156. set('.env-left', env.desc + fire + boost);
  157. }
  158. renderHud(st) {
  159. if (!this.hudBuilt) {
  160. this.hudBuilt = true;
  161. $('#hud').innerHTML = '<div><div class="layer" id="hud-layer">0<small>层</small></div><div class="meta" id="hud-sub"></div></div><div class="meta hud-meta" id="hud-meta"></div>';
  162. $('#env-strip').innerHTML = '<span class="env-dot"></span><b></b><span class="env-eff"></span><span class="env-prog"><i></i></span><span class="env-left"></span><span class="env-left" id="tune-hint" style="margin-left:auto;color:#cbd5e1"></span>';
  163. }
  164. const lf = this.s.layer;
  165. this.html('#hud-layer', `${fmt(Math.floor(lf), { int: true })}<small>层</small>`);
  166. this.setText('#hud-sub', `距下一层 ${fmtPct(Math.min(0.99, lf - Math.floor(lf)), 0)} · 本轮第 ${fmt(Math.floor(lf) - st.start + 1, { int: true })} 层`);
  167. this.setText('#hud-meta', `${fmt(st.prod)} 本源/秒 · 约 ${st.minutesPerLayer < 0.01 ? '<0.01' : st.minutesPerLayer.toFixed(2)} 分/层(含跳关) · 跳关 ${fmtPct(st.skipP, 0)}`);
  168. }
  169. refreshMainline(st) {
  170. const s = this.s;
  171. const ch = s.escaped ? 5 : C.chapterOf(s.layer);
  172. const info = C.CHAPTERS[ch];
  173. const prog = Math.min(1, s.layer / C.TOTAL_LAYERS);
  174. const bar = $('#mainline .esc-bar .fill');
  175. if (bar) bar.style.width = (prog * 100).toFixed(2) + '%';
  176. const el = $('#esc-layer'); if (el) { const v = `第 ${fmt(Math.floor(s.layer), { int: true })} / ${C.TOTAL_LAYERS} 层`; if (el.textContent !== v) el.textContent = v; }
  177. const t = $('#ch-title'); if (t) { const v = s.escaped ? '冲出空洞 · 自由轮回' : info.title; if (t.textContent !== v) { t.textContent = v; this.setText('#mainline .ch-desc', s.escaped ? `你已完成 ${s.escapeCount || 1} 次逃逸;禅定循环会继续累积自由轮回加成(×${C.freedomMul(s).toFixed(2)})。` : info.desc); const idx = $('#mainline .ch-title .idx'); if (idx) idx.textContent = `CH.${ch + 1} / 6`; } }
  178. const tag = $('#mainline .panel-title .tag'); if (tag) { const v = fmtPct(prog, 2); if (tag.textContent !== v) tag.textContent = v; }
  179. }
  180. setText(sel, v) { const e = $(sel); if (e && e.textContent !== v) e.textContent = v; }
  181. html(sel, v) { const e = $(sel); if (e && this.cache.get(sel) !== v) { e.innerHTML = v; this.cache.set(sel, v); } }
  182. renderTop(st) {
  183. if (!st) st = this.stats || F.computeStats(this.s);
  184. const s = this.s;
  185. const ch = C.chapterOf(s.layer);
  186. const t = s.escaped ? (s.escapedT || 0) : null;
  187. this.html('#topstats', `
  188. <div class="tstat"><span class="k">世界树等级</span><span class="v num">D${s.treeLv}</span></div>
  189. <div class="tstat optional"><span class="k">回归</span><span class="v num">${s.rebirths}</span></div>
  190. <div class="tstat optional"><span class="k">位面</span><span class="v">${C.PLANES[s.currentPlane].tier} · ${C.PLANES[s.currentPlane].name}</span></div>
  191. <div class="tstat"><span class="k">当前章节</span><span class="v">${s.escaped ? '已冲出空洞' : C.CHAPTERS[ch].title}</span></div>`);
  192. }
  193. renderLeft() {
  194. const s = this.s;
  195. this.html('#resources', `
  196. <div class="panel-title">资源 · ${C.PLANES[s.currentPlane].essence}</div>
  197. <div class="res-row">
  198. <div class="res"><div class="k"><span class="dot"></span>本源 <span style="font-size:10px;color:var(--muted-2)">· 本轮</span></div>
  199. <div class="v num" id="res-essence"><span class="num">0</span></div><div class="d" id="res-essence-rate">0 / 秒</div></div>
  200. <div class="res"><div class="k"><span class="dot gold"></span>时间结晶 <span style="font-size:10px;color:var(--muted-2)">· 永久</span></div>
  201. <div class="v num" id="res-crystal"><span class="num">0</span></div><div class="d" id="res-crystal-rate">转生结算,永久</div></div>
  202. </div>`);
  203. this.renderMainline();
  204. this.renderUpgrades();
  205. }
  206. renderMainline() {
  207. const s = this.s;
  208. const ch = s.escaped ? 5 : C.chapterOf(s.layer);
  209. const info = C.CHAPTERS[ch];
  210. const prog = Math.min(1, s.layer / C.TOTAL_LAYERS);
  211. const marks = C.CHAPTERS.slice(1).map((c) => {
  212. const pct = (c.at / C.TOTAL_LAYERS) * 100;
  213. return `<div class="mark ${s.layer >= c.at ? 'done' : ''}" style="left:${pct}%"><span>${c.short}</span></div>`;
  214. }).join('');
  215. let guide = '';
  216. if (!s.flags.guideDone) {
  217. const step = this.guideStep();
  218. if (step) guide = `<div class="guide" style="margin-bottom:10px"><div class="g">${step}</div><button class="x" data-act="guide-x" title="我知道了">×</button></div>`;
  219. }
  220. this.html('#mainline', `
  221. ${guide}
  222. <div class="panel-title">主线 · 逃逸进度 <span class="tag">${fmtPct(prog, 2)}</span></div>
  223. <div class="chapter">
  224. <div class="ch-title"><span class="idx">CH.${ch + 1} / 6</span><span id="ch-title">${s.escaped ? '冲出空洞 · 自由轮回' : info.title}</span></div>
  225. <div class="ch-desc" id="ch-desc">${s.escaped ? `空洞已被甩在身后。你已完成 ${s.escapeCount || 1} 次逃逸;禅定循环将继续为你累积自由轮回加成(×${C.freedomMul(s).toFixed(2)})。` : info.desc}</div>
  226. </div>
  227. <div class="esc-track">
  228. <div class="esc-bar"><div class="fill" style="width:${(prog * 100).toFixed(2)}%"></div>${marks}</div>
  229. <span id="esc-layer">第 ${fmt(Math.floor(s.layer), { int: true })} / ${C.TOTAL_LAYERS} 层</span><span id="esc-goal">${s.escaped ? '已抵达' : '目标:冲出空洞'}</span>
  230. </div>`);
  231. }
  232. guideStep() {
  233. const s = this.s;
  234. if (s.playSec < 12) return '世界树正在沿连续空间行军。<b>本源</b>在持续生长,先点「升级根须」让它长得更快。';
  235. if (s.rebirths === 0 && s.layer < 10) return '推进速度在加深后放缓。<b>本源</b>够了就买「根须」:产出 ×1.10、推进 ×5%。';
  236. if (s.rebirths === 0 && s.layer >= 10) return '本节快到顶了——点右侧 <b>「回溯」</b>炼化时间结晶,下一次轮回会更快。';
  237. if (s.planes[0].explore < 100 && !s.flags.riftDone2) return '时空裂缝已开启:去 <b>里世界</b> 打一局(约 1~5 分钟),用探索度锚定位面。';
  238. return null;
  239. }
  240. refreshGuide(st) {
  241. // 小步骤完成标记后自动消失
  242. if (this.s.flags.guideDone) return;
  243. const step = this.guideStep();
  244. const g = $('#mainline .guide .g');
  245. if (!step) { const el = $('#mainline .guide'); if (el) el.remove(); return; }
  246. if (!g) { this.renderMainline(); return; }
  247. if (g.innerHTML !== step) g.innerHTML = step;
  248. }
  249. renderUpgrades() {
  250. const s = this.s;
  251. // 首次渲染后只动态刷新价格/收益数值,避免每次重绘整块 DOM
  252. if (this.upgBuilt) {
  253. for (const k of C.UPGRADE_KINDS) { const lv = s.upgrades[k] || 0; this.setText('#upg-n-' + k, 'Lv ' + lv); }
  254. return;
  255. }
  256. this.upgBuilt = true;
  257. const rows = C.UPGRADE_KINDS.filter((k) => k === 'root' || k === 'canopy').map((k) => {
  258. const c = C.COST[k];
  259. const lv = s.upgrades[k] || 0;
  260. const ic = k === 'root' ? I.tree() : I.canopy();
  261. return `<div class="upg">
  262. <div class="ic">${ic}</div>
  263. <div class="info"><div class="n"><span>${c.name}</span><span class="lv" id="upg-n-${k}">Lv ${lv}</span></div><div class="d" data-desc="${k}">${this.upgradeDesc(k, lv)}</div></div>
  264. <button class="buy" data-act="upg" data-k="${k}" id="buy-${k}"><span class="c" id="cost-${k}">—</span><span class="n2">点击购买</span></button>
  265. </div>`;
  266. }).join('');
  267. this.html('#upgrades', `<div class="panel-title">本轮升级</div>${rows}`);
  268. }
  269. upgradeDesc(k, lv) {
  270. if (k === 'root') return `产出 <b>×${C.rootProdMul(lv + BATCH / 2).toFixed(2)}</b> · 推进速度 <b>×${C.rootSpeedMul(lv).toFixed(2)}</b>`;
  271. return `跳关触发率 <b>${fmtPct(C.canopySkip(lv), 1)}</b>(每级 +0.5%,封顶 60%)`;
  272. }
  273. refreshUpgradeButtons() {
  274. const s = this.s;
  275. for (const k of C.UPGRADE_KINDS) {
  276. const btn = $('#buy-' + k);
  277. if (!btn) continue;
  278. const lv = s.upgrades[k] || 0;
  279. const n = C.maxAffordable(k, lv, s.essence * 0.9);
  280. const cost = C.batchCost(k, lv, n);
  281. const can = n > 0;
  282. btn.disabled = !can;
  283. btn.classList.toggle('ok', can);
  284. btn.classList.toggle('pulse', can && lv === 0);
  285. this.setText('#cost-' + k, can ? `${n} 级 · ${fmt(cost)}` : `${fmt(C.costOf(k, lv))}`);
  286. const d = $(`#upgrades [data-desc="${k}"]`);
  287. if (d) { const v = this.upgradeDesc(k, lv); if (d.innerHTML !== v) d.innerHTML = v; }
  288. }
  289. }
  290. refreshLives() {
  291. const s = this.s;
  292. if (!this.lifeEls) {
  293. const raceHead = (r) => `<div class="race-head"><span class="chip" style="background:${C.RACES[r].color}">${r}</span><span style="font-weight:500;letter-spacing:0;text-transform:none">${C.RACES[r].bond.split(':')[0]}</span><span class="bond" id="bond-${r}"></span></div>`;
  294. const lifeRow = (l) => `<div class="life" data-life="${l.id}" id="life-${l.id}"><div class="ic">${lifeIcon(l.icon)}</div><div class="info"><div class="n"><span>${l.name}</span><span class="lv" id="life-desc-${l.id}"></span></div><div class="s">${l.skill}</div></div><button class="buy" data-act="life" data-id="${l.id}" id="life-buy-${l.id}"><span class="c"></span></button></div>`;
  295. const block = (r) => `<div class="race-block">${raceHead(r)}${C.LIVES.filter((l) => l.race === r).map(lifeRow).join('')}</div>`;
  296. this.html('#lives', `<div class="panel-title">兵种 · 常驻跑道</div>${block('生命')}${block('星穹')}${block('虚空')}`);
  297. this.lifeEls = true;
  298. this.lifeEls = true;
  299. }
  300. const sk = F.lifeSkill(s);
  301. const bondN = sk.stacks;
  302. for (const r of Object.keys(C.RACES)) {
  303. const el = $('#bond-' + r);
  304. if (el) {
  305. const txt = r === '虚空' ? `跳关 +${(bondN[r] * C.RACE_SKIP_BONUS * 100).toFixed(0)}%` : `×${Math.pow(1.3, bondN[r]).toFixed(2)}`;
  306. if (el.textContent !== txt) el.textContent = txt;
  307. el.classList.toggle('on', bondN[r] > 0);
  308. }
  309. }
  310. C.LIVES.forEach((l, i) => {
  311. const row = $('#life-' + l.id);
  312. if (!row) return;
  313. const unlocked = F.lifeUnlocked(s, i);
  314. const lv = s.lives[l.id] || 0;
  315. row.classList.toggle('locked', !unlocked);
  316. this.setText('#life-desc-' + l.id, unlocked ? `Lv ${lv}` : '未解锁');
  317. const btn = $('#life-buy-' + l.id);
  318. const cost = F.lifeCost(s, l.id);
  319. const can = unlocked && s.essence >= cost;
  320. btn.disabled = !can;
  321. btn.classList.toggle('ok', can);
  322. btn.innerHTML = unlocked ? `<span class="c">${fmt(cost)}</span><span style="font-size:10px;color:var(--muted)">本源</span>` : `<span class="c" style="color:var(--muted)">锁定</span>`;
  323. });
  324. }
  325. renderRight() {
  326. this.renderRebirthStatic();
  327. this.renderPerm();
  328. this.renderPlanes();
  329. }
  330. renderRebirthStatic() {
  331. this.html('#rebirth', `
  332. <div class="panel-title">时间回溯</div>
  333. <div class="reb-card">
  334. <div class="k">预计炼化 <span style="font-weight:400;letter-spacing:0">· 首次建议 ≥20 层</span></div>
  335. <div class="v"><span id="reb-gain">0</span><small>结晶</small></div>
  336. <div class="line"><span>本轮深度 <b id="reb-depth">0</b></span><span>回溯代价 <b id="reb-cost">1</b></span><span>收益效率 <b id="reb-eff">—</b></span></div>
  337. </div>
  338. <div class="actions" style="grid-template-columns:1fr 1fr;margin-top:9px">
  339. <button class="act primary" data-act="rebirth" id="btn-rebirth"><span class="t">回溯 ${'<span class="kbd">R</span>'}</span><span class="s" id="reb-sub">炼化时间结晶</span></button>
  340. <button class="act" data-act="auto" id="btn-auto" title="右键切换 60/120/300 秒节奏"><span class="t">禅定</span><span class="s" id="auto-sub">挂机自动回溯</span></button>
  341. </div>
  342. <div class="sub-line" style="margin-top:8px"><span>自由轮回加成 <b id="reb-freedom">×1.00</b></span><span>转生衰减 <b id="reb-decay">×1</b></span></div>`);
  343. }
  344. refreshRebirth() {
  345. const s = this.s;
  346. const st = this.stats || F.computeStats(s);
  347. const T = s.maxLayerRound || 0;
  348. const gain = st.reward;
  349. const cost = C.rebirthCost(T);
  350. this.setText('#reb-gain', fmt(gain));
  351. this.setText('#reb-depth', fmt(Math.max(T, s.layer || 0), { int: true }));
  352. this.setText('#reb-cost', fmt(cost, { int: true }));
  353. this.setText('#reb-eff', `×${(gain / Math.max(1, cost)).toFixed(2)}`);
  354. const btn = $('#btn-rebirth');
  355. btn.classList.toggle('can', gain / Math.max(1, cost) >= 1);
  356. const r = F.rebirthFloor(s);
  357. const btnS = $('#reb-sub');
  358. const sub = s.escaped ? '逃逸完成 · 可自由轮回' : `下一轮回从第 ${fmt(r, { int: true })} 层起飞`;
  359. if (btnS.textContent !== sub) btnS.textContent = sub;
  360. btn.disabled = (T < 3) || !!s.planeRun;
  361. this.setText('#reb-freedom', '×' + C.freedomMul(s).toFixed(2));
  362. this.setText('#reb-decay', '×' + Math.pow(0.5, 0).toFixed(0));
  363. }
  364. renderPerm() {
  365. const s = this.s;
  366. const nextCost = F.permCost(s, 'stem');
  367. const nextProd = C.treeProdMul(s.treeLv + 1) / C.treeProdMul(s.treeLv);
  368. const nextSpd = C.treeSpeedMul(s.treeLv + 1) / C.treeSpeedMul(s.treeLv);
  369. const relicCost = s.relics.length < 8 ? C.relicCost(s.relics.length) : null;
  370. const relics = C.RELICS.map((r, i) => `<div class="relic ${i < s.relics.length ? '' : 'off'}" title="${r.name}:${r.desc}">${relicIcon(r.icon)}</div>`).join('');
  371. this.html('#perm', `
  372. <div class="panel-title">永久投资 · 时间结晶</div>
  373. <div class="perm">
  374. <div class="info"><div class="n"><span>世界树等级 <span style="font-size:11px;color:var(--muted);font-weight:500">D${s.treeLv}</span></span></div>
  375. <div class="d">产出 ×${nextProd.toFixed(2)} · 速度 ×${nextSpd.toFixed(2)}(永久)</div></div>
  376. <button class="buy" data-act="buy-tree" id="buy-tree"><span class="c" id="tree-cost">${fmt(nextCost, { int: true })}</span><span style="font-size:10px;color:var(--muted)">结晶</span></button>
  377. </div>
  378. <div class="perm">
  379. <div class="info"><div class="n"><span>遗物 ${s.relics.length}/8</span></div><div class="d">每件 本源产出 ×1.25(独立乘区)</div>
  380. <div class="relics">${relics}</div></div>
  381. <button class="buy" data-act="buy-relic" id="buy-relic" ${relicCost == null ? 'disabled' : ''}><span class="c" id="relic-cost">${relicCost == null ? '已收集' : fmt(relicCost, { int: true })}</span><span style="font-size:10px;color:var(--muted)">结晶</span></button>
  382. </div>`);
  383. }
  384. refreshPermButtons() {
  385. const s = this.s;
  386. const tb = $('#buy-tree');
  387. if (tb) { const can = s.crystals >= F.permCost(s, 'stem'); tb.disabled = !can; tb.classList.toggle('ok', can); }
  388. const rb = $('#buy-relic');
  389. if (rb && s.relics.length < 8) { const can = s.crystals >= C.relicCost(s.relics.length); rb.disabled = !can; rb.classList.toggle('ok', can); }
  390. }
  391. renderPlanes() {
  392. const s = this.s;
  393. const cards = C.PLANES.map((p, i) => {
  394. const ex = s.planes[i].explore;
  395. const unlocked = C.planeUnlocked(s, i);
  396. const tier = C.exploreTierOf(ex);
  397. const lock = i > 0 ? C.PLANE_UNLOCK_AT.find((u) => u.plane === i) : null;
  398. // 主题卡图:缺失(img 未登记或加载失败)时 onerror 隐藏,退回纯文字卡,不留裂图
  399. const art = p.img ? `<img class="art" src="${p.img}" alt="${p.name}" loading="lazy" decoding="async" onerror="this.remove()">` : '';
  400. return `<button class="plane-card ${s.currentPlane === i ? 'cur' : ''} ${unlocked ? '' : 'locked'}" data-act="plane" data-p="${i}" ${unlocked ? '' : 'disabled'}>
  401. ${art}
  402. <span class="tier" style="background:${p.color}">${p.tier}</span>
  403. <div class="nm">${p.name}</div>
  404. <div class="met">${p.metric} · ${p.essence}</div>
  405. <div class="bar"><i style="width:${ex}%;background:${p.color}"></i></div>
  406. <div class="ex"><span>探索 ${ex.toFixed(0)}/100 · ${tier.at ? tier.label.split(',')[0] : '未勘探'}</span>${ex >= 100 ? '<span class="an">已锚定</span>' : ''}</div>
  407. ${unlocked ? '' : `<div class="ex"><span>需 ${C.PLANES[lock.from].name} 锚定</span></div>`}
  408. </button>`;
  409. }).join('');
  410. const p = C.PLANES[s.currentPlane];
  411. const WORLDTREE_ART = '<figure class="tree-art"><img src="assets/void-escape.png" alt="空洞之外" loading="lazy" decoding="async" onerror="this.parentNode.remove()"><figcaption><b>世界树</b> · 空洞之外,根须仍在生长</figcaption></figure>';
  412. this.html('#planes', `<div class="panel-title">位面 · 规则模板</div>
  413. <div class="plane-list">${cards}</div>
  414. ${WORLDTREE_ART}
  415. <div class="plane-note"><b>${p.name}规则</b>:${p.rule}<br><b>加成</b>:${p.bonus}</div>`);
  416. }
  417. renderActions() {
  418. if (this.actionsKey === 'built') return;
  419. this.actionsKey = 'built';
  420. const s = this.s;
  421. const riftCd = s.riftCdSec || 0;
  422. this.html('#actions', `
  423. <button class="act primary" data-act="rebirth"><span class="t">回溯 <span class="kbd">R</span></span><span class="s">炼化时间结晶 · 重置本轮</span></button>
  424. <button class="act" data-act="rift" id="btn-rift"><span class="t">里世界 <span class="kbd">T</span></span><span class="s" id="rift-sub">${riftCd > 0 ? `冷却 ${Math.ceil(riftCd)} 秒` : '时空裂缝 · 探索位面'}</span></button>
  425. <button class="act" data-act="auto" id="btn-auto2" title="右键切换 60/120/300 秒节奏"><span class="t">禅定 <span class="kbd">A</span></span><span class="s">${s.autoOn ? `开启 · 每 ${S.autoRebirthEvery(s)} 秒` : '挂机自动回溯'}</span></button>
  426. <button class="act" data-act="save"><span class="t">存档</span><span class="s">导出 / 导入 / 重置</span></button>`);
  427. }
  428. refreshAutoButtons() {
  429. const s = this.s;
  430. for (const id of ['btn-auto', 'btn-auto2']) {
  431. const b = $('#' + id);
  432. if (!b) continue;
  433. b.classList.toggle('primary', !!s.autoOn);
  434. b.classList.toggle('can', !s.autoOn && s.playSec > 20);
  435. }
  436. if (s.autoOn && this._autoCycleAt && performance.now() - this._autoCycleAt < 1200) this.toast(`禅定节奏:每 ${S.autoRebirthEvery(s)} 秒回溯一次`);
  437. if ($('#auto-sub')) this.setText('#auto-sub', s.autoOn ? `每 ${S.autoRebirthEvery(s)} 秒 · 已开启(点击关闭)` : '挂机时自动回溯');
  438. }
  439. refreshActions() {
  440. const s = this.s;
  441. const sub = $('#rift-sub');
  442. if (sub) { const v = (s.riftCdSec || 0) > 0 ? `冷却 ${Math.ceil(s.riftCdSec)} 秒` : '时空裂缝 · 探索位面'; if (sub.textContent !== v) sub.textContent = v; }
  443. const b = $('#btn-rift'); if (b) b.disabled = (s.riftCdSec || 0) > 0;
  444. const sub2 = $('#btn-auto2 .s'); if (sub2) { const v = s.autoOn ? `开启 · 每 ${S.autoRebirthEvery(s)} 秒` : '挂机自动回溯'; if (sub2.textContent !== v) sub2.textContent = v; }
  445. const a2 = $('#btn-auto2'); if (a2) { a2.classList.toggle('can', !s.autoOn && s.playSec > 20); }
  446. const cd = $('#plane-cd'); if (cd) { const v = s.planes.filter((p) => p.explore >= 100).length ? `锚定 ${s.planes.filter((p) => p.explore >= 100).length} 处采集中` : '未锚定'; if (cd.textContent !== v) cd.textContent = v; }
  447. this.refreshPermButtons();
  448. }
  449. // ───────────── 日志 ─────────────
  450. log(text, kind = 'info') {
  451. const feed = $('#feed');
  452. if (!feed) return;
  453. const row = document.createElement('div');
  454. row.className = 'row ' + kind;
  455. const t = new Date();
  456. row.innerHTML = `<time>${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}:${String(t.getSeconds()).padStart(2, '0')}</time><span>${esc(text)}</span>`;
  457. feed.prepend(row);
  458. while (feed.children.length > 40) feed.lastChild.remove();
  459. }
  460. toast(text, kind = '') {
  461. const el = document.createElement('div');
  462. el.className = 'toast ' + kind;
  463. el.textContent = text;
  464. $('#toasts').appendChild(el);
  465. setTimeout(() => { el.style.opacity = '0'; el.style.transition = 'opacity .3s'; setTimeout(() => el.remove(), 320); }, 2400);
  466. while ($('#toasts').children.length > 3) $('#toasts').firstChild.remove();
  467. }
  468. // ───────────── 弹窗队列 ─────────────
  469. pushDialog(d) {
  470. if (d.kind === 'civ' && this.dialog && this.dialog.kind === 'civ') return;
  471. this.dialogQueue.push(d);
  472. if (!this.modalOpen) this.nextDialog();
  473. }
  474. nextDialog() {
  475. const d = this.dialogQueue.shift();
  476. if (!d) { this.closeModal(); return; }
  477. this.dialog = d;
  478. this.openModal(d);
  479. }
  480. beginModal() { this.modalOpen = true; $('#modal-mask').hidden = false; }
  481. closeModal() {
  482. this.modalOpen = false;
  483. this.dialog = null;
  484. $('#modal-mask').hidden = true;
  485. }
  486. setModal(tag, tagCls, title, bodyHtml, footHtml) {
  487. $('#modal-tag').className = 'mtag ' + tagCls;
  488. $('#modal-tag').textContent = tag;
  489. $('#modal-title').textContent = title;
  490. $('#modal-body').innerHTML = bodyHtml;
  491. $('#modal-foot').innerHTML = footHtml || '';
  492. }
  493. closeDialog() {
  494. this.dialog = null;
  495. if (this.dialogQueue.length) this.nextDialog();
  496. else this.closeModal();
  497. }
  498. // ───────────── 交互 ─────────────
  499. readTune() {
  500. const q = new URLSearchParams(location.search);
  501. const ts = Math.max(0.5, Math.min(20, parseFloat(q.get('speed')) || 1));
  502. const rs = Math.max(1, Math.min(1000, parseFloat(q.get('prod')) || 1));
  503. this.tune = { ts, rs };
  504. }
  505. bindKeys() {
  506. document.addEventListener('keydown', (e) => {
  507. if (e.target && /INPUT|TEXTAREA/.test(e.target.tagName)) return;
  508. if (this.riftRun && this.riftRun.state === 'fight' && /^[0-9]$/.test(e.key)) { this.rollRift(+e.key); return; }
  509. if (this.riftRun && this.riftRun.state === 'fight' && e.key === 'ArrowRight') { this.rollRift(5); return; }
  510. if (this.modalOpen) {
  511. if (e.key === 'Escape' && this.dialog && this.dialog.kind !== 'crisis') this.closeDialog();
  512. return;
  513. }
  514. const k = e.key.toLowerCase();
  515. if (k === 'r') this.doRebirth();
  516. else if (k === 't') this.startRift();
  517. else if (k === 'a') this.toggleAuto();
  518. else if (k === '1') this.buy('root');
  519. else if (k === '2') this.buy('canopy');
  520. else if (k === 'q' && this.riftRun) this.rollRift(5);
  521. });
  522. }
  523. bindEvents() {
  524. $('#env-strip').addEventListener('click', (e) => { const d = e.target.closest('.env-dot, b, .env-eff, .env-left'); if (!d) return; e.stopPropagation(); this.toast('当前地质环境:' + ((this.stats && this.stats.env && this.stats.env.desc) || '') ); });
  525. $('#main').addEventListener('click', (e) => {
  526. const rb = e.target.closest('[data-r]');
  527. if (rb) { this.riftAction(rb.dataset.r, rb.dataset.k, rb.dataset.i); return; }
  528. const b = e.target.closest('[data-act]');
  529. if (!b) return;
  530. const act = b.dataset.act;
  531. if (act === 'upg') this.buy(b.dataset.k);
  532. else if (act === 'life') this.buyLife(b.dataset.id);
  533. else if (act === 'rebirth') this.doRebirth();
  534. else if (act === 'auto') this.toggleAuto();
  535. else if (act === 'rift') this.startRift();
  536. else if (act === 'save') this.openSave();
  537. else if (act === 'buy-tree') { if (S.buyTree(this.s)) { this.toast(`世界树升至 D${this.s.treeLv}`, 'good'); this.renderPerm(); } }
  538. else if (act === 'buy-relic') { if (S.buyRelic(this.s)) { this.toast('获得遗物:' + C.RELICS[this.s.relics.length - 1].name, 'good'); this.renderPerm(); } this.log(`遗物入手:${C.RELICS[this.s.relics.length - 1] ? C.RELICS[this.s.relics.length - 1].name : ''}`, 'mile'); }
  539. else if (act === 'plane') this.switchPlane(+b.dataset.p);
  540. else if (act === 'guide-x') { this.s.flags.guideDone = true; this.renderMainline(); this.toast('提示已收起。'); }
  541. this.saveNow();
  542. });
  543. $('#modal').addEventListener('click', (e) => {
  544. const b = e.target.closest('[data-mact]');
  545. if (!b) return;
  546. const m = b.dataset.mact;
  547. if (m === 'close') this.closeDialog();
  548. else if (m === 'crisis') this.answerCrisis(b.dataset.i);
  549. else if (m === 'civ') this.answerCiv(+b.dataset.i);
  550. else if (m === 'save') this.saveActions(b.dataset.sub);
  551. });
  552. $('#modal-x').addEventListener('click', () => {
  553. if (this.dialog && this.dialog.kind === 'crisis') return;
  554. this.closeDialog();
  555. });
  556. const ts = $('.top-save'); if (ts) ts.addEventListener('click', () => this.openSave());
  557. $('#main').addEventListener('contextmenu', (e) => { const b = e.target.closest('[data-act="auto"]'); if (!b) return; e.preventDefault(); S.cycleAutoEvery(this.s); this.toast(`禅定节奏:每 ${S.autoRebirthEvery(this.s)} 秒`); this.saveNow(); });
  558. $$('.vp-btn').forEach((b) => b.addEventListener('click', () => {
  559. $$('.vp-btn').forEach((x) => x.classList.toggle('on', x === b));
  560. document.body.classList.toggle('vp-phone', b.dataset.vp === 'phone');
  561. this.scene._resize();
  562. }));
  563. $$('#tabbar button').forEach((b) => b.addEventListener('click', () => {
  564. $$('#tabbar button').forEach((x) => x.classList.toggle('on', x === b));
  565. const tab = b.dataset.tab;
  566. if (tab === 'rift') { this.startRift(); return; }
  567. $$('.main > .col').forEach((c) => c.classList.toggle('active', c.id === 'col-' + tab));
  568. $('#main').classList.remove('show-right');
  569. this.scene._resize();
  570. }));
  571. window.addEventListener('beforeunload', () => { if (!this._importing) this.saveNow(); });
  572. document.addEventListener('visibilitychange', () => {
  573. if (document.hidden) this.saveNow();
  574. else this.checkOffline();
  575. });
  576. }
  577. buy(kind) {
  578. const r = S.buyUpgrade(this.s, kind);
  579. if (r) {
  580. const el = $('#buy-' + kind);
  581. if (el) { el.style.transform = 'scale(.96)'; setTimeout(() => (el.style.transform = ''), 120); }
  582. }
  583. }
  584. buyLife(id) { if (S.buyLife(this.s, id)) this.saveNow(); }
  585. doRebirth() {
  586. const s = this.s;
  587. if (s.planeRun) { this.toast('里世界中主世界时间冻结,无法回溯。', 'warn'); return; }
  588. if ((s.maxLayerRound || 0) < 3) { this.toast('先让世界树长到第 3 层以上。'); return; }
  589. const est = F.rebirthEstimate(s);
  590. const r = S.rebirth(s);
  591. this.log(`回溯 #${s.rebirths} · 炼化 ${fmt(r.gain)} 结晶 · 种子落在第 ${fmt(r.floor, { int: true })} 层`, 'mile');
  592. this.toast(`回溯完成:+${fmt(r.gain)} 时间结晶`, 'good');
  593. if (r.event) this.pushDialog({ kind: 'milestone', data: r.event });
  594. this.renderLeft(); this.renderRight(); this.renderDynamic();
  595. this.saveNow();
  596. }
  597. toggleAuto() {
  598. const s = this.s;
  599. if (s.autoOn) s.autoOn = false; else s.autoOn = true; // 单击开关;右键禅定按钮切换 60/120/300 秒节奏
  600. this.toast(s.autoOn ? `禅定:每 ${S.autoRebirthEvery(s)} 秒自动回溯(再点切换节奏)` : '禅定关闭:手动决定回溯时机', s.autoOn ? 'good' : '');
  601. this.renderActions(); this.renderDynamic();
  602. this.saveNow();
  603. }
  604. switchPlane(p) {
  605. if (p === this.s.currentPlane) return;
  606. if (S.switchPlane(this.s, p)) {
  607. this.log(`切换位面:${C.PLANES[p].name} —— ${C.PLANES[p].rule}`, 'mile');
  608. this.toast(`进入${C.PLANES[p].name}:${C.PLANES[p].bonus}`);
  609. this.renderLeft(); this.renderRight(); this.renderDynamic();
  610. }
  611. }
  612. // ───────────── 事件弹窗 ─────────────
  613. showCrisis() {
  614. const s = this.s;
  615. const ev = CRISIS_EVENTS[(s.escapeCount || 0 + s.rebirths) % CRISIS_EVENTS.length];
  616. const left = Math.max(0, Math.ceil((s.crisis.popUntil || 0)));
  617. this.setModal('危机事件', 'crisis', ev.title,
  618. `<p>${esc(ev.text)}</p><p class="cd">侵蚀前沿正在逼近:<b id="crisis-cd">${left}</b> 秒内不响应,前沿将吞没 3 层根系并压低产出。</p>
  619. <div class="opts">${ev.options.map((o, i) => `<button class="opt" data-mact="crisis" data-i="${o.effect}"><div class="l">${esc(o.label)}</div><div class="h">${esc(o.hint)}</div></button>`).join('')}</div>`);
  620. this.crisisTimer = setInterval(() => {
  621. const e = $('#crisis-cd');
  622. const l = Math.max(0, Math.ceil((this.s.crisis.popUntil || 0)));
  623. if (e) e.textContent = l;
  624. if (l <= 0 || !this.s.crisis.active) { clearInterval(this.crisisTimer); if (this.dialog && this.dialog.kind === 'crisis') this.closeDialog(); }
  625. }, 1000);
  626. }
  627. answerCrisis(effect) {
  628. const t = S.crisisRespond(this.s, effect);
  629. clearInterval(this.crisisTimer);
  630. if (t) { this.log('危机响应:' + t, 'crisis'); this.toast(t, 'warn'); }
  631. this.closeDialog();
  632. }
  633. showCiv(idx) {
  634. const ev = CIV_EVENTS[idx];
  635. const stage = C.CHAPTERS[C.chapterOf(this.s.layer)].short;
  636. this.setModal(`文明事件 · ${stage}`, 'civ', ev.title,
  637. `<p>${esc(ev.text)}</p><div class="opts">${ev.opts.map((o, i) => `<button class="opt" data-mact="civ" data-i="${i}"><div class="l">${esc(o.label)}</div><div class="h">${esc(o.hint)}</div></button>`).join('')}</div>`);
  638. }
  639. answerCiv(i) {
  640. const t = S.civChoose(this.s, this.dialog.civIdx, i);
  641. if (t) { this.log(`文明事件:${CIV_EVENTS[this.dialog.civIdx].title} —— ${t}`, 'mile'); this.toast(t, 'good'); }
  642. this.closeDialog();
  643. this.renderRight();
  644. }
  645. showMilestone(d) {
  646. this.setModal('里程碑', 'mile', d.title || '里程碑', `<p>${esc(d.text || '')}</p>`,
  647. `<div class="foot-row"><button class="btn" data-mact="close">继续前行</button></div>`);
  648. this.log(`【${d.title || '里程碑'}】${d.text || ''}`, 'mile');
  649. }
  650. openModal(d) {
  651. this.beginModal();
  652. if (d.kind === 'crisis') this.showCrisis();
  653. else if (d.kind === 'civ') this.showCiv(d.civIdx);
  654. else if (d.kind === 'milestone') this.showMilestone(d.data);
  655. else if (d.kind === 'save') this.showSave(this._saveSub);
  656. else if (d.kind === 'offline') this.showOffline(d.data);
  657. else if (d.kind === 'riftResult') this.showRiftResult(d.data);
  658. }
  659. // ───────────── 存档 ─────────────
  660. saveNow() { if (this._importing) return; S.save.write(localStorage, this.s, this.riftRun ? { run: this.riftRun } : null); }
  661. openSave() { this._saveSub = null; this.dialogQueue.push({ kind: 'save' }); if (!this.modalOpen) this.nextDialog(); }
  662. showSave(sub) {
  663. this._saveSub = sub || null;
  664. const s = this.s;
  665. clearTimeout(this._saveTimer);
  666. document.querySelectorAll('.ct-inline').forEach((e) => e.remove());
  667. const inline = (html) => { const d = document.createElement('div'); d.className = 'ct-inline'; d.innerHTML = html; $('#modal-body').appendChild(d); return d; };
  668. if (sub === 'export') {
  669. const txt = S.save.serialize(s, this.riftRun ? { run: this.riftRun } : null);
  670. this.setModal('存档', '', '导出存档', `<p style="margin-top:0">复制下面的 JSON 字符串保存。导入时粘贴即可恢复(含本轮进度与里世界局内状态)。</p><textarea id="save-text" readonly>${esc(txt)}</textarea>`);
  671. const d = inline('<div class="foot-row"><button class="btn ghost" data-mact="save" data-sub="">返回</button><button class="btn" id="copy-save">复制</button></div>');
  672. d.querySelector('#copy-save').onclick = (e) => {
  673. const ta = $('#save-text');
  674. const done = () => { e.target.textContent = '已复制 ✓'; this.toast('存档已复制到剪贴板', 'good'); };
  675. ta.focus(); ta.select();
  676. if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(txt).then(done, () => { try { document.execCommand('copy'); done(); } catch (err) { /* ignore */ } });
  677. else { try { document.execCommand('copy'); done(); } catch (err) { /* ignore */ } }
  678. };
  679. } else if (sub === 'import') {
  680. this.setModal('存档', '', '导入存档', `<p style="margin-top:0">粘贴之前导出的 JSON。非法存档会被拒绝,不会覆盖当前进度。</p><textarea id="save-in" placeholder='{"v":1,"state":{...}}'></textarea><div id="save-msg" style="font-size:12px;color:var(--muted);margin-top:6px"></div>`);
  681. const d = inline('<div class="foot-row"><button class="btn ghost" data-mact="save" data-sub="">返回</button><button class="btn" id="do-import">导入并覆盖</button></div>');
  682. d.querySelector('#do-import').addEventListener('click', () => {
  683. const r = S.save.parse($('#save-in').value);
  684. const msg = $('#save-msg');
  685. if (!r.ok) { msg.style.color = 'var(--danger)'; msg.textContent = '导入失败:' + r.error; return; }
  686. S.save.write(localStorage, r.data.state, r.data.rift);
  687. this._importing = true;
  688. msg.style.color = 'var(--life)'; msg.textContent = '导入成功,正在恢复…';
  689. setTimeout(() => location.reload(), 120);
  690. });
  691. } else if (sub === 'reset') {
  692. this.setModal('存档', '', '硬重置', `<p style="margin-top:0">将清空本地存档并重新开始,<b>不可撤销</b>。确定要这样做吗?</p>`);
  693. const d = inline('<div class="foot-row"><button class="btn ghost" data-mact="save" data-sub="">取消</button><button class="btn" id="do-reset" style="background:#c0492e;border-color:#c0492e">确认清空</button></div>');
  694. d.querySelector('#do-reset').onclick = () => { S.save.clear(localStorage); this._importing = true; location.reload(); };
  695. } else {
  696. let when = '尚未存档';
  697. try { const raw = JSON.parse(localStorage.getItem(C.SAVE_KEY) || '{}'); when = raw.t ? new Date(raw.t).toLocaleString() : when; } catch (e) { /* ignore */ }
  698. this.setModal('存档', '', '存档管理',
  699. `<p style="margin-top:0">自动存档:关键操作后 + 每 30 秒 + 关闭页面前。上次保存:<b>${esc(when)}</b>。</p>
  700. <div class="opts">
  701. <button class="opt" data-mact="save" data-sub="export"><div class="l">导出存档</div><div class="h">生成 JSON 字符串供复制备份</div></button>
  702. <button class="opt" data-mact="save" data-sub="import"><div class="l">导入存档</div><div class="h">粘贴 JSON 恢复进度(校验非法输入)</div></button>
  703. <button class="opt" data-mact="save" data-sub="reset"><div class="l" style="color:var(--danger)">硬重置</div><div class="h">清空存档,二次确认</div></button>
  704. </div>`);
  705. inline('<div class="foot-row"><button class="btn ghost" data-mact="close">关闭</button></div>');
  706. }
  707. }
  708. saveActions(sub) {
  709. if (sub) { this.showSave(sub); return; }
  710. this.showSave(null);
  711. }
  712. showOffline(o) {
  713. this.setModal('离线收益', '', '你不在的这段时间', `<p style="margin-top:0">离线 <b>${esc(fmtTime(o.sec))}</b>(上限 8 小时,效率 60%)。世界树自己长了一段:</p>
  714. <div class="res-row"><div class="res"><div class="k">本源</div><div class="v num">+${fmt(o.essence)}</div></div><div class="res"><div class="k">层数</div><div class="v num">${fmt(o.fromLayer, { int: true })} → ${fmt(o.toLayer, { int: true })}</div></div></div>`,
  715. `<div class="foot-row"><button class="btn" data-mact="close">收下</button></div>`);
  716. }
  717. checkOffline() {
  718. // 页面重新可见时按真实时间补算(离线只结算主世界)
  719. const now = Date.now();
  720. if (!this._lastTickAt) { this._lastTickAt = now; return; }
  721. const gap = (now - this._lastTickAt) / 1000;
  722. this._lastTickAt = now;
  723. if (gap > 60 && !this.s.escaped) {
  724. const o = S.applyOffline(this.s, gap, this.riftRun ? { run: this.riftRun } : null);
  725. if (o && !o.skipped) { this.lastFrame = performance.now(); this.pushDialog({ kind: 'offline', data: o }); this.renderAll(); }
  726. }
  727. }
  728. // ───────────── 里世界 ─────────────
  729. startRift() {
  730. const s = this.s;
  731. if (this.riftRun && this.riftRun.state !== 'result') { this.showTab('center'); this.toast('里世界进行中:主世界已冻结。'); return; }
  732. const run = S.startRift(s);
  733. if (!run) { this.toast(`时空裂缝冷却中:${Math.ceil(s.riftCdSec)} 秒`, 'warn'); return; }
  734. this.riftRun = run;
  735. this.log(`进入里世界(${C.PLANES[s.currentPlane].name} · ${C.PLANES[s.currentPlane].tier})`, 'rift');
  736. this.showTab('center');
  737. this.renderRiftPanel();
  738. this.saveNow();
  739. }
  740. showTab(tab) {
  741. $$('#tabbar button').forEach((x) => x.classList.toggle('on', x.dataset.tab === tab));
  742. $$('.main > .col').forEach((c) => c.classList.toggle('active', c.id === 'col-' + tab));
  743. if (window.innerWidth > 760) { $$('.main > .col').forEach((c) => c.classList.add('active')); }
  744. requestAnimationFrame(() => this.scene._resize());
  745. }
  746. renderRiftPanel() {
  747. const r = this.riftRun;
  748. const slot = $('#rift-slot');
  749. const wrap = $('#canvas-wrap');
  750. if (!r || r.state === 'result') { slot.hidden = true; slot.innerHTML = ''; wrap.hidden = false; $('.actions').hidden = false; this.riftPanelKey = null; return; }
  751. slot.hidden = false; wrap.hidden = true; $('.actions').hidden = true;
  752. if (!slot.querySelector('#rift-live')) slot.innerHTML = '<div class="panel rift-panel" id="rift-live"></div>';
  753. const panel = slot.querySelector('#rift-live');
  754. const key = r.state + ':' + r.step + ':' + (r.buildDone ? 1 : 0);
  755. if (this.riftPanelKey === key) return;
  756. this.riftPanelKey = key;
  757. const env = C.RIFT_ENVS[r.plane];
  758. if (r.state === 'build') {
  759. const left = R.pointsLeft(r);
  760. const slots = R.RULES.map((k) => {
  761. const v = r.attrs[k]; const cap = r.available[k];
  762. return `<div class="slot"><div class="h"><span style="color:${C.RULE_COLORS[k]}">${R.RULE_NAME[k]}</span><span style="color:var(--muted)">${v}/${cap}</span></div>
  763. <div class="v">${v}</div>
  764. <div class="stepper"><button data-r="and" data-k="${k}">+</button><button data-r="sub" data-k="${k}">−</button></div></div>`;
  765. }).join('');
  766. panel.innerHTML = `<div class="rift-head"><span class="elite-tag" style="background:${env.color}">里世界 · ${C.PLANES[r.plane].tier}</span><span class="nm">${env.name}</span><span class="kb">规则浓度 ×${r.density.toFixed(2)}</span></div>
  767. <div style="font-size:12px;color:var(--muted)">${env.desc}</div>
  768. <div class="build-hint">开局分配规则(本源点):剩余 <b>${left}</b> / ${r.budget}——可分配的“规则槽”决定你的下限,本源点决定你的上限。</div>
  769. <div class="slot-bar">${slots}</div>
  770. <div style="font-size:11px;color:var(--muted);margin-top:10px;line-height:1.6">知识 → 攻击 +1.5 誓约 → 生命 +4(最大项时首击豁免)<br>信念 → 生命 +1.5(最大项时每次受击回 0.5×信念) 裁决 → 攻击 +2(并额外削敌)</div>
  771. <div style="display:grid;grid-template-columns:1fr 96px 96px;gap:8px;margin-top:10px">
  772. <button class="btn" data-r="build">进入 ${env.name}</button><button class="btn ghost" data-r="auto">自动分配</button><button class="btn danger" data-r="abandon">放弃本局</button>
  773. </div>`;
  774. } else if (r.state === 'event') {
  775. const m = r.mouth;
  776. panel.innerHTML = `<div class="rift-head"><span class="elite-tag" style="background:${env.color}">奇遇 · 第 ${r.step + 1}/6 幕</span><span class="nm">${esc(m.title)}</span></div>
  777. <div class="step-dots">${Array.from({ length: R.ENCOUNTERS }, (_, i) => `<i class="${i < r.step ? 'past' : i === r.step ? 'now' : ''}"></i>`).join('')}</div>
  778. <div class="taunt">${esc(m.text)}</div>
  779. <div class="card-opts">${m.opts.map((o) => `<button class="opt" data-r="opt" data-i="${o.j}"><div class="l">${esc(o.label)}</div><div class="h">${esc(o.hint)}</div></button>`).join('')}</div>
  780. <div class="kv">${this.riftKv(r)}</div>`;
  781. } else if (r.state === 'fight' || r.state === 'run') {
  782. const m = r.mouth;
  783. const hp = R.hpMaxOf(r), hpm = Math.max(0, r.hp);
  784. const atk = R.atkOf(r);
  785. const kindTag = m.type === 'boss' ? '<span class="elite-tag boss">终局</span>' : m.type === 'elite' ? '<span class="elite-tag">精英</span>' : '<span class="elite-tag" style="background:var(--muted)">战斗</span>';
  786. const hints = [0, 1, 2, 3, 4, 5].map((k) => {
  787. const v = Math.round(atk + k);
  788. const cls = v >= m.threat * 1.75 ? 'crit-hint' : v > m.threat ? 'hint' : '';
  789. return `<button class="roll-btn ${cls}" data-r="roll" data-k="${k}">${v}<div style="font-size:9px;font-weight:500;color:var(--muted)">+${k}</div></button>`;
  790. }).join('');
  791. const last = m.lastLog;
  792. panel.innerHTML = `<div class="rift-head"><span class="elite-tag" style="background:${env.color}">${env.name} · 第 ${r.step + 1}/6 幕</span><span class="nm">${esc(m.name)}</span>${kindTag}</div>
  793. <div class="taunt">“${esc(m.taunt)}”</div>
  794. <div class="hpbar enemy"><i style="width:${(m.hp / m.hpMax * 100).toFixed(1)}%"></i><div class="txt">${fmt(m.hp, { int: true })} / ${fmt(m.hpMax, { int: true })}</div></div>
  795. <div class="fight-grid">
  796. <div class="box"><div class="k">敌人威胁 pK(拼招需 > pK,超杀 ≥ ×1.75)</div><div class="v">${m.threat}</div></div>
  797. <div class="box enemy"><div class="k">你的生命 / 攻击</div><div class="v">${fmt(hpm, { int: true })}<span style="font-size:13px;color:var(--muted)"> / ${fmt(atk, { int: true })}</span></div></div>
  798. </div>
  799. <div class="roll-bar">${hints}</div>
  800. <div style="font-size:10.5px;color:var(--muted-2);margin-top:4px">点击数字 = 挥剑(结果 = 攻击 + 临时战意 0..5;方向键/数字键也可)· <b>Q</b> 全力 5</div>
  801. ${last ? `<div class="log3">上一剑:<b>${({ block: '阻断', win: '拼招', crit: '超杀' })[last.res]}</b> ${last.value} vs ${last.threat} 敌人 −${last.dmg},自己 −${last.back}</div>` : `<div class="log3">选择你的战意:拼招(> pK)削敌、超杀(≥1.75×pK)重创并自伤更少,阻断(≤ pK)会被格挡。</div>`}
  802. <div class="kv">${this.riftKv(r)}</div>
  803. <div style="display:flex;gap:8px;margin-top:8px"><button class="btn ghost" style="flex:1" data-r="abandon">撤退(结算本局)</button></div>`;
  804. }
  805. }
  806. riftKv(r) {
  807. const stepDots = Array.from({ length: R.ENCOUNTERS }, (_, i) => `<i class="${i < r.step ? 'past' : i === r.step ? 'now' : ''}"></i>`).join('');
  808. return `<div>连击/分<b>${r.score}</b></div><div>生命<b>${Math.max(0, Math.round(r.hp))}/${R.hpMaxOf(r)}</b></div><div>攻击<b>${Math.round(R.atkOf(r))}</b>${(r.growth||1) > 1.01 ? ' <span style="color:var(--gold)">锋芒×' + Math.min(3, r.growth).toFixed(2) + '</span>' : ''}</div><div>能量<b>${Math.round(r.energy)}</b></div><div>步数<b>${r.step + 1}/6</b></div>`;
  809. }
  810. renderRiftLive() {
  811. const r = this.riftRun;
  812. if (!r) return;
  813. this.renderRiftPanel();
  814. const panel = $('#rift-live');
  815. if (!panel || panel.hidden) return;
  816. // 战斗中动态部分
  817. if ((r.state === 'fight' || r.state === 'run') && r.mouth) {
  818. const bar = panel.querySelector('.hpbar.enemy');
  819. if (bar) { bar.querySelector('i').style.width = (r.mouth.hp / r.mouth.hpMax * 100).toFixed(1) + '%'; bar.querySelector('.txt').textContent = `${fmt(r.mouth.hp, { int: true })} / ${fmt(r.mouth.hpMax, { int: true })}`; }
  820. const kv = panel.querySelector('.kv');
  821. if (kv) kv.innerHTML = this.riftKv(r);
  822. }
  823. if (r.state === 'event' && r.mouth) {
  824. const dots = panel.querySelector('.step-dots');
  825. if (dots) dots.innerHTML = Array.from({ length: R.ENCOUNTERS }, (_, i) => `<i class="${i < r.step ? 'past' : i === r.step ? 'now' : ''}"></i>`).join('');
  826. }
  827. }
  828. riftAction(act, k, i) {
  829. if (act === 'and') this.stepRiftInput(k, 1);
  830. else if (act === 'sub') this.stepRiftInput(k, -1);
  831. else if (act === 'build') this.riftBuild();
  832. else if (act === 'abandon') this.confirmAbandon();
  833. else if (act === 'opt') this.riftOption(+i);
  834. else if (act === 'roll') this.rollRift(+k);
  835. else if (act === 'auto') { const r = this.riftRun; if (r && r.state === 'build') { R.autoSpend(r); this.riftPanelKey = null; this.renderRiftPanel(); } }
  836. }
  837. confirmAbandon() {
  838. const r = this.riftRun;
  839. if (!r) return;
  840. if (r.state === 'build') { this.abandonRift(); return; }
  841. this.setModal('里世界', 'rift', '撤退确认', `<p style="margin-top:0">提前离开本局:按当前进度结算探索碎片(失败也有价值),主世界时间随即恢复。</p>`, `<button class="btn ghost" data-mact="close">继续探索</button><button class="btn" data-mact="save" data-sub="__abandon" id="btn-abandon-ok">确认撤退</button>`);
  842. this._saveTimer = setTimeout(() => { const b = $('#btn-abandon-ok'); if (b) b.onclick = () => { this.closeModal(); this.abandonRift(); }; this._saveTimer = 0; }, 0);
  843. }
  844. stepRiftInput(k, dir) {
  845. const r = this.riftRun;
  846. if (!r || r.state !== 'build') return;
  847. const cap = r.available[k];
  848. if (dir > 0) { if (r.attrs[k] < cap && R.pointsLeft(r) > 0) r.attrs[k]++; }
  849. else { if (r.attrs[k] > 1) r.attrs[k]--; }
  850. this.riftPanelKey = null;
  851. this.renderRiftPanel();
  852. }
  853. riftBuild() {
  854. const r = this.riftRun;
  855. if (!R.buildDone(r, 0)) { this.toast(`还剩 ${R.pointsLeft(r)} 点规则未分配(每项至少 1).`, 'warn'); return; }
  856. this.riftPanelKey = null; this.renderRiftPanel(); this.saveNow();
  857. }
  858. riftOption(j) {
  859. const r = this.riftRun;
  860. const res = R.applyOption(r, j);
  861. if (!res) return;
  862. this.toast(res.msg || '');
  863. if (res.cleared) this.finishRift();
  864. this.riftPanelKey = null; this.renderRiftPanel(); this.saveNow();
  865. }
  866. rollRift(k) {
  867. const r = this.riftRun;
  868. if (!r || r.state !== 'fight') return;
  869. const res = R.slash(r, k);
  870. if (!res) return;
  871. const a = R.afterSlash(r, res);
  872. const label = { block: '阻断 — 被封挡', win: '拼招 — 命中', crit: '超杀 — 重创' }[res.res];
  873. this.log(`里世界:${label}(${res.value} vs ${res.threat})`, 'rift');
  874. if (a.cleared) this.finishRift();
  875. this.riftPanelKey = null; this.renderRiftPanel(); this.saveNow();
  876. }
  877. abandonRift() {
  878. const r = this.riftRun;
  879. if (!r) return;
  880. if (r.state !== 'result') { r.state = 'result'; r.cleared = false; r.dead = true; }
  881. this.finishRift();
  882. }
  883. finishRift() {
  884. const r = this.riftRun;
  885. if (!r) return;
  886. const res0 = R.riftResult(r, F.computeStats(Object.assign({}, this.s, { planeRun: null })).prodRaw, this.s.planes[r.plane].explore >= 100);
  887. const out = S.endRift(this.s);
  888. this.riftRun = null;
  889. this.riftPanelKey = null;
  890. this.renderRiftPanel();
  891. if (!out) return;
  892. const { res, events } = out;
  893. this.log(`里世界结算:探索度 +${res.explore},本源 +${fmt(res.essence)}${res.shard ? ',徽记 +1' : ''}`, 'rift');
  894. this.lastFrame = performance.now();
  895. this.pushDialog({ kind: 'riftResult', data: res });
  896. events.forEach((e) => this.pushDialog({ kind: 'milestone', data: e }));
  897. this.renderLeft(); this.renderRight(); this.renderAll(); this.saveNow();
  898. }
  899. showRiftResult(res) {
  900. const anchoredNote = res.anchoredNow ? '<p style="color:#1c7a48"><b>位面已锚定!</b>此后该位面将在后台自动采集本源(每 60 秒按本源秒产 2% 结算),并已解锁下一阶时空裂缝。</p>' : '';
  901. this.setModal('里世界结算', 'rift', res.cleared ? '通关 · 位面回声' : '撤离 · 碎片回响',
  902. `<p style="margin-top:0">${res.cleared ? '你走完了全部 6 幕,带着这个位面的规则碎片归来。' : '本局未能走完,但失败也有价值:碎片会带回到世界树。'}</p>
  903. <div class="res-row">
  904. <div class="res"><div class="k">探索度 +</div><div class="v num">${res.explore}</div><div class="d">${res.planeName}</div></div>
  905. <div class="res"><div class="k">本源 +</div><div class="v num">${fmt(res.essence)}</div><div class="d">带回主世界</div></div>
  906. </div>
  907. <div class="sub-line" style="margin-top:10px"><span>得分 <b>${res.score}</b></span><span>徽记 <b>${res.shard ? '+1' : '0'}</b></span><span>步数 <b>${res.steps}/6</b></span><span>当前探索 <b>${res.anchored ? '100(已锚定)' : res.explore + ' 点增量'}</b></span></div>
  908. ${anchoredNote}`,
  909. `<div class="foot-row"><button class="btn" data-mact="close">回到世界树</button></div>`);
  910. }
  911. renderAll() { this.renderStatic(); this.renderDynamic(); }
  912. }
  913. // 小工具:模板里表示空的占位
  914. function d() { return ''; }