state.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. const i = s.curPlanet;
  166. const P = PLANETS[i];
  167. const p = s.planets[i];
  168. if (p.rem <= 0) return out;
  169. const h = s.heat[i];
  170. if (h.until > now) {
  171. if (h.kind === 'bad' && !h.healed) h.value = B.STAR.heatBad;
  172. else h.value = h.kind === 'good' ? -B.STAR.heatGood : 0;
  173. return out;
  174. }
  175. if (h.until > 0) { h.value = 0; h.kind = null; h.healed = false; h.next = now + P.waveSec; }
  176. if (!h.next) h.next = now + B.STAR.heatFirst;
  177. if (now >= h.next) {
  178. // 第 3 次及之后的环境波动是“恶化”;前两次是转机
  179. const seenBad = (s.flags['bad' + i] || 0);
  180. const bad = seenBad >= 2 || Math.random() < 0.35;
  181. h.kind = bad ? 'bad' : 'good';
  182. h.until = now + (bad ? B.STAR.heatBadDur : 12);
  183. h.value = bad ? B.STAR.heatBad : -B.STAR.heatGood;
  184. h.healed = false;
  185. if (bad) s.flags['bad' + i] = seenBad + 1;
  186. out.push({ type: bad ? 'heat-bad' : 'heat-good', planet: i, until: h.until });
  187. }
  188. return out;
  189. }
  190. /** 治愈环境(恶化中的前 8 秒):消耗 = 当前产出 × 1.2 秒 */
  191. export function healCostNow(s, now) {
  192. return Math.ceil(Math.max(1, F.incomeOf(s, now) * B.STAR.healCost));
  193. }
  194. export function heal(s, now = nowSec()) {
  195. const out = [];
  196. const i = s.curPlanet;
  197. const h = s.heat[i];
  198. // 可治愈窗口:恶化开始后的前 8 秒(直到结束前 2 秒)
  199. if (!h || h.kind !== 'bad' || h.healed || h.until - now < B.STAR.heatBadDur - B.STAR.healWindow) return out;
  200. const c = healCostNow(s, now);
  201. if (s.res < c) return out;
  202. s.res -= c; h.healed = true; h.value = 0;
  203. out.push({ type: 'heal', planet: i, cost: c });
  204. return out;
  205. }
  206. // ── 事件 ─────────────────────────────────────────────
  207. export function pickRandomEvent(s) {
  208. const seen = s.scene.events || {};
  209. const pool = RANDOM_EVENTS.filter((e) => !seen[e.id] && (e.planet === 'any' || e.planet.includes(s.curPlanet)));
  210. if (!pool.length) return null;
  211. return pool[Math.floor(Math.random() * pool.length)];
  212. }
  213. /** 环境恶化的下一步:可能触发危机抉择 */
  214. export function openCrisis(s) {
  215. const P = PLANETS[s.curPlanet];
  216. const e = CRISIS_EVENTS[0];
  217. const inst = { ...e, text: e.text.replace('{planet}', P.name).replace('{wave}', P.wave ? P.wave.name : '环境风暴') };
  218. s.scene.current = { kind: 'crisis', ev: inst };
  219. return inst;
  220. }
  221. export function resolveEvent(s, idx, now = nowSec()) {
  222. const out = [];
  223. const cur = s.scene.current;
  224. if (!cur) return out;
  225. const ch = cur.ev.choices[idx];
  226. if (!ch) return out;
  227. applyEffect(s, ch.action, now, out);
  228. if (cur.kind === 'random') {
  229. s.scene.events[cur.ev.id] = now;
  230. s.scene.next = now + rand(B.EVENT.idleMin, B.EVENT.idleMax);
  231. }
  232. s.stats.eventsResolved++;
  233. out.push({ type: 'event-done', ev: cur.ev, choice: ch });
  234. s.scene.current = null;
  235. checkAch(s, out);
  236. return out;
  237. }
  238. function rand(a, b) { return a + Math.random() * (b - a); }
  239. function applyEffect(s, a, now, out) {
  240. const i = s.curPlanet;
  241. if (!a) return;
  242. const income = F.incomeOf(s, now);
  243. if (a.type === 'res') { gain(s, income * a.sec); out.push({ type: 'res', amount: income * a.sec }); }
  244. else if (a.type === 'progress') {
  245. s.planets[i].rem = Math.max(0, Math.min(100, s.planets[i].rem - a.pct));
  246. out.push({ type: 'progress', pct: a.pct });
  247. maybeComplete(s, i, out);
  248. } else if (a.type === 'lifeLevel') {
  249. const ls = F.availableLives(s, i);
  250. if (ls.length) {
  251. const l = ls[Math.floor(Math.random() * ls.length)];
  252. s.lives[i][l.id] = (s.lives[i][l.id] || 0) + a.n;
  253. out.push({ type: 'life-gain', life: l, n: a.n });
  254. checkAch(s, out);
  255. }
  256. } else if (a.type === 'buff') {
  257. s.perm = { prod: a.prod, until: now + a.sec };
  258. out.push({ type: 'buff', prod: a.prod, sec: a.sec });
  259. } else if (a.type === 'storm') {
  260. gain(s, income * a.gain);
  261. s.heat[i] = Object.assign(s.heat[i], { kind: 'bad', until: now + a.sec, value: B.STAR.heatBad * 0.5, healed: false });
  262. out.push({ type: 'res', amount: income * a.gain });
  263. }
  264. }
  265. // ── 星球完成 ─────────────────────────────────────────
  266. export function maybeComplete(s, i, out) {
  267. const p = s.planets[i];
  268. if (p.rem > 0) return false;
  269. if (s.flags['done' + i]) return false;
  270. s.flags['done' + i] = 1;
  271. p.rem = 0;
  272. out.push({ type: 'planet-done', planet: i });
  273. checkAch(s, out);
  274. return true;
  275. }
  276. // ── 主 tick(每秒) ───────────────────────────────────
  277. /** 返回 { world: 世界/成就类事件, ui: 需要 UI 表现的事件 } */
  278. export function tick(s, now = nowSec(), dt = 1) {
  279. const out = [];
  280. s.playSec += dt;
  281. gain(s, F.incomeOf(s, now) * dt);
  282. const i = s.curPlanet;
  283. const p = s.planets[i];
  284. if (p.rem > 0) {
  285. p.rem = Math.max(0, p.rem - F.growRateOf(s, i, now) * dt);
  286. out.push(...stepHeat(s, dt, now));
  287. maybeComplete(s, i, out);
  288. }
  289. // 随机事件:空闲计时到了就打开
  290. if (!s.scene.current && now >= (s.scene.next || 0) && s.tutorial.step >= 99) {
  291. const ev = pickRandomEvent(s);
  292. if (ev) { s.scene.current = { kind: 'random', ev }; out.push({ type: 'event-open', ev }); }
  293. else s.scene.next = now + rand(B.EVENT.idleMin, B.EVENT.idleMax);
  294. }
  295. tutorialAdvance(s, out);
  296. return { world: out, ui: heatOpen(s, out) };
  297. }
  298. /** 环境恶化后的危机:自动打开一次“抉择”事件(前面的 -45% 生产已经是猝不及防的部分) */
  299. function heatOpen(s, worldOut) {
  300. const ui = [];
  301. const bad = worldOut.find((e) => e.type === 'heat-bad');
  302. if (bad && !s.scene.current) {
  303. const ev = openCrisis(s);
  304. ui.push({ type: 'event-open', ev, crisis: true });
  305. }
  306. return ui;
  307. }
  308. /** 离线结算:最多 8 小时,产出按 35%/s 计(自动产出),改造按 30% 速度补算 */
  309. export function applyOffline(s, gap, now = nowSec()) {
  310. const cap = Math.min(Math.max(0, gap), B.RES.offlineSec);
  311. if (cap < 60) return null;
  312. const res = F.incomeOf(s, now) * cap;
  313. const i = s.curPlanet;
  314. const p = s.planets[i];
  315. const grow = p.rem > 0 ? Math.min(p.rem, F.growRateOf(s, i, now) * cap * 0.3) : 0;
  316. gain(s, res);
  317. p.rem = Math.max(0, p.rem - grow);
  318. const out = [];
  319. maybeComplete(s, i, out);
  320. s.scene.next = (s.scene.next || now) + cap;
  321. return { sec: cap, res, grow, events: out };
  322. }
  323. // ── 纪元(轮回) ──────────────────────────────────────
  324. export function canEra(s) {
  325. return s.planets[0].rem <= 0 && s.rootLv >= B.ERA.minRootLv;
  326. }
  327. export function eraPreview(s) {
  328. return B.eraReward(F.clearedCount(s), F.progressSum(s));
  329. }
  330. export function doEra(s, now = nowSec()) {
  331. const out = [];
  332. if (!canEra(s)) return out;
  333. const reward = eraPreview(s);
  334. s.crystals += reward; s.eras++; s.stats.curios++;
  335. // 全部星球回到 100%,生命全部重新生长;等级门槛与星空共鸣让新纪元更快
  336. s.planets = PLANETS.map((p, idx) => ({ rem: 100, explore: 0, best: s.planets[idx].best, unlockedAt: idx === 0 ? now : 0 }));
  337. s.lives = PLANETS.map(() => ({}));
  338. s.heat = PLANETS.map(() => ({ kind: null, until: 0, value: 0, next: 0, healed: false }));
  339. s.rootLv = 0; s.res = B.RES.start; s.curPlanet = 0;
  340. s.flags = {}; s.perm = { prod: 1, until: 0 };
  341. // 新纪元:全部星球的改造从 100% 重新开始(等级门槛、星辰共鸣、结晶加成让新纪元更快)
  342. s.scene.current = null; s.scene.next = now + B.EVENT.firstAfter;
  343. s.tutorial.step = 99;
  344. out.push({ type: 'era', reward, crystals: s.crystals, eras: s.eras });
  345. checkAch(s, out);
  346. return out;
  347. }
  348. /** 星辰洗礼:用结晶换一次三选一的永久加成 */
  349. export function curioOptions(s) {
  350. const els = B.STEM_ELEMENTS.slice();
  351. // 确定性排列(存档里用 curioSeed 记录),保证界面刷新不变
  352. const seed = s.flags.curioSeed || (s.flags.curioSeed = Math.random());
  353. 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);
  354. return order.slice(0, B.CURIO.pick);
  355. }
  356. export function canCurio(s) { return s.crystals >= B.CURIO.cost; }
  357. export function doCurio(s, elId) {
  358. const out = [];
  359. if (!canCurio(s)) return out;
  360. if (!curioOptions(s).some((e) => e.id === elId)) return out;
  361. s.crystals -= B.CURIO.cost;
  362. s.stems[elId] = (s.stems[elId] || 0) + 1;
  363. s.flags.curioSeed = Math.random(); // 下一次三选一换一组
  364. s.stats.curios++;
  365. out.push({ type: 'curio', el: elId, stems: s.stems[elId] });
  366. checkAch(s, out);
  367. return out;
  368. }
  369. export { planetById };