| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396 |
- // 存档状态层:唯一可写状态 + 全部玩家动作(动作返回事件列表,UI 负责呈现)。
- // 逻辑与渲染彻底分离:本文件不碰 DOM。署名:FmodeCode
- import * as B from '../core/balance.js';
- import * as F from '../core/formulas.js';
- import { PLANETS, planetById } from '../data/planets.js';
- import { LIFE } from '../data/lives.js';
- import { RANDOM_EVENTS, CRISIS_EVENTS } from '../data/events.js';
- import { newlyUnlocked, achById } from './achievements.js';
- export const nowSec = () => Date.now() / 1000;
- export function newState(t = nowSec()) {
- return {
- v: B.SAVE_VERSION, created: t, savedAt: t, playSec: 0,
- res: B.RES.start,
- rootLv: 0,
- curPlanet: 0,
- planets: PLANETS.map((p, i) => ({ rem: 100, explore: 0, best: 0, unlockedAt: i === 0 ? t : 0 })),
- lives: PLANETS.map(() => ({})),
- heat: PLANETS.map(() => ({ kind: null, until: 0, value: 0, next: 0, healed: false })),
- crystals: 0, eras: 0, stems: {},
- ach: {}, seen: {}, story: {},
- tutorial: { step: 1, taps: 0, starOpened: false, done: false, lifeModalAt: 0 },
- scene: { next: t + B.EVENT.firstAfter, current: null, events: {} },
- perm: { prod: 1, until: 0 },
- stats: { taps: 0, explores: 0, lifeBuys: 0, rootBuys: 0, curios: 0, eventsResolved: 0 },
- flags: {},
- };
- }
- // ── 存档 ─────────────────────────────────────────────
- export const save = {
- serialize(s) { return JSON.stringify({ v: B.SAVE_VERSION, t: Date.now(), state: s }); },
- parse(text) {
- let raw;
- try { raw = JSON.parse(String(text).trim()); } catch (e) { return { ok: false, error: '不是合法的 JSON' }; }
- if (!raw || !raw.state || typeof raw.state !== 'object') return { ok: false, error: '缺少 state 字段' };
- if (raw.v > B.SAVE_VERSION) return { ok: false, error: '存档来自更新的版本' };
- return { ok: true, data: migrate(raw) };
- },
- load(storage) {
- try { const t = storage.getItem(B.SAVE_KEY); if (!t) return null; const r = save.parse(t); return r.ok ? r.data : null; } catch (e) { return null; }
- },
- write(storage, s) { try { s.savedAt = Date.now(); storage.setItem(B.SAVE_KEY, save.serialize(s)); return true; } catch (e) { return false; } },
- clear(storage) { try { storage.removeItem(B.SAVE_KEY); } catch (e) { /* 忽略 */ } },
- };
- /** 补齐缺省字段,做安全清洗(防止手改存档把游戏弄坏) */
- export function migrate(raw) {
- const base = newState();
- const s = Object.assign(base, raw.state || {});
- s.planets = PLANETS.map((p, i) => Object.assign({ rem: 100, explore: 0, best: 0, unlockedAt: 0 }, (s.planets || [])[i] || {}));
- s.lives = PLANETS.map((p, i) => (s.lives && s.lives[i]) || {});
- s.heat = PLANETS.map((p, i) => Object.assign({ kind: null, until: 0, value: 0, next: 0, healed: false }, (s.heat || [])[i] || {}));
- for (const k of ['ach', 'seen', 'stems', 'flags']) if (!s[k] || typeof s[k] !== 'object') s[k] = {};
- s.stats = Object.assign(base.stats, s.stats || {});
- s.tutorial = Object.assign(base.tutorial, s.tutorial || {});
- s.scene = Object.assign(base.scene, s.scene || {});
- s.perm = Object.assign(base.perm, s.perm || {});
- s.res = Math.max(0, Number(s.res) || 0);
- if (typeof s.res !== 'number') s.res = base.res;
- s.rootLv = Math.max(0, Math.floor(Number(s.rootLv) || 0));
- s.curPlanet = Math.min(PLANETS.length - 1, Math.max(0, Math.floor(Number(s.curPlanet) || 0)));
- s.v = B.SAVE_VERSION;
- return s;
- }
- // ── 通用 ─────────────────────────────────────────────
- function gain(s, x) { s.res += x; }
- function checkAch(s, out) {
- for (const id of newlyUnlocked(s)) { s.ach[id] = nowSec(); out.push({ type: 'ach', id, ach: achById(id) }); }
- }
- /** 引导推进:一次动作里可能连续满足多步(例如升级同时触发了第一步与第二步),逐条推进 */
- function tutorialAdvance(s, out) {
- const T = s.tutorial;
- if (!T || T.step >= 99) return;
- for (let guard = 0; guard < 6; guard++) {
- const step = F.TUT_STEPS[T.step];
- if (!step || !step.check(s)) break;
- T.step = T.step + 1 >= 6 ? 99 : T.step + 1;
- out.push({ type: 'tut', step: T.step });
- }
- }
- // ── 点击世界树 ────────────────────────────────────────
- export function tap(s, now = nowSec()) {
- const out = [];
- const g = F.tapOf(s, now);
- gain(s, g);
- s.stats.taps++;
- if (s.tutorial.step === 1) s.tutorial.taps++;
- out.push({ type: 'tap', gain: g });
- tutorialAdvance(s, out);
- checkAch(s, out);
- return out;
- }
- // ── 根系 ─────────────────────────────────────────────
- export function rootCostNow(s) { return F.rootCostAt(s, s.rootLv); }
- export function buyRoot(s, n = 1) {
- const out = [];
- for (let k = 0; k < n; k++) {
- const c = rootCostNow(s);
- if (s.res < c) break;
- s.res -= c; s.rootLv++; s.stats.rootBuys++;
- out.push({ type: 'root', level: s.rootLv, cost: c });
- }
- tutorialAdvance(s, out); checkAch(s, out);
- return out;
- }
- // ── 生命 ─────────────────────────────────────────────
- export function lifeAvailable(s, id) {
- return F.availableLives(s, s.curPlanet).some((l) => l.id === id);
- }
- export function lifeCostNow(s, id) {
- const l = LIFE.find((x) => x.id === id);
- const lv = s.lives[s.curPlanet][id] || 0;
- const P = PLANETS[s.curPlanet];
- return Math.ceil(B.lifeCost(l, s.curPlanet, lv, P.lvMul, P.ratioMul || 1));
- }
- /**
- * 种下 / 升级生命。
- * 第一次购买 = “种下”(写章节叙事,解锁成就),之后为升级。
- */
- export function buyLife(s, id) {
- const out = [];
- const i = s.curPlanet;
- const l = LIFE.find((x) => x.id === id);
- if (!l || l.planet !== i) return out;
- if (!lifeAvailable(s, id)) return out;
- const cur = s.lives[i][id];
- const first = cur === undefined;
- const cost = lifeCostNow(s, id);
- if (s.res < cost) return out;
- s.res -= cost;
- s.lives[i][id] = (cur || 0) + 1;
- s.stats.lifeBuys++;
- out.push({ type: 'life', id, first, level: s.lives[i][id], planet: i });
- tutorialAdvance(s, out); checkAch(s, out);
- return out;
- }
- // ── 星球:进入 / 勘探 ─────────────────────────────────
- export function enterPlanet(s, i) {
- const out = [];
- if (!F.isPlanetUnlocked(s, i)) return out;
- s.curPlanet = i;
- out.push({ type: 'enter', planet: i });
- return out;
- }
- export function unlockCost(i) { return Math.ceil(PLANETS[i].baseTime * B.STAR.unlockMul * Math.pow(1.25, i)); }
- export function exploreCostNow(s, i = s.curPlanet) {
- return Math.ceil(PLANETS[i].exploreCost * Math.pow(B.STAR.exploreMul, s.planets[i].explore || 0));
- }
- export function explore(s) {
- const out = [];
- const i = s.curPlanet;
- const p = s.planets[i];
- if (p.rem <= 0 || (p.explore || 0) >= B.STAR.exploreMax) return out;
- const c = exploreCostNow(s, i);
- if (s.res < c) return out;
- s.res -= c;
- p.explore = (p.explore || 0) + 1;
- s.stats.explores++;
- out.push({ type: 'explore', planet: i, level: p.explore });
- checkAch(s, out);
- return out;
- }
- // ── 环境波动 ─────────────────────────────────────────
- /** 推进环境波动计时(每秒调用)。返回事件(转机 / 恶化) */
- export function stepHeat(s, t, now) {
- const out = [];
- // 新手引导期间不打断环境波动:计时不断延后,引导完成后才开始第一次波动
- if (!(s.tutorial && s.tutorial.done)) {
- const hg = s.heat[s.curPlanet];
- if (hg) hg.next = now + B.STAR.heatFirst;
- return out;
- }
- const i = s.curPlanet;
- const P = PLANETS[i];
- const p = s.planets[i];
- if (p.rem <= 0) return out;
- const h = s.heat[i];
- if (h.until > now) {
- if (h.kind === 'bad' && !h.healed) h.value = B.STAR.heatBad;
- else h.value = h.kind === 'good' ? -B.STAR.heatGood : 0;
- return out;
- }
- if (h.until > 0) { h.value = 0; h.kind = null; h.healed = false; h.next = now + P.waveSec; }
- if (!h.next) h.next = now + B.STAR.heatFirst;
- if (now >= h.next) {
- // 第 3 次及之后的环境波动是“恶化”;前两次是转机
- const seenBad = (s.flags['bad' + i] || 0);
- const bad = seenBad >= 2 || Math.random() < 0.35;
- h.kind = bad ? 'bad' : 'good';
- h.until = now + (bad ? B.STAR.heatBadDur : 12);
- h.value = bad ? B.STAR.heatBad : -B.STAR.heatGood;
- h.healed = false;
- if (bad) s.flags['bad' + i] = seenBad + 1;
- out.push({ type: bad ? 'heat-bad' : 'heat-good', planet: i, until: h.until });
- }
- return out;
- }
- /** 治愈环境(恶化中的前 8 秒):消耗 = 当前产出 × 1.2 秒 */
- export function healCostNow(s, now) {
- return Math.ceil(Math.max(1, F.incomeOf(s, now) * B.STAR.healCost));
- }
- export function heal(s, now = nowSec()) {
- const out = [];
- const i = s.curPlanet;
- const h = s.heat[i];
- // 可治愈窗口:恶化开始后的前 8 秒(直到结束前 2 秒)
- if (!h || h.kind !== 'bad' || h.healed || h.until - now < B.STAR.heatBadDur - B.STAR.healWindow) return out;
- const c = healCostNow(s, now);
- if (s.res < c) return out;
- s.res -= c; h.healed = true; h.value = 0;
- out.push({ type: 'heal', planet: i, cost: c });
- return out;
- }
- // ── 事件 ─────────────────────────────────────────────
- export function pickRandomEvent(s) {
- const seen = s.scene.events || {};
- const pool = RANDOM_EVENTS.filter((e) => !seen[e.id] && (e.planet === 'any' || e.planet.includes(s.curPlanet)));
- if (!pool.length) return null;
- return pool[Math.floor(Math.random() * pool.length)];
- }
- /** 环境恶化的下一步:可能触发危机抉择 */
- export function openCrisis(s) {
- const P = PLANETS[s.curPlanet];
- const e = CRISIS_EVENTS[0];
- const inst = { ...e, text: e.text.replace('{planet}', P.name).replace('{wave}', P.wave ? P.wave.name : '环境风暴') };
- s.scene.current = { kind: 'crisis', ev: inst };
- return inst;
- }
- export function resolveEvent(s, idx, now = nowSec()) {
- const out = [];
- const cur = s.scene.current;
- if (!cur) return out;
- const ch = cur.ev.choices[idx];
- if (!ch) return out;
- applyEffect(s, ch.action, now, out);
- if (cur.kind === 'random') {
- s.scene.events[cur.ev.id] = now;
- s.scene.next = now + rand(B.EVENT.idleMin, B.EVENT.idleMax);
- }
- s.stats.eventsResolved++;
- out.push({ type: 'event-done', ev: cur.ev, choice: ch });
- s.scene.current = null;
- checkAch(s, out);
- return out;
- }
- function rand(a, b) { return a + Math.random() * (b - a); }
- function applyEffect(s, a, now, out) {
- const i = s.curPlanet;
- if (!a) return;
- const income = F.incomeOf(s, now);
- if (a.type === 'res') { gain(s, income * a.sec); out.push({ type: 'res', amount: income * a.sec }); }
- else if (a.type === 'progress') {
- s.planets[i].rem = Math.max(0, Math.min(100, s.planets[i].rem - a.pct));
- out.push({ type: 'progress', pct: a.pct });
- maybeComplete(s, i, out);
- } else if (a.type === 'lifeLevel') {
- const ls = F.availableLives(s, i);
- if (ls.length) {
- const l = ls[Math.floor(Math.random() * ls.length)];
- s.lives[i][l.id] = (s.lives[i][l.id] || 0) + a.n;
- out.push({ type: 'life-gain', life: l, n: a.n });
- checkAch(s, out);
- }
- } else if (a.type === 'buff') {
- s.perm = { prod: a.prod, until: now + a.sec };
- out.push({ type: 'buff', prod: a.prod, sec: a.sec });
- } else if (a.type === 'storm') {
- gain(s, income * a.gain);
- s.heat[i] = Object.assign(s.heat[i], { kind: 'bad', until: now + a.sec, value: B.STAR.heatBad * 0.5, healed: false });
- out.push({ type: 'res', amount: income * a.gain });
- }
- }
- // ── 星球完成 ─────────────────────────────────────────
- export function maybeComplete(s, i, out) {
- const p = s.planets[i];
- if (p.rem > 0) return false;
- if (s.flags['done' + i]) return false;
- s.flags['done' + i] = 1;
- p.rem = 0;
- out.push({ type: 'planet-done', planet: i });
- checkAch(s, out);
- return true;
- }
- // ── 主 tick(每秒) ───────────────────────────────────
- /** 返回 { world: 世界/成就类事件, ui: 需要 UI 表现的事件 } */
- export function tick(s, now = nowSec(), dt = 1) {
- const out = [];
- s.playSec += dt;
- gain(s, F.incomeOf(s, now) * dt);
- const i = s.curPlanet;
- const p = s.planets[i];
- if (p.rem > 0) {
- p.rem = Math.max(0, p.rem - F.growRateOf(s, i, now) * dt);
- out.push(...stepHeat(s, dt, now));
- maybeComplete(s, i, out);
- }
- // 随机事件:空闲计时到了就打开
- if (!s.scene.current && now >= (s.scene.next || 0) && s.tutorial.step >= 99) {
- const ev = pickRandomEvent(s);
- if (ev) { s.scene.current = { kind: 'random', ev }; out.push({ type: 'event-open', ev }); }
- else s.scene.next = now + rand(B.EVENT.idleMin, B.EVENT.idleMax);
- }
- tutorialAdvance(s, out);
- return { world: out, ui: heatOpen(s, out) };
- }
- /** 环境恶化后的危机:自动打开一次“抉择”事件(前面的 -45% 生产已经是猝不及防的部分) */
- function heatOpen(s, worldOut) {
- const ui = [];
- const bad = worldOut.find((e) => e.type === 'heat-bad');
- if (bad && !s.scene.current) {
- const ev = openCrisis(s);
- ui.push({ type: 'event-open', ev, crisis: true });
- }
- return ui;
- }
- /** 离线结算:最多 8 小时,产出按 35%/s 计(自动产出),改造按 30% 速度补算 */
- export function applyOffline(s, gap, now = nowSec()) {
- const cap = Math.min(Math.max(0, gap), B.RES.offlineSec);
- if (cap < 60) return null;
- const res = F.incomeOf(s, now) * cap;
- const i = s.curPlanet;
- const p = s.planets[i];
- const grow = p.rem > 0 ? Math.min(p.rem, F.growRateOf(s, i, now) * cap * 0.3) : 0;
- gain(s, res);
- p.rem = Math.max(0, p.rem - grow);
- const out = [];
- maybeComplete(s, i, out);
- s.scene.next = (s.scene.next || now) + cap;
- return { sec: cap, res, grow, events: out };
- }
- // ── 纪元(轮回) ──────────────────────────────────────
- export function canEra(s) {
- return s.planets[0].rem <= 0 && s.rootLv >= B.ERA.minRootLv;
- }
- export function eraPreview(s) {
- return B.eraReward(F.clearedCount(s), F.progressSum(s));
- }
- export function doEra(s, now = nowSec()) {
- const out = [];
- if (!canEra(s)) return out;
- const reward = eraPreview(s);
- s.crystals += reward; s.eras++; s.stats.curios++;
- // 全部星球回到 100%,生命全部重新生长;等级门槛与星空共鸣让新纪元更快
- s.planets = PLANETS.map((p, idx) => ({ rem: 100, explore: 0, best: s.planets[idx].best, unlockedAt: idx === 0 ? now : 0 }));
- s.lives = PLANETS.map(() => ({}));
- s.heat = PLANETS.map(() => ({ kind: null, until: 0, value: 0, next: 0, healed: false }));
- s.rootLv = 0; s.res = B.RES.start; s.curPlanet = 0;
- s.flags = {}; s.perm = { prod: 1, until: 0 };
- // 新纪元:全部星球的改造从 100% 重新开始(等级门槛、星辰共鸣、结晶加成让新纪元更快)
- s.scene.current = null; s.scene.next = now + B.EVENT.firstAfter;
- s.tutorial.step = 99;
- out.push({ type: 'era', reward, crystals: s.crystals, eras: s.eras });
- checkAch(s, out);
- return out;
- }
- /** 星辰洗礼:用结晶换一次三选一的永久加成 */
- export function curioOptions(s) {
- const els = B.STEM_ELEMENTS.slice();
- // 确定性排列(存档里用 curioSeed 记录),保证界面刷新不变
- const seed = s.flags.curioSeed || (s.flags.curioSeed = Math.random());
- const order = els.map((e, k) => ({ e, k: (k + Math.floor(seed * 997)) % els.length })).sort((a, b) => a.k - b.k).map((x) => x.e);
- return order.slice(0, B.CURIO.pick);
- }
- export function canCurio(s) { return s.crystals >= B.CURIO.cost; }
- export function doCurio(s, elId) {
- const out = [];
- if (!canCurio(s)) return out;
- if (!curioOptions(s).some((e) => e.id === elId)) return out;
- s.crystals -= B.CURIO.cost;
- s.stems[elId] = (s.stems[elId] || 0) + 1;
- s.flags.curioSeed = Math.random(); // 下一次三选一换一组
- s.stats.curios++;
- out.push({ type: 'curio', el: elId, stems: s.stems[elId] });
- checkAch(s, out);
- return out;
- }
- export { planetById };
|