diff --git a/README.md b/README.md index 37e190d8..69f27689 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,7 @@ npm start # 启动服务器:http://localhost:3000 | 暂停(独立模拟) | 作战中(含最终攻势 / 隐秘核心)点顶栏的「暂停」或按 `Space`,再点「继续作战」(或 `Space`)继续;同盟模拟的作战不能暂停 | | 表情 | 左下角「交流」,左右滑动(或方向键)换主题,冷却 1 秒 | | 观战 | 自己的作战结束后(或休整期)点左侧队友头像 →「前往查看」;不参战的朋友可以在大厅输入同盟密钥点「观战」(每个同盟最多 2 名观战者,本作新增) | +| 统计(本机) | 标题画面右上角、大厅、等待室的「统计」:胜率、策略通过率、称号、战斗累计和对局记录(点一行回看结算页);只存在本机浏览器里,可以导出 / 导入,没清完第一个回合就退出的对局不计入统计([玩法指南 §12](docs/PLAYING.md#13-统计本机)) | 完整的规则、数值和小技巧见 **[docs/PLAYING.md](docs/PLAYING.md)**(游戏内左下角也有「玩法说明」)。 diff --git a/docs/PLAYING.md b/docs/PLAYING.md index a67b2350..b1b7029b 100644 --- a/docs/PLAYING.md +++ b/docs/PLAYING.md @@ -177,3 +177,18 @@ ## 12. 反馈问题 遇到报错、卡住或结果不对时,打开「设置」→「问题反馈」,点「复制诊断信息」,再到 [GitHub issue](https://github.com/sganggs/Stronghold-Protocol/issues) 里描述发生了什么并粘贴进去。诊断信息包括游戏版本、浏览器和设备、当前所在的阶段与回合,以及打开页面以来记录到的错误(最多保留最近 40 条)。战斗中复制时,默认附上这场战斗的数据,开发者可以用它重现这场战斗;不想附上可以关掉「附上本场战斗」。诊断信息只在你的浏览器里生成,不会自动上传;你和其他玩家的名字、房间号会被替换成 ``、``、`` 这样的占位符。剪贴板不可用时(部分 App 内置浏览器),内容会显示在下方的文本框里,手动全选复制即可。 + +## 13. 统计(本机) + +标题画面右上角、大厅和等待室顶栏的「统计」打开**统计数据**页:这台设备上你参与过的对局的记录。记录只存在这个浏览器里(`localStorage`),不会上传到服务器,服务器也不保存任何对局历史;换浏览器、换设备或清除网站数据后,记录不会跟过去。要搬家,用页面顶部的「导出」(一个 JSON 文件)和另一台设备上的「导入」(按记录合并,重复的跳过)。 + +| 页签 | 内容 | +|---|---| +| 总览 | 总局数、胜场、胜率、到达 / 通关隐秘核心的次数、最远回合、累计时长;各难度一行;六种结算称号各拿过几次 | +| 策略 | 每个策略用了几局、通过几局(你自己撑到最后、队伍获胜才算通过)和通过率 | +| 战斗累计 | 击倒敌人、领袖伤害、造成伤害等结算页上的数字,在打到结算的对局里累加 | +| 对局记录 | 每局一行,最新的在上面(一次显示 50 行,「显示更多」继续);点一行回看那一局的结算页(最新的 30 局可以回看,更早的只留汇总,点不开) | + +**什么算一局**:打到结算页的对局,以及中途退出(「放弃模拟」)前至少清完 1 个回合的对局,计入以上所有统计——和官方一样,中途退出按淘汰处理,通过的回合数就是退出时已经通过的回合。**进去就退、没清完第一个回合就退的对局不计入统计**(不算一局,不影响胜率和策略通过率),但会留在「对局记录」里,标着「中途退出」和「不计入统计」。已经被淘汰后再退出的对局算(你输了这一局)。下面这些不会记录:观战;被服务器结束的对局(服务器重启、同盟解散);关掉页面后没有再回来的对局。 + +**存储与隐私**:最多保留最近 1000 局,所有记录加起来不超过约 0.8 MB(超出时最旧的先丢)。只有最新的 30 局保留完整的阵容、盟约和队友信息,更早的压缩成你自己的一行汇总。同盟对局的记录里有**队友的代号**,它们保存在本机,也会出现在你导出的文件里;不会发给任何人。想删掉就点「清空」(会先确认),或清除这个网站的数据。读不出来的存档(损坏的数据)会另存为备份并重新开始记录,不会让页面出错;由更新版本导出的文件会被拒绝导入,也不会被旧版本覆盖。 diff --git a/public/css/screens/stats.css b/public/css/screens/stats.css new file mode 100644 index 00000000..7ddda452 --- /dev/null +++ b/public/css/screens/stats.css @@ -0,0 +1,193 @@ +/* ========================================================================================== + screens/stats.css — 统计数据 (js/screens/stats.js): the local match record as a full-screen overlay in the grammar of + 干员调配 (screens/loadout.css) — a top bar with the back button, four tabs (总览 / 策略 / 战斗累计 / 对局记录) and + 导出 / 导入 / 清空, a note line, a scrolling body of number cards, tables, the six 评语 and the history list; a stored + match re-viewed as its settlement fills the overlay (.st--replay). + Sizes are design px ÷ 100 (theme.css root scale); text that must stay readable on phones uses max(.xxrem, N px) + (the root scale is clamped at 40 px there, so a bare .15rem would be 6 px). Ported from PR #323 by @2321Robin. + ========================================================================================== */ + +.st { + position: fixed; inset: 0; z-index: 55; /* like .lo: above every screen (1) and the in-match banners (40), below the connection + banner (60), modals / confirm dialogs (80), toasts and tooltips */ + display: flex; flex-direction: column; + padding: var(--sa-t, 0px) var(--sa-r, 0px) var(--sa-b, 0px) var(--sa-l, 0px); + background: var(--bg-0); + color: var(--text-hi); + outline: none; + animation: st-in 200ms var(--ease-out) backwards; + overscroll-behavior: contain; +} +@keyframes st-in { from { opacity: 0; } } +.st__bg { + position: absolute; inset: 0; pointer-events: none; + background: + radial-gradient(70% 90% at 18% 10%, rgba(78, 216, 175, .07), transparent 60%), + radial-gradient(60% 70% at 100% 100%, rgba(246, 163, 41, .05), transparent 60%), + linear-gradient(rgba(78, 216, 175, .035) 1px, transparent 1px) 0 0 / .6rem .6rem, + linear-gradient(90deg, rgba(78, 216, 175, .035) 1px, transparent 1px) 0 0 / .6rem .6rem, + linear-gradient(180deg, #0f1312, #090b0a); +} +.st-top, .st-note, .st-body { position: relative; } +/* the app screens behind the overlay do not need to animate */ +.sp-stats-open .app-root > .screen { visibility: hidden; } +/* a stored match re-viewed as its settlement (the result screen fills the overlay) */ +.st--replay { background: var(--bg-0); } + +/* ---- top bar ----------------------------------------------------------------------------------------------------- */ +.st-top { + flex: none; display: grid; grid-template-columns: minmax(max-content, 1fr) minmax(0, auto) minmax(max-content, 1fr); align-items: center; gap: .2rem; + height: max(1rem, 48px); padding: 0 .36rem; + background: linear-gradient(180deg, rgba(8, 10, 9, .95), rgba(10, 13, 12, .6)); + border-bottom: 1px solid var(--line); +} +.st-top::after { + content: ''; position: absolute; left: .36rem; right: .36rem; bottom: -1px; height: 1px; + background: linear-gradient(90deg, var(--mint-700), transparent 26%, transparent 74%, var(--mint-700)); +} +.st-top__left { justify-self: start; display: flex; align-items: center; gap: .14rem; } +.st-top__center { display: flex; flex-direction: column; align-items: center; gap: .02rem; min-width: 0; } +.st-top__right { justify-self: end; display: flex; align-items: center; gap: .16rem; min-width: 0; } +.st-tabs { display: flex; align-items: stretch; gap: .04rem; max-width: 100%; overflow-x: auto; scrollbar-width: none; } +.st-tab { + display: inline-flex; align-items: center; padding: .02rem .16rem; font: inherit; font-size: max(.24rem, 13px); font-weight: 900; + letter-spacing: .12em; line-height: 1.2; color: var(--text-lo); background: transparent; border: 0; border-bottom: 2px solid transparent; cursor: pointer; + touch-action: manipulation; white-space: nowrap; +} +.st-tab:hover { color: var(--text-hi); } +.st-tab.is-on { color: var(--text-hi); border-bottom-color: var(--mint-500); } + +/* the note lines under the bar: where the data lives, what went wrong with the stored value */ +.st-note { + flex: none; display: flex; align-items: center; gap: .08rem; margin: 0; padding: .07rem .36rem; + font-size: max(.15rem, 10px); color: var(--text-lo); + background: linear-gradient(90deg, rgba(78, 216, 175, .08), transparent 70%); + border-bottom: 1px solid rgba(47, 58, 53, .6); +} +.st-note .icon { width: max(.16rem, 11px); height: max(.16rem, 11px); color: var(--mint-500); flex: none; } +.st-note.is-warn { color: var(--amber); background: linear-gradient(90deg, rgba(246, 163, 41, .12), transparent 70%); } +.st-note.is-warn .icon { color: var(--amber); } + +/* ---- body ------------------------------------------------------------------------------------------------------------ */ +.st-body { + flex: 1 1 auto; min-height: 0; overflow-y: auto; -webkit-overflow-scrolling: touch; overscroll-behavior: contain; + padding: .2rem .36rem .32rem; scrollbar-width: thin; scrollbar-color: var(--line-3) transparent; +} +.st-body > * { max-width: max(12.4rem, 760px); margin-left: auto; margin-right: auto; } +.st-loading { flex: 1; display: grid; place-items: center; min-height: 2rem; } +.st-empty { margin: .6rem auto; text-align: center; font-size: max(.2rem, 13px); color: var(--text-lo); letter-spacing: .06em; } + +.st-sec__h { display: flex; align-items: baseline; gap: .12rem; margin: 0 0 .1rem; font-size: max(.22rem, 14px); font-weight: 800; letter-spacing: .1em; color: var(--text-hi); } +.st-sub { margin: .22rem 0 .08rem; font-size: max(.17rem, 12px); font-weight: 700; letter-spacing: .08em; color: var(--text-md); } + +/* number cards */ +.st-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(max(1.5rem, 96px), 1fr)); gap: .08rem; } +.st-card { + display: flex; flex-direction: column; gap: .02rem; min-width: 0; padding: .08rem .12rem .07rem; + background: rgba(255, 255, 255, .03); border: 1px solid var(--line); +} +.st-card--mint { border-color: var(--mint-800); background: var(--mint-a10); } +.st-card--gold { border-color: rgba(246, 163, 41, .45); background: rgba(246, 163, 41, .07); } +.st-card__num { font-size: max(.3rem, 17px); font-weight: 900; line-height: 1.15; color: var(--text-hi); overflow-wrap: anywhere; } +.st-card--mint .st-card__num { color: var(--mint-400); } +.st-card--gold .st-card__num { color: var(--amber); } +.st-card__label { font-size: max(.14rem, 10px); color: var(--text-md); letter-spacing: .06em; } +.st-split { display: flex; gap: .26rem; margin: .1rem 0 .14rem; font-size: max(.15rem, 11px); color: var(--text-md); } +.st-split b { margin-left: .06rem; font-size: max(.18rem, 12px); color: var(--text-hi); } + +/* tables (难度 / 策略 / 对局记录) */ +.st-tablewrap { overflow-x: auto; } +.st-table { width: 100%; border-collapse: collapse; font-size: max(.17rem, 11px); } +.st-table th { + padding: .05rem .1rem; text-align: left; font-size: max(.14rem, 10px); font-weight: 600; letter-spacing: .08em; + color: var(--text-lo); border-bottom: 1px solid var(--line-2); white-space: nowrap; +} +.st-table td { padding: .06rem .1rem; color: var(--text-md); border-bottom: 1px solid var(--line); vertical-align: middle; } +/* the per-difficulty and per-strategy tables stay narrow enough to read across; the history takes the width */ +.st-table:not(.st-table--history) { max-width: max(9.4rem, 560px); } +.st-table th.num, .st-table td.num { text-align: right; } +.st-table tbody tr:hover td { background: rgba(78, 216, 175, .05); } +.st-table td.st-diff { color: var(--d-color, var(--text-md)); font-weight: 700; white-space: nowrap; } +.st-band { display: inline-flex; align-items: center; gap: .06rem; color: var(--text-hi); white-space: nowrap; vertical-align: middle; } +.st-band .bandicon { flex: none; } +.st-t { font-family: var(--font-num); font-size: max(.15rem, 10px); color: var(--text-lo); white-space: nowrap; } +.st-rate { white-space: nowrap; } +.st-rate b { color: var(--text-hi); font-weight: 700; } +.st-bar { display: inline-block; width: max(.8rem, 48px); height: max(.07rem, 4px); margin-right: .1rem; vertical-align: middle; background: var(--line); } +.st-bar i { display: block; height: 100%; background: var(--mint-500); } + +/* 对局记录: result colours, the 不计入统计 chip, clickable rows */ +.st-res { white-space: nowrap; } +.t-win { color: var(--mint-400); font-weight: 800; } +.t-lose { color: var(--red-premium); font-weight: 800; } +.t-quit { color: var(--amber); font-weight: 800; } +.st-chip { + display: inline-block; margin-left: .08rem; padding: 0 .06rem; font-style: normal; font-size: max(.12rem, 9px); letter-spacing: .04em; + color: var(--text-lo); border: 1px solid var(--line-2); white-space: nowrap; +} +.st-table tr.is-excluded td { opacity: .6; } +.st-table tr.is-clickable { cursor: pointer; } +.st-table tr.is-clickable:hover td, .st-table tr.is-clickable:focus-visible td { background: rgba(78, 216, 175, .1); color: var(--text-hi); } +.st-table tr.is-clickable:focus-visible { outline: 2px solid var(--mint-400); outline-offset: -2px; } +.st-go { width: .24rem; color: var(--text-lo); } +.st-go .icon { width: max(.18rem, 12px); height: max(.18rem, 12px); } +.st-table tr.is-clickable:hover .st-go { color: var(--mint-400); } +.st-more { display: flex; justify-content: center; margin: .14rem 0 0; } +.st-hint { margin: .1rem 0 0; font-size: max(.13rem, 10px); line-height: 1.6; color: var(--text-lo); letter-spacing: .04em; } + +/* the six 评语 with their counts */ +.st-titles { display: grid; grid-template-columns: repeat(auto-fill, minmax(max(1.9rem, 120px), 1fr)); gap: .08rem; } +.st-title { display: flex; align-items: center; gap: .08rem; min-width: 0; padding: .06rem .1rem; background: rgba(255, 255, 255, .03); border: 1px solid var(--line); } +.st-title.is-none { opacity: .45; } +.st-title__icon { width: max(.38rem, 24px); height: max(.38rem, 24px); flex: none; object-fit: contain; } +.st-title__text { display: flex; flex-direction: column; min-width: 0; } +.st-title__text span { font-size: max(.15rem, 10px); color: var(--text-md); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.st-title__text b { font-size: max(.22rem, 14px); font-weight: 900; color: var(--amber); line-height: 1.1; } + +/* what counts (the rule of ui/stats.js countsTowardStats) */ +.st-rule { display: flex; flex-wrap: wrap; align-items: center; gap: .06rem; margin: .24rem 0 0; font-size: max(.14rem, 10px); line-height: 1.6; color: var(--text-lo); } +.st-rule .icon { width: max(.16rem, 11px); height: max(.16rem, 11px); flex: none; color: var(--mint-500); } +.st-rule b { color: var(--amber); font-weight: 700; } + +/* 战斗累计 */ +.st-sums { display: grid; grid-template-columns: repeat(auto-fill, minmax(max(2.4rem, 150px), 1fr)); gap: .06rem; } +.st-sum { display: flex; align-items: baseline; justify-content: space-between; gap: .08rem; padding: .08rem .12rem; background: rgba(255, 255, 255, .03); border: 1px solid var(--line); } +.st-sum span { font-size: max(.15rem, 10px); color: var(--text-md); } +.st-sum b { font-size: max(.22rem, 14px); font-weight: 800; color: var(--text-hi); } + +/* the shared Button scales with the root (40 px/rem on phones ⇒ 6–7 px text, 14–20 px tall): the overlay's own controls keep a + readable size and a tappable height */ +.st .st-back { height: max(.5rem, 32px); padding: 0 max(.2rem, 10px) 0 max(.12rem, 6px); font-size: max(.18rem, 12px); } +.st .st-top__right .btn, .st .st-more .btn { height: max(.36rem, 28px); padding: 0 max(.16rem, 8px); font-size: max(.15rem, 11px); } + +/* the entry buttons of the lobby / room top bars: on the narrowest phones (≤ 700 px) the icon alone — the room's top bar has + no room for another label beside 玩法说明 (its title ran under the label at 640 px); the name stays aria-label / title */ +@media (max-width: 700px) { + .stats-entry .btn__icon + .btn__label { + position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; + } +} + +/* ---- narrow / short viewports ------------------------------------------------------------------------------------------ */ +@media (max-width: 1200px) { + .st-tab { padding: .02rem .08rem; letter-spacing: .04em; } +} +/* phones in landscape (up to 932 px wide): 返回 shows its icon only (the text stays its name) */ +@media (max-width: 1000px) { + .st-top .btn__icon + .btn__label { + position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; + } +} +@media (max-width: 760px) { + .st-top { padding: 0 .16rem; gap: .1rem; } + .st-top::after { left: .16rem; right: .16rem; } + .st-note { padding: .07rem .16rem; } + .st-body { padding: .12rem .16rem .2rem; } +} +@media (max-height: 520px) { + .st-note { display: none; } + .st-body { padding-top: .12rem; } + .st-split { margin: .06rem 0 .08rem; } +} +.sp-coarse .st-tab, .sp-coarse .st-table tr.is-clickable td { min-height: 30px; } +@media (prefers-reduced-motion: reduce) { .st { animation: none; } } diff --git a/public/css/screens/title.css b/public/css/screens/title.css index ed29a4ab..7afeaada 100644 --- a/public/css/screens/title.css +++ b/public/css/screens/title.css @@ -243,6 +243,9 @@ .title-invite .icon { width: .2rem; height: .2rem; } .title-invite b { font-size: .2rem; letter-spacing: .2em; color: #ffd08a; } .title-conn { display: flex; align-items: center; justify-content: center; gap: .1rem; min-height: .32rem; font-size: .14rem; color: var(--text-lo); } +/* 统计 (the local stats page) beside the language menu in the top-right corner */ +.title-corner__tools { display: flex; align-items: center; justify-content: flex-end; gap: .1rem; margin-bottom: .1rem; } +.title-corner__tools .title-lang { margin-bottom: 0; } /* language menu (中文 | English | …, ui/lang.js) in the top-right corner; more than four languages make it a list */ .title-lang { display: inline-flex; margin-bottom: .1rem; } .title-lang button { min-width: .74rem; height: .3rem; font-size: .14rem; cursor: pointer; } diff --git a/public/i18n/en.json b/public/i18n/en.json index a5ca5dc3..41a19fd6 100644 --- a/public/i18n/en.json +++ b/public/i18n/en.json @@ -1068,5 +1068,67 @@ "选择「{name}」的朝向": "Choose {name}'s facing", "选择朝向": "Choose a facing", "朝向:{dir}": "Facing: {dir}", - "开发版 · 不稳定,请勿用于公开服务器": "Development build · unstable, not for public servers" + "开发版 · 不稳定,请勿用于公开服务器": "Development build · unstable, not for public servers", + "统计数据": "Statistics", + "统计": "Stats", + "总览": "Overview", + "总局数": "Games", + "胜场": "Wins", + "胜率": "Win rate", + "到达隐秘核心": "Hidden Core reached", + "通关隐秘核心": "Hidden Core cleared", + "最远回合": "Best round", + "累计时长": "Time played", + "{n} 分": "{n} min", + "难度": "Difficulty", + "局数": "Games", + "隐秘核心通关": "Hidden Core clears", + "使用局数": "Used", + "通过局数": "Cleared", + "通过率": "Clear rate", + "称号": "Titles", + "战斗累计": "Combat totals", + "时间": "Time", + "模式": "Mode", + "结果": "Result", + "点击查看该局结算": "View this match's settlement", + "单人": "Solo", + "同盟": "Co-op", + "胜": "Win", + "负": "Loss", + "已导出 {n} 条对局记录": "Exported {n} match {n|record|records}", + "已导入 {added} 条记录{tail}": "Imported {added} {added|record|records}{tail}", + "(跳过重复 {skipped} 条)": " ({skipped} {skipped|duplicate|duplicates} skipped)", + "没有新记录(全部与现有数据重复)": "Nothing new (everything already exists)", + "导入失败:不是有效的统计导出文件": "Import failed: not a valid stats export file", + "已清空本机统计数据": "Local stats cleared", + "本机数据 · 仅记录本浏览器中你参与的对局": "Local data · only matches you took part in, in this browser", + "检测到更新版本的统计数据,请先升级客户端再查看,以免覆盖数据。": "Stats data from a newer version detected — upgrade the client before viewing, or the data could be overwritten.", + "还没有记录 —— 完成一局对局后,这里会开始积累。": "No records yet — finish a match and the page starts filling in.", + "未知": "Unknown", + "对局记录": "Match history", + "{n} 小时": "{n} h", + "计入统计:打到结算的对局,以及中途退出前至少清完 1 个回合的对局;更早退出的对局只留在对局记录里。": "Counted: matches played to the settlement, and matches given up after clearing at least 1 round. Matches given up earlier stay in the match history only.", + "另有 {n} 局未计入统计": "{n} more {n|match|matches} not counted", + "没有清完第一个回合就退出,不计入统计": "Left before clearing the first round — not counted", + "中途退出的对局没有结算可看": "A match given up has no settlement to view", + "较早的对局只保留汇总,不能回看结算": "Older matches keep only their summary — no settlement to view", + "中途退出": "Left early", + "不计入统计": "Not counted", + "显示更多(还有 {n} 局)": "Show more ({n} left)", + "点击一行,回看该局结算;中途退出的对局只留记录。": "Click a row to re-view that match's settlement; a match given up only leaves its entry.", + "最多保留最近 {max} 局,只有最新的 {full} 局能回看结算。": "Only the latest {max} matches are kept, and only the newest {full} can show their settlement again.", + "返回统计": "Back to Stats", + "文件过大,无法导入": "File too large to import", + "无法写入本机存储,可能已满": "Could not write to local storage — it may be full", + "({n} 条无法读取)": " ({n} unreadable)", + "导入失败:这份文件由更新版本的客户端导出,请先升级客户端": "Import failed: this file was exported by a newer client — upgrade the client first", + "清空统计数据": "Clear Statistics", + "将删除本机保存的 {n} 条对局记录,无法恢复。": "This deletes the {n} match {n|record|records} stored on this device. It cannot be undone.", + "导出为文件(可在别的设备上导入)": "Export to a file (import it on another device)", + "从导出的文件导入(与现有记录合并)": "Import from an exported file (merged with the current records)", + "清空本机的统计数据": "Clear the statistics stored on this device", + "本机数据:只保存在这个浏览器里,不会上传到服务器;同盟对局里队友的代号也会存在本机(导出文件里也有)。": "Local data: kept only in this browser, never uploaded to the server. Teammates' names from Team Simulations are stored here too (and appear in an export file).", + "本机保存的统计数据无法读取,已另存为备份,从现在起重新记录。": "The stats stored on this device could not be read. They were set aside as a backup and recording starts afresh.", + "有 {n} 条记录已损坏,已忽略。": "{n} damaged {n|record was|records were} ignored." } diff --git a/public/i18n/ja.json b/public/i18n/ja.json index f7745aa1..a3e99abd 100644 --- a/public/i18n/ja.json +++ b/public/i18n/ja.json @@ -1074,5 +1074,67 @@ "{files} 没有下载成功,这一页无法显示;已保存的设置不受影响。请刷新页面;仍不行时,请检查广告拦截插件和网络。": "{files}をダウンロードできなかったため、このページを表示できません。保存済みの設定に影響はありません。ページを更新してください。それでも解決しない場合は、広告ブロッカーとネットワークを確認してください。", "全员无伤!": "全員無傷!", "生命值减少 −{n}": "耐久値減少 −{n}", - "当前语言的界面文字为机器翻译,可能不够准确,欢迎在 GitHub 上指正。": "この言語の画面表示は機械翻訳のため、不正確な場合があります。GitHubでの修正提案を歓迎します。" + "当前语言的界面文字为机器翻译,可能不够准确,欢迎在 GitHub 上指正。": "この言語の画面表示は機械翻訳のため、不正確な場合があります。GitHubでの修正提案を歓迎します。", + "统计数据": "統計データ", + "统计": "統計", + "总览": "概要", + "总局数": "対戦数", + "胜场": "勝利数", + "胜率": "勝率", + "到达隐秘核心": "シークレットコア到達", + "通关隐秘核心": "シークレットコアクリア", + "最远回合": "最高ラウンド", + "累计时长": "累計プレイ時間", + "{n} 分": "{n}分", + "难度": "難易度", + "局数": "対戦数", + "隐秘核心通关": "シークレットコアクリア", + "使用局数": "使用回数", + "通过局数": "クリア回数", + "通过率": "クリア率", + "称号": "称号", + "战斗累计": "戦闘累計", + "时间": "日時", + "模式": "モード", + "结果": "結果", + "点击查看该局结算": "この対戦の結果を見る", + "单人": "単独", + "同盟": "連合", + "胜": "勝", + "负": "敗", + "已导出 {n} 条对局记录": "対戦記録を{n}件エクスポートしました", + "已导入 {added} 条记录{tail}": "{added}件の記録をインポートしました{tail}", + "(跳过重复 {skipped} 条)": "(重複{skipped}件をスキップ)", + "没有新记录(全部与现有数据重复)": "新しい記録はありません(すべて既存のデータと重複しています)", + "导入失败:不是有效的统计导出文件": "インポートに失敗しました:有効な統計のエクスポートファイルではありません", + "已清空本机统计数据": "この端末の統計データを消去しました", + "本机数据 · 仅记录本浏览器中你参与的对局": "この端末のデータ · このブラウザで参加した対戦のみ記録されます", + "检测到更新版本的统计数据,请先升级客户端再查看,以免覆盖数据。": "より新しいバージョンの統計データが見つかりました。上書きを避けるため、クライアントを更新してから表示してください。", + "还没有记录 —— 完成一局对局后,这里会开始积累。": "記録はまだありません — 対戦を1つ終えると、ここに蓄積されていきます。", + "未知": "不明", + "对局记录": "対戦履歴", + "{n} 小时": "{n}時間", + "计入统计:打到结算的对局,以及中途退出前至少清完 1 个回合的对局;更早退出的对局只留在对局记录里。": "集計対象:結果画面まで進んだ対戦と、1ラウンド以上クリアしてから途中退出した対戦。それより早く退出した対戦は対戦履歴にのみ残ります。", + "另有 {n} 局未计入统计": "他に{n}件の対戦が集計対象外です", + "没有清完第一个回合就退出,不计入统计": "最初のラウンドをクリアする前に退出したため、集計対象外です", + "中途退出的对局没有结算可看": "途中退出した対戦には表示できる結果がありません", + "较早的对局只保留汇总,不能回看结算": "古い対戦は要約のみ保存されているため、結果は表示できません", + "中途退出": "途中退出", + "不计入统计": "集計対象外", + "显示更多(还有 {n} 局)": "さらに表示(残り{n}件)", + "点击一行,回看该局结算;中途退出的对局只留记录。": "行をクリックすると、その対戦の結果をもう一度見られます。途中退出した対戦は記録のみ残ります。", + "最多保留最近 {max} 局,只有最新的 {full} 局能回看结算。": "保存されるのは直近{max}件のみで、結果を再表示できるのは最新の{full}件だけです。", + "返回统计": "統計に戻る", + "文件过大,无法导入": "ファイルが大きすぎるためインポートできません", + "无法写入本机存储,可能已满": "ローカルストレージに書き込めません。容量がいっぱいの可能性があります", + "({n} 条无法读取)": "(読み取れない記録{n}件)", + "导入失败:这份文件由更新版本的客户端导出,请先升级客户端": "インポートに失敗しました:このファイルはより新しいバージョンのクライアントでエクスポートされています。先にクライアントを更新してください", + "清空统计数据": "統計データを消去", + "将删除本机保存的 {n} 条对局记录,无法恢复。": "この端末に保存されている対戦記録{n}件を削除します。元に戻せません。", + "导出为文件(可在别的设备上导入)": "ファイルにエクスポート(別の端末でインポートできます)", + "从导出的文件导入(与现有记录合并)": "エクスポートしたファイルからインポート(既存の記録と統合)", + "清空本机的统计数据": "この端末の統計データを消去", + "本机数据:只保存在这个浏览器里,不会上传到服务器;同盟对局里队友的代号也会存在本机(导出文件里也有)。": "この端末のデータ:このブラウザにのみ保存され、サーバーには送信されません。連合演算の仲間の名前もこの端末に保存されます(エクスポートファイルにも含まれます)。", + "本机保存的统计数据无法读取,已另存为备份,从现在起重新记录。": "この端末に保存された統計データを読み取れませんでした。バックアップとして退避し、記録を最初からやり直します。", + "有 {n} 条记录已损坏,已忽略。": "破損した記録{n}件を無視しました。" } diff --git a/public/i18n/ko.json b/public/i18n/ko.json index 4a364e8b..35fab8a2 100644 --- a/public/i18n/ko.json +++ b/public/i18n/ko.json @@ -1070,5 +1070,67 @@ "{files} 没有下载成功,这一页无法显示;已保存的设置不受影响。请刷新页面;仍不行时,请检查广告拦截插件和网络。": "{files} 다운로드에 실패하여 이 페이지를 표시할 수 없습니다. 저장된 설정에는 영향이 없습니다. 페이지를 새로고침해 주세요. 그래도 안 되면 광고 차단 확장 프로그램과 네트워크를 확인해 주세요.", "全员无伤!": "전원 무사!", "生命值减少 −{n}": "목표 HP 감소 −{n}", - "当前语言的界面文字为机器翻译,可能不够准确,欢迎在 GitHub 上指正。": "현재 언어의 인터페이스 텍스트는 기계 번역이므로 정확하지 않을 수 있습니다. GitHub에서 수정 제안을 환영합니다." + "当前语言的界面文字为机器翻译,可能不够准确,欢迎在 GitHub 上指正。": "현재 언어의 인터페이스 텍스트는 기계 번역이므로 정확하지 않을 수 있습니다. GitHub에서 수정 제안을 환영합니다.", + "统计数据": "통계", + "统计": "통계", + "总览": "개요", + "总局数": "총 판수", + "胜场": "승리", + "胜率": "승률", + "到达隐秘核心": "숨겨진 핵심 도달", + "通关隐秘核心": "숨겨진 핵심 클리어", + "最远回合": "최고 라운드", + "累计时长": "누적 플레이 시간", + "{n} 分": "{n}분", + "难度": "난이도", + "局数": "판수", + "隐秘核心通关": "숨겨진 핵심 클리어", + "使用局数": "사용 판수", + "通过局数": "클리어 판수", + "通过率": "클리어율", + "称号": "평가", + "战斗累计": "전투 누적", + "时间": "시간", + "模式": "모드", + "结果": "결과", + "点击查看该局结算": "이 판의 정산 보기", + "单人": "독립", + "同盟": "동맹", + "胜": "승", + "负": "패", + "已导出 {n} 条对局记录": "기록 {n}건을 내보냈습니다", + "已导入 {added} 条记录{tail}": "기록 {added}건을 가져왔습니다{tail}", + "(跳过重复 {skipped} 条)": " (중복 {skipped}건 건너뜀)", + "没有新记录(全部与现有数据重复)": "새 기록이 없습니다(모두 기존 데이터와 중복)", + "导入失败:不是有效的统计导出文件": "가져오기 실패: 올바른 통계 내보내기 파일이 아닙니다", + "已清空本机统计数据": "이 기기의 통계 데이터를 삭제했습니다", + "本机数据 · 仅记录本浏览器中你参与的对局": "이 기기의 데이터 · 이 브라우저에서 참여한 판만 기록됩니다", + "检测到更新版本的统计数据,请先升级客户端再查看,以免覆盖数据。": "더 최신 버전의 통계 데이터가 감지되었습니다. 데이터를 덮어쓰지 않도록 클라이언트를 업데이트한 뒤 확인하세요.", + "还没有记录 —— 完成一局对局后,这里会开始积累。": "아직 기록이 없습니다 — 한 판을 마치면 여기에 쌓이기 시작합니다.", + "未知": "알 수 없음", + "对局记录": "판 기록", + "{n} 小时": "{n}시간", + "计入统计:打到结算的对局,以及中途退出前至少清完 1 个回合的对局;更早退出的对局只留在对局记录里。": "집계 대상: 정산까지 진행한 판, 그리고 1라운드 이상 클리어한 뒤 중도 포기한 판. 그보다 일찍 나간 판은 판 기록에만 남습니다.", + "另有 {n} 局未计入统计": "집계에 포함되지 않은 판이 {n}건 더 있습니다", + "没有清完第一个回合就退出,不计入统计": "첫 라운드를 클리어하기 전에 나가서 집계에 포함되지 않습니다", + "中途退出的对局没有结算可看": "중도 포기한 판은 볼 수 있는 정산이 없습니다", + "较早的对局只保留汇总,不能回看结算": "오래된 판은 요약만 저장되어 정산을 볼 수 없습니다", + "中途退出": "중도 퇴장", + "不计入统计": "집계 제외", + "显示更多(还有 {n} 局)": "더 보기 (남은 {n}건)", + "点击一行,回看该局结算;中途退出的对局只留记录。": "행을 누르면 해당 판의 정산을 다시 볼 수 있습니다. 중도 포기한 판은 기록만 남습니다.", + "最多保留最近 {max} 局,只有最新的 {full} 局能回看结算。": "최근 {max}판까지만 보관하며, 정산을 다시 볼 수 있는 것은 최신 {full}판뿐입니다.", + "返回统计": "통계로 돌아가기", + "文件过大,无法导入": "파일이 너무 커서 가져올 수 없습니다", + "无法写入本机存储,可能已满": "로컬 저장소에 쓰지 못했습니다. 공간이 가득 찼을 수 있습니다", + "({n} 条无法读取)": " (읽을 수 없는 기록 {n}건)", + "导入失败:这份文件由更新版本的客户端导出,请先升级客户端": "가져오기 실패: 더 최신 버전 클라이언트에서 내보낸 파일입니다. 먼저 클라이언트를 업데이트하세요", + "清空统计数据": "통계 데이터 비우기", + "将删除本机保存的 {n} 条对局记录,无法恢复。": "이 기기에 저장된 기록 {n}건을 삭제합니다. 되돌릴 수 없습니다.", + "导出为文件(可在别的设备上导入)": "파일로 내보내기 (다른 기기에서 가져올 수 있습니다)", + "从导出的文件导入(与现有记录合并)": "내보낸 파일에서 가져오기 (기존 기록과 병합)", + "清空本机的统计数据": "이 기기의 통계 데이터 비우기", + "本机数据:只保存在这个浏览器里,不会上传到服务器;同盟对局里队友的代号也会存在本机(导出文件里也有)。": "이 기기의 데이터: 이 브라우저에만 저장되며 서버로 전송되지 않습니다. 동맹 시뮬레이션에서 함께한 동료의 이름도 이 기기에 저장됩니다(내보낸 파일에도 포함).", + "本机保存的统计数据无法读取,已另存为备份,从现在起重新记录。": "이 기기에 저장된 통계 데이터를 읽을 수 없습니다. 백업으로 따로 보관했으며 지금부터 새로 기록합니다.", + "有 {n} 条记录已损坏,已忽略。": "손상된 기록 {n}건을 무시했습니다." } diff --git a/public/i18n/zh-TW.json b/public/i18n/zh-TW.json index f19c5760..f66904f4 100644 --- a/public/i18n/zh-TW.json +++ b/public/i18n/zh-TW.json @@ -1072,5 +1072,67 @@ "游戏数据没有载入": "遊戲資料沒有載入", "{files} 没有下载成功,这一页无法显示;已保存的设置不受影响。请刷新页面;仍不行时,请检查广告拦截插件和网络。": "{files} 沒有下載成功,這一頁無法顯示;已儲存的設定不受影響。請重新整理頁面;仍不行時,請檢查廣告攔截擴充功能和網路。", "全员无伤!": "全員無傷!", - "生命值减少 −{n}": "生命值減少 −{n}" + "生命值减少 −{n}": "生命值減少 −{n}", + "统计数据": "統計資料", + "统计": "統計", + "总览": "總覽", + "总局数": "總局數", + "胜场": "勝場", + "胜率": "勝率", + "到达隐秘核心": "到達隱秘核心", + "通关隐秘核心": "通關隱秘核心", + "最远回合": "最遠回合", + "累计时长": "累計時長", + "{n} 分": "{n} 分", + "难度": "難度", + "局数": "局數", + "隐秘核心通关": "隱秘核心通關", + "使用局数": "使用局數", + "通过局数": "通過局數", + "通过率": "通過率", + "称号": "稱號", + "战斗累计": "戰鬥累計", + "时间": "時間", + "模式": "模式", + "结果": "結果", + "点击查看该局结算": "點擊查看該局結算", + "单人": "單人", + "同盟": "同盟", + "胜": "勝", + "负": "負", + "已导出 {n} 条对局记录": "已匯出 {n} 筆對局記錄", + "已导入 {added} 条记录{tail}": "已匯入 {added} 筆記錄{tail}", + "(跳过重复 {skipped} 条)": "(略過重複 {skipped} 筆)", + "没有新记录(全部与现有数据重复)": "沒有新記錄(全部與現有資料重複)", + "导入失败:不是有效的统计导出文件": "匯入失敗:不是有效的統計匯出檔案", + "已清空本机统计数据": "已清空本機統計資料", + "本机数据 · 仅记录本浏览器中你参与的对局": "本機資料 · 僅記錄本瀏覽器中你參與的對局", + "检测到更新版本的统计数据,请先升级客户端再查看,以免覆盖数据。": "偵測到更新版本的統計資料,請先升級用戶端再查看,以免覆蓋資料。", + "还没有记录 —— 完成一局对局后,这里会开始积累。": "還沒有記錄 —— 完成一局對局後,這裡會開始累積。", + "未知": "未知", + "对局记录": "對局記錄", + "{n} 小时": "{n} 小時", + "计入统计:打到结算的对局,以及中途退出前至少清完 1 个回合的对局;更早退出的对局只留在对局记录里。": "計入統計:打到結算的對局,以及中途退出前至少清完 1 個回合的對局;更早退出的對局只留在對局記錄裡。", + "另有 {n} 局未计入统计": "另有 {n} 局未計入統計", + "没有清完第一个回合就退出,不计入统计": "沒有清完第一個回合就退出,不計入統計", + "中途退出的对局没有结算可看": "中途退出的對局沒有結算可看", + "较早的对局只保留汇总,不能回看结算": "較早的對局只保留彙總,不能回看結算", + "中途退出": "中途退出", + "不计入统计": "不計入統計", + "显示更多(还有 {n} 局)": "顯示更多(還有 {n} 局)", + "点击一行,回看该局结算;中途退出的对局只留记录。": "點擊一行,回看該局結算;中途退出的對局只留記錄。", + "最多保留最近 {max} 局,只有最新的 {full} 局能回看结算。": "最多保留最近 {max} 局,只有最新的 {full} 局能回看結算。", + "返回统计": "返回統計", + "文件过大,无法导入": "檔案過大,無法匯入", + "无法写入本机存储,可能已满": "無法寫入本機儲存空間,可能已滿", + "({n} 条无法读取)": "({n} 筆無法讀取)", + "导入失败:这份文件由更新版本的客户端导出,请先升级客户端": "匯入失敗:這份檔案由更新版本的用戶端匯出,請先升級用戶端", + "清空统计数据": "清空統計資料", + "将删除本机保存的 {n} 条对局记录,无法恢复。": "將刪除本機保存的 {n} 筆對局記錄,無法復原。", + "导出为文件(可在别的设备上导入)": "匯出為檔案(可在別的裝置上匯入)", + "从导出的文件导入(与现有记录合并)": "從匯出的檔案匯入(與現有記錄合併)", + "清空本机的统计数据": "清空本機的統計資料", + "本机数据:只保存在这个浏览器里,不会上传到服务器;同盟对局里队友的代号也会存在本机(导出文件里也有)。": "本機資料:只保存在這個瀏覽器裡,不會上傳到伺服器;同盟對局裡隊友的代號也會存在本機(匯出檔案裡也有)。", + "本机保存的统计数据无法读取,已另存为备份,从现在起重新记录。": "本機保存的統計資料無法讀取,已另存為備份,從現在起重新記錄。", + "有 {n} 条记录已损坏,已忽略。": "有 {n} 筆記錄已損毀,已略過。" } diff --git a/public/index.html b/public/index.html index 82a085e0..2fd445cc 100644 --- a/public/index.html +++ b/public/index.html @@ -38,6 +38,7 @@ + diff --git a/public/js/main.js b/public/js/main.js index 4e3a52f1..9aa06279 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -49,6 +49,8 @@ import { settingsStore } from './ui/settings.js'; import { GuideHost } from './ui/guide.js'; import { installDeviceSupport } from './ui/device.js'; import { LoadoutHost } from './screens/loadout.js'; +import { StatsHost } from './screens/stats.js'; +import { recordResult, installStatsRecorder } from './ui/stats.js'; import { installLoadoutSync, installOwnershipSync, installDiySync } from './ui/loadoutSync.js'; import { startBuildGuard } from './ui/buildGuard.js'; import { initLang, useLang, tickerText } from './ui/lang.js'; @@ -220,7 +222,13 @@ function wireNet() { net.on('m.public', (msg) => { matchAt = Date.now(); store.patch('match', { public: payload(msg) }); maybeFinishRestore(); }); net.on('m.private', (msg) => { matchAt = Date.now(); store.patch('match', { private: payload(msg) }); }); net.on('m.field', (msg) => store.patch('match', { field: payload(msg) })); - net.on('m.result', (msg) => store.patch('match', { result: payload(msg) })); + net.on('m.result', (msg) => { + const res = payload(msg); + store.patch('match', { result: res }); + // 本机统计 (PR #323): every arrival, including the lobby's result replay after a reconnect / reload — + // replays dedupe by content id inside recordResult (spectator seats' copies build no record at all) + recordResult(res, { myId: store.get().me.playerId, roomMode: store.get().room?.mode ?? null, now: Date.now() }); + }); net.on('m.toast', (msg) => { const kind = ['info', 'success', 'warn', 'error'].includes(msg.kind) ? msg.kind : 'info'; // msgid + params (server ≥ 0.2.0) or the text itself as a msgid, in the current language @@ -288,6 +296,7 @@ function App() { <${UiHosts} /> <${GuideHost} /> <${LoadoutHost} /> + <${StatsHost} /> `; } @@ -342,6 +351,7 @@ async function boot() { })); wireNet(); + installStatsRecorder(store); // follows the match on screen, so a 放弃模拟 can be recorded (ui/stats.js) installLoadoutSync({ net }); installOwnershipSync({ net }); installDiySync({ net }); diff --git a/public/js/screens/lobby.js b/public/js/screens/lobby.js index 5274507f..33ba0478 100644 --- a/public/js/screens/lobby.js +++ b/public/js/screens/lobby.js @@ -16,6 +16,7 @@ import { DIFFICULTIES, DIFFICULTY_NAMES, DIFFICULTY_COLORS, ROOM_CODE_LEN, MAX_S import { html, Button, Icon, MicroLabel, Panel, TextField, PingPill, AvatarFrame, Tooltip, Spinner, DifficultyIcon, doctorNo } from '../ui/components.js'; import { toast, toastError } from '../ui/toasts.js'; import { GuideButton } from '../ui/guide.js'; +import { openStats } from './stats.js'; import { LoadoutButton } from './loadout.js'; import { net, identity } from '../net.js'; import { store, useStore, shallowEqual, loadPref, savePref } from '../store.js'; @@ -311,6 +312,7 @@ export function LobbyScreen() {

${t('选择模拟协议')}

+ <${Button} variant="secondary" size="sm" icon="chart" class="stats-entry" onClick=${openStats} title=${t('统计数据')} aria-label=${t('统计数据')}>${t('统计')} <${GuideButton} class="lobby-guide" variant="secondary" label=${t('玩法说明')} /> <${LoadoutButton} from="lobby" size="sm" class="lobby-loadout" label=${t('干员调配')} />
diff --git a/public/js/screens/result.js b/public/js/screens/result.js index ec7572bf..dbba1907 100644 --- a/public/js/screens/result.js +++ b/public/js/screens/result.js @@ -103,12 +103,22 @@ function PlayerCard({ p, myId, titles, best, solo = false }) { `; } -/** RESULT screen. */ +/** RESULT screen of the match on screen: reads the store; 返回同盟 / 返回大厅 drops the match. */ export function ResultScreen() { const res = useStore((s) => s.match.result); const pub = useStore((s) => s.match.public); const myId = useStore((s) => s.me.playerId); const hasRoom = useStore((s) => !!s.room); + const back = () => store.set({ match: emptyMatch() }); + return html`<${ResultView} res=${res} pub=${pub} myId=${myId} backLabel=${hasRoom ? t('返回同盟') : t('返回大厅')} onBack=${back} />`; +} + +/** + * The settlement view of one m.result payload — the live screen above, and the stats page's re-view of a stored match + * (screens/stats.js, which hands it the payload recordToResult rebuilt; `quiet`: no settlement jingle). + * @param {{ res: any, pub?: any, myId?: string|null, backLabel: string, onBack: () => void, quiet?: boolean }} props + */ +export function ResultView({ res, pub = null, myId = null, backLabel, onBack, quiet = false }) { const gd = useGameData(); const r = normalizeResult(res, pub); const titles = Array.isArray(gd.config?.titles) ? gd.config.titles : []; @@ -118,8 +128,7 @@ export function ResultScreen() { for (const p of r.players) if (Number.isFinite(p.stats[k]) && p.stats[k] > 0 && (top == null || p.stats[k] > top.v)) top = { v: p.stats[k], id: p.playerId }; if (top && r.players.length > 1) best[k] = top.id; } - useEffect(() => { audio.sfx(r.victory ? 'settlementSucceed' : 'settlementFail'); }, []); - const back = () => store.set({ match: emptyMatch() }); + useEffect(() => { if (!quiet) audio.sfx(r.victory ? 'settlementSucceed' : 'settlementFail'); }, []); const boss = r.bossId ? gd.boss(r.bossId) : null; // the Hidden Core medal (and its corrupted leader) only once R15 was actually fought const hidden = r.hiddenBossId && r.hiddenReached ? gd.boss(r.hiddenBossId) : null; @@ -150,7 +159,7 @@ export function ResultScreen() {
${mins ? html`

${tParts('本局耗时 {n} 分钟', { n: html`${mins}`, mins })}

` : null}
- <${Button} variant="primary" size="xl" icon="chevronLeft" onClick=${back}>${hasRoom ? t('返回同盟') : t('返回大厅')} + <${Button} variant="primary" size="xl" icon="chevronLeft" onClick=${onBack}>${backLabel}
diff --git a/public/js/screens/room.js b/public/js/screens/room.js index e636211d..e9b48763 100644 --- a/public/js/screens/room.js +++ b/public/js/screens/room.js @@ -19,6 +19,7 @@ import { import { toast, toastError } from '../ui/toasts.js'; import { copyText } from '../ui/clipboard.js'; import { GuideButton } from '../ui/guide.js'; +import { openStats } from './stats.js'; import { LoadoutButton } from './loadout.js'; import { net } from '../net.js'; import { store, useStore, shallowEqual, emptyMatch, isSpectating } from '../store.js'; @@ -306,6 +307,7 @@ export function RoomScreen() { <${PingPill} ms=${conn.ping} online=${online} /> <${MicroLabel}>${t('当前延迟')}
+ <${Button} variant="secondary" size="sm" icon="chart" class="stats-entry" onClick=${openStats} title=${t('统计数据')} aria-label=${t('统计数据')}>${t('统计')} <${GuideButton} class="room-guide" variant="secondary" label=${t('玩法说明')} />
diff --git a/public/js/screens/stats.js b/public/js/screens/stats.js new file mode 100644 index 00000000..b4be15d7 --- /dev/null +++ b/public/js/screens/stats.js @@ -0,0 +1,360 @@ +// The local stats viewer (统计数据): this browser's record of the matches the player took part in — see ui/stats.js for +// what is recorded, what counts and how the storage is bounded. A full-screen overlay opened imperatively from the +// title screen / lobby / room (`openStats()`); is mounted once by main.js. Ported from PR #323 by +// @2321Robin; reworked for 0.2.2 in the grammar of 干员调配 (top bar with tabs, a note line, a scrolling body). +// +// 总览 – games, wins, win rate, hidden-core reaches / clears, best round, time played; the difficulties; the six +// 评语 (titles) with their counts; what counts and what was left out +// 策略 – per strategy (band): games used / passed (self alive on a winning team) / pass rate +// 战斗累计 – the player's summed combat bookkeeping of the settled matches +// 对局记录 – every stored match, newest first. A settled row re-views that match's settlement screen (the record is +// inverted into an m.result payload for ); a match given up early is marked 中途退出 and, +// when it did not count, 不计入统计 +// Everything is 本机数据 (localStorage, `sp.pref.stats`) and the page says so, teammates' names included. 导出 / 导入 (a +// JSON file, merged by record id on the way in) moves it between devices; 清空 resets it after a confirm dialog. +// The host renders nothing until opened and the game data files the replay needs load only then (the lobby alone never +// downloads them): the overview reads config / bands / assets only. + +import { useEffect, useMemo, useRef, useState } from '../../vendor/hooks.module.js'; +import { DIFFICULTIES, DIFFICULTY_NAMES, DIFFICULTY_COLORS } from '../../../shared/constants.js'; +import { html, Icon, MicroLabel, Spinner, Button, confirmDialog } from '../ui/components.js'; +import { useGameData, makeLookups, BandIcon, Img } from '../ui/gameComponents.js'; +import { data, useData } from '../data.js'; +import { fmtNum } from '../ui/gameLogic.js'; +import { titleIconUrl } from '../ui/assetUrls.js'; +import { useDocClass } from '../ui/device.js'; +import { createStore, useStore, selectRoute } from '../store.js'; +import { ResultView } from './result.js'; +import { toast, toastError } from '../ui/toasts.js'; +import { + loadStats, saveStats, emptyStats, importStats, exportStats, aggregateStats, countsTowardStats, selfRowOf, roundsOf, + recordToResult, MAX_RECORDS, FULL_KEEP, IMPORT_MAX_CHARS, +} from '../ui/stats.js'; +import { t, N_ } from '../../../shared/i18n.js'; + +const cx = (...p) => p.flat().filter(Boolean).join(' '); + +/** Rows of 对局记录 shown at first and added by each 显示更多. */ +export const HISTORY_PAGE = 50; + +const statsStore = createStore({ open: false, tab: 'overview' }); + +/** Open the stats viewer (title screen / lobby / room entry points). */ +export function openStats() { + data.load('config'); + data.load('bands'); + data.load('assets'); + statsStore.set({ open: true, tab: 'overview' }); +} +export const closeStats = () => statsStore.set({ open: false }); + +const TABS = [ + { id: 'overview', name: N_('总览'), micro: 'OVERVIEW' }, + { id: 'bands', name: N_('策略'), micro: 'STRATEGIES' }, + { id: 'totals', name: N_('战斗累计'), micro: 'COMBAT TOTALS' }, + { id: 'history', name: N_('对局记录'), micro: 'HISTORY' }, +]; + +const pct = (n, d) => (d > 0 ? `${Math.round((n / d) * 100)}%` : '—'); +const dateTime = (ms) => { + if (!ms) return '—'; + const d = new Date(ms); + const p = (n) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; +}; +/** Time played: minutes up to 99, then hours with one decimal. */ +function playedText(ms) { + const mins = Math.round((ms || 0) / 60000); + return mins < 100 ? t('{n} 分', { n: fmtNum(mins) }) : t('{n} 小时', { n: (mins / 60).toFixed(1) }); +} +const difficultyName = (d) => (DIFFICULTY_NAMES[d] ? t(DIFFICULTY_NAMES[d]) : t('未知')); + +/** Save `text` as a download. Silent no-op when the browser refuses downloads. */ +function downloadText(filename, text) { + try { + const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 4000); + } catch { /* ignore */ } +} + +/** Read a picked file as text (`File.text()`, with a FileReader fallback for older Safari). */ +function readFileText(file) { + if (typeof file?.text === 'function') return file.text(); + return new Promise((resolve, reject) => { + const fr = new FileReader(); + fr.onload = () => resolve(String(fr.result ?? '')); + fr.onerror = () => reject(fr.error || new Error('read failed')); + fr.readAsText(file); + }); +} + +/** `stronghold-stats-20261008-2130.json` */ +function exportFilename(now = new Date()) { + const p = (n) => String(n).padStart(2, '0'); + return `stronghold-stats-${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}.json`; +} + +/** One labelled number card. */ +function StatCard({ label, micro, value, tone }) { + return html`
+ <${MicroLabel} tone=${tone === 'gold' ? 'gold' : 'mint'}>${micro} + ${value} + ${label} +
`; +} + +function Section({ title, micro, children, class: cls }) { + return html`
+

${title}<${MicroLabel}>${micro}

+ ${children} +
`; +} + +/** 总览: cards, the per-difficulty table, the six titles, and the line about what counts. */ +function Overview({ agg, gd }) { + const rows = DIFFICULTIES.filter((d) => agg.byDifficulty[d]).concat(Object.keys(agg.byDifficulty).filter((d) => !DIFFICULTIES.includes(d))); + const titles = (Array.isArray(gd.config?.titles) ? gd.config.titles : []).map((x) => ({ ...x, count: agg.titles[x.id]?.count || 0 })); + return html`<${Section} title=${t('总览')} micro="OVERVIEW"> +
+ <${StatCard} micro="GAMES" value=${fmtNum(agg.count)} label=${t('总局数')} /> + <${StatCard} micro="WINS" value=${fmtNum(agg.wins)} label=${t('胜场')} tone="mint" /> + <${StatCard} micro="WIN RATE" value=${pct(agg.wins, agg.count)} label=${t('胜率')} tone="gold" /> + <${StatCard} micro="HIDDEN CORE" value=${fmtNum(agg.hidden.reached)} label=${t('到达隐秘核心')} /> + <${StatCard} micro="HIDDEN CLEAR" value=${fmtNum(agg.hidden.cleared)} label=${t('通关隐秘核心')} /> + <${StatCard} micro="BEST ROUND" value=${fmtNum(agg.rounds.max)} label=${t('最远回合')} /> + <${StatCard} micro="TIME PLAYED" value=${playedText(agg.duration.totalMs)} label=${t('累计时长')} /> +
+

${t('单人')} ${fmtNum(agg.byMode.solo)}${t('同盟')} ${fmtNum(agg.byMode.coop)}

+ ${rows.length ? html`
+ + + ${rows.map((d) => { + const v = agg.byDifficulty[d]; + return html` + + + + + + `; + })} + +
${t('难度')}${t('局数')}${t('胜场')}${t('胜率')}${t('隐秘核心通关')}
${difficultyName(d)}${fmtNum(v.games)}${fmtNum(v.wins)}${pct(v.wins, v.games)}${fmtNum(v.hiddenCleared)}
` : null} + ${titles.length ? html`

${t('称号')}

+
+ ${titles.map((x) => html`
+ <${Img} src=${titleIconUrl(gd.m, x.picId)} class="st-title__icon" fallback=${html`<${Icon} name="crown" />`} /> +
${x.name}${fmtNum(x.count)}
+
`)} +
` : null} +

<${Icon} name="info" />${t('计入统计:打到结算的对局,以及中途退出前至少清完 1 个回合的对局;更早退出的对局只留在对局记录里。')}${agg.excluded + ? html` ${t('另有 {n} 局未计入统计', { n: agg.excluded })}` : null}

+ `; +} + +/** 策略: per-band used / passed / pass rate, most used first (the user's headline ask). */ +function Bands({ agg, gd }) { + const rows = Object.entries(agg.bands).sort((a, b) => (b[1].games - a[1].games) || (b[1].wins - a[1].wins)); + return html`<${Section} title=${t('策略')} micro="STRATEGIES"> + ${rows.length ? html`
+ + + ${rows.map(([bandId, v]) => { + const band = gd.band(bandId); + const rate = v.games > 0 ? Math.round((v.wins / v.games) * 100) : 0; + return html` + + + + + `; + })} + +
${t('策略')}${t('使用局数')}${t('通过局数')}${t('通过率')}
${band ? html`<${BandIcon} bandId=${band.bandId} size="xs" />${band.name}` : bandId}${fmtNum(v.games)}${fmtNum(v.wins)}${pct(v.wins, v.games)}
` : html`

${t('还没有记录 —— 完成一局对局后,这里会开始积累。')}

`} + `; +} + +const SUM_ROWS = [ + ['kills', N_('击倒敌人')], ['bossDamage', N_('领袖伤害')], ['dmgDealt', N_('造成伤害')], ['activatedLayers', N_('盟约层数')], + ['merges', N_('晋升次数')], ['itemsEquipped', N_('配发装备')], ['gold', N_('消耗资金')], ['perfectRounds', N_('完美作战')], + ['refreshes', N_('刷新次数')], ['leaks', N_('未击倒')], ['lpLost', N_('损失生命')], +]; + +/** 战斗累计: the self player's sums over the settled matches. */ +function CombatSums({ agg }) { + const rows = SUM_ROWS.filter(([k]) => Number.isFinite(agg.sums[k])); + return html`<${Section} title=${t('战斗累计')} micro="COMBAT TOTALS"> + ${rows.length ? html`
+ ${rows.map(([k, label]) => html`
${t(label)}${fmtNum(agg.sums[k])}
`)} +
` : html`

${t('还没有记录 —— 完成一局对局后,这里会开始积累。')}

`} + `; +} + +/** One 对局记录 row: what it was, who won, whether it counted and whether the settlement can be re-viewed. */ +function HistoryRow({ rec, gd, onOpen }) { + const self = selfRowOf(rec); + const quit = rec.end === 'quit'; + const counted = countsTowardStats(rec); + const won = self ? !!self.victory : !!rec.victory; + const band = self?.bandId ? gd.band(self.bandId) : null; + const rounds = roundsOf(rec); + const known = Number.isFinite(self?.roundsPassed) || Number.isFinite(rec.roundsPassed); + const view = !quit && !rec.compact; // a quit has nothing settled; a compacted record no rows left + const open = () => onOpen(rec); + return html` { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); } } : undefined}> + ${dateTime(rec.t)} + ${difficultyName(rec.difficulty)} + ${rec.roomMode === 'solo' ? t('单人') : rec.roomMode === 'coop' ? t('同盟') : '—'} + ${band ? html`<${BandIcon} bandId=${band.bandId} size="xs" />${band.name}` : self?.bandId || '—'} + ${quit ? html`${t('中途退出')}` : html`${won ? t('胜') : t('负')}`} + ${!counted ? html`${t('不计入统计')}` : null} + ${known ? fmtNum(rounds) : '—'} + ${view ? html`<${Icon} name="chevronRight" />` : null} + `; +} + +/** 对局记录: every stored match, newest first, HISTORY_PAGE rows at a time. */ +function History({ records, gd, onOpen }) { + const [shown, setShown] = useState(HISTORY_PAGE); + const rows = records.slice(0, shown); + return html`<${Section} title=${t('对局记录')} micro=${`HISTORY · ${records.length}`}> + ${rows.length ? html`
+ + ${rows.map((r) => html`<${HistoryRow} key=${r.id} rec=${r} gd=${gd} onOpen=${onOpen} />`)} +
${t('时间')}${t('难度')}${t('模式')}${t('策略')}${t('结果')}${t('回合')}
+ ${records.length > shown ? html`
<${Button} size="sm" variant="secondary" onClick=${() => setShown(shown + HISTORY_PAGE)}>${t('显示更多(还有 {n} 局)', { n: records.length - shown })}
` : null} +

${t('点击一行,回看该局结算;中途退出的对局只留记录。')} ${t('最多保留最近 {max} 局,只有最新的 {full} 局能回看结算。', { max: MAX_RECORDS, full: FULL_KEEP })}

` + : html`

${t('还没有记录 —— 完成一局对局后,这里会开始积累。')}

`} + `; +} + +/** A stored match re-viewed as its settlement screen: the full game data is loaded now (the lobby alone never loads it). */ +function Replay({ rec, onBack }) { + const gd = useGameData(); + const res = useMemo(() => recordToResult(rec), [rec]); + if (!gd.ready) return html`
<${Spinner} size="md" />
`; + return html`<${ResultView} res=${res} pub=${null} myId=${rec.selfId} backLabel=${t('返回统计')} onBack=${onBack} quiet=${true} />`; +} + +/** The overlay, rendered while open (its data hooks run only then). */ +function StatsScreen({ tab }) { + const ready = useData('config', 'bands', 'assets'); + const gd = useMemo(() => makeLookups(ready), [ready, data.locale()]); + const [stats, setStats] = useState(() => loadStats()); + const [replay, setReplay] = useState(null); + const boxRef = useRef(null); + const fileRef = useRef(null); + const replayRef = useRef(null); + replayRef.current = replay; + const inMatch = useStore((s) => selectRoute(s) === 'game'); + useDocClass('sp-stats-open'); + + // a match starting (the host pressed 开始) takes the player to its briefing: the overlay must not sit on top of it + useEffect(() => { if (inMatch) closeStats(); }, [inMatch]); + useEffect(() => { + const onKey = (e) => { + if (e.key !== 'Escape' || document.querySelector('.modal')) return; // a confirm dialog on top takes the Esc + e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); + if (replayRef.current) setReplay(null); else closeStats(); + }; + window.addEventListener('keydown', onKey, true); + const timer = setTimeout(() => boxRef.current?.focus?.(), 30); + return () => { window.removeEventListener('keydown', onKey, true); clearTimeout(timer); }; + }, []); + + const agg = useMemo(() => aggregateStats(stats.records), [stats]); + const reload = () => setStats(loadStats()); + + const doExport = () => { + try { + const payload = exportStats(stats); + downloadText(exportFilename(), JSON.stringify(payload)); + toast(t('已导出 {n} 条对局记录', { n: payload.records.length }), 'success'); + } catch (err) { + toastError(err); + } + }; + const doFile = async (e) => { + const file = e.currentTarget.files?.[0]; + e.currentTarget.value = ''; // allow re-picking the same file + if (!file) return; + if (file.size > IMPORT_MAX_CHARS) { toast(t('文件过大,无法导入'), 'error'); return; } + try { + const raw = JSON.parse(await readFileText(file)); + const { stats: merged, added, skipped, dropped } = importStats(raw, loadStats()); + if (added && !saveStats(merged)) { toast(t('无法写入本机存储,可能已满'), 'error'); return; } + reload(); + const tail = (skipped ? t('(跳过重复 {skipped} 条)', { skipped }) : '') + (dropped ? t('({n} 条无法读取)', { n: dropped }) : ''); + toast(added ? t('已导入 {added} 条记录{tail}', { added, tail }) : t('没有新记录(全部与现有数据重复)'), 'success'); + } catch (err) { + toast(err?.code === 'stats-newer-version' ? t('导入失败:这份文件由更新版本的客户端导出,请先升级客户端') : t('导入失败:不是有效的统计导出文件'), 'error'); + } + }; + const doClear = async () => { + const ok = await confirmDialog({ + title: t('清空统计数据'), micro: 'CLEAR STATISTICS', danger: true, okText: t('清空'), + text: t('将删除本机保存的 {n} 条对局记录,无法恢复。', { n: stats.records.length }), + }); + if (!ok) return; + if (!saveStats(emptyStats())) { try { globalThis.localStorage?.removeItem('sp.pref.stats'); } catch { /* ignore */ } } + reload(); + toast(t('已清空本机统计数据'), 'success'); + }; + + if (replay) return html``; + + const tabInfo = TABS.find((x) => x.id === tab) || TABS[0]; + const empty = !stats.records.length; + return html``; +} + +/** Global stats viewer host — mounted once by main.js; renders nothing (and loads nothing) until opened. */ +export function StatsHost() { + const { open, tab } = useStore((s) => s, Object.is, statsStore); + if (!open) return null; + return html`<${StatsScreen} tab=${tab} />`; +} + diff --git a/public/js/screens/title.js b/public/js/screens/title.js index 2ff7873d..48b2d9b0 100644 --- a/public/js/screens/title.js +++ b/public/js/screens/title.js @@ -14,6 +14,7 @@ import { useMemo, useState } from '../../vendor/hooks.module.js'; import { NAME_MAX_LEN, APP_VERSION, DEV_BUILD } from '../../../shared/constants.js'; import { html, Button, Icon, MicroLabel, TextField, PingPill } from '../ui/components.js'; import { GuideButton } from '../ui/guide.js'; +import { openStats } from './stats.js'; import { toast } from '../ui/toasts.js'; import { net, identity } from '../net.js'; import { store, useStore, shallowEqual } from '../store.js'; @@ -245,7 +246,10 @@ export function TitleScreen() {
- <${LangToggle} class="title-lang" /> +
+ <${Button} variant="ghost" size="sm" icon="chart" class="title-stats" onClick=${openStats} title=${t('统计数据')}>${t('统计')} + <${LangToggle} class="title-lang" /> +
<${MicroLabel} tone="hi">TARGET POINT
<${MicroLabel}>STRONGHOLD PROTOCOL
diff --git a/public/js/ui/components.js b/public/js/ui/components.js index 25716906..ea56ad73 100644 --- a/public/js/ui/components.js +++ b/public/js/ui/components.js @@ -55,6 +55,8 @@ export const ICONS = { users: { d: 'M9 4a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7zM2 20a7 6.5 0 0 1 14 0zM16.5 5a3 3 0 1 1 0 6 3 3 0 0 1 0-6zm.9 8.1A6.5 6 0 0 1 22.5 20H18a8.6 8 0 0 0-2.4-6.1 6 6 0 0 1 1.8-.8z' }, rook: { d: 'M5 3h3v2h2V3h4v2h2V3h3v5l-2 2v7l2 2v2H5v-2l2-2v-7L5 8z' }, signal: { d: 'M2 17h3v4H2zm6-4h3v8H8zm6-4h3v12h-3zm6-4h3v16h-3z' }, + // 统计 (the stats page's entry): three columns on a baseline — apart from `signal`, the ping bars + chart: { d: 'M4 12h4v7H4zm6-6h4v13h-4zm6 3h4v10h-4zM3 20h18v2H3z' }, refresh: { d: 'M12 4a8 8 0 0 1 7.4 5H17v2h6V5h-2v2.3A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8zm0 16a8 8 0 0 1-7.4-5H7v-2H1v6h2v-2.3A10 10 0 0 0 22 12h-2a8 8 0 0 1-8 8z' }, snow: { d: 'M11 2h2v4.2l2.3-2.3 1.4 1.4-3.7 3.7v2h2l3.7-3.7 1.4 1.4-2.3 2.3H22v2h-4.2l2.3 2.3-1.4 1.4-3.7-3.7h-2v2l3.7 3.7-1.4 1.4-2.3-2.3V22h-2v-4.2l-2.3 2.3-1.4-1.4 3.7-3.7v-2H9l-3.7 3.7-1.4-1.4L6.2 13H2v-2h4.2L3.9 8.7l1.4-1.4L9 11h2V9L7.3 5.3l1.4-1.4L11 6.2z' }, chevronRight: { d: 'M8.6 5 7.2 6.4 12.8 12l-5.6 5.6L8.6 19l7-7z' }, diff --git a/public/js/ui/matchChrome.js b/public/js/ui/matchChrome.js index 6a9921ab..27cb6bf6 100644 --- a/public/js/ui/matchChrome.js +++ b/public/js/ui/matchChrome.js @@ -12,6 +12,7 @@ import { net } from '../net.js'; import { store, useStore, shallowEqual, emptyMatch, createStore, isSpectating } from '../store.js'; import { GIcon } from './gameComponents.js'; import { GuideButton } from './guide.js'; +import { recordQuit } from './stats.js'; import { t, tParts, N_ } from '../../../shared/i18n.js'; /** @@ -37,18 +38,27 @@ export const awayEnds = (s, prev) => (!!prev?.match?.public && !s?.match?.public store.subscribe((s, prev) => { if (awayStore.get().away && awayEnds(s, prev)) awayStore.set({ away: false }); }); /** - * Leave the match for good (g.leave → room.leave), then drop local room/match state. + * Leave the match for good (g.leave → room.leave), then drop local room/match state. The server sends a leaver no + * settlement, so the page records the match itself before it is cleared (本机统计, ui/stats.js recordQuit: a 中途退出 + * entry of the history; it counts only when a round had been cleared) — once the leave went through. * @returns {Promise} */ export async function quitMatch() { + const before = store.get(); + let left = false; try { try { await net.request('g.leave', {}); } catch (err) { if (err?.code !== 'NOT_IN_ROOM' && err?.code !== 'WRONG_PHASE' && err?.code !== 'OFFLINE') throw err; } try { await net.request('room.leave', {}); } catch (err) { if (err?.code !== 'NOT_IN_ROOM' && err?.code !== 'OFFLINE') throw err; } + left = true; } catch (err) { toastError(err); } finally { + // (a settlement that arrived while the leave was in flight is the match's record already) + if (left && !store.get().match.result) { + try { recordQuit(before); } catch (err) { console.warn('[stats] quit record failed', err); } + } store.set({ room: null, match: emptyMatch() }); } } diff --git a/public/js/ui/stats.js b/public/js/ui/stats.js new file mode 100644 index 00000000..6d6651f9 --- /dev/null +++ b/public/js/ui/stats.js @@ -0,0 +1,744 @@ +// Local match statistics: every match the local player took part in is appended as one record to localStorage +// (`sp.pref.stats`). Per-browser only — the server keeps matches in memory and has no identity, so there is nowhere +// else for cross-match numbers to live; nothing here is ever sent anywhere. The stats page labels itself 本机数据 and +// offers JSON export / import for moving between devices. (Ported from PR #323 by @2321Robin, reworked for 0.2.2.) +// +// Two kinds of record (`end`): +// 'settled' the match reached its settlement: m.result arrived (server/match/results.js buildResult). The record +// keeps what the settlement offers — the match frame (difficulty, mode, boss, seed, duration, hidden-core +// outcome, reason) and one row per player (band, title, lineup, bonds, the stat block) — so the page can +// re-view the settlement screen (recordToResult). +// 'quit' the player gave up (放弃模拟) before the settlement; the server sends a leaver nothing, so the record is +// built from what the client knew at that moment (buildQuitRecord): the frame, the player's own row, the +// rounds cleared. It is listed in the history, marked 中途退出, and cannot be re-viewed. +// +// What counts (countsTowardStats, the owner's decision of 2026-10-08: a match entered and left right away must not +// count): every aggregate — games, wins, win rate, hidden core, best round, time played, the strategy table, titles +// and the combat totals — is taken over the records that count. A settled record always counts. A quit record counts +// once at least one of the player's own battles had finished — a round cleared (the server's rule: leaving while +// round k runs has passed k − 1 rounds, leaving in its settlement k) or already eliminated. A match left earlier is +// history only. +// +// Bounded storage: at most MAX_RECORDS matches and MAX_CHARS characters of JSON. Only the newest FULL_KEEP records +// keep their full rows (lineups, bonds, teammates' names — what the settlement replay needs); older ones are compacted +// to the player's own summary row, which is all the aggregates read. The oldest records go first when a budget is hit, +// and a write the browser refuses shrinks the list further instead of failing. Teammates' display names are part of +// the newest records and of an export file: they stay on this device unless the player exports them. +// +// Format evolution: the envelope carries a version (`STATS_VERSION`); `migrateStats` walks records through a chain of +// per-version steps and every loaded / imported record passes `normalizeRecord`, a strict schema: missing fields get +// defaults, unknown fields and oversized values are dropped, a row it cannot salvage is dropped. An envelope from a +// NEWER version than this build is refused (never downgraded and written back); an unreadable one is set aside +// (`sp.pref.stats.damaged`) and the history starts again. +// +// Pure logic, no Preact / DOM: Node-testable (test/ui/stats.test.js); localStorage is touched only by loadStats / +// saveStats / their helpers. + +import { PHASE } from '../../../shared/constants.js'; + +/** Current record-envelope version (bump + add a MIGRATIONS step when the record shape changes). */ +export const STATS_VERSION = 1; +/** localStorage key under the app's `sp.pref.` prefix (store.js loadPref). */ +export const STATS_PREF_KEY = 'stats'; +/** Oldest records are dropped beyond this many matches. */ +export const MAX_RECORDS = 1000; +/** The newest records that keep their full rows (lineups, bonds, teammates) — what the settlement replay reads. */ +export const FULL_KEEP = 30; +/** Budget of the stored JSON in characters (a character costs up to 2 bytes of the browser's ~5 MB quota): the oldest records go first. */ +export const MAX_CHARS = 800_000; +/** Largest export file the page reads. */ +export const IMPORT_MAX_CHARS = 8_000_000; + +const FULL_KEY = `sp.pref.${STATS_PREF_KEY}`; +const DAMAGED_KEY = `${FULL_KEY}.damaged`; + +/** @returns {{ v: number, records: Array }} a fresh empty envelope */ +export const emptyStats = () => ({ v: STATS_VERSION, records: [] }); + +const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v); +const int = (v, d) => (Number.isFinite(v) ? Math.round(v) : d); +const num = (v) => (Number.isFinite(v) ? v : null); +const bool = (v, d = false) => (typeof v === 'boolean' ? v : d); +/** A non-empty string, cut to `max` characters. */ +const str = (v, max = 64) => (typeof v === 'string' && v.length ? v.slice(0, max) : null); + +// per-record bounds (an imported file is foreign data: nothing a row holds may grow without limit) +const MAX_PLAYERS = 6; // the game seats 4 +const MAX_LINEUP = 12; +const MAX_ITEMS = 4; +const MAX_BONDS = 24; +const MAX_STAT_KEYS = 24; +const MAX_NAME = 24; + +/** + * Copy only the finite numeric keys of a stats block (the settlement's numbers; a numeric field this build does not + * know is kept too, up to MAX_STAT_KEYS — display can lag, data should not). + * @param {any} raw + * @returns {Record} + */ +function normalizeStatBlock(raw) { + const out = {}; + if (!isObj(raw)) return out; + let n = 0; + for (const [k, v] of Object.entries(raw)) { + if (!Number.isFinite(v) || k.length > 32) continue; + out[k] = v; + if (++n >= MAX_STAT_KEYS) break; + } + return out; +} + +/** + * FNV-1a 32-bit, hex — a content hash needs no crypto, only stability across sessions. + * @param {string} s + * @returns {string} + */ +function fnv1a(s) { + let h = 0x811c9dc5; + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0; + } + return h.toString(16).padStart(8, '0'); +} + +/** + * The record's dedupe id, from match facts the server replays byte-identically on reconnect / reload + * (server/lobby.js result replay): seed + duration + mode + rounds + outcome + who I was. Two distinct + * matches colliding on all of these is not a real scenario; a replayed m.result hits the same id and is + * dropped, which is the point (recording happens on every m.result arrival, replays included). + * @param {any} res raw m.result payload + * @param {string|null|undefined} myId the local player's id at that moment + * @returns {string} + */ +export function recordId(res, myId) { + const r = isObj(res) ? res : {}; + return `r1.${fnv1a([r.seed ?? '-', r.durationMs ?? '-', r.modeId ?? '-', r.roundsPassed ?? '-', r.victory ? 1 : 0, myId ?? '-'].join('|'))}`; +} + +/** + * Normalize ONE player row: known fields defaulted and bounded, unknown fields dropped. `quit`: the record is a quit + * record, whose row may not know its rounds (`roundsPassed: null`). + * @param {any} raw + * @param {boolean} [quit] + * @returns {any} + */ +function normalizePlayerRow(raw, quit = false) { + const p = isObj(raw) ? raw : {}; + // the page and the replay read the title record from the game data by id: the sent texts are not kept + const title = isObj(p.title) && str(p.title.id) ? { id: str(p.title.id) } : null; + const lineup = (Array.isArray(p.lineup) ? p.lineup : []).filter(isObj).slice(0, MAX_LINEUP).map((u) => { + // ids only — the tile position (row/col) is replay detail, not a statistic; items kept (配发装备统计); a 自选 + // pick and a 补位 stand-in kept too, or the replayed card would draw the plain operator + const e = { + id: str(u.id) || '', golden: bool(u.golden), tier: int(u.tier, 0), + items: (Array.isArray(u.items) ? u.items : []).filter((i) => typeof i === 'string' && i.length).slice(0, MAX_ITEMS).map((i) => i.slice(0, 64)), + }; + if (u.kind === 'token') e.kind = 'token'; + if (isObj(u.diy) && str(u.diy.charId)) { + e.diy = { charId: str(u.diy.charId), skillIndex: Number.isInteger(u.diy.skillIndex) ? u.diy.skillIndex : 0, uniEquipId: str(u.diy.uniEquipId) }; + } + if (str(u.standInFor)) e.standInFor = str(u.standInFor); + return e; + }).filter((u) => u.id); + const bonds = (Array.isArray(p.bonds) ? p.bonds : []).filter(isObj).slice(0, MAX_BONDS).map((b) => ({ + bondId: str(b.bondId) || str(b.id) || '', layers: int(b.layers, 0), active: bool(b.active), + })).filter((b) => b.bondId); + return { + playerId: str(p.playerId) || '', + seat: int(p.seat, 0), + name: str(p.name, MAX_NAME) || '', + isBot: bool(p.isBot), + left: bool(p.left), + alive: bool(p.alive, true), + victory: bool(p.victory), // server semantics: team won AND this player was still in at the end + roundsPassed: quit ? num(p.roundsPassed) : int(p.roundsPassed, 0), + eliminatedRound: num(p.eliminatedRound), + lp: num(p.lp), + bandId: str(p.bandId), + title, + trophies: int(p.trophies, 0), + reward: int(p.reward, 0), + lineup, + bonds, + stats: normalizeStatBlock(p.stats), + }; +} + +/** + * Normalize ONE match record to the current shape (a strict schema: missing fields get defaults, unknown ones are + * dropped, every string / list is bounded). A record without an `end` is a settled one — the PR #323 build, which + * never recorded anything else, wrote none. + * @param {any} raw + * @returns {any|null} null when the row is not salvageable (no usable player row at all) + */ +export function normalizeRecord(raw) { + const r = isObj(raw) ? raw : {}; + // a record IS a played match — no usable players array, no record + if (!Array.isArray(r.players)) return null; + const quit = r.end === 'quit'; + const players = r.players.filter(isObj).slice(0, MAX_PLAYERS).map((p) => normalizePlayerRow(p, quit)); + if (!players.length) return null; + const rec = { + id: str(r.id), + v: STATS_VERSION, + t: int(r.t, 0), + end: quit ? 'quit' : 'settled', + victory: bool(r.victory), + roundsPassed: quit ? num(r.roundsPassed) : int(r.roundsPassed, 0), + lastRound: num(r.lastRound), + hiddenReached: bool(r.hiddenReached), + hiddenCleared: bool(r.hiddenCleared), + reason: str(r.reason, 32), + modeId: str(r.modeId), + difficulty: str(r.difficulty, 24), + stageId: str(r.stageId), + bossId: str(r.bossId), + hiddenBossId: str(r.hiddenBossId), + seed: num(r.seed), + durationMs: num(r.durationMs), + teamLp: num(r.teamLp), + roomMode: r.roomMode === 'solo' || r.roomMode === 'coop' ? r.roomMode : null, + selfId: str(r.selfId), + players, + }; + if (r.compact === true) rec.compact = true; + // an id-less (hand-made) record gets a content id, so both copies of it land on the same key + if (!rec.id) rec.id = `c.${fnv1a(JSON.stringify(rec))}`; + return rec; +} + +/** + * The MIGRATIONS chain: `MIGRATIONS[v]` upgrades a v-envelope to v+1, for v = STATS_VERSION and down. + * Empty at v1 — the steps exist so the next format change lands as one function here and every stored / + * imported envelope walks the whole chain. + * @type {Record any>} + */ +export const MIGRATIONS = {}; + +/** Newest first (the stored order): by time, then id. */ +const newestFirst = (a, b) => (b.t - a.t) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); + +/** + * Bring any stored / imported envelope to the current version. + * @param {any} raw + * @returns {{ stats: { v: number, records: any[] }, changed: boolean, newer: boolean, dropped: number }} + * `newer` = the data was written by a NEWER build: returned untouched, callers must not save over it. + * `dropped` = rows that were not salvageable, repeated a record or went beyond MAX_RECORDS: gone from `stats`. + */ +export function migrateStats(raw) { + if (!isObj(raw) || !Array.isArray(raw.records)) return { stats: emptyStats(), changed: false, newer: false, dropped: 0 }; + if ((raw.v ?? 0) > STATS_VERSION) { + return { stats: { v: raw.v, records: raw.records }, changed: false, newer: true, dropped: 0 }; + } + let v = Number.isFinite(raw.v) ? raw.v : 0; + let records = raw.records; + let changed = v !== STATS_VERSION; + while (v < STATS_VERSION) { + const step = MIGRATIONS[v]; + if (typeof step === 'function') records = step({ v, records }).records; + v++; + } + // a hand-edited / merged list can be oversized, unsorted or repeat a record: only the newest MAX_RECORDS survive, newest first + const normalized = []; + const seen = new Set(); // a record listed twice (hand-merged data) counts once: the first copy + for (const r of records) { + const rec = normalizeRecord(r); + if (rec && !seen.has(rec.id)) { seen.add(rec.id); normalized.push(rec); } + } + normalized.sort(newestFirst); + const kept = normalized.slice(0, MAX_RECORDS); + const dropped = records.length - kept.length; + // storage is rewritten (self-healed) when a row went, the order changed or an id-less row got its content id + changed ||= dropped > 0 || kept.some((rec, i) => !isObj(records[i]) || rec.id !== records[i].id); + return { stats: { v: STATS_VERSION, records: kept }, changed, newer: false, dropped }; +} + +/** Read the raw stored string (null when absent or unreadable). */ +function readRaw() { + try { return globalThis.localStorage?.getItem(FULL_KEY) ?? null; } catch { return null; } +} + +/** + * Read + migrate the persisted envelope; self-heals older shapes back to storage. An unreadable value (not JSON, or + * not an envelope) is moved to `sp.pref.stats.damaged` — kept for a manual recovery — and the history starts again. + * @returns {{ v: number, records: any[], newer: boolean, dropped: number, damaged: boolean }} + */ +export function loadStats() { + const raw = readRaw(); + if (raw == null) return { ...emptyStats(), newer: false, dropped: 0, damaged: false }; + let parsed; + try { parsed = JSON.parse(raw); } catch { parsed = undefined; } + if (!isObj(parsed) || !Array.isArray(parsed.records)) { + // keep the bad value where a person can find it; if even that write fails the next save simply replaces it + try { globalThis.localStorage?.setItem(DAMAGED_KEY, raw); globalThis.localStorage?.removeItem(FULL_KEY); } catch { /* keep it in place */ } + return { ...emptyStats(), newer: false, dropped: 0, damaged: true }; + } + const { stats, changed, newer, dropped } = migrateStats(parsed); + if (!newer && changed) saveStats(stats); + return { ...stats, newer, dropped, damaged: false }; +} + +// ---- compaction + the storage budget --------------------------------------------------------------------------- + +const COMPACT_FRAME = ['id', 'v', 't', 'end', 'victory', 'roundsPassed', 'lastRound', 'hiddenReached', 'hiddenCleared', 'reason', 'modeId', + 'difficulty', 'roomMode', 'durationMs', 'selfId']; + +/** + * The compact form of a record: the frame and the player's OWN row without lineup, bonds and name — everything the + * aggregates and the history list read, nothing a replay needs. Teammates are gone. Idempotent. + * @param {any} rec a normalized record + * @returns {any} + */ +export function compactRecord(rec) { + const self = selfRowOf(rec); + const out = {}; + for (const k of COMPACT_FRAME) if (rec[k] != null) out[k] = rec[k]; + out.compact = true; + out.players = self ? [{ + playerId: self.playerId, seat: self.seat, alive: self.alive, victory: self.victory, roundsPassed: self.roundsPassed, + eliminatedRound: self.eliminatedRound, bandId: self.bandId, title: self.title, left: self.left, stats: self.stats, + }] : []; + return out; +} + +/** + * What goes to storage: the newest FULL_KEEP records as they are, older ones compacted, then the oldest dropped until + * the JSON fits `maxChars` (the newest record is always kept). + * @param {any[]} records newest first + * @param {number} [maxChars] + * @returns {any[]} + */ +export function fitToBudget(records, maxChars = MAX_CHARS) { + const kept = []; + let used = 40; // the envelope itself + records.slice(0, MAX_RECORDS).forEach((r, i) => { + const rec = i < FULL_KEEP ? r : compactRecord(r); + const n = JSON.stringify(rec).length + 1; + if (kept.length && used + n > maxChars) return; + used += n; + kept.push(rec); + }); + return kept; +} + +/** + * Persist the envelope. Never overwrites an envelope of a newer build. Compacts and trims to the budget first; a write + * the browser refuses (quota — other keys share it) is retried with half the history, down to a handful of records. + * @param {{ v: number, records: any[], newer?: boolean }} stats + * @returns {boolean} whether a write stuck + */ +export function saveStats(stats) { + if (stats.newer) return false; + let recs = fitToBudget(stats.records); + for (;;) { + try { + const ls = globalThis.localStorage; + if (!ls) return false; // no storage at all (disabled by the browser) + ls.setItem(FULL_KEY, JSON.stringify({ v: STATS_VERSION, records: recs })); + return true; + } catch { /* quota or storage disabled — fall through to shrinking */ } + if (recs.length <= 8) return false; // a small history that still does not fit is foreign quota pressure + recs = recs.slice(0, Math.max(8, Math.ceil(recs.length / 2))); + } +} + +/** + * Derive the room shape ('solo' | 'coop') the way constants.js modeIdFor builds modeIds. + * @param {string|null|undefined} modeId + * @param {string|null|undefined} roomMode room.state `mode` when known + * @returns {'solo'|'coop'|null} + */ +export function roomModeOf(modeId, roomMode) { + if (roomMode === 'solo' || roomMode === 'coop') return roomMode; + if (typeof modeId !== 'string') return null; + if (modeId.includes('_single_')) return 'solo'; + if (modeId.includes('_multi_')) return 'coop'; + return null; +} + +/** + * Build one settled record from a raw m.result payload (+ context). Null when there is nothing to store: payloads + * without players (the error-path settlement) or matches the local player did not take part in (spectator + * seats get every result pushed too — eliminated players, who ARE in players[], keep recording). + * @param {any} res raw m.result payload + * @param {{ myId?: string|null, roomMode?: string|null, now?: number }} ctx + * @returns {any|null} + */ +export function buildRecord(res, ctx = {}) { + const r = isObj(res) ? res : {}; + if (!Array.isArray(r.players) || !r.players.length) return null; + const myId = str(ctx.myId); + const selfRow = r.players.find((p) => isObj(p) && p.playerId === myId); + if (!selfRow) return null; // spectator / observer: not my match + return normalizeRecord({ + v: STATS_VERSION, + t: int(ctx.now, 0), + id: recordId(r, myId), + end: 'settled', + victory: bool(r.victory), + roundsPassed: int(r.roundsPassed, 0), + lastRound: num(r.lastRound), + hiddenReached: bool(r.hiddenReached), + hiddenCleared: bool(r.hiddenCleared), + reason: str(r.reason), + modeId: str(r.modeId), + difficulty: str(r.difficulty), + stageId: str(r.stageId), + bossId: str(r.bossId), + hiddenBossId: str(r.hiddenBossId), + seed: num(r.seed), + durationMs: num(r.durationMs), + teamLp: num(r.teamLp), + roomMode: roomModeOf(str(r.modeId), ctx.roomMode), + selfId: myId, + players: r.players, + }); +} + +// ---- the match left early ---------------------------------------------------------------------------------------- + +/** + * What the page remembers of the match on screen, so that giving it up can still be recorded: when the page first saw + * it, whether that was at the start (a duration is only kept then), and the last round the player was seen alive in + * (the server tells the others at the settlement, a leaver nothing). + * @returns {{ active: boolean, startedAt: number, sawStart: boolean, aliveRound: number|null }} + */ +export const createLiveMatch = () => ({ active: false, startedAt: 0, sawStart: false, aliveRound: null }); + +/** The module's own tracker (fed by installStatsRecorder, read by recordQuit). */ +export const liveMatch = createLiveMatch(); + +/** + * Feed the tracker one app state (cheap: called on every store change). + * @param {ReturnType} live + * @param {any} state the app store state + * @param {number} [now] + */ +export function observeMatch(live, state, now = Date.now()) { + const pub = state?.match?.public; + const inMatch = !!pub && !!pub.phase && pub.phase !== PHASE.LOBBY && pub.phase !== PHASE.RESULT && !state.match.result; + if (!inMatch) { live.active = false; return live; } + const round = Number(pub.round) || 0; + if (!live.active) { + live.active = true; + live.startedAt = now; + live.sawStart = round <= 1; + live.aliveRound = null; + } + const me = Array.isArray(pub.players) ? pub.players.find((p) => isObj(p) && p.playerId === state.me?.playerId) : null; + if (me && me.alive !== false) live.aliveRound = Math.max(live.aliveRound ?? 0, round); + return live; +} + +/** Start following the store (main.js). Returns the unsubscribe function. */ +export function installStatsRecorder(store) { + observeMatch(liveMatch, store.get()); + return store.subscribe((s) => observeMatch(liveMatch, s)); +} + +/** + * The rounds a player who leaves in `phase` of `round` has cleared — the server's rule for a quit (platform.js _quit: + * eliminated in round k ⇒ k − 1 passed; leaving in the settlement of round k counts k). + * @param {string} phase @param {number} round + */ +export function clearedRounds(phase, round) { + const r = Number.isFinite(round) ? round : 0; + return Math.max(0, phase === PHASE.SETTLE ? r : r - 1); +} + +/** + * Build the quit record of a match the local player is leaving (放弃模拟), from the app state and the tracker. Null when + * there is nothing of mine to record: no match on screen, its settlement already here (that one is recorded by + * recordResult), a spectator seat, or a match the page never saw. + * @param {any} state the app store state BEFORE the match is cleared + * @param {{ live?: ReturnType, now?: number }} [ctx] + * @returns {any|null} + */ +export function buildQuitRecord(state, ctx = {}) { + const live = ctx.live ?? liveMatch; + const now = int(ctx.now, Date.now()); + const pub = state?.match?.public; + const myId = str(state?.me?.playerId); + if (!pub || !myId || state.match.result || !live.active) return null; + const row = Array.isArray(pub.players) ? pub.players.find((p) => isObj(p) && p.playerId === myId) : null; + if (!row) return null; // a spectator seat is no player of the match + const alive = row.alive !== false; + const round = Number(pub.round) || 0; + // alive: the rounds cleared so far; already eliminated: the round it was seen alive in, less one (unknown when the + // page never saw it alive — a reload after the elimination) + const roundsPassed = alive ? clearedRounds(pub.phase, round) : (live.aliveRound != null ? Math.max(0, live.aliveRound - 1) : null); + return normalizeRecord({ + v: STATS_VERSION, + t: now, + id: `q.${fnv1a([myId, live.startedAt, pub.modeId ?? '-', state.room?.code ?? '-'].join('|'))}`, + end: 'quit', + victory: false, + roundsPassed, + lastRound: num(pub.lastRound), + hiddenReached: pub.phase === PHASE.HIDDEN_CORE, + hiddenCleared: false, + reason: 'quit', + modeId: str(pub.modeId), + difficulty: str(pub.difficulty), + stageId: str(pub.stageId), + bossId: str(pub.bossId), + hiddenBossId: str(pub.hiddenBossId), + seed: null, + durationMs: live.sawStart ? Math.max(0, now - live.startedAt) : null, + teamLp: num(pub.teamLp), + roomMode: roomModeOf(str(pub.modeId), state.room?.mode), + selfId: myId, + players: [{ + playerId: myId, seat: row.seat, name: row.name, isBot: false, left: true, alive, victory: false, roundsPassed, + eliminatedRound: alive ? null : live.aliveRound, lp: row.lp, bandId: row.bandId, + }], + }); +} + +/** + * The m.result-shaped payload behind a settled record — the inverse of buildRecord. The stats page's history + * rows hand this to the settlement view (screens/result.js reads it through normalizeResult): a finished match can be + * RE-VIEWED because the record kept every field the payload had. Whatever a record never stored is simply absent and + * normalizeResult defaults it, exactly like a tolerant live payload. A quit record (nothing was settled) and a + * compacted one (its rows are gone) have no settlement to show. + * @param {any} rec + * @returns {any|null} null when the row is not a usable, full, settled record + */ +export function recordToResult(rec) { + const r = normalizeRecord(rec); + if (!r || r.end === 'quit' || r.compact) return null; + const res = { + victory: r.victory, + roundsPassed: r.roundsPassed, + hiddenReached: r.hiddenReached, + hiddenCleared: r.hiddenCleared, + reason: r.reason, + modeId: r.modeId, + difficulty: r.difficulty, + bossId: r.bossId, + hiddenBossId: r.hiddenBossId, + seed: r.seed, + durationMs: r.durationMs, + teamLp: r.teamLp, + players: r.players, + }; + if (Number.isFinite(r.lastRound)) res.lastRound = r.lastRound; + return res; +} + +/** + * Append one record: replays (same content id) are dropped, newest first, capped at MAX_RECORDS. + * @param {{ v: number, records: any[] }} stats + * @param {any} record + * @returns {{ stats: { v: number, records: any[] }, added: boolean }} + */ +export function appendRecord(stats, record) { + if (!record || !record.id) return { stats, added: false }; + if (stats.records.some((r) => r.id === record.id)) return { stats, added: false }; + const records = [record, ...stats.records].slice(0, MAX_RECORDS); + return { stats: { v: STATS_VERSION, records }, added: true }; +} + +/** load → append → save of one built record (never over an envelope of a newer build). @returns {any|null} the record when stored */ +function storeRecord(rec) { + if (!rec) return null; + const stats = loadStats(); + if (stats.newer) return null; + const { stats: next, added } = appendRecord(stats, rec); + if (added && !saveStats(next)) console.warn('[stats] localStorage write failed (quota?), record not persisted'); + return added ? rec : null; +} + +/** + * Record a finished match end-to-end (load → append → save). Returns the built record, or null when + * nothing was stored (no players / not my match / replay). + * @param {any} res raw m.result payload + * @param {{ myId?: string|null, roomMode?: string|null, now?: number }} [ctx] + * @returns {any|null} + */ +export function recordResult(res, ctx = {}) { + return storeRecord(buildRecord(res, ctx)); +} + +/** + * Record the match the player is giving up (放弃模拟), before the app clears its state. Returns the record, or null. + * @param {any} state the app store state before the match is cleared + * @param {{ live?: ReturnType, now?: number }} [ctx] + * @returns {any|null} + */ +export function recordQuit(state, ctx = {}) { + const live = ctx.live ?? liveMatch; + const rec = storeRecord(buildQuitRecord(state, ctx)); + live.active = false; // one record per match + return rec; +} + +/** + * Merge two envelopes (import into existing): union by record id, newest first, capped. + * @param {{ records: any[] }} a current (wins ties) + * @param {{ records: any[] }} b incoming + * @returns {{ v: number, records: any[] }} + */ +export function mergeStats(a, b) { + const byId = new Map(); + for (const r of [...(Array.isArray(b?.records) ? b.records : []), ...(Array.isArray(a?.records) ? a.records : [])]) { + const rec = normalizeRecord(r); + if (rec) byId.set(rec.id, rec); + } + const records = [...byId.values()].sort(newestFirst).slice(0, MAX_RECORDS); + return { v: STATS_VERSION, records }; +} + +/** + * Parse + migrate + merge an exported / pasted payload into the current data. + * @param {any} raw parsed JSON of the imported file + * @param {{ records: any[] }} current current envelope + * @returns {{ stats: { v: number, records: any[] }, added: number, skipped: number, dropped: number }} + * added = records new to this device; skipped = duplicates of records it has; dropped = rows of the file that could + * not be read + */ +export function importStats(raw, current) { + if (isObj(raw) && raw.kind != null && raw.kind !== 'local-stats') { + const err = new Error('not a stats export'); // the page shows its own text + err.code = 'stats-bad-file'; + throw err; + } + if (!isObj(raw) || !Array.isArray(raw.records)) { + const err = new Error('not a stats export'); + err.code = 'stats-bad-file'; + throw err; + } + const { stats: incoming, newer, dropped } = migrateStats(raw); + if (newer) { + const err = new Error('exported by a newer client'); // the page shows its own text + err.code = 'stats-newer-version'; + throw err; + } + const have = new Set((Array.isArray(current?.records) ? current.records : []).map((r) => r.id)); + const merged = mergeStats(current, incoming); + const added = incoming.records.filter((r) => !have.has(r.id)).length; + return { stats: merged, added, skipped: incoming.records.length - added, dropped }; +} + +/** + * The payload the export button downloads (envelope + a little provenance). + * @param {{ records: any[] }} stats + * @returns {{ app: string, kind: string, v: number, exportedAt: string, records: any[] }} + */ +export function exportStats(stats) { + return { + app: 'stronghold-protocol', + kind: 'local-stats', + v: STATS_VERSION, + exportedAt: new Date().toISOString(), + records: fitToBudget(Array.isArray(stats?.records) ? stats.records : []), + }; +} + +// ---- aggregation (what the page shows; records may hold more than any view uses) ------------------------------------ + +const SELF_STATS = ['dmgDealt', 'kills', 'bossDamage', 'activatedLayers', 'merges', 'itemsEquipped', 'gold', 'perfectRounds', 'refreshes', 'leaks', 'lpLost']; + +/** + * The row that "is me" in a record: selfId, else the only human, else seat 0 — records written by + * recordResult always have selfId; the fallbacks only serve imported / hand-made data. + * @param {any} rec + * @returns {any|null} + */ +export function selfRowOf(rec) { + const ps = Array.isArray(rec?.players) ? rec.players : []; + return ps.find((p) => p.playerId && p.playerId === rec.selfId) + || ps.find((p) => !p.isBot) + || ps[0] + || null; +} + +/** Whether this record counts as a win for its self player (per-row victory = team won AND still in). */ +const selfWon = (rec, self) => (self ? !!self.victory : !!rec.victory); + +/** + * The rounds the player passed in a record: its own row's (the table the settlement prints per player), else the + * team's; 0 when the record does not know. + * @param {any} rec + */ +export function roundsOf(rec) { + const self = selfRowOf(rec); + const v = self && Number.isFinite(self.roundsPassed) ? self.roundsPassed : rec?.roundsPassed; + return Number.isFinite(v) ? v : 0; +} + +/** + * Whether a record enters the aggregates (see the header). A settled record always does. A quit record does once the + * player had finished at least one battle: cleared a round, or was already eliminated; a match given up before that — + * entered and left right away — is history only. + * @param {any} rec a normalized record + * @returns {boolean} + */ +export function countsTowardStats(rec) { + if (!isObj(rec)) return false; + if (rec.end !== 'quit') return true; + const self = selfRowOf(rec); + if (!self) return false; + return self.alive === false || (Number.isFinite(self.roundsPassed) && self.roundsPassed >= 1); +} + +/** + * Aggregate records for the stats page — over the records that count; `total` / `excluded` say how many did not. + * Everything is keyed by ids (bandId / titleId / difficulty); the page maps them to names and icons through the game + * data. The combat totals read the settled records' stat blocks (a quit record has none). + * @param {any[]} records + * @returns {any} + */ +export function aggregateStats(records) { + const all = Array.isArray(records) ? records : []; + const rs = all.filter(countsTowardStats); + const out = { + total: all.length, count: rs.length, excluded: all.length - rs.length, wins: 0, + rounds: { total: 0, max: 0 }, + duration: { totalMs: 0 }, + hidden: { reached: 0, cleared: 0 }, + byDifficulty: {}, byMode: { solo: 0, coop: 0 }, + titles: {}, bands: {}, sums: {}, + }; + for (const rec of rs) { + const self = selfRowOf(rec); + const won = selfWon(rec, self); + if (won) out.wins++; + const rounds = roundsOf(rec); + out.rounds.total += rounds; + out.rounds.max = Math.max(out.rounds.max, rounds); + out.duration.totalMs += num(rec.durationMs) || 0; + if (rec.hiddenReached) out.hidden.reached++; + if (rec.hiddenCleared) out.hidden.cleared++; + + const d = rec.difficulty || 'UNKNOWN'; + const bd = (out.byDifficulty[d] ||= { games: 0, wins: 0, hiddenCleared: 0 }); + bd.games++; + if (won) bd.wins++; + if (rec.hiddenCleared) bd.hiddenCleared++; + + if (rec.roomMode === 'solo' || rec.roomMode === 'coop') out.byMode[rec.roomMode]++; + + const titleId = self?.title?.id; + if (titleId) { + const t = (out.titles[titleId] ||= { count: 0 }); + t.count++; + } + + const bandId = self?.bandId; + if (bandId) { + const b = (out.bands[bandId] ||= { games: 0, wins: 0 }); + b.games++; + if (won) b.wins++; + } + + if (rec.end !== 'quit' && self && isObj(self.stats)) { + for (const k of SELF_STATS) { + const v = self.stats[k]; + if (Number.isFinite(v)) out.sums[k] = (out.sums[k] || 0) + v; + } + } + } + return out; +} diff --git a/test/fixtures/stats-results.json b/test/fixtures/stats-results.json new file mode 100644 index 00000000..a298adce --- /dev/null +++ b/test/fixtures/stats-results.json @@ -0,0 +1 @@ +{"solo-normal":{"victory":false,"roundsPassed":13,"hiddenReached":false,"hiddenCleared":false,"reason":"defeat","teamLp":0,"modeId":"mode_single_normal","difficulty":"NORMAL","stageId":"act2autochess_m04","bossId":"boss_1","hiddenBossId":"boss_8","seed":101,"durationMs":291900,"players":[{"playerId":"p_0","seat":0,"name":"P0","isBot":false,"left":false,"alive":true,"victory":false,"roundsPassed":13,"eliminatedRound":null,"lp":0,"bandId":"band_sarkazb","lineup":[{"id":"chess_char_1_14_b","golden":true,"tier":1,"row":11,"col":7,"items":[]},{"id":"chess_char_3_13_b","golden":true,"tier":3,"row":11,"col":8,"items":["chess_item_3_06_e_a","chess_item_4_08_e_a"]},{"id":"chess_char_3_14_a","golden":false,"tier":3,"row":10,"col":5,"items":["chess_item_3_03_e_a","chess_item_5_02_e_a"]},{"id":"chess_char_5_14_a","golden":false,"tier":5,"row":10,"col":8,"items":["chess_item_3_01_e_a","chess_item_1_01_e_b"]},{"id":"chess_char_1_02_b","golden":true,"tier":1,"row":9,"col":6,"items":["chess_item_3_11_e_a","chess_item_2_01_e_b"]},{"id":"chess_char_1_20_b","golden":true,"tier":1,"row":9,"col":7,"items":[]},{"id":"chess_char_5_06_a","golden":false,"tier":5,"row":9,"col":8,"items":["chess_item_3_08_e_a"]},{"id":"chess_char_4_07_b","golden":true,"tier":4,"row":9,"col":9,"items":["chess_item_6_05_e_a","chess_item_3_09_e_a"]}],"bonds":[{"bondId":"indomShip","count":3,"active":true,"tier":2,"layers":30},{"bondId":"visiShip","count":2,"active":true,"tier":1,"layers":19},{"bondId":"kjeragShip","count":3,"active":true,"tier":1,"layers":12},{"bondId":"skillfulShip","count":3,"active":true,"tier":1,"layers":8},{"bondId":"suntShip","count":5,"active":true,"tier":2,"layers":0},{"bondId":"steadShip","count":1,"active":false,"tier":0,"layers":8},{"bondId":"swiftShip","count":1,"active":false,"tier":0,"layers":6},{"bondId":"preciShip","count":0,"active":false,"tier":0,"layers":2},{"bondId":"arcaneShip","count":0,"active":false,"tier":0,"layers":2}],"stats":{"dmgDealt":2724948,"kills":327,"leaks":19,"gold":133,"refreshes":14,"merges":5,"itemsEquipped":21,"bossDamage":509756,"activatedLayers":69,"lpLost":10,"perfectRounds":12},"title":{"id":"comment_2","name":"不朽盟约","picId":"comment_icon_2","text":"激活的盟约层数总和最高"},"trophies":0,"reward":320}]},"coop4-hard":{"victory":true,"roundsPassed":14,"hiddenReached":false,"hiddenCleared":false,"reason":"victory","teamLp":37,"modeId":"mode_multi_hard","difficulty":"HARD","stageId":"act2autochess_m04","bossId":"boss_2","hiddenBossId":"boss_10","seed":102,"durationMs":308166.2697753906,"players":[{"playerId":"p_0","seat":0,"name":"P0","isBot":false,"left":false,"alive":true,"victory":true,"roundsPassed":14,"eliminatedRound":null,"lp":16,"bandId":"band_quintus","lineup":[{"id":"chess_char_3_09_b","golden":true,"tier":3,"row":11,"col":8,"items":["chess_item_4_08_e_a","chess_item_4_07_e_a"]},{"id":"chess_char_3_17_a","golden":false,"tier":3,"row":10,"col":3,"items":["chess_item_4_03_e_a","chess_item_3_05_e_b"]},{"id":"chess_char_6_19_a","golden":false,"tier":6,"row":10,"col":4,"items":["chess_item_3_01_e_a","chess_item_2_04_e_a"]},{"id":"chess_char_1_10_b","golden":true,"tier":1,"row":10,"col":5,"items":[]},{"id":"chess_char_4_04_a","golden":false,"tier":4,"row":10,"col":7,"items":[]},{"id":"chess_char_6_07_a","golden":false,"tier":6,"row":10,"col":8,"items":["chess_item_4_04_e_a"]},{"id":"chess_char_2_18_a","golden":false,"tier":2,"row":9,"col":8,"items":["chess_item_1_01_e_a","chess_item_1_05_e_a"]},{"id":"chess_char_5_07_a","golden":false,"tier":5,"row":9,"col":9,"items":["chess_item_4_06_e_a","chess_item_3_03_e_a"]}],"bonds":[{"bondId":"raidShip","count":2,"active":true,"tier":1,"layers":147},{"bondId":"kazimierzShip","count":3,"active":true,"tier":1,"layers":78},{"bondId":"arcaneShip","count":2,"active":true,"tier":1,"layers":18},{"bondId":"steadShip","count":2,"active":true,"tier":1,"layers":3},{"bondId":"soloShip","count":1,"active":true,"tier":1,"layers":0},{"bondId":"suntShip","count":2,"active":true,"tier":1,"layers":0},{"bondId":"visiShip","count":1,"active":false,"tier":0,"layers":21},{"bondId":"swiftShip","count":1,"active":false,"tier":0,"layers":18},{"bondId":"kjeragShip","count":1,"active":false,"tier":0,"layers":16}],"stats":{"dmgDealt":6871190,"kills":393,"leaks":21,"gold":148,"refreshes":23,"merges":3,"itemsEquipped":33,"bossDamage":945575,"activatedLayers":246,"lpLost":10,"perfectRounds":7},"title":{"id":"comment_3","name":"坚若磐石","picId":"comment_icon_3","text":"目标生命值损失最少"},"trophies":5,"reward":425},{"playerId":"p_1","seat":1,"name":"P1","isBot":false,"left":false,"alive":true,"victory":true,"roundsPassed":14,"eliminatedRound":null,"lp":6,"bandId":"band_ducklord","lineup":[{"id":"chess_char_4_13_a","golden":false,"tier":4,"row":12,"col":5,"items":[]},{"id":"chess_char_1_02_b","golden":true,"tier":1,"row":12,"col":8,"items":["chess_item_4_06_e_b","chess_item_4_08_e_a"]},{"id":"chess_char_3_14_b","golden":true,"tier":3,"row":11,"col":8,"items":[]},{"id":"chess_char_3_13_b","golden":true,"tier":3,"row":10,"col":3,"items":["chess_item_5_07_e_a"]},{"id":"chess_char_6_03_b","golden":true,"tier":6,"row":10,"col":4,"items":["chess_item_2_01_e_a","chess_item_2_04_e_b"]},{"id":"chess_char_3_06_b","golden":true,"tier":3,"row":10,"col":5,"items":["chess_item_4_04_e_a","chess_item_3_08_e_b"]},{"id":"chess_char_4_04_b","golden":true,"tier":4,"row":10,"col":7,"items":["chess_item_3_02_e_a","chess_item_1_02_e_a"]},{"id":"chess_char_6_06_a","golden":false,"tier":6,"row":10,"col":8,"items":["chess_item_4_02_e_a"]}],"bonds":[{"bondId":"sargonShip","count":3,"active":true,"tier":1,"layers":52},{"bondId":"kjeragShip","count":3,"active":true,"tier":1,"layers":43},{"bondId":"visiShip","count":2,"active":true,"tier":1,"layers":40},{"bondId":"steadShip","count":2,"active":true,"tier":1,"layers":24},{"bondId":"skillfulShip","count":2,"active":true,"tier":1,"layers":13},{"bondId":"suntShip","count":6,"active":true,"tier":2,"layers":0},{"bondId":"preciShip","count":0,"active":false,"tier":0,"layers":2},{"bondId":"arcaneShip","count":0,"active":false,"tier":0,"layers":2}],"stats":{"dmgDealt":3293490,"kills":314,"leaks":51,"gold":154,"refreshes":26,"merges":7,"itemsEquipped":19,"bossDamage":220004,"activatedLayers":172,"lpLost":21,"perfectRounds":8},"title":{"id":"comment_4","name":"精英云集","picId":"comment_icon_4","text":"晋升精锐次数最多"},"trophies":5,"reward":425},{"playerId":"ai_0","seat":2,"name":"AI0","isBot":true,"left":false,"alive":true,"victory":true,"roundsPassed":14,"eliminatedRound":null,"lp":7,"bandId":"band_yu","lineup":[{"id":"chess_char_3_20_a","golden":false,"tier":3,"row":12,"col":4,"items":["chess_item_2_01_e_a"]},{"id":"chess_char_6_05_a","golden":false,"tier":6,"row":12,"col":5,"items":[]},{"id":"chess_char_6_12_a","golden":false,"tier":6,"row":12,"col":7,"items":["chess_item_4_07_e_a","chess_item_3_11_e_a"]},{"id":"chess_char_5_10_a","golden":false,"tier":5,"row":11,"col":3,"items":[]},{"id":"chess_char_3_11_a","golden":false,"tier":3,"row":11,"col":8,"items":["chess_item_1_05_e_b","chess_item_1_01_e_a"]},{"id":"chess_char_4_10_b","golden":true,"tier":4,"row":10,"col":3,"items":["chess_item_3_06_e_a","chess_item_3_07_e_a"]},{"id":"chess_char_1_08_b","golden":true,"tier":1,"row":10,"col":8,"items":["chess_item_4_11_e_a"]},{"id":"chess_char_5_14_a","golden":false,"tier":5,"row":9,"col":9,"items":["chess_item_5_02_e_b","chess_item_3_03_e_a"]}],"bonds":[{"bondId":"preciShip","count":3,"active":true,"tier":2,"layers":89},{"bondId":"soloShip","count":1,"active":true,"tier":1,"layers":20},{"bondId":"kjeragShip","count":3,"active":true,"tier":1,"layers":19},{"bondId":"siracusaShip","count":3,"active":true,"tier":1,"layers":16},{"bondId":"swiftShip","count":2,"active":true,"tier":1,"layers":5},{"bondId":"visiShip","count":2,"active":true,"tier":1,"layers":0},{"bondId":"emptyShip","count":2,"active":true,"tier":1,"layers":0},{"bondId":"suntShip","count":2,"active":true,"tier":1,"layers":0},{"bondId":"arcaneShip","count":1,"active":false,"tier":0,"layers":42},{"bondId":"skillfulShip","count":0,"active":false,"tier":0,"layers":22},{"bondId":"deputShip","count":1,"active":false,"tier":0,"layers":20},{"bondId":"steadShip","count":0,"active":false,"tier":0,"layers":4},{"bondId":"sargonShip","count":1,"active":false,"tier":0,"layers":2}],"stats":{"dmgDealt":4192977,"kills":324,"leaks":48,"gold":151,"refreshes":16,"merges":3,"itemsEquipped":15,"bossDamage":610492,"activatedLayers":149,"lpLost":17,"perfectRounds":5},"title":{"id":"comment_6","name":"挥金如土","picId":"comment_icon_6","text":"消耗资金最多"},"trophies":5,"reward":425},{"playerId":"ai_1","seat":3,"name":"AI1","isBot":true,"left":false,"alive":true,"victory":true,"roundsPassed":14,"eliminatedRound":null,"lp":8,"bandId":"band_vodfox","lineup":[{"id":"chess_char_5_02_a","golden":false,"tier":5,"row":12,"col":4,"items":[]},{"id":"chess_char_4_14_a","golden":false,"tier":4,"row":12,"col":5,"items":[]},{"id":"chess_char_4_20_a","golden":false,"tier":4,"row":11,"col":8,"items":["chess_item_1_01_e_b","chess_item_5_02_e_a"]},{"id":"chess_char_3_17_b","golden":true,"tier":3,"row":10,"col":3,"items":["chess_item_3_04_e_a","chess_item_3_11_e_b"]},{"id":"chess_char_4_19_a","golden":false,"tier":4,"row":10,"col":4,"items":["chess_item_3_05_e_a"]},{"id":"chess_char_3_12_a","golden":false,"tier":3,"row":10,"col":5,"items":[]},{"id":"chess_char_6_17_a","golden":false,"tier":6,"row":10,"col":8,"items":["chess_item_5_01_e_a","chess_item_4_04_e_a"]},{"id":"chess_char_1_19_b","golden":true,"tier":1,"row":9,"col":9,"items":["chess_item_4_10_e_a","chess_item_3_11_e_a"]}],"bonds":[{"bondId":"preciShip","count":3,"active":true,"tier":2,"layers":177},{"bondId":"kazimierzShip","count":6,"active":true,"tier":2,"layers":52},{"bondId":"swiftShip","count":2,"active":true,"tier":1,"layers":33},{"bondId":"raidShip","count":2,"active":true,"tier":1,"layers":0},{"bondId":"soloShip","count":1,"active":true,"tier":1,"layers":0},{"bondId":"suntShip","count":2,"active":true,"tier":1,"layers":0},{"bondId":"indomShip","count":0,"active":false,"tier":0,"layers":18},{"bondId":"kjeragShip","count":0,"active":false,"tier":0,"layers":11},{"bondId":"visiShip","count":1,"active":false,"tier":0,"layers":8},{"bondId":"steadShip","count":0,"active":false,"tier":0,"layers":6},{"bondId":"sargonShip","count":1,"active":false,"tier":0,"layers":2},{"bondId":"arcaneShip","count":0,"active":false,"tier":0,"layers":2}],"stats":{"dmgDealt":5326588,"kills":308,"leaks":34,"gold":149,"refreshes":21,"merges":2,"itemsEquipped":16,"bossDamage":1413858,"activatedLayers":262,"lpLost":11,"perfectRounds":4},"title":{"id":"comment_1","name":"卫戍之星","picId":"comment_icon_1","text":"对敌方领袖造成伤害最高(仅胜利时)"},"trophies":5,"reward":425}]},"coop4-abyss":{"victory":false,"roundsPassed":9,"hiddenReached":false,"hiddenCleared":false,"reason":"eliminated","teamLp":null,"modeId":"mode_multi_abyss","difficulty":"ABYSS","stageId":"act1autochess_m04","bossId":"boss_2","hiddenBossId":"boss_10","seed":103,"durationMs":94400,"players":[{"playerId":"p_0","seat":0,"name":"P0","isBot":false,"left":false,"alive":false,"victory":false,"roundsPassed":7,"eliminatedRound":8,"lp":0,"bandId":"band_mlyss","lineup":[],"bonds":[{"bondId":"sargonShip","count":0,"active":false,"tier":0,"layers":23},{"bondId":"steadShip","count":0,"active":false,"tier":0,"layers":12},{"bondId":"skillfulShip","count":0,"active":false,"tier":0,"layers":3}],"stats":{"dmgDealt":849856,"kills":77,"leaks":48,"gold":63,"refreshes":1,"merges":1,"itemsEquipped":6,"bossDamage":0,"activatedLayers":0,"lpLost":34,"perfectRounds":3},"title":{"id":"comment_6","name":"挥金如土","picId":"comment_icon_6","text":"消耗资金最多"},"trophies":1,"reward":149},{"playerId":"ai_0","seat":1,"name":"AI0","isBot":true,"left":false,"alive":false,"victory":false,"roundsPassed":7,"eliminatedRound":8,"lp":0,"bandId":"band_malkie","lineup":[],"bonds":[{"bondId":"preciShip","count":0,"active":false,"tier":0,"layers":19},{"bondId":"arcaneShip","count":0,"active":false,"tier":0,"layers":8},{"bondId":"kjeragShip","count":0,"active":false,"tier":0,"layers":7},{"bondId":"steadShip","count":0,"active":false,"tier":0,"layers":5},{"bondId":"sargonShip","count":0,"active":false,"tier":0,"layers":2},{"bondId":"indomShip","count":0,"active":false,"tier":0,"layers":2}],"stats":{"dmgDealt":644546,"kills":66,"leaks":59,"gold":62,"refreshes":2,"merges":2,"itemsEquipped":2,"bossDamage":0,"activatedLayers":0,"lpLost":37,"perfectRounds":3},"title":null,"trophies":1,"reward":149},{"playerId":"ai_1","seat":2,"name":"AI1","isBot":true,"left":false,"alive":false,"victory":false,"roundsPassed":9,"eliminatedRound":10,"lp":0,"bandId":"band_sarkazb","lineup":[],"bonds":[{"bondId":"steadShip","count":0,"active":false,"tier":0,"layers":59},{"bondId":"sargonShip","count":0,"active":false,"tier":0,"layers":56},{"bondId":"indomShip","count":0,"active":false,"tier":0,"layers":24},{"bondId":"deputShip","count":0,"active":false,"tier":0,"layers":10},{"bondId":"suntShip","count":0,"active":false,"tier":0,"layers":10},{"bondId":"kjeragShip","count":0,"active":false,"tier":0,"layers":8},{"bondId":"soloShip","count":0,"active":false,"tier":0,"layers":8}],"stats":{"dmgDealt":1583411,"kills":124,"leaks":60,"gold":85,"refreshes":6,"merges":4,"itemsEquipped":5,"bossDamage":0,"activatedLayers":0,"lpLost":47,"perfectRounds":5},"title":{"id":"comment_4","name":"精英云集","picId":"comment_icon_4","text":"晋升精锐次数最多"},"trophies":2,"reward":191},{"playerId":"ai_2","seat":3,"name":"AI2","isBot":true,"left":false,"alive":false,"victory":false,"roundsPassed":7,"eliminatedRound":8,"lp":0,"bandId":"band_justin","lineup":[],"bonds":[{"bondId":"steadShip","count":0,"active":false,"tier":0,"layers":12},{"bondId":"swiftShip","count":0,"active":false,"tier":0,"layers":7},{"bondId":"sargonShip","count":0,"active":false,"tier":0,"layers":6},{"bondId":"kazimierzShip","count":0,"active":false,"tier":0,"layers":4},{"bondId":"preciShip","count":0,"active":false,"tier":0,"layers":2},{"bondId":"arcaneShip","count":0,"active":false,"tier":0,"layers":2}],"stats":{"dmgDealt":757780,"kills":82,"leaks":43,"gold":63,"refreshes":2,"merges":1,"itemsEquipped":8,"bossDamage":0,"activatedLayers":0,"lpLost":32,"perfectRounds":3},"title":{"id":"comment_5","name":"万事俱备","picId":"comment_icon_5","text":"装备配发数量最多"},"trophies":1,"reward":149}]}} diff --git a/test/ui/stats.e2e.test.js b/test/ui/stats.e2e.test.js new file mode 100644 index 00000000..8cd268ea --- /dev/null +++ b/test/ui/stats.e2e.test.js @@ -0,0 +1,348 @@ +// Browser E2E of the 统计数据 page (public/js/screens/stats.js, ui/stats.js; PR #323 by @2321Robin, reworked for 0.2.2) +// against the real server, headless Chrome (puppeteer-core + system Chrome). Opt-in: SP_E2E=1 node --test test/ui/stats.e2e.test.js +// +// 1. A seeded history (records built from three REAL m.result payloads, test/fixtures/stats-results.json) on desktop +// 1920×1080 and a phone in landscape 844×390: the four tabs, the counting rule on screen (the match left in the first +// round is listed as 中途退出 / 不计入统计 and left out of the totals), the row click that re-views a settlement and +// its 返回统计, Esc, the title screen's entry; zero console errors. Screenshots: test/e2e/out/stats-*.png +// 2. The data actions: 导出 hands out a file the page itself imports again (nothing new), a corrupt file and a newer +// one are refused with a message and change nothing, 清空 asks first (the confirm dialog sits above the overlay and +// Esc closes only it), unreadable storage is set aside with a notice, a newer build's data is never overwritten. +// 3. The real flows: a solo match given up in the briefing is history only; one given up after round 1 counts (1 round +// cleared, the server's own rule); a match played to its settlement is recorded once — also after a reload (the +// lobby replays m.result). + +import { test, describe, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, writeFileSync, mkdirSync, mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { Client, sleep, startRealServer, hasChrome, OUT } from '../e2e/client.mjs'; +import { buildRecord, buildQuitRecord, createLiveMatch, observeMatch, STATS_VERSION } from '../../public/js/ui/stats.js'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const ENABLED = process.env.SP_E2E === '1' && hasChrome(); +const FIX = JSON.parse(readFileSync(path.join(ROOT, 'test/fixtures/stats-results.json'), 'utf8')); +const BANDS = Object.keys(JSON.parse(readFileSync(path.join(ROOT, 'data/bands.json'), 'utf8'))); +const NOW = Date.parse('2026-10-08T21:30:00'); +const DAY = 86400000; + +/** n settled records from the real payloads (cycling solo / 4-player co-op, difficulties, outcomes, bands) + two quit records. */ +function seed(n = 24) { + const recs = []; + const names = ['solo-normal', 'coop4-hard', 'coop4-abyss']; + for (let i = 0; i < n; i++) { + const res = JSON.parse(JSON.stringify(FIX[names[i % 3]])); + const solo = i % 3 === 0; + const diff = ['FUNNY', 'NORMAL', 'HARD', 'ABYSS'][i % 4]; + const win = i % 5 < 2; + Object.assign(res, { seed: 1000 + i, difficulty: diff, modeId: `mode_${solo ? 'single' : 'multi'}_${diff.toLowerCase()}`, victory: win, reason: win ? 'victory' : 'defeat', roundsPassed: win ? 14 : 4 + (i % 8), durationMs: (8 + (i % 13)) * 60000 }); + const me = res.players.find((p) => p.playerId === 'p_0'); + Object.assign(me, { bandId: BANDS[i % 7], victory: win, alive: win, roundsPassed: res.roundsPassed, title: i % 3 ? { id: `comment_${1 + (i % 6)}` } : null }); + recs.unshift(buildRecord(res, { myId: 'p_0', roomMode: solo ? 'solo' : 'coop', now: NOW - i * 0.6 * DAY })); + } + const state = (phase, round) => ({ + me: { playerId: 'p_0' }, room: { code: 'ABCD', mode: 'solo' }, + match: { public: { phase, round, lastRound: 14, modeId: 'mode_single_hard', difficulty: 'HARD', players: [{ playerId: 'p_0', seat: 0, name: 'Doctor', alive: true, lp: 30, bandId: BANDS[2] }] }, result: null }, + }); + const quit = (phase, round, t) => { const live = createLiveMatch(); observeMatch(live, state('INFO_CHECK', 0), t - 600000); return buildQuitRecord(state(phase, round), { live, now: t }); }; + recs.push(quit('PREP', 1, NOW - 2 * 3600e3), quit('PREP', 7, NOW - 1.3 * DAY)); + return { v: STATS_VERSION, records: recs.sort((a, b) => b.t - a.t) }; +} + +describe('统计数据 page (real server, headless Chrome)', { skip: !ENABLED && 'set SP_E2E=1 (and have Chrome) to run' }, () => { + let srv; + let puppeteer; + const clients = []; + + before(async () => { + puppeteer = (await import('puppeteer-core')).default; + srv = await startRealServer(); + mkdirSync(OUT, { recursive: true }); + }); + after(async () => { for (const c of clients) await c.close(); await srv?.stop(); }); + + /** A fresh browser on `base` with `sp.pref.stats` (a string) stored before the page loads. */ + async function open({ w = 1920, h = 1080, stored = null, entered = true, base = srv.base, lang = null } = {}) { + const c = new Client(puppeteer, base, 'stats', { prefix: 'stats', w, h }); + clients.push(c); + c.browser = await puppeteer.launch({ + executablePath: process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true, + args: ['--no-sandbox', '--mute-audio', '--force-device-scale-factor=1'], + }); + const [first] = await c.browser.pages(); + c.page = first || await c.browser.newPage(); + await c.page.setViewport({ width: w, height: h, hasTouch: w < 1000, isMobile: w < 1000 }); + c.page.on('console', (m) => { if (m.type() === 'error') c.problems.push(`console: ${m.text()}`); }); + c.page.on('pageerror', (e) => c.problems.push(`pageerror: ${e.message}`)); + await c.page.evaluateOnNewDocument((stored, entered, lang) => { + localStorage.setItem('sp.name', 'Doctor'); + if (entered) sessionStorage.setItem('sp.entered', '1'); + if (lang) localStorage.setItem('sp.pref.lang', JSON.stringify(lang)); + if (stored != null && !sessionStorage.getItem('sp.e2e.seeded')) { localStorage.setItem('sp.pref.stats', stored); sessionStorage.setItem('sp.e2e.seeded', '1'); } + }, stored, entered, lang); + await c.page.goto(`${base}/`, { waitUntil: 'domcontentloaded' }); + await c.page.waitForFunction((needOnline) => (!needOnline || globalThis.__SP__?.store.get().connection.status === 'online') && !!document.querySelector('.screen'), { timeout: 30000 }, entered); + return c; + } + const texts = (c, sel) => c.page.$$eval(sel, (els) => els.map((e) => e.innerText.replace(/\s+/g, ' ').trim())); + const stored = (c) => c.page.evaluate(() => { const r = localStorage.getItem('sp.pref.stats'); return r ? JSON.parse(r) : null; }); + const openStats = async (c, from = '.lobby-screen .topbar__right .btn') => { + await c.click(from, '统计'); + await c.page.waitForSelector('.st .st-tab', { visible: true, timeout: 15000 }); + }; + const toast = (c) => c.page.waitForFunction(() => document.querySelector('.toast')?.textContent || false, { timeout: 8000 }).then((h) => h.jsonValue()); + const noProblems = (c) => assert.deepEqual(c.problems, [], 'no console errors / failed requests'); + + test('desktop: tabs, the counting rule on screen, a settlement re-viewed, Esc, the title entry', async () => { + const env = seed(); + const c = await open({ stored: JSON.stringify(env) }); + await c.page.waitForSelector('.lobby-screen'); + await openStats(c); + // 总览: 24 settled + the quit after 6 rounds count, the first-round one does not + const cards = await texts(c, '.st-card__num'); + assert.equal(cards[0], '25', 'games'); + assert.match(await c.page.$eval('.st-rule', (e) => e.textContent), /另有 1 局未计入统计/); + assert.equal(await c.page.$$eval('.st-title', (els) => els.length), 6, 'the six 评语'); + await c.page.screenshot({ path: path.join(OUT, 'stats-overview-desktop.png') }); + // 策略 / 战斗累计 + await c.click('.st-tab[data-tab="bands"]'); + assert.ok((await c.page.$$eval('.st-table tbody tr', (r) => r.length)) >= 5, 'strategy rows'); + await c.page.screenshot({ path: path.join(OUT, 'stats-bands-desktop.png') }); + await c.click('.st-tab[data-tab="totals"]'); + assert.ok((await c.page.$$eval('.st-sum', (r) => r.length)) >= 8, 'combat totals'); + // 对局记录: every record, the left-early ones marked, the first-round one dimmed, only settled rows open + await c.click('.st-tab[data-tab="history"]'); + const rows = await texts(c, '.st-table--history tbody tr'); + assert.equal(rows.length, 26); + assert.equal(rows.filter((r) => r.includes('中途退出')).length, 2); + assert.equal(rows.filter((r) => r.includes('不计入统计')).length, 1); + assert.equal(await c.page.$$eval('.st-table--history tr.is-excluded', (r) => r.length), 1); + assert.equal(await c.page.$$eval('.st-table--history tr.is-clickable', (r) => r.length), 24); + await c.page.screenshot({ path: path.join(OUT, 'stats-history-desktop.png') }); + // a row re-views the settlement (the real result screen), 返回统计 comes back to the list, Esc closes + await c.click('.st-table--history tr.is-clickable'); + await c.page.waitForSelector('.st--replay .result', { visible: true, timeout: 20000 }); + await sleep(900); + await c.page.screenshot({ path: path.join(OUT, 'stats-replay-desktop.png') }); + assert.ok(await c.page.$('.st--replay .rcard.is-self'), 'the player\'s own card is marked 你 (the record\'s own id)'); + await c.page.keyboard.press('Escape'); + await c.page.waitForSelector('.st .st-tab', { timeout: 5000 }); + assert.ok(!(await c.exists('.st--replay')), 'Esc in the re-view goes back to the list'); + await c.page.keyboard.press('Escape'); + await c.page.waitForFunction(() => !document.querySelector('.st'), { timeout: 5000 }); + assert.ok(await c.exists('.lobby-screen')); + noProblems(c); + await c.close(); + // the title screen's entry (not entered yet: no connection needed), in English + const t = await open({ stored: JSON.stringify(env), entered: false, lang: 'en' }); + await t.click('.title-corner .btn', 'Stats'); + await t.page.waitForSelector('.st .st-tab', { visible: true, timeout: 15000 }); + assert.match(await t.page.$eval('.st-top', (e) => e.textContent), /Overview/); + await t.page.screenshot({ path: path.join(OUT, 'stats-overview-title-en.png') }); + noProblems(t); + await t.close(); + }); + + test('phone in landscape (844×390): the page and the re-view fit; no console errors', async () => { + const c = await open({ w: 844, h: 390, stored: JSON.stringify(seed()) }); + await c.page.waitForSelector('.lobby-screen'); + await openStats(c); + const fits = () => c.page.evaluate(() => { + const st = document.querySelector('.st').getBoundingClientRect(); + const top = document.querySelector('.st-top').getBoundingClientRect(); + const right = document.querySelector('.st-top__right').getBoundingClientRect(); + const tabs = document.querySelector('.st-tabs').getBoundingClientRect(); + return { w: st.width, topH: top.height, rightEdge: right.right, tabsRight: tabs.right, rightLeft: right.left, scrollW: document.documentElement.scrollWidth }; + }); + const f = await fits(); + assert.ok(f.rightEdge <= f.w + 1 && f.tabsRight <= f.rightLeft + 1, `the top bar fits: ${JSON.stringify(f)}`); + assert.ok(f.scrollW <= 845, 'no horizontal page scroll'); + await c.page.screenshot({ path: path.join(OUT, 'stats-overview-phone.png') }); + await c.click('.st-tab[data-tab="history"]'); + await c.page.screenshot({ path: path.join(OUT, 'stats-history-phone.png') }); + await c.click('.st-table--history tr.is-clickable'); + await c.page.waitForSelector('.st--replay .result', { visible: true, timeout: 20000 }); + await sleep(900); + await c.page.screenshot({ path: path.join(OUT, 'stats-replay-phone.png') }); + await c.click('.st--replay .btn--primary', '返回统计'); + await c.page.waitForSelector('.st .st-tab', { timeout: 5000 }); + noProblems(c); + }); + + test('the data actions: export → import (nothing new), a corrupt file, a newer file, 清空 with its confirm dialog', async () => { + const c = await open({ stored: JSON.stringify(seed(6)) }); + await c.page.waitForSelector('.lobby-screen'); + await openStats(c); + // 导出: capture the blob the page hands to the browser + await c.page.evaluate(() => { + HTMLAnchorElement.prototype.click = function click() { globalThis.__dl = { name: this.download, href: this.href }; }; + }); + await c.click('[data-testid="stats-export"]'); + await c.page.waitForFunction(() => !!globalThis.__dl, { timeout: 5000 }); + const exported = await c.page.evaluate(async () => { const r = await fetch(globalThis.__dl.href); return { name: globalThis.__dl.name, text: await r.text() }; }); + assert.match(exported.name, /^stronghold-stats-\d{8}-\d{4}\.json$/); + const payload = JSON.parse(exported.text); + assert.equal(payload.kind, 'local-stats'); + assert.equal(payload.records.length, 8); + const dir = mkdtempSync(path.join(tmpdir(), 'sp-stats-')); + const upload = async (name, text) => { + const file = path.join(dir, name); + writeFileSync(file, text); + const input = await c.page.$('.st input[type="file"]'); + await input.uploadFile(file); + }; + await c.page.evaluate(() => document.querySelectorAll('.toast').forEach((e) => e.remove())); + // 导入 the same file: nothing new + await upload('same.json', exported.text); + assert.match(await toast(c), /没有新记录/); + assert.equal((await stored(c)).records.length, 8); + await c.page.evaluate(() => document.querySelectorAll('.toast').forEach((e) => e.remove())); + // a corrupt file and a newer one change nothing + await upload('bad.json', '{"records": [1, 2'); + assert.match(await toast(c), /不是有效的统计导出文件/); + await c.page.evaluate(() => document.querySelectorAll('.toast').forEach((e) => e.remove())); + await upload('newer.json', JSON.stringify({ kind: 'local-stats', v: 99, records: [] })); + assert.match(await toast(c), /更新版本/); + assert.equal((await stored(c)).records.length, 8); + await c.page.evaluate(() => document.querySelectorAll('.toast').forEach((e) => e.remove())); + // 导入 a file with one new record: merged, newest first + const extra = { ...payload.records[0], id: 'r1.cafe0001', t: NOW + DAY }; + await upload('extra.json', JSON.stringify({ ...payload, records: [extra] })); + assert.match(await toast(c), /已导入 1 条记录/); + assert.equal((await stored(c)).records[0].id, 'r1.cafe0001'); + // 清空: the confirm dialog is above the overlay, Esc closes only it, the second time confirms + await c.click('[data-testid="stats-clear"]'); + await c.page.waitForSelector('.modal', { visible: true }); + assert.match(await c.page.$eval('.modal', (e) => e.textContent), /将删除本机保存的 9 条对局记录/); + await sleep(250); // the dialog's key handler is attached by its effect, a moment after it paints + await c.page.keyboard.press('Escape'); + await c.page.waitForFunction(() => !document.querySelector('.modal'), { timeout: 3000 }); + assert.ok(await c.exists('.st'), 'Esc closed the dialog only'); + assert.equal((await stored(c)).records.length, 9, 'nothing deleted'); + await c.click('[data-testid="stats-clear"]'); + await c.page.waitForSelector('.modal', { visible: true }); + await c.click('.modal__actions button.btn--danger'); + await c.page.waitForFunction(() => /还没有记录/.test(document.querySelector('.st-body')?.textContent || ''), { timeout: 5000 }); + assert.deepEqual((await stored(c)).records, []); + noProblems(c); + }); + + test('corrupt and newer storage: a notice, no crash; the newer build\'s data is never overwritten', async () => { + const bad = '{"v":1,"records":[{"players":['; + const c = await open({ stored: bad }); + await c.page.waitForSelector('.lobby-screen'); + await openStats(c); + assert.match(await c.page.$eval('.st-note.is-warn', (e) => e.textContent), /无法读取,已另存为备份/); + assert.equal(await c.page.evaluate(() => localStorage.getItem('sp.pref.stats.damaged')), bad, 'kept as a backup'); + noProblems(c); + await c.close(); + const newer = JSON.stringify({ v: STATS_VERSION + 3, records: [{ players: [{ playerId: 'x' }], future: true }] }); + const n = await open({ stored: newer }); + await n.page.waitForSelector('.lobby-screen'); + await openStats(n); + assert.match(await n.page.$eval('.st-body', (e) => e.textContent), /更新版本的统计数据/); + assert.ok(await n.page.$eval('[data-testid="stats-clear"]', (b) => b.disabled), 'no 清空 over data this build cannot read'); + assert.equal(await n.page.evaluate(() => localStorage.getItem('sp.pref.stats')), newer); + noProblems(n); + }); +}); + +describe('统计数据: the real flows (a fast real server, headless Chrome)', { skip: !ENABLED && 'set SP_E2E=1 (and have Chrome) to run' }, () => { + let puppeteer; + const servers = []; + before(async () => { puppeteer = (await import('puppeteer-core')).default; }); + after(async () => { for (const s of servers) await s.stop(); }); + + const stored = (c) => c.page.evaluate(() => { const r = localStorage.getItem('sp.pref.stats'); return r ? JSON.parse(r) : null; }); + async function toSoloMatch(c) { + await c.click('.mode-card', '独立模拟'); + await sleep(300); + await c.click('.diff-card', '标准模拟'); + await c.click('.create-box button', '开始独立模拟'); + await c.waitFor((s) => !!s.room, 'solo room'); + if (!(await c.st()).phase) await c.click('.room-bar__right button', '开始模拟', { timeout: 20000 }); + await c.waitFor((s) => s.phase === 'INFO_CHECK', 'briefing', 30000); + } + async function toPrep(c) { + await c.click('.brief__foot .btn--primary', '准备就绪'); + await c.waitFor((s) => s.phase === 'BAND_DRAFT', 'band draft', 30000); + await c.click('.dband', null, { nth: 1 }); + await c.click('.draft-detail__btns .btn--primary', '确认选择'); + await c.waitFor((s) => s.phase === 'PREP' && s.round === 1, 'prep round 1', 60000); + await sleep(1500); + } + async function giveUp(c) { + await c.click('.stephead .btn--danger, .gtop__exit', null, { timeout: 8000 }); + await c.click('.modal__actions button', '放弃模拟'); + await c.waitFor((s) => !s.room && !s.phase, 'back in the lobby', 15000); + } + + test('given up in the briefing: history only; given up after round 1: it counts', async () => { + const srv = await startRealServer({ fast: { timerScale: 0.25, combatSpeed: 8 } }); + servers.push(srv); + const c = new Client(puppeteer, srv.base, 'stats', { prefix: 'stats', w: 1600, h: 900 }); + try { + await c.open(); + await c.enter('Doc'); + // entered and left right away + await toSoloMatch(c); + await giveUp(c); + let env = await stored(c); + assert.equal(env.records.length, 1); + assert.equal(env.records[0].end, 'quit'); + assert.equal(env.records[0].players[0].roundsPassed, 0); + // through round 1, then given up in round 2 + await toSoloMatch(c); + await toPrep(c); + await c.click('.readybtn'); + await c.waitFor((s) => s.round >= 2 && ['PREP', 'ROUND_START', 'SP_DRAFT'].includes(s.phase), 'round 2 (round 1 cleared)', 120000); + await giveUp(c); + env = await stored(c); + assert.equal(env.records.length, 2); + assert.equal(env.records[0].end, 'quit'); + assert.equal(env.records[0].players[0].roundsPassed, 1, 'one round cleared — the server\'s own count for a quit in round 2'); + assert.ok(env.records[0].players[0].bandId, 'its strategy'); + // the page: one game counted, one left out, both in the history + await c.click('.lobby-screen .topbar__right .btn', '统计'); + await c.page.waitForSelector('.st .st-card', { visible: true }); + assert.equal((await c.page.$$eval('.st-card__num', (els) => els.map((e) => e.textContent)))[0], '1'); + assert.match(await c.page.$eval('.st-rule', (e) => e.textContent), /另有 1 局未计入统计/); + await c.click('.st-tab[data-tab="history"]'); + const rows = await c.page.$$eval('.st-table--history tbody tr', (trs) => trs.map((tr) => tr.innerText.replace(/\s+/g, ' ').trim())); + assert.equal(rows.length, 2); + assert.ok(rows[0].includes('中途退出') && !rows[0].includes('不计入统计'), rows[0]); + assert.ok(rows[1].includes('中途退出') && rows[1].includes('不计入统计'), rows[1]); + await c.shot('history-real'); + assert.deepEqual(c.problems, []); + } finally { await c.close(); } + }); + + test('played to its settlement: one record, and a reload (the lobby replays m.result) adds no second one', async () => { + const srv = await startRealServer({ fast: { timerScale: 0.25, combatSpeed: 8, finishAfter: 1 } }); + servers.push(srv); + const c = new Client(puppeteer, srv.base, 'stats', { prefix: 'stats', w: 1600, h: 900 }); + try { + await c.open(); + await c.enter('Doc'); + await toSoloMatch(c); + await toPrep(c); + await c.click('.readybtn'); + await c.waitFor((s) => s.result, 'the settlement', 120000); + await sleep(500); + let env = await stored(c); + assert.equal(env.records.length, 1); + assert.equal(env.records[0].end, 'settled'); + assert.equal(env.records[0].roomMode, 'solo'); + assert.equal(env.records[0].selfId, (await c.st()).me); + await c.page.reload({ waitUntil: 'domcontentloaded' }); + await c.page.waitForFunction(() => !!globalThis.__SP__ && !!document.querySelector('.screen'), { timeout: 30000 }); + await c.waitFor((s) => s.result, 'the replayed settlement after a reload', 30000); + await sleep(500); + env = await stored(c); + assert.equal(env.records.length, 1, 'the replay is the same record'); + assert.deepEqual(c.problems, []); + } finally { await c.close(); } + }); +}); diff --git a/test/ui/stats.test.js b/test/ui/stats.test.js new file mode 100644 index 00000000..a2369650 --- /dev/null +++ b/test/ui/stats.test.js @@ -0,0 +1,727 @@ +// Unit tests (Node) for the 本机对局统计 record store (public/js/ui/stats.js; PR #323 by @2321Robin, reworked for 0.2.2): +// record building from a raw m.result (spectator copies and player-less error results build nothing), +// replay dedupe by content id (the lobby re-pushes m.result on reconnect / reload), +// the counting rule (a match left before a round was cleared is history only — the owner's decision of 2026-10-08), +// the match left early (放弃模拟): quit records built from the page's view of the match, +// bounded storage (MAX_RECORDS, MAX_CHARS, the compacted older records, a refused write), +// corrupt / old storage (unreadable JSON, damaged rows, a pre-`end` envelope, a newer one never overwritten), +// import merge semantics (newest first) and the aggregate the stats page renders. +// localStorage is faked per test (Node has none); recordResult / recordQuit / loadStats / saveStats go through it. + +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { + STATS_VERSION, MAX_RECORDS, MAX_CHARS, FULL_KEEP, emptyStats, buildRecord, recordId, appendRecord, recordResult, recordQuit, + loadStats, saveStats, migrateStats, normalizeRecord, importStats, exportStats, aggregateStats, selfRowOf, roomModeOf, + recordToResult, compactRecord, fitToBudget, countsTowardStats, roundsOf, clearedRounds, createLiveMatch, observeMatch, + buildQuitRecord, installStatsRecorder, liveMatch, MIGRATIONS, +} from '../../public/js/ui/stats.js'; +import { createStore, emptyMatch } from '../../public/js/store.js'; +import { normalizeResult } from '../../public/js/ui/gameLogic.js'; +import { PHASE } from '../../shared/constants.js'; + +/** A realistic m.result in the shape server/match/results.js buildResult emits (replayed byte-identically). */ +function baseResult(over = {}) { + return { + t: 'm.result', + victory: true, roundsPassed: 15, hiddenReached: true, hiddenCleared: true, reason: 'hidden_cleared', + teamLp: 24, modeId: 'mode_single_hard', difficulty: 'HARD', stageId: 'stage_hard', bossId: 'enemy_boss', hiddenBossId: 'enemy_hidden', + seed: 123456789, durationMs: 952123, + players: [ + { + playerId: 'p1', seat: 0, name: '罗宾', isBot: false, left: false, alive: true, victory: true, + roundsPassed: 16, eliminatedRound: null, lp: 24, bandId: 'band_amiya', + title: { id: 'comment_1', name: '卫戍之星', picId: 'comment_icon_1', text: '对敌方领袖造成伤害最高(仅胜利时)' }, + trophies: 30, reward: 88, + lineup: [{ id: 'char_290_vigna', golden: false, tier: 2, row: 10, col: 5, items: ['item_eq_1'] }], + bonds: [{ bondId: 'steadShip', count: 3, tier: 1, layers: 12, active: true }], + stats: { dmgDealt: 15234.7, kills: 41, leaks: 2, gold: 880, refreshes: 5, merges: 6, itemsEquipped: 4, bossDamage: 5000.5, activatedLayers: 99, lpLost: 3, perfectRounds: 7 }, + }, + { + playerId: 'p2', seat: 1, name: '队友B', isBot: false, left: false, alive: false, victory: false, + roundsPassed: 9, eliminatedRound: 10, lp: 0, bandId: 'band_fang', title: null, trophies: 0, reward: 40, + lineup: [], bonds: [], stats: { kills: 3 }, + }, + ], + ...over, + }; +} + +/** Fake localStorage: Map-backed, with an optional byte budget that makes setItem throw like a full quota. */ +function fakeStorage({ budget = Infinity } = {}) { + const m = new Map(); + return { + getItem: (k) => (m.has(k) ? m.get(k) : null), + setItem(k, v) { if (String(v).length > budget) { const e = new Error('quota'); e.name = 'QuotaExceededError'; throw e; } m.set(k, String(v)); }, + removeItem: (k) => { m.delete(k); }, + get raw() { return m.get('sp.pref.stats') ?? null; }, + get damaged() { return m.get('sp.pref.stats.damaged') ?? null; }, + }; +} +/** Run `fn` with a fake localStorage installed. */ +function withStorage(opts, fn) { + if (typeof opts === 'function') { fn = opts; opts = {}; } + const ls = fakeStorage(opts); + globalThis.localStorage = ls; + try { return fn(ls); } finally { delete globalThis.localStorage; } +} +/** n settled records, newest first, t = n−1 … 0 */ +function manyRecords(n, mk = (i) => baseResult({ seed: i })) { + let stats = emptyStats(); + for (let i = 0; i < n; i++) stats = appendRecord(stats, buildRecord(mk(i), { myId: 'p1', now: i })).stats; + return stats; +} + +// ---- the match on screen, as the app store holds it --------------------------------------------------------------------- + +/** An app state with a running match: `phase` of `round`, the local player p1 (alive unless `alive: false`). */ +function liveState({ phase = PHASE.PREP, round = 1, alive = true, spectator = false, result = null, roomMode = 'solo', difficulty = 'HARD' } = {}) { + const players = spectator ? [{ playerId: 'p9', seat: 0, name: '别人', alive: true, lp: 20, bandId: 'band_x' }] + : [{ playerId: 'p1', seat: 0, name: '罗宾', alive, lp: alive ? 22 : 0, bandId: 'band_amiya' }]; + return { + me: { playerId: 'p1', name: '罗宾' }, + room: { code: 'ABCD', mode: roomMode }, + match: { + public: { phase, round, lastRound: 14, modeId: roomMode === 'solo' ? `mode_single_${difficulty.toLowerCase()}` : `mode_multi_${difficulty.toLowerCase()}`, difficulty, stageId: 'stage_a', bossId: 'boss_2', hiddenBossId: 'boss_10', players }, + private: null, field: null, result, battle: null, + }, + }; +} +/** The tracker as it would stand after watching `states` (one `now` per state). */ +function watched(states, t0 = 1_000_000) { + const live = createLiveMatch(); + states.forEach((s, i) => observeMatch(live, s, t0 + i * 1000)); + return live; +} + +describe('local stats: record building', () => { + test('builds one full record from a raw m.result (frame + players + self marking)', () => { + const rec = buildRecord(baseResult(), { myId: 'p1', roomMode: 'solo', now: 1700000000000 }); + assert.ok(rec); + assert.equal(rec.v, STATS_VERSION); + assert.equal(rec.end, 'settled'); + assert.equal(rec.t, 1700000000000); + assert.equal(rec.selfId, 'p1'); + assert.equal(rec.victory, true); + assert.equal(rec.difficulty, 'HARD'); + assert.equal(rec.seed, 123456789); + assert.equal(rec.durationMs, 952123); + assert.equal(rec.roomMode, 'solo'); + assert.equal(rec.id, recordId(baseResult(), 'p1')); + assert.equal(rec.players.length, 2); + const self = rec.players[0]; + assert.equal(self.bandId, 'band_amiya'); + assert.deepEqual(self.title, { id: 'comment_1' }, 'the title is kept by id: its texts come from the game data'); + assert.equal(self.stats.bossDamage, 5000.5); + assert.deepEqual(self.lineup, [{ id: 'char_290_vigna', golden: false, tier: 2, items: ['item_eq_1'] }]); + assert.deepEqual(self.bonds, [{ bondId: 'steadShip', layers: 12, active: true }]); + }); + + test('a 自选 pick and a 补位 stand-in survive in the lineup, or the replayed card would draw the plain operator', () => { + const res = baseResult(); + res.players[0].lineup = [ + { id: 'chess_diy_a', golden: true, tier: 5, row: 1, col: 1, items: [], diy: { charId: 'char_112_siege', skillIndex: 2, uniEquipId: 'uniequip_002_siege', extra: 'x' } }, + { id: 'chess_x', golden: false, tier: 1, items: [], standInFor: 'char_002_amiya' }, + { id: 'tok_1', kind: 'token', golden: false, tier: 0, items: [] }, + ]; + const back = buildRecord(res, { myId: 'p1', now: 1 }).players[0].lineup; + assert.deepEqual(back[0].diy, { charId: 'char_112_siege', skillIndex: 2, uniEquipId: 'uniequip_002_siege' }); + assert.equal(back[1].standInFor, 'char_002_amiya'); + assert.equal(back[2].kind, 'token'); + }); + + test('a spectator seat copy (my id not among players) records nothing; so do player-less error results', () => { + assert.equal(buildRecord(baseResult(), { myId: 'spec9', now: 1 }), null); + assert.equal(buildRecord(baseResult({ players: [] }), { myId: 'p1', now: 1 }), null); + assert.equal(buildRecord(null, { myId: 'p1' }), null); + }); + + test('roomMode falls back to the modeId (single → solo, multi → coop, else null)', () => { + assert.equal(roomModeOf('mode_multi_funny', null), 'coop'); + assert.equal(roomModeOf('mode_single_normal', 'coop'), 'coop'); // explicit room mode wins + assert.equal(roomModeOf('mode_training_1', null), null); + assert.equal(buildRecord(baseResult({ modeId: 'mode_multi_hard' }), { myId: 'p1', now: 1 }).roomMode, 'coop'); + }); +}); + +describe('local stats: replay dedupe', () => { + test('the replayed m.result (same content) appends once; a different seed is a new game', () => { + const stats = emptyStats(); + const res = baseResult(); + const first = appendRecord(stats, buildRecord(res, { myId: 'p1', now: 1000 })); + assert.equal(first.added, true); + const replay = appendRecord(first.stats, buildRecord(res, { myId: 'p1', now: 999000 })); + assert.equal(replay.added, false); // the reload / reconnect replay + assert.equal(replay.stats.records.length, 1); + assert.equal(replay.stats.records[0].t, 1000); // the FIRST arrival's timestamp is kept + const other = appendRecord(replay.stats, buildRecord(baseResult({ seed: 42, durationMs: 55555 }), { myId: 'p1', now: 2000 })); + assert.equal(other.added, true); + assert.equal(other.stats.records.length, 2); + assert.equal(other.stats.records[0].id, recordId(baseResult({ seed: 42, durationMs: 55555 }), 'p1')); + }); + + test('recordResult end-to-end over faked localStorage: replay arrives, nothing is written twice', () => { + withStorage(() => { + const res = baseResult(); + const rec = recordResult(res, { myId: 'p1', roomMode: 'solo', now: 1000 }); + assert.ok(rec); + assert.equal(recordResult(res, { myId: 'p1', roomMode: 'solo', now: 2000 }), null); // replay dropped + const loaded = loadStats(); + assert.equal(loaded.records.length, 1); + assert.equal(loaded.records[0].id, rec.id); + }); + }); +}); + +describe('local stats: the counting rule (a match entered and left right away does not count)', () => { + /** A quit record whose player left in `phase` of `round` (alive unless told otherwise). */ + const quitAt = (phase, round, o = {}) => { + const s = liveState({ phase, round, ...o }); + return buildQuitRecord(s, { live: watched([liveState({ phase: PHASE.INFO_CHECK, round: 0 }), s]), now: 5_000_000 }); + }; + + test('a settled match always counts — even one lost in the first rounds', () => { + const rec = buildRecord(baseResult({ victory: false, roundsPassed: 0, players: [{ ...baseResult().players[0], victory: false, alive: false, roundsPassed: 0 }] }), { myId: 'p1', now: 1 }); + assert.equal(rec.end, 'settled'); + assert.equal(countsTowardStats(rec), true); + }); + + test('left before the first round was cleared: history only; once a round is cleared it counts', () => { + // the server's rule (platform.js _quit): leaving while round k runs has passed k − 1 rounds, leaving in its settlement k + for (const [phase, round, passed, counts] of [ + [PHASE.INFO_CHECK, 0, 0, false], [PHASE.BAND_DRAFT, 0, 0, false], [PHASE.PREP, 1, 0, false], [PHASE.COMBAT, 1, 0, false], + [PHASE.SETTLE, 1, 1, true], [PHASE.PREP, 2, 1, true], [PHASE.COMBAT, 9, 8, true], [PHASE.FINAL_ASSAULT, 14, 13, true], + ]) { + const rec = quitAt(phase, round); + assert.equal(rec.end, 'quit', `${phase} ${round}`); + assert.equal(rec.players[0].roundsPassed, passed, `${phase} ${round}: rounds cleared`); + assert.equal(clearedRounds(phase, round), passed); + assert.equal(countsTowardStats(rec), counts, `${phase} ${round}: counts`); + } + }); + + test('left after being eliminated: it counts (the player lost it), the rounds are those it was seen alive in, less one', () => { + const s = [liveState({ phase: PHASE.INFO_CHECK, round: 0 }), liveState({ round: 4 }), liveState({ round: 5 }), liveState({ phase: PHASE.SETTLE, round: 5, alive: false }), liveState({ phase: PHASE.PREP, round: 8, alive: false })]; + const live = watched(s); + const rec = buildQuitRecord(s[4], { live, now: 9e6 }); + assert.equal(rec.players[0].alive, false); + assert.equal(rec.players[0].eliminatedRound, 5); + assert.equal(rec.players[0].roundsPassed, 4, 'eliminated in round 5 ⇒ 4 passed (the round 8 it left in is not its)'); + assert.equal(roundsOf(rec), 4); + assert.equal(countsTowardStats(rec), true); + // a page that never saw it alive (a reload after the elimination) does not know the rounds — it still counts + const unknown = buildQuitRecord(s[4], { live: watched([s[4]]), now: 9e6 }); + assert.equal(unknown.players[0].roundsPassed, null); + assert.equal(roundsOf(unknown), 0); + assert.equal(countsTowardStats(unknown), true); + }); + + test('the aggregates take only the records that count; total / excluded say what was left out', () => { + const settled = buildRecord(baseResult(), { myId: 'p1', roomMode: 'solo', now: 3000 }); + const peek = quitAt(PHASE.PREP, 1); // entered, left in the first round + const played = quitAt(PHASE.PREP, 6); // 5 rounds cleared, then gave up + const agg = aggregateStats([settled, peek, played]); + assert.equal(agg.total, 3); + assert.equal(agg.count, 2); + assert.equal(agg.excluded, 1); + assert.equal(agg.wins, 1); + assert.equal(agg.rounds.max, 16, 'the best of the player\'s own rounds'); + assert.equal(agg.rounds.total, 16 + 5, 'the peek adds nothing'); + assert.equal(agg.byDifficulty.HARD.games, 2); + assert.deepEqual(agg.bands.band_amiya, { games: 2, wins: 1 }); + assert.equal(agg.byMode.solo, 2); + }); + + test('combat totals read the settled records only (a quit record has no stat block)', () => { + const agg = aggregateStats([buildRecord(baseResult(), { myId: 'p1', now: 1 }), quitAt(PHASE.PREP, 6)]); + assert.equal(agg.sums.kills, 41); + assert.equal(agg.count, 2); + }); + + test('the history keeps every record, counted or not: the page filters nothing out of the list', () => { + const peek = quitAt(PHASE.INFO_CHECK, 0); + assert.equal(countsTowardStats(peek), false); + withStorage(() => { + let stats = emptyStats(); + stats = appendRecord(stats, peek).stats; + stats = appendRecord(stats, buildRecord(baseResult(), { myId: 'p1', now: 7e6 })).stats; + assert.equal(saveStats(stats), true); + const back = loadStats(); + assert.equal(back.records.length, 2); + assert.deepEqual(back.records.map((r) => r.end).sort(), ['quit', 'settled']); + assert.equal(back.records.find((r) => r.end === 'quit').players[0].roundsPassed, 0); + }); + }); +}); + +describe('local stats: the match left early (放弃模拟)', () => { + test('builds a quit record from the page\'s view: frame, own row, no teammates, no stats, no replay', () => { + const s = liveState({ phase: PHASE.PREP, round: 3, roomMode: 'coop', difficulty: 'ABYSS' }); + const rec = buildQuitRecord(s, { live: watched([liveState({ phase: PHASE.INFO_CHECK, round: 0, roomMode: 'coop', difficulty: 'ABYSS' }), s]), now: 2_000_000 }); + assert.equal(rec.end, 'quit'); + assert.equal(rec.reason, 'quit'); + assert.equal(rec.victory, false); + assert.equal(rec.difficulty, 'ABYSS'); + assert.equal(rec.roomMode, 'coop'); + assert.equal(rec.modeId, 'mode_multi_abyss'); + assert.equal(rec.selfId, 'p1'); + assert.equal(rec.players.length, 1); + assert.equal(rec.players[0].left, true); + assert.equal(rec.players[0].bandId, 'band_amiya'); + assert.deepEqual(rec.players[0].stats, {}); + assert.equal(rec.durationMs, 1_000_000, 'seen from the start: now − when the page first saw it'); + assert.equal(recordToResult(rec), null, 'nothing was settled: no settlement screen to show'); + assert.match(rec.id, /^q\./); + }); + + test('no record for: no match on screen, a settlement already there, a spectator seat, a match the page never saw', () => { + const s = liveState({ round: 2 }); + const live = watched([s]); + assert.equal(buildQuitRecord({ ...s, match: { ...s.match, public: null } }, { live }), null); + assert.equal(buildQuitRecord(liveState({ round: 2, result: { victory: true, players: [] } }), { live }), null); + assert.equal(buildQuitRecord(liveState({ round: 2, spectator: true }), { live: watched([liveState({ round: 2, spectator: true })]) }), null); + assert.equal(buildQuitRecord(s, { live: createLiveMatch() }), null); + }); + + test('a match first seen mid-way (a reload) keeps no duration; the tracker restarts for the next match', () => { + const s = liveState({ phase: PHASE.PREP, round: 6 }); + const live = watched([s]); + assert.equal(live.sawStart, false); + assert.equal(buildQuitRecord(s, { live, now: 9e6 }).durationMs, null); + // the match ends (result) and a new one starts: a fresh start + observeMatch(live, liveState({ phase: PHASE.RESULT, round: 14, result: { victory: true } }), 1); + assert.equal(live.active, false); + observeMatch(live, liveState({ phase: PHASE.INFO_CHECK, round: 0 }), 2); + assert.equal(live.active, true); + assert.equal(live.sawStart, true); + }); + + test('recordQuit stores it through localStorage once; the settlement of the same match is a different record', () => { + withStorage(() => { + const s = liveState({ phase: PHASE.PREP, round: 4 }); + const live = watched([liveState({ phase: PHASE.INFO_CHECK, round: 0 }), s]); + const rec = recordQuit(s, { live, now: 3e6 }); + assert.ok(rec); + assert.equal(live.active, false, 'one record per match'); + assert.equal(recordQuit(s, { live, now: 3e6 }), null); + assert.equal(loadStats().records.length, 1); + assert.equal(loadStats().records[0].players[0].roundsPassed, 3); + }); + }); +}); + +describe('local stats: following the app store', () => { + test('installStatsRecorder watches a match from its start; a quit is recorded with its duration, then the tracker rests', () => { + withStorage(() => { + const first = liveState({ phase: PHASE.INFO_CHECK, round: 0 }); + const store = createStore({ me: first.me, room: first.room, match: emptyMatch() }); + const off = installStatsRecorder(store); + try { + assert.equal(liveMatch.active, false); + store.patch('match', { public: first.match.public }); + assert.equal(liveMatch.active, true); + assert.equal(liveMatch.sawStart, true); + store.patch('match', { public: liveState({ phase: PHASE.PREP, round: 3 }).match.public }); + const rec = recordQuit(store.get()); + assert.ok(rec); + assert.equal(rec.players[0].roundsPassed, 2); + assert.ok(rec.durationMs >= 0); + assert.equal(liveMatch.active, false, 'recorded once'); + // the app clears the match: still at rest; a new match is a fresh start + store.set({ match: emptyMatch() }); + assert.equal(liveMatch.active, false); + store.patch('match', { public: first.match.public }); + assert.equal(liveMatch.active, true); + } finally { off(); } + }); + }); +}); + +describe('local stats: bounded storage', () => { + test(`the store caps at MAX_RECORDS (${MAX_RECORDS}), dropping the oldest`, () => { + const stats = manyRecords(MAX_RECORDS + 30); + assert.equal(stats.records.length, MAX_RECORDS); + assert.equal(stats.records[0].t, MAX_RECORDS + 29); // newest first + assert.equal(stats.records.at(-1).t, 30); // oldest 30 dropped + }); + + test(`only the newest ${FULL_KEEP} records keep their rows: the older ones are compacted to the player's own summary`, () => { + withStorage((ls) => { + assert.equal(saveStats(manyRecords(FULL_KEEP + 20)), true); + const stored = JSON.parse(ls.raw).records; + assert.equal(stored.length, FULL_KEEP + 20); + assert.equal(stored.slice(0, FULL_KEEP).every((r) => !r.compact && r.players.length === 2), true); + const old = stored.at(-1); + assert.equal(old.compact, true); + assert.equal(old.players.length, 1, 'no teammates'); + assert.equal(old.players[0].name, undefined, 'no names'); + assert.equal(old.players[0].lineup, undefined); + // what the aggregates read is all still there + const back = loadStats().records; + assert.deepEqual(aggregateStats(back).bands, aggregateStats(manyRecords(FULL_KEEP + 20).records).bands); + assert.equal(aggregateStats(back).sums.kills, 41 * (FULL_KEEP + 20)); + // …and the settlement of a compacted record cannot be re-viewed + assert.equal(recordToResult(back.at(-1)), null); + assert.ok(recordToResult(back[0])); + }); + }); + + test('compactRecord is idempotent and keeps the frame', () => { + const rec = buildRecord(baseResult(), { myId: 'p1', now: 5 }); + const c = compactRecord(rec); + assert.equal(JSON.stringify(compactRecord(normalizeRecord(c))), JSON.stringify(c)); + assert.equal(c.difficulty, 'HARD'); + assert.equal(c.durationMs, 952123); + assert.equal(selfRowOf(normalizeRecord(c)).bandId, 'band_amiya'); + }); + + test(`a store of ${MAX_RECORDS} real-size co-op matches fits MAX_CHARS (${MAX_CHARS}) — the oldest few go; solo matches all stay`, () => { + // a 4-player settlement with 10-unit lineups, 12 bonds and every stat, as server/match/results.js builds it + const row = (i) => ({ + playerId: `p${i}`, seat: i, name: `博士${i}`, isBot: i > 1, left: false, alive: true, victory: true, roundsPassed: 14, eliminatedRound: null, lp: 12, + bandId: `band_${i}`, title: { id: 'comment_3', name: '坚若磐石', picId: 'comment_icon_3', text: '目标生命值损失最少' }, trophies: 5, reward: 425, + lineup: Array.from({ length: 10 }, (_, k) => ({ id: `chess_char_${k}_0${i}_a`, golden: k % 2 === 0, tier: 1 + (k % 6), row: 12, col: k, items: ['chess_item_4_08_e_a', 'chess_item_4_07_e_a'] })), + bonds: Array.from({ length: 12 }, (_, k) => ({ bondId: `bond${k}Ship`, count: 3, tier: 1, layers: 100 + k, active: true })), + stats: { dmgDealt: 6871190, kills: 393, leaks: 21, gold: 148, refreshes: 23, merges: 3, itemsEquipped: 33, bossDamage: 945575, activatedLayers: 246, lpLost: 10, perfectRounds: 7 }, + }); + const coop = (i) => baseResult({ seed: i, modeId: 'mode_multi_hard', players: [row(1), row(2), row(3), row(4)].map((r, k) => (k === 0 ? { ...r, playerId: 'p1' } : r)) }); + const stats = manyRecords(MAX_RECORDS, coop); + const fit = fitToBudget(stats.records); + assert.ok(fit.length >= 900 && fit.length <= MAX_RECORDS, `kept ${fit.length}`); + assert.equal(fit[0].t, MAX_RECORDS - 1, 'the newest first'); + assert.ok(JSON.stringify({ v: 1, records: fit }).length <= MAX_CHARS); + withStorage((ls) => { assert.equal(saveStats(stats), true); assert.ok(ls.raw.length <= MAX_CHARS); }); + const solo = manyRecords(MAX_RECORDS, (i) => baseResult({ seed: i, players: [baseResult().players[0]] })); + assert.equal(fitToBudget(solo.records).length, MAX_RECORDS); + }); + + test('over the character budget the oldest records go first; the newest is always kept', () => { + const stats = manyRecords(200); + const fit = fitToBudget(stats.records, 60_000); + assert.ok(fit.length < 200 && fit.length > FULL_KEEP, `kept ${fit.length}`); + assert.equal(fit[0].t, 199); + assert.equal(fit.at(-1).t, 200 - fit.length); + assert.ok(JSON.stringify({ v: 1, records: fit }).length <= 60_000); + // a budget below one record still keeps the newest + assert.deepEqual(fitToBudget(stats.records, 10).map((r) => r.t), [199]); + }); + + test('a write the browser refuses (quota) is retried with half the history; a hopeless one reports failure instead of throwing', () => { + const probe = JSON.stringify({ v: STATS_VERSION, records: [compactRecord(buildRecord(baseResult(), { myId: 'p1', now: 1 }))] }).length; + withStorage({ budget: probe * 40 }, (ls) => { + const stats = manyRecords(300); + assert.equal(saveStats(stats), true); + const back = JSON.parse(ls.raw).records; + assert.ok(back.length < 300 && back.length >= 8, `shrank to ${back.length}`); + assert.equal(back[0].t, 299, 'the newest kept'); + }); + withStorage({ budget: 10 }, () => assert.equal(saveStats(manyRecords(20)), false)); + // no localStorage at all (a locked-down browser): quiet failure + assert.equal(saveStats(manyRecords(2)), false); + assert.deepEqual(loadStats().records, []); + }); + + test('every string and list of an (imported) record is bounded', () => { + const rec = normalizeRecord({ + players: Array.from({ length: 30 }, (_, i) => ({ + playerId: `p${i}`, name: 'N'.repeat(500), bandId: 'b'.repeat(500), + lineup: Array.from({ length: 100 }, (_, k) => ({ id: `u${k}`, items: Array(50).fill('x'.repeat(500)) })), + bonds: Array.from({ length: 100 }, (_, k) => ({ bondId: `b${k}`, layers: 1 })), + stats: Object.fromEntries(Array.from({ length: 200 }, (_, k) => [`stat${k}`, k])), + bigUnknown: 'z'.repeat(1e5), + })), + bigUnknown: 'y'.repeat(1e6), + }); + assert.ok(JSON.stringify(rec).length < 40_000, `${JSON.stringify(rec).length} chars`); + assert.equal(rec.players.length, 6); + assert.equal(rec.players[0].lineup.length, 12); + assert.equal(rec.players[0].lineup[0].items.length, 4); + assert.equal(rec.players[0].name.length, 24); + assert.equal(Object.keys(rec.players[0].stats).length, 24); + assert.equal(rec.bigUnknown, undefined); + }); +}); + +describe('local stats: corrupt and old storage', () => { + test('an unversioned PR-era envelope (no `end`) normalizes with defaults as settled records and self-heals on load', () => { + withStorage((ls) => { + const old = { records: [{ players: [{ playerId: 'p1', stats: { kills: 2 }, futureField: { x: 1 } }], futureTop: 1 }] }; + ls.setItem('sp.pref.stats', JSON.stringify(old)); + const loaded = loadStats(); + assert.equal(loaded.v, STATS_VERSION); + assert.equal(loaded.damaged, false); + assert.equal(loaded.records.length, 1); + const rec = loaded.records[0]; + assert.equal(rec.end, 'settled'); + assert.equal(countsTowardStats(rec), true); + assert.equal(rec.victory, false); + assert.equal(rec.roundsPassed, 0); + assert.equal(rec.selfId, null); + assert.equal(rec.players[0].roundsPassed, 0); + assert.equal(rec.players[0].alive, true); + assert.deepEqual(rec.players[0].stats, { kills: 2 }); + assert.equal(rec.players[0].futureField, undefined, 'a strict schema: unknown fields do not survive (a newer build bumps the version instead)'); + assert.equal(rec.futureTop, undefined); + assert.match(rec.id, /^c\./, 'an id-less row gets a content id'); + const rewritten = JSON.parse(ls.raw); + assert.equal(rewritten.v, STATS_VERSION); // self-healed back to storage + assert.equal(rewritten.records[0].id, rec.id); + }); + }); + + test('unreadable storage (not JSON, not an envelope) is set aside as a backup and the history starts again', () => { + for (const bad of ['{"v":1,"records":[', 'null', '[1,2,3]', '"hello"', '{"v":1}', '{"records":"nope"}']) { + withStorage((ls) => { + ls.setItem('sp.pref.stats', bad); + const loaded = loadStats(); + assert.equal(loaded.damaged, true, bad); + assert.deepEqual(loaded.records, [], bad); + assert.equal(ls.damaged, bad, `${bad}: kept where a person can find it`); + assert.equal(ls.raw, null); + // and recording works again straight away + assert.ok(recordResult(baseResult(), { myId: 'p1', now: 1 })); + assert.equal(loadStats().records.length, 1); + assert.equal(loadStats().damaged, false); + }); + } + }); + + test('damaged rows are dropped and counted, the good ones kept (in order, newest first); the storage is rewritten without them', () => { + withStorage((ls) => { + const good = (seed, t) => ({ ...buildRecord(baseResult({ seed }), { myId: 'p1', now: t }) }); + ls.setItem('sp.pref.stats', JSON.stringify({ + v: STATS_VERSION, + records: [good(1, 100), null, 42, 'junk', { nope: 1 }, { players: [] }, { players: [null, 3] }, good(2, 300), good(3, 200)], + })); + const loaded = loadStats(); + assert.deepEqual(loaded.records.map((r) => r.t), [300, 200, 100], 'sorted newest first'); + assert.equal(loaded.dropped, 6); + assert.equal(JSON.parse(ls.raw).records.length, 3, 'self-healed'); + assert.equal(loadStats().dropped, 0); + }); + }); + + test('a record listed twice (hand-merged data) counts once', () => { + withStorage((ls) => { + const rec = buildRecord(baseResult(), { myId: 'p1', now: 100 }); + ls.setItem('sp.pref.stats', JSON.stringify({ v: STATS_VERSION, records: [rec, { ...rec }, rec] })); + const loaded = loadStats(); + assert.equal(loaded.records.length, 1); + assert.equal(loaded.dropped, 2); + assert.equal(aggregateStats(loaded.records).count, 1); + }); + }); + + test('numbers that are not numbers, wrong types and absurd values normalize instead of crashing the page', () => { + const rec = normalizeRecord({ + t: 'yesterday', victory: 'yes', roundsPassed: NaN, durationMs: '5', difficulty: 12, roomMode: 'both', end: 'whatever', + players: [{ playerId: 7, seat: 'x', name: {}, alive: 'no', stats: { kills: '3', gold: NaN, dmgDealt: 5, deep: { a: 1 } }, lineup: [1, null, { id: 5 }], bonds: 'many', title: 'comment_1' }], + }); + assert.equal(rec.end, 'settled'); + assert.equal(rec.t, 0); + assert.equal(rec.victory, false); + assert.equal(rec.roundsPassed, 0); + assert.equal(rec.durationMs, null); + assert.equal(rec.difficulty, null); + assert.equal(rec.roomMode, null); + const p = rec.players[0]; + assert.equal(p.playerId, ''); + assert.equal(p.alive, true); + assert.deepEqual(p.stats, { dmgDealt: 5 }); + assert.deepEqual(p.lineup, []); + assert.deepEqual(p.bonds, []); + assert.equal(p.title, null); + // and the whole page reads it + assert.doesNotThrow(() => aggregateStats([rec])); + assert.doesNotThrow(() => recordToResult(rec)); + }); + + test('a NEWER envelope is returned untouched and flagged — nothing records over it', () => { + withStorage((ls) => { + const newer = JSON.stringify({ v: STATS_VERSION + 5, records: [{ players: [], brandNew: true }] }); + ls.setItem('sp.pref.stats', newer); + const loaded = loadStats(); + assert.equal(loaded.newer, true); + assert.equal(ls.raw, newer); + assert.equal(recordResult(baseResult(), { myId: 'p1', now: 1 }), null, 'a result is not written over a newer build\'s data'); + assert.equal(recordQuit(liveState({ round: 3 }), { live: watched([liveState({ round: 3 })]) }), null); + assert.equal(saveStats(loaded), false); + assert.equal(ls.raw, newer, 'still byte for byte'); + const mig = migrateStats(JSON.parse(newer)); + assert.equal(mig.newer, true); + assert.equal(mig.changed, false); + }); + }); + + test('a list longer than MAX_RECORDS (hand-edited, merged) is cut to the newest on load', () => { + withStorage((ls) => { + const recs = Array.from({ length: MAX_RECORDS + 50 }, (_, i) => buildRecord(baseResult({ seed: i }), { myId: 'p1', now: i })); + ls.setItem('sp.pref.stats', JSON.stringify({ v: STATS_VERSION, records: recs })); + const loaded = loadStats(); + assert.equal(loaded.records.length, MAX_RECORDS); + assert.equal(loaded.records[0].t, MAX_RECORDS + 49); + assert.equal(loaded.dropped, 50); + }); + }); + + test('the MIGRATIONS hook runs: v → v+1 steps apply in order (dry-run with a temporary step)', () => { + const original = MIGRATIONS[0]; + MIGRATIONS[0] = ({ records }) => ({ v: 1, records: records.map((r) => ({ ...r, victory: true })) }); + try { + const { stats, changed } = migrateStats({ v: 0, records: [{ players: [{ playerId: 'p1' }] }] }); + assert.equal(changed, true); + assert.equal(stats.records[0].victory, true); + assert.equal(stats.v, STATS_VERSION); + } finally { + if (original === undefined) delete MIGRATIONS[0]; else MIGRATIONS[0] = original; + } + }); +}); + +describe('local stats: export / import merge', () => { + test('export → import round-trips; merge unions by id, newest first, and counts added / skipped', () => { + withStorage(() => { + const rec = recordResult(baseResult(), { myId: 'p1', now: 1000 }); + const exported = exportStats(loadStats()); + assert.equal(exported.kind, 'local-stats'); + assert.equal(exported.records.length, 1); + assert.equal(exported.records[0].id, rec.id); + + // importing into the SAME store: everything is a duplicate + const same = importStats(exported, loadStats()); + assert.equal(same.added, 0); + assert.equal(same.skipped, 1); + assert.equal(same.stats.records.length, 1); + + // a second device's store (one shared + one newer record) merges by id + const theirs = exportStats({ records: [buildRecord(baseResult({ seed: 777 }), { myId: 'p1', now: 5000 }), rec] }); + const merged = importStats(JSON.parse(JSON.stringify(theirs)), loadStats()); + assert.equal(merged.added, 1); + assert.equal(merged.skipped, 1); + assert.equal(merged.stats.records.length, 2); + assert.equal(merged.stats.records[0].t, 5000, 'newest first: the history list shows the latest matches at the top'); + saveStats(merged.stats); + assert.deepEqual(loadStats().records.map((r) => r.t), [5000, 1000]); + // a match recorded after the import goes on top, and the cap would drop the oldest, not the newest + recordResult(baseResult({ seed: 5 }), { myId: 'p1', now: 9000 }); + assert.deepEqual(loadStats().records.map((r) => r.t), [9000, 5000, 1000]); + }); + }); + + test('an import over the cap keeps the newest MAX_RECORDS', () => { + const a = manyRecords(MAX_RECORDS); + const b = { v: 1, kind: 'local-stats', records: Array.from({ length: 40 }, (_, i) => buildRecord(baseResult({ seed: 5000 + i }), { myId: 'p1', now: 10_000 + i })) }; + const out = importStats(JSON.parse(JSON.stringify(b)), a); + assert.equal(out.added, 40); + assert.equal(out.stats.records.length, MAX_RECORDS); + assert.equal(out.stats.records[0].t, 10_039); + }); + + test('importing a NEWER export, another tool\'s file or junk is refused with a code, nothing is merged', () => { + assert.throws(() => importStats({ v: STATS_VERSION + 1, records: [] }, emptyStats()), (e) => e.code === 'stats-newer-version'); + assert.throws(() => importStats({ kind: 'stronghold.loadout', v: 1, records: [] }, emptyStats()), (e) => e.code === 'stats-bad-file'); + for (const junk of [{ hello: 'world' }, [], 'text', 42, null]) { + assert.throws(() => importStats(junk, emptyStats()), (e) => e.code === 'stats-bad-file', JSON.stringify(junk)); + } + }); + + test('rows of an import that cannot be read are dropped and reported; the rest merge', () => { + const out = importStats({ kind: 'local-stats', v: 1, records: [buildRecord(baseResult(), { myId: 'p1', now: 1 }), null, { players: [] }, 'x'] }, emptyStats()); + assert.equal(out.added, 1); + assert.equal(out.dropped, 3); + assert.equal(out.stats.records.length, 1); + }); +}); + +describe('local stats: aggregation (what the page renders)', () => { + const records = [ + buildRecord(baseResult(), { myId: 'p1', roomMode: 'solo', now: 1000 }), + buildRecord(baseResult({ victory: false, roundsPassed: 8, hiddenReached: false, hiddenCleared: false, difficulty: 'NORMAL', modeId: 'mode_multi_normal', durationMs: 300000, seed: 2, + players: [ + { ...baseResult().players[0], alive: true, victory: false, roundsPassed: 8, title: null, stats: { kills: 10, gold: 200 } }, + baseResult().players[1], + ] }), { myId: 'p1', roomMode: 'coop', now: 2000 }), + ]; + const agg = aggregateStats(records); + + test('totals, wins (per-row victory), rounds and duration', () => { + assert.equal(agg.count, 2); + assert.equal(agg.total, 2); + assert.equal(agg.excluded, 0); + assert.equal(agg.wins, 1); // game 2 was a loss + assert.equal(agg.rounds.max, 16, 'the player\'s own rounds (the settlement prints them per player)'); + assert.equal(agg.rounds.total, 16 + 8); + assert.equal(agg.duration.totalMs, 952123 + 300000); + assert.equal(agg.hidden.reached, 1); + assert.equal(agg.hidden.cleared, 1); + assert.equal(agg.byMode.solo, 1); + assert.equal(agg.byMode.coop, 1); + }); + + test('per-difficulty rows; an unknown difficulty is keyed UNKNOWN (never a translated text)', () => { + assert.deepEqual(agg.byDifficulty.HARD, { games: 1, wins: 1, hiddenCleared: 1 }); + assert.deepEqual(agg.byDifficulty.NORMAL, { games: 1, wins: 0, hiddenCleared: 0 }); + const odd = aggregateStats([normalizeRecord({ players: [{ playerId: 'p1' }] })]); + assert.deepEqual(Object.keys(odd.byDifficulty), ['UNKNOWN']); + }); + + test('per-band games / passed and self titles', () => { + assert.deepEqual(agg.bands.band_amiya, { games: 2, wins: 1 }); + assert.equal(agg.titles.comment_1.count, 1); // only the win granted 卫戍之星 + }); + + test('combat sums over the self player only', () => { + assert.equal(agg.sums.kills, 41 + 10); + assert.equal(agg.sums.gold, 880 + 200); + assert.equal(agg.sums.leaks, 2); // game 2's self row has no leaks → skipped, not NaN + }); + + test('selfRowOf fallbacks: selfId, else first human, else first row; anonymous record → null', () => { + assert.equal(selfRowOf(records[0]).playerId, 'p1'); + const noSelf = normalizeRecord({ players: [{ playerId: 'a', isBot: true }, { playerId: 'b', isBot: false }] }); + assert.equal(selfRowOf(noSelf).playerId, 'b'); + assert.equal(selfRowOf({ players: [] }), null); + }); + + test('an empty list aggregates to zeros', () => { + const e = aggregateStats([]); + assert.equal(e.count, 0); + assert.equal(e.rounds.max, 0); + assert.deepEqual(e.byDifficulty, {}); + assert.equal(aggregateStats(null).total, 0); + }); +}); + +describe('local stats: recordToResult (history row → settlement re-view)', () => { + test('record → m.result payload → normalizeResult renders the same settlement the live push did', () => { + const rec = buildRecord(baseResult(), { myId: 'p1', roomMode: 'solo', now: 1000 }); + const res = recordToResult(rec); + assert.ok(res); + const view = normalizeResult(res, null); + assert.equal(view.victory, true); + assert.equal(view.difficulty, 'HARD'); + assert.equal(view.modeId, 'mode_single_hard'); + assert.equal(view.roundsPassed, 15); + assert.equal(view.hiddenReached, true); + assert.equal(view.hiddenCleared, true); + assert.equal(view.durationMs, 952123); + assert.equal(view.players.length, 2); + const self = view.players.find((p) => p.playerId === 'p1'); + assert.equal(self.bandId, 'band_amiya'); + assert.equal(self.title.id, 'comment_1'); + assert.equal(self.stats.kills, 41); + assert.equal(self.stats.bossDamage, 5000.5); + assert.equal(self.lineup[0].id, 'char_290_vigna'); + assert.equal(self.lineup[0].golden, false); + const mate = view.players.find((p) => p.playerId === 'p2'); + assert.equal(mate.alive, false); + assert.equal(mate.roundsPassed, 9); + }); + + test('a null lastRound is passed through as absent (normalizeResult defaults it); garbage → null', () => { + const rec = buildRecord(baseResult({ lastRound: undefined }), { myId: 'p1', now: 1 }); + assert.equal('lastRound' in recordToResult(rec), false); + assert.equal(recordToResult(null), null); + assert.equal(recordToResult({ players: [] }), null); + }); +});