state.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // 存档状态层:唯一可写状态 + 全部玩家动作(动作返回事件列表,UI 负责呈现)。
  2. // 逻辑与渲染彻底分离:本文件不碰 DOM。署名:FmodeCode
  3. import * as B from '../core/balance.js';
  4. import * as F from '../core/formulas.js';
  5. import { PLANETS, planetById } from '../data/planets.js';
  6. import { LIFE } from '../data/lives.js';
  7. import { RANDOM_EVENTS, CRISIS_EVENTS } from '../data/events.js';
  8. import { newlyUnlocked, achById } from './achievements.js';
  9. export const nowSec = () => Date.now() / 1000;
  10. export function newState(t = nowSec()) {
  11. return {
  12. v: B.SAVE_VERSION, created: t, savedAt: t, playSec: 0,
  13. res: B.RES.start,
  14. rootLv: 0,
  15. curPlanet: 0,
  16. planets: PLANETS.map((p, i) => ({ rem: 100, explore: 0, best: 0, unlockedAt: i === 0 ? t : 0 })),
  17. lives: PLANETS.map(() => ({})),
  18. heat: PLANETS.map(() => ({ kind: null, until: 0, value: 0, next: 0, healed: false })),
  19. crystals: 0, eras: 0, stems: {},
  20. ach: {}, seen: {}, story: {},
  21. tutorial: { step: 1, taps: 0, starOpened: false, done: false, lifeModalAt: 0 },
  22. scene: { next: t + B.EVENT.firstAfter, current: null, events: {} },
  23. perm: { prod: 1, until: 0 },
  24. stats: { taps: 0, explores: 0, lifeBuys: 0, rootBuys: 0, curios: 0, eventsResolved: 0 },
  25. flags: {},
  26. };
  27. }
  28. // ── 存档 ─────────────────────────────────────────────
  29. export const save = {
  30. serialize(s) { return JSON.stringify({ v: B.SAVE_VERSION, t: Date.now(), state: s }); },
  31. parse(text) {
  32. let raw;
  33. try { raw = JSON.parse(String(text).trim()); } catch (e) { return { ok: false, error: '不是合法的 JSON' }; }
  34. if (!raw || !raw.state || typeof raw.state !== 'object') return { ok: false, error: '缺少 state 字段' };
  35. if (raw.v > B.SAVE_VERSION) return { ok: false, error: '存档来自更新的版本' };
  36. return { ok: true, data: migrate(raw) };
  37. },
  38. load(storage) {
  39. 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; }
  40. },
  41. write(storage, s) { try { s.savedAt = Date.now(); storage.setItem(B.SAVE_KEY, save.serialize(s)); return true; } catch (e) { return false; } },
  42. clear(storage) { try { storage.removeItem(B.SAVE_KEY); } catch (e) { /* 忽略 */ } },
  43. };
  44. /** 补齐缺省字段,做安全清洗(防止手改存档把游戏弄坏) */
  45. export function migrate(raw) {
  46. const base = newState();
  47. const s = Object.assign(base, raw.state || {});
  48. s.planets = PLANETS.map((p, i) => Object.assign({ rem: 100, explore: 0, best: 0, unlockedAt: 0 }, (s.planets || [])[i] || {}));
  49. s.lives = PLANETS.map((p, i) => (s.lives && s.lives[i]) || {});
  50. s.heat = PLANETS.map((p, i) => Object.assign({ kind: null, until: 0, value: 0, next: 0, healed: false }, (s.heat || [])[i] || {}));
  51. for (const k of ['ach', 'seen', 'stems', 'flags']) if (!s[k] || typeof s[k] !== 'object') s[k] = {};
  52. s.stats = Object.assign(base.stats, s.stats || {});
  53. s.tutorial = Object.assign(base.tutorial, s.tutorial || {});
  54. s.scene = Object.assign(base.scene, s.scene || {});
  55. s.perm = Object.assign(base.perm, s.perm || {});
  56. s.res = Math.max(0, Number(s.res) || 0);
  57. if (typeof s.res !== 'number') s.res = base.res;
  58. s.rootLv = Math.max(0, Math.floor(Number(s.rootLv) || 0));
  59. s.curPlanet = Math.min(PLANETS.length - 1, Math.max(0, Math.floor(Number(s.curPlanet) || 0)));
  60. s.v = B.SAVE_VERSION;
  61. return s;
  62. }
  63. // ── 通用 ─────────────────────────────────────────────
  64. function gain(s, x) { s.res += x; }
  65. function checkAch(s, out) {
  66. for (const id of newlyUnlocked(s)) { s.ach[id] = nowSec(); out.push({ type: 'ach', id, ach: achById(id) }); }
  67. }
  68. /** 引导推进:一次动作里可能连续满足多步(例如升级同时触发了第一步与第二步),逐条推进 */
  69. function tutorialAdvance(s, out) {
  70. const T = s.tutorial;
  71. if (!T || T.step >= 99) return;
  72. for (let guard = 0; guard < 6; guard++) {
  73. const step = F.TUT_STEPS[T.step];
  74. if (!step || !step.check(s)) break;
  75. T.step = T.step + 1 >= 6 ? 99 : T.step + 1;
  76. out.push({ type: 'tut', step: T.step });
  77. }
  78. }
  79. // ── 点击世界树 ────────────────────────────────────────
  80. export function tap(s, now = nowSec()) {
  81. const out = [];
  82. const g = F.tapOf(s, now);
  83. gain(s, g);
  84. s.stats.taps++;
  85. if (s.tutorial.step === 1) s.tutorial.taps++;
  86. out.push({ type: 'tap', gain: g });
  87. tutorialAdvance(s, out);
  88. checkAch(s, out);
  89. return out;
  90. }
  91. // ── 根系 ─────────────────────────────────────────────
  92. export function rootCostNow(s) { return F.rootCostAt(s, s.rootLv); }
  93. export function buyRoot(s, n = 1) {
  94. const out = [];
  95. for (let k = 0; k < n; k++) {
  96. const c = rootCostNow(s);
  97. if (s.res < c) break;
  98. s.res -= c; s.rootLv++; s.stats.rootBuys++;
  99. out.push({ type: 'root', level: s.rootLv, cost: c });
  100. }
  101. tutorialAdvance(s, out); checkAch(s, out);
  102. return out;
  103. }
  104. // ── 生命 ─────────────────────────────────────────────
  105. export function lifeAvailable(s, id) {
  106. return F.availableLives(s, s.curPlanet).some((l) => l.id === id);
  107. }
  108. export function lifeCostNow(s, id) {
  109. const l = LIFE.find((x) => x.id === id);
  110. const lv = s.lives[s.curPlanet][id] || 0;
  111. const P = PLANETS[s.curPlanet];
  112. return Math.ceil(B.lifeCost(l, s.curPlanet, lv, P.lvMul, P.ratioMul || 1));
  113. }
  114. /**
  115. * 种下 / 升级生命。
  116. * 第一次购买 = “种下”(写章节叙事,解锁成就),之后为升级。
  117. */
  118. export function buyLife(s, id) {
  119. const out = [];
  120. const i = s.curPlanet;
  121. const l = LIFE.find((x) => x.id === id);
  122. if (!l || l.planet !== i) return out;
  123. if (!lifeAvailable(s, id)) return out;
  124. const cur = s.lives[i][id];
  125. const first = cur === undefined;
  126. const cost = lifeCostNow(s, id);
  127. if (s.res < cost) return out;
  128. s.res -= cost;
  129. s.lives[i][id] = (cur || 0) + 1;
  130. s.stats.lifeBuys++;
  131. out.push({ type: 'life', id, first, level: s.lives[i][id], planet: i });
  132. tutorialAdvance(s, out); checkAch(s, out);
  133. return out;
  134. }
  135. // ── 星球:进入 / 勘探 ─────────────────────────────────
  136. export function enterPlanet(s, i) {
  137. const out = [];
  138. if (!F.isPlanetUnlocked(s, i)) return out;
  139. s.curPlanet = i;
  140. out.push({ type: 'enter', planet: i });
  141. return out;
  142. }
  143. export function unlockCost(i) { return Math.ceil(PLANETS[i].baseTime * B.STAR.unlockMul * Math.pow(1.25, i)); }
  144. export function exploreCostNow(s, i = s.curPlanet) {
  145. return Math.ceil(PLANETS[i].exploreCost * Math.pow(B.STAR.exploreMul, s.planets[i].explore || 0));
  146. }
  147. export function explore(s) {
  148. const out = [];
  149. const i = s.curPlanet;
  150. const p = s.planets[i];
  151. if (p.rem <= 0 || (p.explore || 0) >= B.STAR.exploreMax) return out;
  152. const c = exploreCostNow(s, i);
  153. if (s.res < c) return out;
  154. s.res -= c;
  155. p.explore = (p.explore || 0) + 1;
  156. s.stats.explores++;
  157. out.push({ type: 'explore', planet: i, level: p.explore });
  158. checkAch(s, out);
  159. return out;
  160. }
  161. // ── 环境波动 ─────────────────────────────────────────
  162. /** 推进环境波动计时(每秒调用)。返回事件(转机 / 恶化) */
  163. export function stepHeat(s, t, now) {
  164. const out = [];
  165. // 新手引导期间不打断环境波动:计时不断延后,引导完成后才开始第一次波动
  166. if (!(s.tutorial && s.tutorial.done)) {
  167. const hg = s.heat[s.curPlanet];
  168. if (hg) hg.next = now + B.STAR.heatFirst;
  169. return out;
  170. }
  171. const i = s.curPlanet;
  172. const P = PLANETS[i];
  173. const p = s.planets[i];
  174. if (p.rem <= 0) return out;
  175. const h = s.heat[i];
  176. if (h.until > now) {
  177. if (h.kind === 'bad' && !h.healed) h.value = B.STAR.heatBad;
  178. else h.value = h.kind === 'good' ? -B.STAR.heatGood : 0;
  179. return out;
  180. }
  181. if (h.until > 0) { h.value = 0; h.kind = null; h.healed = false; h.next = now + P.waveSec; }
  182. if (!h.next) h.next = now + B.STAR.heatFirst;
  183. if (now >= h.next) {
  184. // 第 3 次及之后的环境波动是“恶化”;前两次是转机
  185. const seenBad = (s.flags['bad' + i] || 0);
  186. const bad = seenBad >= 2 || Math.random() < 0.35;
  187. h.kind = bad ? 'bad' : 'good';
  188. h.until = now + (bad ? B.STAR.heatBadDur : 12);
  189. h.value = bad ? B.STAR.heatBad : -B.STAR.heatGood;
  190. h.healed = false;
  191. if (bad) s.flags['bad' + i] = seenBad + 1;
  192. out.push({ type: bad ? 'heat-bad' : 'heat-good', planet: i, until: h.until });
  193. }
  194. return out;
  195. }
  196. /** 治愈环境(恶化中的前 8 秒):消耗 = 当前产出 × 1.2 秒 */
  197. export function healCostNow(s, now) {
  198. return Math.ceil(Math.max(1, F.incomeOf(s, now) * B.STAR.healCost));
  199. }
  200. export function heal(s, now = nowSec()) {
  201. const out = [];
  202. const i = s.curPlanet;
  203. const h = s.heat[i];
  204. // 可治愈窗口:恶化开始后的前 8 秒(直到结束前 2 秒)
  205. if (!h || h.kind !== 'bad' || h.healed || h.until - now < B.STAR.heatBadDur - B.STAR.healWindow) return out;
  206. const c = healCostNow(s, now);
  207. if (s.res < c) return out;
  208. s.res -= c; h.healed = true; h.value = 0;
  209. out.push({ type: 'heal', planet: i, cost: c });
  210. return out;
  211. }
  212. // ── 事件 ─────────────────────────────────────────────
  213. export function pickRandomEvent(s) {
  214. const seen = s.scene.events || {};
  215. const pool = RANDOM_EVENTS.filter((e) => !seen[e.id] && (e.planet === 'any' || e.planet.includes(s.curPlanet)));
  216. if (!pool.length) return null;
  217. return pool[Math.floor(Math.random() * pool.length)];
  218. }
  219. /** 环境恶化的下一步:可能触发危机抉择 */
  220. export function openCrisis(s) {
  221. const P = PLANETS[s.curPlanet];
  222. const e = CRISIS_EVENTS[0];
  223. const inst = { ...e, text: e.text.replace('{planet}', P.name).replace('{wave}', P.wave ? P.wave.name : '环境风暴') };
  224. s.scene.current = { kind: 'crisis', ev: inst };
  225. return inst;
  226. }
  227. export function resolveEvent(s, idx, now = nowSec()) {
  228. const out = [];
  229. const cur = s.scene.current;
  230. if (!cur) return out;
  231. const ch = cur.ev.choices[idx];
  232. if (!ch) return out;
  233. applyEffect(s, ch.action, now, out);
  234. if (cur.kind === 'random') {
  235. s.scene.events[cur.ev.id] = now;
  236. s.scene.next = now + rand(B.EVENT.idleMin, B.EVENT.idleMax);
  237. }
  238. s.stats.eventsResolved++;
  239. out.push({ type: 'event-done', ev: cur.ev, choice: ch });
  240. s.scene.current = null;
  241. checkAch(s, out);
  242. return out;
  243. }
  244. function rand(a, b) { return a + Math.random() * (b - a); }
  245. function applyEffect(s, a, now, out) {
  246. const i = s.curPlanet;
  247. if (!a) return;
  248. const income = F.incomeOf(s, now);
  249. if (a.type === 'res') { gain(s, income * a.sec); out.push({ type: 'res', amount: income * a.sec }); }
  250. else if (a.type === 'progress') {
  251. s.planets[i].rem = Math.max(0, Math.min(100, s.planets[i].rem - a.pct));
  252. out.push({ type: 'progress', pct: a.pct });
  253. maybeComplete(s, i, out);
  254. } else if (a.type === 'lifeLevel') {
  255. const ls = F.availableLives(s, i);
  256. if (ls.length) {
  257. const l = ls[Math.floor(Math.random() * ls.length)];
  258. s.lives[i][l.id] = (s.lives[i][l.id] || 0) + a.n;
  259. out.push({ type: 'life-gain', life: l, n: a.n });
  260. checkAch(s, out);
  261. }
  262. } else if (a.type === 'buff') {
  263. s.perm = { prod: a.prod, until: now + a.sec };
  264. out.push({ type: 'buff', prod: a.prod, sec: a.sec });
  265. } else if (a.type === 'storm') {
  266. gain(s, income * a.gain);
  267. s.heat[i] = Object.assign(s.heat[i], { kind: 'bad', until: now + a.sec, value: B.STAR.heatBad * 0.5, healed: false });
  268. out.push({ type: 'res', amount: income * a.gain });
  269. }
  270. }
  271. // ── 星球完成 ─────────────────────────────────────────
  272. export function maybeComplete(s, i, out) {
  273. const p = s.planets[i];
  274. if (p.rem > 0) return false;
  275. if (s.flags['done' + i]) return false;
  276. s.flags['done' + i] = 1;
  277. p.rem = 0;
  278. out.push({ type: 'planet-done', planet: i });
  279. checkAch(s, out);
  280. return true;
  281. }
  282. // ── 主 tick(每秒) ───────────────────────────────────
  283. /** 返回 { world: 世界/成就类事件, ui: 需要 UI 表现的事件 } */
  284. export function tick(s, now = nowSec(), dt = 1) {
  285. const out = [];
  286. s.playSec += dt;
  287. gain(s, F.incomeOf(s, now) * dt);
  288. const i = s.curPlanet;
  289. const p = s.planets[i];
  290. if (p.rem > 0) {
  291. p.rem = Math.max(0, p.rem - F.growRateOf(s, i, now) * dt);
  292. out.push(...stepHeat(s, dt, now));
  293. maybeComplete(s, i, out);
  294. }
  295. // 随机事件:空闲计时到了就打开
  296. if (!s.scene.current && now >= (s.scene.next || 0) && s.tutorial.step >= 99) {
  297. const ev = pickRandomEvent(s);
  298. if (ev) { s.scene.current = { kind: 'random', ev }; out.push({ type: 'event-open', ev }); }
  299. else s.scene.next = now + rand(B.EVENT.idleMin, B.EVENT.idleMax);
  300. }
  301. tutorialAdvance(s, out);
  302. return { world: out, ui: heatOpen(s, out) };
  303. }
  304. /** 环境恶化后的危机:自动打开一次“抉择”事件(前面的 -45% 生产已经是猝不及防的部分) */
  305. function heatOpen(s, worldOut) {
  306. const ui = [];
  307. const bad = worldOut.find((e) => e.type === 'heat-bad');
  308. if (bad && !s.scene.current) {
  309. const ev = openCrisis(s);
  310. ui.push({ type: 'event-open', ev, crisis: true });
  311. }
  312. return ui;
  313. }
  314. /** 离线结算:最多 8 小时,产出按 35%/s 计(自动产出),改造按 30% 速度补算 */
  315. export function applyOffline(s, gap, now = nowSec()) {
  316. const cap = Math.min(Math.max(0, gap), B.RES.offlineSec);
  317. if (cap < 60) return null;
  318. const res = F.incomeOf(s, now) * cap;
  319. const i = s.curPlanet;
  320. const p = s.planets[i];
  321. const grow = p.rem > 0 ? Math.min(p.rem, F.growRateOf(s, i, now) * cap * 0.3) : 0;
  322. gain(s, res);
  323. p.rem = Math.max(0, p.rem - grow);
  324. const out = [];
  325. maybeComplete(s, i, out);
  326. s.scene.next = (s.scene.next || now) + cap;
  327. return { sec: cap, res, grow, events: out };
  328. }
  329. // ── 纪元(轮回) ──────────────────────────────────────
  330. export function canEra(s) {
  331. return s.planets[0].rem <= 0 && s.rootLv >= B.ERA.minRootLv;
  332. }
  333. export function eraPreview(s) {
  334. return B.eraReward(F.clearedCount(s), F.progressSum(s));
  335. }
  336. export function doEra(s, now = nowSec()) {
  337. const out = [];
  338. if (!canEra(s)) return out;
  339. const reward = eraPreview(s);
  340. s.crystals += reward; s.eras++; s.stats.curios++;
  341. // 全部星球回到 100%,生命全部重新生长;等级门槛与星空共鸣让新纪元更快
  342. s.planets = PLANETS.map((p, idx) => ({ rem: 100, explore: 0, best: s.planets[idx].best, unlockedAt: idx === 0 ? now : 0 }));
  343. s.lives = PLANETS.map(() => ({}));
  344. s.heat = PLANETS.map(() => ({ kind: null, until: 0, value: 0, next: 0, healed: false }));
  345. s.rootLv = 0; s.res = B.RES.start; s.curPlanet = 0;
  346. s.flags = {}; s.perm = { prod: 1, until: 0 };
  347. // 新纪元:全部星球的改造从 100% 重新开始(等级门槛、星辰共鸣、结晶加成让新纪元更快)
  348. s.scene.current = null; s.scene.next = now + B.EVENT.firstAfter;
  349. s.tutorial.step = 99;
  350. out.push({ type: 'era', reward, crystals: s.crystals, eras: s.eras });
  351. checkAch(s, out);
  352. return out;
  353. }
  354. /** 星辰洗礼:用结晶换一次三选一的永久加成 */
  355. export function curioOptions(s) {
  356. const els = B.STEM_ELEMENTS.slice();
  357. // 确定性排列(存档里用 curioSeed 记录),保证界面刷新不变
  358. const seed = s.flags.curioSeed || (s.flags.curioSeed = Math.random());
  359. 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);
  360. return order.slice(0, B.CURIO.pick);
  361. }
  362. export function canCurio(s) { return s.crystals >= B.CURIO.cost; }
  363. export function doCurio(s, elId) {
  364. const out = [];
  365. if (!canCurio(s)) return out;
  366. if (!curioOptions(s).some((e) => e.id === elId)) return out;
  367. s.crystals -= B.CURIO.cost;
  368. s.stems[elId] = (s.stems[elId] || 0) + 1;
  369. s.flags.curioSeed = Math.random(); // 下一次三选一换一组
  370. s.stats.curios++;
  371. out.push({ type: 'curio', el: elId, stems: s.stems[elId] });
  372. checkAch(s, out);
  373. return out;
  374. }
  375. export { planetById };