main.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // 入口:读档(含迁移 / 离线结算)→ 启动 UI。署名:FmodeCode
  2. import * as C from './config.js';
  3. import * as S from './state.js';
  4. import { App } from './ui.js';
  5. function boot() {
  6. let loaded = null;
  7. try { loaded = S.save.load(localStorage); } catch (e) { loaded = null; }
  8. let state = loaded ? loaded.state : S.newState();
  9. // 极早期存档 / 缺省字段补救:保证 UI 依赖的字段存在
  10. if (state && typeof state === 'object') {
  11. const d = S.newState();
  12. for (const k of Object.keys(d)) if (state[k] === undefined) state[k] = d[k];
  13. for (const k of Object.keys(d.upgrades)) if (state.upgrades[k] === undefined) state.upgrades[k] = 0;
  14. if (!Array.isArray(state.planes) || state.planes.length < 4) state.planes = d.planes;
  15. if (!state.stats) state.stats = d.stats;
  16. if (!state.flags) state.flags = {};
  17. if (!state.round) state.round = { refines: 0 };
  18. if (!state.crisis) state.crisis = d.crisis;
  19. if (!state.magic) state.magic = d.magic;
  20. }
  21. let rift = loaded ? loaded.rift : null;
  22. // 里世界对象需带 active 标记以冻结主世界
  23. if (rift && rift.run && rift.run.state !== 'result') { rift.run.active = true; }
  24. else rift = null;
  25. let offline = null;
  26. try {
  27. if (loaded && !(rift && rift.run)) {
  28. const gap = (Date.now() - loaded.savedAt) / 1000;
  29. offline = S.applyOffline(state, gap, null);
  30. }
  31. } catch (e) { offline = null; }
  32. const app = new App(state, rift);
  33. window.__wt = app; // 便于调试与自动化验收(只读)
  34. app.renderAll();
  35. app._lastTickAt = Date.now();
  36. if (offline && !offline.skipped) app.pushDialog({ kind: 'offline', data: offline });
  37. app.log('世界树已苏醒:空洞的侵蚀仍在继续。', 'mile');
  38. S.save.write(localStorage, state, rift);
  39. // 页面重新可见 / 获得焦点时补算离线
  40. document.addEventListener('visibilitychange', () => {
  41. if (!document.hidden) { app._lastTickAt = app._lastTickAt || Date.now(); }
  42. });
  43. window.addEventListener('focus', () => {
  44. const now = Date.now();
  45. const gap = (now - (app._lastTickAt || now)) / 1000;
  46. app._lastTickAt = now;
  47. if (gap > 60 && !state.escaped && !(rift && rift.run)) {
  48. const o = S.applyOffline(state, gap, null);
  49. if (o && !o.skipped) { app.pushDialog({ kind: 'offline', data: o }); app.renderAll(); }
  50. }
  51. });
  52. }
  53. if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
  54. else boot();