From 8276d48eb436371e24962dce27941b71f5fe244e Mon Sep 17 00:00:00 2001
From: timeance <30307526+timeance@users.noreply.github.com>
Date: Wed, 18 Nov 2026 03:30:54 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=88=98=E6=8A=A5=E9=98=85?=
=?UTF-8?q?=E8=AF=BB=E4=BD=93=E9=AA=8C=E5=B9=B6=E7=BB=9F=E4=B8=80=E8=AF=84?=
=?UTF-8?q?=E5=88=86=E4=B8=8E=E8=83=9C=E8=B4=9F=E5=8F=A3=E5=BE=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
CHANGELOG.md | 6 +
README.md | 2 +-
docs/API_NOTES.md | 6 +-
docs/THIRD_PARTY.md | 2 +-
docs/VALIDATION.md | 6 +-
main.py | 7 +-
metadata.yaml | 2 +-
models.py | 41 ++++-
render.py | 310 +++++++++++++++++++++++++-------------
scoring.py | 78 +++++-----
service.py | 136 ++++++++++-------
templates/_macros.html | 24 ++-
templates/base.html | 103 +++++++------
templates/match.html | 100 ++++++------
templates/overview.html | 18 ++-
templates/recent.html | 18 ++-
tests/test_models.py | 21 ++-
tests/test_render.py | 192 +++++++++++++++++------
tests/test_report_data.py | 22 ++-
tests/test_scoring.py | 87 +++++++++--
tests/test_service.py | 184 +++++++++++++++++++++-
tools/render_previews.py | 65 ++++++--
views/settings/index.html | 2 +-
23 files changed, 1018 insertions(+), 414 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index abfc86d..52d3fde 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# 更新日志
+## 0.1.6 · 2026-11-18
+
+- 玩家概览标出胜率来自多少场,雷达区分实际胜率与赛果超预期;少量对局直接显示胜负场数。
+- 近期战绩更容易逐场扫读,单局玩家改为分队表格。双方数据不全时不再绘制误导性的对比条。
+- 修正部分兵种资料缺失导致整份评分消失的问题。图片开关、主题和发送方式移到常用设置顶部。
+
## 0.1.5 · 2026-11-18
- 玩家概览与近期战绩图片加宽,排版更紧凑,表格数字不再拆行。
diff --git a/README.md b/README.md
index 76fdc06..68eb37c 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。以简洁排版展示玩家概览、近期战绩与单局核心数据,支持图片战报和默认账号绑定,不依赖大模型。
-用 `ba me` 查看综合评分、称号和五维雷达图。图中的「胜负预期」衡量近期战果相对赛前预期的表现;「实际胜率」是近期已知胜负对局中获胜的比例。`ba recent` 查看逐局评分,`ba last` 查看最近一局的赛前预测、双方对比和玩家数据。
+用 `ba me` 查看综合评分和五维表现。「实际胜率」是已知赛果中获胜的比例;「赛果超预期」则看对手强弱:同样十战五胜,赢下更多不被看好的对局,这项表现会更好。`ba recent` 查看逐局评分,`ba last` 对比双方队伍与玩家。
> 数据来源 [BATrace](https://dash.batrace.top/),如有帮助请支持该平台。更新内容见 [更新日志](CHANGELOG.md)。
diff --git a/docs/API_NOTES.md b/docs/API_NOTES.md
index f577282..cf3d93c 100644
--- a/docs/API_NOTES.md
+++ b/docs/API_NOTES.md
@@ -85,11 +85,11 @@ SteamID64 与 STB ID 均保持字符串;**未找到可靠的 Steam→STB 映
`scoring.py` 使用 `assets/scoring-model.json`,移植 ba-dragon 固定提交的 `computeDragonScore`。近期战绩使用逐局分,不显示称号;玩家概览接收按时间从新到旧排列的对局,先跳过无效局,再取最多 20 场,将逐局标准分从旧到新输入 Kalman 滤波器,短局权重较低。再查 `playerPct` 得到 1–10 综合分,按显示分数及 `tiers` 给出称号;它不是单局显示分的平均值。1 场有效对局也可评分,`sample_size` 保留实际场数;0 场时综合分、称号和前四维均为 `None`。
-五个雷达值均为 0–100。分值 K/D、摧毁贡献、占点贡献分别表示相对同条件玩家的表现百分位;占点不计入综合分。「胜负预期」是逐局 `phi((S-E)/outSd)` 的平均表现:`S` 采用上游模型内部的排位 ELO 涨跌,`E` 由双方赛前 ELO 和其他挂机者修正得出。前四项均按可用分项取平均后四舍五入为百分制整数。与上游缺失值回退不同,插件在缺少本人或在线队友占点时跳过该局的占点轴,缺少任何参战者所需的 ELO 或摧毁/损失价值时跳过整局。已归一化的真实零仍参与计算。
+雷达的「交换效率」「摧毁贡献」「夺点表现」分别是相对同条件玩家的表现分;夺点次数不等于守点时长,也不计入综合分。「赛果超预期」取逐局 `phi((S-E)/outSd)` 的平均值。`S` 优先用该玩家、该对局明确的 `won`;明确记录互相矛盾则跳过该局。没有明确赛果时,模型仍可用 ELO 涨跌估计 `S`,但不据此给公开战绩补写胜负。`E` 由双方赛前 ELO 和其他挂机者修正得出。兵种花费中个别缺失的观测不覆盖同一份资料中有效的观测;没有可用花费时才采用模型总体基准。
-第五维 `win_rate` 由服务层传入,仅统计近期样本中目标玩家有明确布尔 `won` 的对局。没有已知赛果时为 `None`,已知赛果全部为负时为 `0`;即使没有有效评分局,也可独立提供该轴。两种胜负指标不互相填补,评分本身不触发网络请求。
+第五维「实际胜率」仅统计近期窗口中该玩家有明确赛果的不同对局;概览胜率则使用分析记录中的不同对局。两者都排除缺少对局 ID、没有明确赛果或赛果冲突的记录。图中区分评分有效场数与胜率分母,少于 5 场已知赛果时列出胜负数,不画该轴。模型没有同版本、同 ELO 段、同窗口的原始胜率分布,实际胜率按原始百分比显示,不套用总评分的分位表。近期伤害交换比只使用同场伤害与承伤均已知的记录,以总伤害除以总承伤;不以某场 `dmr` 代替近期结果。评分本身不触发网络请求。
-`ba last` 的单局图片顶部展示基于双方赛前 ELO 的赛前预测及双队摘要;中部左侧兵种构成、右侧双方对比;底部展示队伍玩家数据。摘要区分赛前平均 ELO(`OldRating`)与赛后平均 ELO(`NewRating`)。预测是模型估算,不表示实际赛果。兵种构成按模型的单位角色与基础价格估算出动花费,缺少单位价格或记录时保留不完整说明,不冒充实际结算。
+`ba last` 的单局图片顶部展示基于双方赛前 ELO 的胜率估算及队伍摘要;中部左侧兵种构成、右侧双方对比;底部按队列出玩家。正式队伍为 A/B,观战组不参与对比。两队人数不等,或详情缺少近期列表中已知的同队玩家时,不作预测、不画比例条;名单较完整的详情仍可用于比较。仅某项统计不全时,保留该项已知数字及覆盖人数,不画该项比例条。兵种构成按模型的单位角色与基础价格估算出动价值,不等于实际结算。
所有战报图片页脚内嵌 `assets/github-mark-black.svg` 或 `assets/github-mark-white.svg`,并包含 `timeance/astrbot_plugin_BA_stats` 与固定文字「数据来源 BATracer」。设置提示仍原样保留「数据来源 BATrace ,如有帮助请支持该平台」。
diff --git a/docs/THIRD_PARTY.md b/docs/THIRD_PARTY.md
index fa9b723..56e0974 100644
--- a/docs/THIRD_PARTY.md
+++ b/docs/THIRD_PARTY.md
@@ -17,7 +17,7 @@
`scoring.py` 将固定提交中的 `src/shared/dragon/score.ts`、`roles.ts`、`model.ts` 相关逻辑移植为 Python;`assets/scoring-model.json` 从同一提交的 `src/shared/dragon/model.json` 提取评分参数,单位表仅保留角色和基础价格。模型内的 `source` 记录仓库、提交、来源文件和完整 MIT 文本。
-玩家概览使用 `computeDragonScore` 的 Kalman 聚合、玩家分位表、分档和四个表现分项;分档称号取自 `src/renderer/src/features/players/PlayerDetail.tsx`。第五项「实际胜率」由插件服务根据明确的 `won` 计算并传入评分模块。近期战绩保持逐局评分。未移植单局奖项、时间线或实力 ELO;这些模型分数不代表官方评价。
+玩家概览使用 `computeDragonScore` 的 Kalman 聚合、玩家分位表、分档和四个表现分项;分档称号取自 `src/renderer/src/features/players/PlayerDetail.tsx`。插件优先采用可核对的明确赛果计算赛果表现。第五项「实际胜率」仅使用明确的 `won`,按对局去重;没有套用上游综合评分的分位表。近期战绩保持逐局评分。未移植单局奖项、时间线或实力 ELO;这些模型分数不代表官方评价。
[BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt) 和模型的 `source.licenseText` 均原样保留固定提交的 `LICENSE`,包括 `Copyright (c) 2026 AlexanderHYu` 及 `Copyright (c) 2025-2026 Zola (Zawinzala)` 与原文件的沿用部分说明。分发这些移植代码或模型时,安装包、源码和 Gemini 文案包均应保留完整上游版权及 MIT 许可;文案润色不修改该文本。
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index 5e9190e..e4e40c3 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -1,8 +1,10 @@
# 验证记录
-验证日期:2026-11-18(Asia/Hong_Kong)。版本:v0.1.5。
+## v0.1.6 · 战绩与图片
-## 本次结果
+2026-11-18(Asia/Hong_Kong)。端到端样例覆盖明确胜负与 ELO 方向相反、重复赛果冲突、近期与分析样本分母不同、伤害数据部分缺失。浏览器检查手机聊天比例下的雷达、近期卡片、分队玩家表,以及两种主题的设置页。
+
+## v0.1.5 验证结果
| 项目 | 结果 |
| --- | --- |
diff --git a/main.py b/main.py
index 1f8dae5..21f0592 100644
--- a/main.py
+++ b/main.py
@@ -28,6 +28,9 @@
from .web_settings import SettingsError, WebSettings
+PLUGIN_VERSION = "0.1.6"
+
+
def extract_arguments(event, prefixes):
"""Rebuild Plain/At components; keep quoted nickname spacing and true IDs."""
parts, mentions = [], []
@@ -155,7 +158,7 @@ async def initialize(self):
await self.storage.open()
self._images.mkdir(parents=True, exist_ok=True)
self._prune_images()
- self.diagnostics.record("plugin_start", status="0.1.5")
+ self.diagnostics.record("plugin_start", status=PLUGIN_VERSION)
async def _run(self, awaitable, *, timed=True):
if self._closed:
@@ -309,7 +312,7 @@ async def _status(self):
"schema": "响应结构变化", "identity_mismatch": "身份校验失败",
"no_data": "暂无收录", "upstream": "上游暂不可用", "queue_full": "队列已满",
"not_configured": "接入未配置", "closed": "客户端已关闭", "daily_quota": "每日额度已用完"}
- return (f"断箭战报 v0.1.5\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n"
+ return (f"断箭战报 v{PLUGIN_VERSION}\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n"
f"今日总请求:{usage['global']}/{GLOBAL_DAILY_LIMIT}(固定上限);北京时间 0 点重置\n"
f"本次运行请求:{status['requests']};进行中:{status['inflight']}\n"
f"API 缓存:{await self.storage.cache_count()} 条;命中:{status['cache_hits']};旧缓存:{status['stale_hits']}\n"
diff --git a/metadata.yaml b/metadata.yaml
index 53f67b0..d503d4e 100644
--- a/metadata.yaml
+++ b/metadata.yaml
@@ -2,7 +2,7 @@ name: astrbot_plugin_ba_stats
display_name: 断箭战报
short_desc: "《断箭》战绩查询,支持玩家评分、五维雷达图与图片战报。"
desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,展示玩家评分、五维雷达图、逐局评分、赛前预测与双方对比,支持账号绑定、群友查询及图片或文字展示。在设置中心或原生插件配置中开启在线查询后使用。"
-version: "0.1.5"
+version: "0.1.6"
author: timeance
repo: https://github.com/timeance/astrbot_plugin_BA_stats
astrbot_version: ">=4.29.4"
diff --git a/models.py b/models.py
index ec5d713..462508a 100644
--- a/models.py
+++ b/models.py
@@ -6,6 +6,7 @@
from __future__ import annotations
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from datetime import datetime
import math
@@ -13,6 +14,9 @@
from urllib.parse import quote
Outcome = Literal["win", "loss", "unknown"]
+AnalysisOutcome = Literal["win", "loss", "conflict"]
+PROFILE_AXES = (("kd", "交换效率"), ("contrib", "摧毁贡献"), ("obj", "夺点表现"),
+ ("outcome", "赛果超预期"), ("win_rate", "实际胜率"))
Mode = Literal["ranked", "custom", "unknown"]
T = TypeVar("T")
@@ -116,6 +120,33 @@ def canonical_id(value: Any) -> str:
return result
+def analysis_outcomes(analysis: Mapping | None) -> dict[str, AnalysisOutcome]:
+ """Resolve explicit results by exact match ID; absence is distinct from conflict."""
+ outcomes: dict[str, AnalysisOutcome] = {}
+ for point in (analysis or {}).get("trend", {}).get("points", []):
+ try:
+ mid = canonical_id(point.get("matchId"))
+ except ValueError:
+ continue
+ won = point.get("won")
+ if point.get("wonConflict") is True:
+ outcomes[mid] = "conflict"
+ elif isinstance(won, bool):
+ result = "win" if won else "loss"
+ outcomes[mid] = result if outcomes.get(mid, result) == result else "conflict"
+ return outcomes
+
+
+def win_rate_sample(outcomes: Iterable[AnalysisOutcome]) -> dict:
+ wins = losses = 0
+ for outcome in outcomes:
+ wins += outcome == "win"
+ losses += outcome == "loss"
+ size = wins + losses
+ return {"value": 100 * wins / size if size else None,
+ "sample_size": size, "wins": wins, "losses": losses}
+
+
def _object(value: Any) -> dict[str, Any]:
if not isinstance(value, dict):
raise ValueError("expected an object")
@@ -207,10 +238,16 @@ def _parse_analysis(payload: Any) -> dict[str, Any]:
previous["endTime"] is None or point["endTime"] > previous["endTime"]
):
points[positions[mid]] = point
- points[positions[mid]]["won"] = next(iter(outcomes)) if len(outcomes) == 1 else None
+ for mid, outcomes in results.items():
+ point = points[positions[mid]]
+ point["won"] = next(iter(outcomes)) if len(outcomes) == 1 else None
+ if len(outcomes) > 1:
+ point["wonConflict"] = True
units = []
for raw in _array(analysis, "highlightUnits"):
row = _object(raw)
+ if row.get("unitId") is None:
+ continue
units.append({
"unitId": canonical_id(row.get("unitId")),
"unitName": _name(row.get("unitName")) or None,
@@ -224,6 +261,8 @@ def _parse_analysis(payload: Any) -> dict[str, Any]:
categories = []
for raw in _array(analysis, "categoryPreferences"):
row = _object(raw)
+ if row.get("categoryKey") is None:
+ continue
categories.append({
"categoryKey": canonical_id(row.get("categoryKey")),
"percentage": _percentage(row.get("percentage")),
diff --git a/render.py b/render.py
index 7eacd1f..56fb3fe 100644
--- a/render.py
+++ b/render.py
@@ -1,6 +1,6 @@
"""One presentation contract for HTML cards and their plain-text fallback.
-Service -> Renderer view contract (independent of models.py):
+Service -> Renderer view contract:
kind: "overview" | "recent" | "match"; title: optional display title.
player: {id: str, name: str, source_url?: str}; required for player cards.
metrics: [{label: str, value: number | str | None, unit?: str,
@@ -10,14 +10,16 @@
rows (recent): [{id, started_at, map_name, mode, outcome, duration_seconds,
elo_delta, kills, losses, destroyed_value, lost_value, unit_exchange,
value_exchange, source_url}]. Every field except id may be absent.
- match (match): {id, map_name, mode, started_at, duration_seconds, winner}.
+ match (match): {id, map_name, mode, started_at, duration_seconds, winner,
+ roster_complete?: bool}.
teams (match): [{name, outcome, players: [{id, name, elo, elo_before, elo_delta, kills,
losses, destroyed_value, lost_value, unit_exchange, value_exchange}]}].
Team sizes are unrestricted; never pad absent players with dummy rows.
common_units (overview, optional): [{name: str, count?: int}].
profile_rating (overview): {score: 1..10 | None, title, tone, sample_size,
+ win_rate_sample: {value, wins, losses, sample_size},
dimensions: [{key: kd|contrib|obj|outcome|win_rate, label, value: 0..100 | None}]}.
- The last axis is actual win rate. Missing axes never become zero points.
+ The two sample sizes are independent. Missing axes never become zero.
style_scope (overview): actual analysis sample label, e.g. 近100场风格.
scope: str describing actual sample / mode / coverage (never inferred).
fetched_at, source_updated_at: aware datetime or ISO 8601 with timezone.
@@ -56,14 +58,20 @@
from jinja2 import Environment, FileSystemLoader, select_autoescape
+if __package__:
+ from .models import PROFILE_AXES as _PROFILE_AXES
+else:
+ from models import PROFILE_AXES as _PROFILE_AXES
+
MISSING = "暂无"
_TITLES = {"overview": "玩家概览", "recent": "近期战绩", "match": "单局战报"}
_OUTCOMES = {"win": "胜利", "loss": "失利", "unknown": "胜负暂无"}
_MODES = {"ranked": "排位", "custom": "自定义", "unknown": "暂无"}
_ROLES = {"装甲": "armor", "步兵": "infantry", "侦察": "recon", "炮兵": "artillery",
"防空": "air-defense", "直升机": "helicopter", "固定翼": "aircraft", "后勤/运输": "logistics"}
-_PROFILE_AXES = (("kd", "分值 K/D"), ("contrib", "摧毁贡献"), ("obj", "占点贡献"),
- ("outcome", "胜负预期"), ("win_rate", "实际胜率"))
+_MIN_WIN_RATE_SAMPLE = 5
+_RECENT_WIN_RATE_WINDOW = 20
+_FORMAL_TEAMS = ("A 队", "B 队")
def _plain(value, default=MISSING) -> str:
@@ -84,6 +92,29 @@ def _number(value) -> Decimal | None:
return None
+def _count(value) -> int | None:
+ number = _number(value)
+ return int(number) if number is not None and number >= 0 and number == number.to_integral_value() else None
+
+
+def _win_rate(value, sample, wins) -> tuple[str, str, Decimal | None]:
+ """Keep the known-result count separate from the rating's usable matches."""
+ number = _number(value)
+ sample, wins = _count(sample), _count(wins)
+ if sample is not None and wins is not None and wins > sample:
+ return MISSING, "", None
+ if not sample:
+ return MISSING, "0 场有赛果" if sample == 0 else "", None
+ note = f"{sample} 场有赛果"
+ if sample < _MIN_WIN_RATE_SAMPLE:
+ return (f"{wins} 胜 {sample - wins} 负" if wins is not None else MISSING), note, None
+ if number is None or not 0 <= number <= 100:
+ return MISSING, note, None
+ if wins is not None:
+ note = f"{wins} 胜 {sample - wins} 负 · {note}"
+ return _numeric(number, "percent", compact=True) + "%", note, number
+
+
def _numeric(value, style="decimal", *, compact=False) -> str:
parsed = _number(value)
if parsed is None:
@@ -133,13 +164,15 @@ def _records(value) -> list[Mapping]:
return [_mapping(item) for item in value] if isinstance(value, (list, tuple)) else []
-def _outcome(value) -> dict:
+def _outcome(value, conflict=False) -> dict:
+ if conflict is True:
+ return {"key": "conflict", "label": "赛果冲突"}
key = value if isinstance(value, str) and value in _OUTCOMES else "unknown"
return {"key": key, "label": _OUTCOMES[key]}
class Renderer:
- """Render self-contained cards without network access or model imports."""
+ """Render self-contained cards without network access."""
WIDTHS = {"overview": 640, "recent": 800, "match": 900}
@@ -209,6 +242,12 @@ def _metric(metric: Mapping, *, compact=False) -> dict:
style = "decimal"
formatted = _plain(value) if isinstance(value, str) else _numeric(value, style, compact=compact)
unit = _plain(metric.get("unit"), "")
+ note = _plain(metric.get("note"), "")
+ if style == "percent" and "sample_size" in metric and "wins" in metric:
+ display, sample_note, _ = _win_rate(value, metric.get("sample_size"), metric.get("wins"))
+ formatted, unit = (display[:-1], "%") if display.endswith("%") else (display, "")
+ return {"label": _plain(metric.get("label")), "value": formatted, "unit": unit,
+ "display": display, "note": " · ".join(dict.fromkeys(part for part in (sample_note, note) if part))}
if style == "percent" and not unit:
unit = "%"
if formatted == MISSING:
@@ -219,42 +258,42 @@ def _metric(metric: Mapping, *, compact=False) -> dict:
"value": formatted,
"unit": unit,
"display": display,
- "note": _plain(metric.get("note"), ""),
+ "note": note,
}
- def _exchange(self, item: Mapping, *, elo: bool = False) -> list[dict]:
+ def _player_metrics(self, item: Mapping, *, detail=False, damage_source=None) -> list[dict]:
"""Pair comparable values, preserving zero and unknown independently."""
def value(key, style="decimal"):
raw = item.get(key)
- return _plain(raw) if isinstance(raw, str) else _numeric(raw, style, compact=not elo)
+ return _plain(raw) if isinstance(raw, str) else _numeric(raw, style, compact=True)
def pair(first, second, style="decimal"):
return f"{value(first, style)} / {value(second, style)}"
- metrics = []
- if elo:
- rating = value("elo")
- delta = value("elo_delta", "signed")
- metrics.append({"label": "ELO", "value": rating + (f" ({delta})" if delta != MISSING else "")})
- metrics.extend([
+ rating = value("elo")
+ delta = value("elo_delta", "signed")
+ metrics = [
+ {"label": "ELO", "value": rating + (f" ({delta})" if delta != MISSING else "")},
{"label": "分值 K/D", "value": value("value_exchange")},
{"label": "摧毁 / 损失", "value": pair("destroyed_value", "lost_value")},
{"label": "击杀 / 阵亡", "value": pair("kills", "losses", "integer")},
- ])
- if not elo:
- metrics[-2], metrics[-1] = metrics[-1], metrics[-2]
- if elo:
- if any(item.get(key) is not None for key in ("damage_dealt", "damage_received")):
- metrics.append({"label": "伤害 / 承伤", "value": pair("damage_dealt", "damage_received")})
- for key, label, style in (("objectives", "占点", "integer"),
- ("spawned_value", "出兵花费", "decimal"),
- ("supply", "补给消耗", "decimal")):
- if item.get(key) is not None:
- metrics.append({"label": label, "value": value(key, style)})
+ ]
+ if not detail:
+ return [self._metric(metric) for metric in metrics]
+ if any(item.get(key) is not None for key in ("damage_dealt", "damage_received")):
+ metrics.append({"label": "伤害 / 承伤", "value": pair("damage_dealt", "damage_received")})
+ if item.get("damage_exchange") is not None:
+ metrics.append({"label": "伤害交换比", "value": value("damage_exchange"),
+ "note": "分析样本" if damage_source == "analysis" else ""})
+ for key, label, style in (("objectives", "占点", "integer"),
+ ("spawned_value", "出动价值", "decimal"),
+ ("supply", "补给消耗", "decimal")):
+ if item.get(key) is not None:
+ metrics.append({"label": label, "value": value(key, style)})
return [self._metric(metric) for metric in metrics]
@staticmethod
- def _profile(value) -> dict:
+ def _profile(value, recent_rows) -> dict:
rating = _mapping(value)
score = _number(rating.get("score"))
if score is not None and not 1 <= score <= 10:
@@ -263,8 +302,8 @@ def _profile(value) -> dict:
supplied = {item.get("key"): item for item in _records(rating.get("dimensions"))
if isinstance(item.get("key"), str)}
- center = (180, 114)
- radius = 66
+ center = (240, 162)
+ radius = 112
def point(index, radius):
angle = -pi / 2 + index * 2 * pi / 5
@@ -274,25 +313,42 @@ def coordinates(points):
return " ".join(f"{x:.2f},{y:.2f}" for x, y in points)
axes = []
+ positions = ((240, 25, "middle"), (387, 121, "start"), (335, 269, "start"),
+ (145, 269, "end"), (93, 121, "end"))
+ results = _mapping(rating.get("win_rate_sample"))
+ win_window = _count(results.get("window_size"))
+ if win_window is None:
+ win_window = min(len(_records(recent_rows)), _RECENT_WIN_RATE_WINDOW)
for index, (key, label) in enumerate(_PROFILE_AXES):
- number = _number(supplied.get(key, {}).get("value"))
+ dimension = supplied.get(key, {})
+ number = _number(dimension.get("value"))
if number is not None and not 0 <= number <= 100:
number = None
- x, y = point(index, 88)
+ display, note = _numeric(number, compact=True), ""
+ has_sample = False
+ if key == "win_rate":
+ display, note, number = _win_rate(results.get("value", number), results.get("sample_size"),
+ results.get("wins"))
+ has_sample = bool(_count(results.get("sample_size")))
+ if has_sample and win_window:
+ note = f"近 {win_window} 场 · {note}" if note else f"近 {win_window} 场"
+ x, y, anchor = positions[index]
xy = point(index, float(number) * radius / 100) if number is not None else None
- axes.append({"key": key, "label": label,
- "display": _numeric(number, compact=True) + ("%" if key == "win_rate" and number is not None else ""),
- "x": f"{x:.2f}", "y": f"{y - 4:.2f}",
- "anchor": "middle" if index == 0 else "start" if index in (1, 2) else "end",
+ axes.append({"key": key, "label": label, "display": display, "note": note,
+ "x": x, "y": y, "anchor": anchor,
"line": coordinates([center, point(index, radius)]),
- "point": xy})
- complete = all(axis["point"] is not None for axis in axes)
+ "point": xy, "has_fact": display != MISSING or has_sample})
+ available = sum(axis["point"] is not None for axis in axes)
+ sample = _count(rating.get("sample_size"))
return {"score": format(score, ".1f") if score is not None else MISSING,
"title": _plain(rating.get("title"), "") if score is not None else "",
"tone": tone if score is not None and tone in {"low", "medium", "high"} else "medium",
+ "sample": f"{sample} 场有效" if sample is not None else "",
"axes": axes,
+ "facts": [axis for axis in axes if axis["has_fact"]],
+ "radar": available >= 4,
"rings": [coordinates([point(index, radius * step / 4) for index in range(5)]) for step in range(1, 5)],
- "polygon": coordinates([axis["point"] for axis in axes]) if complete else "",
+ "polygon": coordinates([axis["point"] for axis in axes]) if available == len(axes) else "",
}
def _prepare(self, view: dict) -> dict:
@@ -301,6 +357,15 @@ def _prepare(self, view: dict) -> dict:
raise ValueError("unknown card kind")
player = _mapping(view.get("player"))
match = _mapping(view.get("match"))
+ metrics = []
+ for item in _records(view.get("metrics")):
+ if kind == "overview" and item.get("label") == "分析样本胜率":
+ window = _count(item.get("window_size"))
+ if window is None:
+ window = _count(_mapping(player.get("analysis")).get("matchCount"))
+ if window:
+ item = {**item, "label": f"近{window}场胜率"}
+ metrics.append(self._metric(item, compact=kind != "match"))
prepared = {
"kind": kind,
"width": self.WIDTHS[kind],
@@ -312,7 +377,7 @@ def _prepare(self, view: dict) -> dict:
"id": _plain(player.get("id")),
"source_url": _safe_url(player.get("source_url")),
},
- "metrics": [self._metric(item, compact=kind != "match") for item in _records(view.get("metrics"))],
+ "metrics": metrics,
"scope": _plain(view.get("scope")),
"fetched_at": self._time(view.get("fetched_at")),
"source_updated_at": self._time(view.get("source_updated_at")),
@@ -337,9 +402,10 @@ def _prepare(self, view: dict) -> dict:
"pagination": "",
}
if kind == "overview":
- prepared["profile_rating"] = self._profile(view.get("profile_rating"))
+ prepared["profile_rating"] = self._profile(view.get("profile_rating"), view.get("rows"))
for item in _records(view.get("rows")):
score = _number(item.get("score"))
+ kd = item.get("value_exchange")
prepared["rows"].append({
"score": format(score, ".1f") if score is not None else MISSING,
"score_band": item.get("score_band") if item.get("score_band") in {"low", "medium", "high"} else "medium",
@@ -347,10 +413,10 @@ def _prepare(self, view: dict) -> dict:
"started_at": self._time(item.get("started_at")),
"map_name": _plain(item.get("map_name")),
"mode": _MODES.get(_plain(item.get("mode")), _plain(item.get("mode"))),
- "outcome": _outcome(item.get("outcome")),
+ "outcome": _outcome(item.get("outcome"), item.get("outcome_conflict")),
"duration": self._duration(item.get("duration_seconds")),
"elo_delta": _numeric(item.get("elo_delta"), "signed", compact=True),
- "exchange": self._exchange(item),
+ "kd": _plain(kd) if isinstance(kd, str) else _numeric(kd, compact=True),
"source_url": _safe_url(item.get("source_url")),
})
prepared["match"] = {
@@ -360,12 +426,24 @@ def _prepare(self, view: dict) -> dict:
"started_at": self._time(match.get("started_at")),
"duration": self._duration(match.get("duration_seconds")),
"winner": _plain(match.get("winner")),
- "target_outcome": _outcome(match.get("target_outcome")),
+ "target_outcome": _outcome(match.get("target_outcome"), match.get("target_outcome_conflict")),
}
raw_teams = _records(view.get("teams"))
+ side_members = {}
+ target_id = prepared["player"]["id"]
for team in raw_teams:
members = _records(team.get("players"))
- team_metrics = [self._metric(item) for item in _records(team.get("metrics"))]
+ side = ({"0": "a", "1": "b"}.get(_plain(team.get("id")), "neutral") if "id" in team
+ else dict(zip(_FORMAL_TEAMS, ("a", "b"))).get(team.get("name"), "neutral"))
+ if side != "neutral":
+ side_members[side] = members
+ team_metrics = {
+ _plain(item.get("label")): {
+ **self._metric(item), "number": _number(item.get("value")),
+ "complete": item.get("complete", not item.get("note")) is True,
+ }
+ for item in _records(team.get("metrics"))
+ }
summary = []
# The service's mean ELO is the post-match value, not the prediction's
# pre-match input. Never reconstruct a missing pre-match rating.
@@ -375,66 +453,84 @@ def _prepare(self, view: dict) -> dict:
summary.append(self._metric({"label": label, "value": sum(values) / len(values) if complete else None,
"format": "signed" if field == "elo_delta" else "decimal"}))
for label in ("赛后平均 ELO", "摧毁分"):
- metric = next((item for item in team_metrics if item["label"] == label), self._metric({"label": label}))
- summary.append(metric)
+ summary.append(team_metrics.get(label, self._metric({"label": label})))
composition = []
for item in _records(team.get("composition")):
percentage = _number(item.get("percentage"))
- composition.append({"name": _plain(item.get("name")), "percentage": _numeric(percentage, "percent"),
- "number": percentage if percentage is not None and 0 <= percentage <= 100 else None,
- "role": _ROLES.get(item.get("name"), "other")})
+ composition.append({"name": _plain(item.get("name")),
+ "number": percentage if percentage is not None and 0 <= percentage <= 100 else None})
total = sum((item["number"] or 0) for item in composition)
# Service omits zero-spend roles from a complete composition. Only
# a full, unqualified 100% distribution makes that omission zero.
composition_complete = (bool(composition) and all(item["number"] is not None for item in composition)
and abs(total - 100) <= Decimal("0.01") and not team.get("composition_note"))
+ roster = []
+ for item in members:
+ is_target = target_id != MISSING and _plain(item.get("id")) == target_id
+ roster.append({"name": _plain(item.get("name")), "is_target": is_target,
+ "metrics": self._player_metrics(
+ item, detail=is_target, damage_source=match.get("target_damage_exchange_source"))})
prepared["teams"].append({
"name": _plain(team.get("name")),
- "side": "a" if team.get("name") == "A 队" else "b" if team.get("name") == "B 队" else "neutral",
+ "side": side,
"outcome": _outcome(team.get("outcome")),
"metrics": team_metrics,
"summary": [summary[index] for index in (0, 2, 1, 3)],
"composition": composition,
"composition_complete": composition_complete,
"composition_note": _plain(team.get("composition_note"), ""),
- "players": [
- {"id": _plain(item.get("id")), "name": _plain(item.get("name")),
- "is_target": bool(player.get("id")) and item.get("id") == player.get("id"),
- "metrics": self._exchange(item, elo=True)}
- for item in members
- ],
+ "players": roster,
})
+ team_by_side = {team["side"]: team for team in prepared["teams"]}
+ sides = [team_by_side.get(side, {}) for side in ("a", "b")]
+ prepared["formal_teams"] = [team for team in sides if team]
+ prepared["teams"] = prepared["formal_teams"] + [team for team in prepared["teams"] if team["side"] == "neutral"]
+ a_members, b_members = (side_members.get(side, []) for side in ("a", "b"))
+ comparable_rosters = match.get("roster_complete") is not False and len(a_members) == len(b_members)
prediction = _mapping(view.get("prediction"))
a, b = _number(prediction.get("a")), _number(prediction.get("b"))
- prepared["prediction"] = ({"a": _numeric(a, "percent"), "b": _numeric(b, "percent"), "width": float(a)}
- if a is not None and b is not None and 0 <= a <= 100 and 0 <= b <= 100 else None)
- # Each comparison row keeps the actual team order and both denominators.
- labels = list(dict.fromkeys(m["label"] for team in prepared["teams"][:2] for m in team["metrics"]))
+ prepared["prediction"] = None
+ if (comparable_rosters and a_members
+ and all(_number(member.get("elo_before")) is not None or
+ (_number(member.get("elo")) is not None and _number(member.get("elo_delta")) is not None)
+ for member in a_members + b_members)
+ and a is not None and b is not None and 0 <= a <= 100 and 0 <= b <= 100
+ and abs(a + b - 100) <= Decimal("0.01")):
+ rounded = int(a + Decimal("0.5"))
+ prepared["prediction"] = {"a": rounded, "b": 100 - rounded, "width": float(a)}
+ prepared["prediction_note"] = "按赛前 ELO 估算" if prepared["prediction"] else "暂无可用预测"
+
+ labels = dict.fromkeys(label for team in sides for label in team.get("metrics", {}))
prepared["comparisons"] = []
for label in labels:
- pair = [next((m for m in team["metrics"] if m["label"] == label), None) for team in prepared["teams"][:2]]
- if len(pair) == 2:
- numbers = [_number(next((m.get("value") for m in _records(team.get("metrics"))
- if _plain(m.get("label")) == label), None)) for team in raw_teams[:2]]
- prepared["comparisons"].append({"label": label,
- "values": [m["display"] if m else MISSING for m in pair],
- "notes": [m["note"] if m else "" for m in pair], "width": _split_width(numbers)})
- category_names = list(dict.fromkeys(category["name"] for team in prepared["teams"][:2]
- for category in team["composition"]))
+ pair = [team.get("metrics", {}).get(label, {}) for team in sides]
+ width = (_split_width([m.get("number") for m in pair])
+ if comparable_rosters and all(m.get("complete") for m in pair) else None)
+ prepared["comparisons"].append({
+ "label": label, "values": [m.get("display", MISSING) for m in pair],
+ "notes": [m.get("note", "") for m in pair], "width": width,
+ })
+ category_names = list(dict.fromkeys(category["name"] for team in sides
+ for category in team.get("composition", [])))
category_names.sort(key=lambda name: list(_ROLES).index(name) if name in _ROLES else len(_ROLES))
prepared["composition_rows"] = []
- if len(prepared["teams"]) >= 2:
- for name in category_names:
- values = [next((category["number"] for category in team["composition"] if category["name"] == name),
- Decimal(0) if team["composition_complete"] else None) for team in prepared["teams"][:2]]
- prepared["composition_rows"].append({"label": name, "role": _ROLES.get(name, "other"),
- "values": [_numeric(value, "percent") + "%" if value is not None else MISSING for value in values],
- "width": _split_width(values)})
+ for name in category_names:
+ values = [next((category["number"] for category in team.get("composition", []) if category["name"] == name),
+ Decimal(0) if team.get("composition_complete") else None) for team in sides]
+ width = (_split_width(values)
+ if comparable_rosters and all(team.get("composition_complete") for team in sides) else None)
+ prepared["composition_rows"].append({
+ "label": name, "role": _ROLES.get(name, "other"),
+ "values": [_numeric(v, "percent", compact=True) + "%" if v is not None else MISSING for v in values],
+ "width": width,
+ })
page = _number(view.get("page"))
page_count = _number(view.get("page_count"))
row_total = _number(view.get("row_total"))
row_start = _number(view.get("row_start"))
- if kind == "recent" and all(value is not None and value == value.to_integral_value() for value in (page, page_count, row_total, row_start)):
+ if (kind == "recent" and page_count is not None and page_count > 1
+ and all(value is not None and value == value.to_integral_value()
+ for value in (page, page_count, row_total, row_start))):
end = int(row_start) + len(prepared["rows"]) - 1 if prepared["rows"] else 0
prepared["pagination"] = f"第 {int(page)}/{int(page_count)} 页 · 本页 {int(row_start)}–{end} 场 / 共 {int(row_total)} 场"
return prepared
@@ -463,12 +559,18 @@ def metrics(items):
if data["kind"] == "overview":
profile = data["profile_rating"]
- lines.append("综合评分 " + profile["score"] + (" · " + profile["title"] if profile["title"] else ""))
+ lines.append(" · ".join(part for part in (f"综合评分 {profile['score']}", profile["title"], profile["sample"])
+ if part))
for offset in range(0, len(data["metrics"]), 2):
lines.append(metrics(data["metrics"][offset:offset + 2]))
if not data["metrics"]:
lines.append("统计指标:暂无")
- lines.append("五维表现:" + " · ".join(f"{axis['label']} {axis['display']}" for axis in profile["axes"]))
+ if profile["facts"]:
+ lines.append("五维表现 · 近期:" + " · ".join(
+ f"{axis['label']} {axis['display']}" + (f"({axis['note']})" if axis["note"] else "")
+ for axis in (profile["axes"] if profile["radar"] else profile["facts"])))
+ else:
+ lines.append("五维表现:暂无数据")
if data["style_scope"]:
lines.append(data["style_scope"] + (":暂无" if not data["categories"] else ""))
if data["categories"]:
@@ -489,14 +591,8 @@ def metrics(items):
lines.append(f"{row['name']} · {row['count']} 场 · 胜率 {rate}")
elif data["kind"] == "recent":
for row in data["rows"]:
- heading = [f"评分 {row['score']}", row['outcome']['label'], row['map_name']]
- if row['duration'] != MISSING:
- heading.append(row['duration'])
- lines.append(" · ".join(heading))
- detail = [f"ELO {row['elo_delta']}"] if row['elo_delta'] != MISSING else []
- detail.extend(f"{m['label']} {m['display']}" for m in row['exchange'])
- lines.append(" · ".join(detail))
- lines[-1] += f" · #{row['id']}"
+ lines.append(f"评分 {row['score']} · {row['map_name']} · {row['outcome']['label']} · ELO {row['elo_delta']}")
+ lines.append(f"分值 K/D {row['kd']} · 时长 {row['duration']} · #{row['id']}")
if not data["rows"]:
lines.append("近期对局:暂无")
else:
@@ -512,26 +608,38 @@ def metrics(items):
if meta:
lines.append(" · ".join(meta))
prediction = data["prediction"]
- lines.append(f"赛前预测 A {prediction['a']}% : B {prediction['b']}%(按赛前 ELO 估算)" if prediction else "赛前预测:暂无")
- if data["comparisons"]:
- lines.append("双方对比(" + " / ".join(t["name"] for t in data["teams"][:2]) + ")")
- for row in data["comparisons"]:
- lines.append(f"{row['label']}:" + " / ".join(v + (f"({n})" if n else "") for v, n in zip(row['values'], row['notes'])))
- lines.append("兵种构成(基础花费估算)")
- for team in data["teams"]:
- lines.append(team['name'] + ":" + (" · ".join(f"{c['name']} {c['percentage']}%" for c in team['composition']) or "暂无"))
+ lines.append(
+ f"赛前预测:A 队 {prediction['a']}% · B 队 {prediction['b']}%({data['prediction_note']})"
+ if prediction else f"赛前预测:{data['prediction_note']}"
+ )
+ for team in data["formal_teams"]:
+ lines.append(f"{team['name']} · {len(team['players'])} 人 · {team['outcome']['label']}")
+ lines.append(metrics(team["summary"]))
+ lines.append("兵种构成(按基础出动价值估算 · A 队 / B 队)")
+ for row in data["composition_rows"]:
+ lines.append(f"{row['label']}:" + " / ".join(row["values"]))
+ if not data["composition_rows"]:
+ lines.append("暂无完整兵种构成")
+ for team in data["formal_teams"]:
if team['composition_note']:
- lines.append(team['composition_note'])
- lines.append("玩家")
+ lines.append(f"{team['name']}:{team['composition_note']}")
+ lines.append("双方对比(A 队 / B 队)")
+ for row in data["comparisons"]:
+ lines.append(f"{row['label']}:" + " / ".join(
+ v + (f"({n})" if n else "") for v, n in zip(row["values"], row["notes"])))
+ if not data["comparisons"]:
+ lines.append("暂无对比数据")
+ lines.append("队伍玩家")
for team in data["teams"]:
heading = f"{team['name']} · {len(team['players'])} 人"
if team['outcome']['key'] != 'unknown':
heading += " · " + team['outcome']['label']
lines.extend(["", heading])
for player in team["players"]:
- lines.append(player['name'] + ("(查询玩家)" if player['is_target'] else ""))
- for offset in range(0, len(player['metrics']), 3):
- lines.append(metrics(player['metrics'][offset:offset + 3]))
+ name = player["name"] + ("(查询玩家)" if player["is_target"] else "")
+ lines.append(name + " · " + metrics(player["metrics"][:4]))
+ if player["metrics"][4:]:
+ lines.append(metrics(player["metrics"][4:]))
if not team["players"]:
lines.append("队员:暂无")
if not data["teams"]:
diff --git a/scoring.py b/scoring.py
index 6be20f3..fd6cf9d 100644
--- a/scoring.py
+++ b/scoring.py
@@ -16,16 +16,14 @@
from typing import Literal
try:
- from .models import Match, Participant
+ from .models import PROFILE_AXES, AnalysisOutcome, Match, Participant, analysis_outcomes, win_rate_sample
except ImportError: # Standalone tests use the repository as their import root.
- from models import Match, Participant
+ from models import PROFILE_AXES, AnalysisOutcome, Match, Participant, analysis_outcomes, win_rate_sample
MODEL = json.loads((Path(__file__).parent / "assets" / "scoring-model.json").read_text(encoding="utf-8"))
ROLE_KEYS = ("armor", "inf", "recon", "arty", "aa", "heli", "jet")
CAT_KEYS = ("recon", "infantry", "vehicles", "support", "logistic", "helicopters", "aircrafts")
-_PROFILE_AXES = (("kd", "分值 K/D"), ("contrib", "摧毁贡献"), ("obj", "占点贡献"),
- ("outcome", "胜负预期"), ("win_rate", "实际胜率"))
_PROFILE_TIERS = {"dragon": ("真龙", "high"), "solid": ("有龙样", "high"),
"average": ("泯然众人", "medium"), "weak": ("有点蛆", "low"), "qu": ("纯蛆", "low")}
ROLE_NAMES = {"armor": "装甲", "inf": "步兵", "recon": "侦察", "arty": "炮兵",
@@ -62,11 +60,11 @@ def _expect(own: float, opponent: float) -> float:
def match_prediction(match: Match) -> dict[str, float] | None:
"""A=team '0', B=team '1'; percentages in 0..100, using pre-match ELO.
- Every participant on both teams must have a pre-match observation. No AFK
- penalty applies to a pre-match prediction. Spectators are excluded.
+ Both teams must have equal, nonempty rosters and every player needs a
+ pre-match observation. No AFK penalty applies; spectators are excluded.
"""
teams = [[p for p in match.players if p.team == team] for team in ("0", "1")]
- if any(not team for team in teams):
+ if not teams[0] or len(teams[0]) != len(teams[1]):
return None
averages = []
for team in teams:
@@ -78,20 +76,18 @@ def match_prediction(match: Match) -> dict[str, float] | None:
return {"a": a, "b": 100 - a}
-def _career_roles(analysis: Mapping | None) -> dict[str, float] | None:
+def _career_roles(analysis: Mapping | None) -> dict[str, float]:
"""rolesFromCareer, including the upstream prior of 30% category spend."""
analysis = analysis or {}
- categories = analysis.get("categoryPreferences", [])
- highlights = analysis.get("highlightUnits", [])
- if not isinstance(categories, list) or not isinstance(highlights, list):
- return None
+ categories = analysis.get("categoryPreferences")
+ highlights = analysis.get("highlightUnits")
buckets = {}
- for unit in highlights:
- if not isinstance(unit, Mapping):
- return None
+ for unit in highlights if isinstance(highlights, list) else ():
+ if not isinstance(unit, Mapping) or unit.get("unitId") is None:
+ continue
category, cost = unit.get("categoryType"), unit.get("totalCost")
if not _nonnegative(category) or int(category) != category or not _nonnegative(cost):
- return None
+ continue
if category >= len(CAT_KEYS):
continue
bucket = buckets.setdefault(CAT_KEYS[int(category)], {"total": 0.0})
@@ -100,9 +96,9 @@ def _career_roles(analysis: Mapping | None) -> dict[str, float] | None:
role = entry[0] if entry and entry[0] else "_none"
bucket[role] = bucket.get(role, 0.0) + cost
roles = dict.fromkeys(ROLE_KEYS, 0.0)
- for category in categories:
+ for category in categories if isinstance(categories, list) else ():
if not isinstance(category, Mapping) or not _nonnegative(category.get("totalCost")):
- return None
+ continue
key, spend = str(category.get("categoryKey")), category["totalCost"]
default = MODEL["catSplit"].get(key, {})
bucket = buckets.get(key, {})
@@ -148,19 +144,22 @@ def _inactive(match: Match, players: list[Participant]) -> set[str]:
return result
-def _match_features(match: Match, me: Participant, trade: tuple[float, float]) -> dict | None:
+def _match_features(match: Match, me: Participant, trade: tuple[float, float],
+ outcome: AnalysisOutcome | None) -> dict | None:
"""The matchFeatures inputs used by computeDragonScore, with strict gaps."""
players = [p for p in match.players if p.team in ("0", "1")]
- if me.team not in ("0", "1") or not players:
+ if me.team not in ("0", "1") or outcome == "conflict":
return None
# Financial counters and rating observations cannot be reconstructed from
# analysis trend points or post-match team averages.
if any(not _nonnegative(p.destroyed_value) or not _nonnegative(p.lost_value)
- or _old_rating(p) is None or not _finite(p.elo) for p in players):
+ or _old_rating(p) is None for p in players):
return None
old = _old_rating(me)
- if old is None or not _finite(me.elo) or abs(me.elo - old) < 0.01:
+ # Keep the rated-match gate independent of the source of S.
+ if not _finite(me.elo) or abs(me.elo - old) < 0.01:
return None
+ won = (me.elo > old) if outcome is None else (outcome == "win")
team = [p for p in players if p.team == me.team]
opponent = [p for p in players if p.team != me.team]
if not team or not opponent:
@@ -187,7 +186,7 @@ def _match_features(match: Match, me: Participant, trade: tuple[float, float]) -
elif MODEL["weights"]["obj"]:
return None
return {"eloN": (old - 2100) / 400, "gapN": (old - average(players)) / 400,
- "S": 1 if me.elo > old else 0, "E": expected,
+ "S": int(won), "E": expected,
"x": {"kd": math.log2((dw + 200) / (lw + 200)),
"con": math.log2((dw + 200) / (avg_dw + 200)),
"obj": obj}}
@@ -257,29 +256,38 @@ def recent_score(match: Match, participant: Participant, analysis: Mapping | Non
if me is None or (analysis is not None and not isinstance(analysis, Mapping)):
return None
roles = _career_roles(analysis)
- if roles is None:
- return None
- features = _match_features(match, me, _career_trade(roles))
+ outcome = analysis_outcomes(analysis).get(match.id)
+ features = _match_features(match, me, _career_trade(roles), outcome)
if features is None:
return None
combined, _ = _career_performance(features, roles)
return _to10(_percentile(combined, MODEL["matchPct"]["career"]))
-def profile_rating(matches: list[Match], player_id: str, analysis: Mapping | None,
- win_rate: float | None) -> dict:
+def profile_rating(matches: list[Match], player_id: str, analysis: Mapping | None) -> dict:
"""Aggregate up to 20 valid recent rows. Input matches are newest first.
- The caller supplies the independent observed win percentage from explicit
- analysis won records. The model's Elo-derived S never supplies this axis.
+ The win-rate axis uses the newest 20 distinct matches with the player,
+ independently of score eligibility, and only their explicit results.
"""
roles = _career_roles(analysis) if analysis is None or isinstance(analysis, Mapping) else None
+ outcomes = analysis_outcomes(analysis) if roles is not None else {}
observations = []
+ recent_results = []
+ seen = set()
if roles is not None:
trade = _career_trade(roles)
for match in matches:
+ if match.id in seen:
+ continue
me = next((p for p in match.players if p.player_id == player_id), None)
- features = _match_features(match, me, trade) if me is not None else None
+ if me is None:
+ continue
+ seen.add(match.id)
+ outcome = outcomes.get(match.id)
+ if len(seen) <= 20 and outcome is not None:
+ recent_results.append(outcome)
+ features = _match_features(match, me, trade, outcome)
if features is None:
continue
combined, parts = _career_performance(features, roles)
@@ -288,7 +296,8 @@ def profile_rating(matches: list[Match], player_id: str, analysis: Mapping | Non
break
score = title = tone = None
- axes = {"win_rate": win_rate if _finite(win_rate) and 0 <= win_rate <= 100 else None}
+ win_rate = win_rate_sample(recent_results)
+ axes = {"win_rate": win_rate["value"]}
if observations:
k = MODEL["kalman"]
mean, variance = 0.0, k["P0"]
@@ -301,13 +310,14 @@ def profile_rating(matches: list[Match], player_id: str, analysis: Mapping | Non
score = _to10(_percentile(mean, MODEL["playerPct"]))
tier = next(t for threshold, t in MODEL["tiers"] if score >= _to10(threshold))
title, tone = _PROFILE_TIERS[tier]
- for key, _ in _PROFILE_AXES[:-1]:
+ for key, _ in PROFILE_AXES[:-1]:
values = [parts[key] for _, _, parts in observations if key in parts]
if values:
axes[key] = math.floor(sum(values) / len(values) * 100 + 0.5)
return {"score": score, "title": title, "tone": tone, "sample_size": len(observations),
+ "win_rate_sample": win_rate,
"dimensions": [{"key": key, "label": label, "value": axes.get(key)}
- for key, label in _PROFILE_AXES]}
+ for key, label in PROFILE_AXES]}
def score_band(score: float | None) -> Literal["low", "medium", "high"] | None:
diff --git a/service.py b/service.py
index c8da816..f34ae3e 100644
--- a/service.py
+++ b/service.py
@@ -10,7 +10,7 @@
from .client import participant_for
from .commands import Request, Target
-from .models import FetchResult, Match, Participant, Player
+from .models import FetchResult, Match, Participant, Player, analysis_outcomes, win_rate_sample
from .pending import PendingManager
from .scoring import match_prediction, profile_rating, recent_score, score_band, team_composition
from .storage import Binding
@@ -39,11 +39,11 @@ class Response:
instructions: tuple[tuple[str, str], ...] = ()
-def ratio(numerator, denominator):
+def ratio(numerator, denominator, zero_label="无损失"):
if numerator is None or denominator is None:
return None
if denominator == 0:
- return "无损失" if numerator > 0 else None
+ return zero_label if numerator > 0 else None
return numerator / denominator
@@ -61,21 +61,16 @@ def participant_view(p: Participant):
lost_value=p.lost_value, unit_exchange=ratio(p.kills, p.losses),
value_exchange=ratio(p.destroyed_value, p.lost_value),
damage_dealt=p.damage_dealt, damage_received=p.damage_received,
+ damage_exchange=ratio(p.damage_dealt, p.damage_received, "无承伤"),
objectives=p.objectives, spawned_value=p.spawned_value, supply=p.supply,
outcome=p.outcome, outcome_source=None)
-def analysis_outcomes(player):
- """Only explicit booleans for this player's exact match IDs can supply results."""
- outcomes = {}
- for point in player.analysis.get("trend", {}).get("points", []):
- mid = point.get("matchId")
- if mid is not None:
- known = outcomes.setdefault(mid, set())
- if isinstance(point.get("won"), bool):
- known.add(point["won"])
- return {mid: ("win" if True in known else "loss") if len(known) == 1 else "unknown"
- for mid, known in outcomes.items()}
+def outcome_view(result):
+ known = result in ("win", "loss")
+ return {"outcome": result if known else "unknown",
+ "outcome_source": "analysis" if known else None,
+ "outcome_conflict": result == "conflict"}
def map_name(match, player=None):
@@ -88,21 +83,23 @@ def map_name(match, player=None):
def recent_rows(matches, player_id, player=None, *, with_scores=True):
rows = []
- outcomes = analysis_outcomes(player) if player is not None and player.id == player_id else {}
+ analysis = player.analysis if player is not None and player.id == player_id else None
+ outcomes = analysis_outcomes(analysis)
for match in matches:
person = participant_for(match, player_id)
if person is None:
continue
row = participant_view(person)
+ result = outcomes.get(match.id)
if with_scores:
- score = recent_score(match, person, player.analysis if player is not None and player.id == player_id else None)
- row.update(score=score, score_band=score_band(score))
- outcome = outcomes.get(match.id, person.outcome)
+ score = recent_score(match, person, analysis)
+ row.update(score=score, score_band=score_band(score),
+ score_outcome_source=("analysis" if result is not None else "elo_delta")
+ if score is not None else None)
row.update(id=match.id, started_at=match.started_at, ended_at=match.ended_at,
map_name=map_name(match, player),
- mode=match.mode, outcome=outcome,
- outcome_source="analysis" if outcomes.get(match.id) in {"win", "loss"} else None,
- duration_seconds=match.duration_seconds, source_url=match.source_url)
+ mode=match.mode, duration_seconds=match.duration_seconds,
+ source_url=match.source_url, **outcome_view(result))
rows.append(row)
return rows
@@ -113,37 +110,50 @@ def team_metrics(players):
("destroyed_value", "摧毁分", "decimal"), ("lost_value", "损失分", "decimal"),
("elo", "赛后平均 ELO", "decimal"), ("kills", "击杀", "integer"),
("losses", "阵亡", "integer"), ("damage_dealt", "伤害", "decimal"),
- ("spawned_value", "出兵花费", "decimal"), ("objectives", "占点", "integer"),
+ ("spawned_value", "出动价值", "decimal"), ("objectives", "占点", "integer"),
("supply", "补给", "decimal"),
):
values = [p[field] for p in players if p[field] is not None]
if not values:
continue
value = sum(values) / len(values) if field == "elo" else sum(values)
- metric = {"label": label, "value": value, "format": style}
- if len(values) != len(players):
+ complete = len(values) == len(players)
+ metric = {"key": field, "label": label, "value": value, "format": style,
+ "observed_count": len(values), "participant_count": len(players),
+ "complete": complete}
+ if not complete:
metric["note"] = f"{len(values)}/{len(players)} 人有数据"
metrics.append(metric)
return metrics
-def match_view(result, player=None):
+def match_view(result, player=None, *, recent_match=None):
match = result.data
target = participant_for(match, player.id) if player is not None else None
- target_outcome = analysis_outcomes(player).get(match.id, "unknown") if target is not None else "unknown"
+ target_result = outcome_view(analysis_outcomes(player.analysis).get(match.id) if target is not None else None)
+ target_damage = target_damage_source = None
+ if target is not None:
+ if target.damage_dealt is not None and target.damage_received is not None:
+ target_damage = ratio(target.damage_dealt, target.damage_received, "无承伤")
+ target_damage_source = "match" if target_damage is not None else None
+ else:
+ target_damage = next((point["dmr"] for point in player.analysis.get("trend", {}).get("points", [])
+ if point.get("matchId") == match.id and point.get("dmr") is not None), None)
+ target_damage_source = "analysis" if target_damage is not None else None
teams = OrderedDict()
+ winner_team = match.winner_team if match.winner_team in ("0", "1") else None
for person in match.players:
key = person.team
if key not in teams:
- teams[key] = {"name": {"0": "A 队", "1": "B 队"}.get(key, f"分队 {key if key is not None else '未知'}"),
+ teams[key] = {"id": key,
+ "name": {"0": "A 队", "1": "B 队"}.get(key, f"分队 {key if key is not None else '未知'}"),
"outcome": "unknown", "players": []}
row = participant_view(person)
- if player is not None and person.player_id == player.id:
- row.update(outcome=target_outcome,
- outcome_source="analysis" if target_outcome != "unknown" else None)
+ if person is target:
+ row.update(target_result, damage_exchange=target_damage)
teams[key]["players"].append(row)
- if match.winner_team is not None and person.team is not None:
- teams[key]["outcome"] = "win" if person.team == match.winner_team else "loss"
+ if winner_team is not None and key in ("0", "1"):
+ teams[key]["outcome"] = "win" if key == winner_team else "loss"
# Stable A/B ordering is independent of the source participant-map order.
teams = OrderedDict(sorted(teams.items(), key=lambda pair: {"0": 0, "1": 1}.get(pair[0], 2)))
for key, team in teams.items():
@@ -157,16 +167,32 @@ def match_view(result, player=None):
if composition["missing_participants"]:
notes.append(f"{composition['missing_participants']} 人缺单位数据,构成暂无")
team["composition_note"] = ";".join(notes)
+ coverage = {}
+ coverage_labels = []
+ if recent_match is not None and recent_match.id == match.id:
+ for team_id, label in (("0", "A"), ("1", "B")):
+ known = {p.player_id for p in recent_match.players if p.team == team_id}
+ if not known:
+ continue
+ reported = {p["id"] for p in teams.get(team_id, {}).get("players", [])}
+ matched = len(known & reported)
+ coverage[team_id] = {"matched": matched, "known": len(known)}
+ coverage_labels.append(f"{label} {matched}/{len(known)}")
+ # The recent roster can prove a gap but cannot prove completeness.
+ roster_incomplete = any(c["matched"] < c["known"] for c in coverage.values())
view = {"kind": "match", "match": {
"id": match.id, "map_name": map_name(match, player), "mode": match.mode,
"started_at": match.started_at, "ended_at": match.ended_at, "duration_seconds": match.duration_seconds,
- "winner": {"0": "A 队", "1": "B 队"}.get(match.winner_team, f"分队 {match.winner_team}")
- if match.winner_team is not None else None,
- "target_outcome": target_outcome,
- "target_outcome_source": "analysis" if target_outcome != "unknown" else None,
- }, "teams": list(teams.values()), "prediction": match_prediction(match),
+ "winner": {"0": "A 队", "1": "B 队"}.get(winner_team),
+ "target_damage_exchange": target_damage, "target_damage_exchange_source": target_damage_source,
+ **{f"target_{key}": value for key, value in target_result.items()},
+ }, "teams": list(teams.values()), "prediction": None if roster_incomplete else match_prediction(match),
+ "comparison_team_ids": ["0", "1"] if "0" in teams and "1" in teams else [],
"scope": f"单局 · 实际收录 {len(match.players)} 名玩家",
"source_url": match.source_url, **freshness(result)}
+ if roster_incomplete:
+ view["match"].update(roster_complete=False, roster_coverage=coverage)
+ view["scope"] += " · 同场已知名单覆盖:" + "、".join(coverage_labels)
if player:
view["player"] = asdict(player)
if not match.complete:
@@ -200,19 +226,26 @@ def common_units(player, matches):
def overview_metrics(player, rows):
- pairs = [row for row in rows if row["destroyed_value"] is not None and row["lost_value"] is not None]
- points = player.analysis.get("trend", {}).get("points", [])
- known = [point["won"] for point in points if isinstance(point.get("won"), bool)]
- dated = [point for point in points if point.get("endTime") is not None and point.get("dmr") is not None]
- latest = max(dated, key=lambda point: point["endTime"]) if dated else None
- return [
+ metrics = [
{"label": "ELO", "value": player.elo},
- {"label": "近期分值 K/D", "value": ratio(sum(row["destroyed_value"] for row in pairs),
- sum(row["lost_value"] for row in pairs)) if pairs else None},
- {"label": "分析样本胜率", "value": 100 * sum(known) / len(known) if known else None,
- "format": "percent"},
- {"label": "单局伤害交换比", "value": latest["dmr"] if latest else None},
]
+ for label, numerator, denominator, zero_label in (
+ ("近期分值 K/D", "destroyed_value", "lost_value", "无损失"),
+ ("近期伤害交换比", "damage_dealt", "damage_received", "无承伤"),
+ ):
+ pairs = [(row[numerator], row[denominator]) for row in rows
+ if row[numerator] is not None and row[denominator] is not None]
+ if not pairs and numerator == "damage_dealt":
+ continue
+ metric = {"label": label,
+ "value": ratio(sum(a for a, _ in pairs), sum(b for _, b in pairs), zero_label) if pairs else None,
+ "sample_size": len(pairs), "window_size": len(rows)}
+ if len(pairs) != len(rows):
+ metric["note"] = f"{len(pairs)}/{len(rows)} 场有数据"
+ metrics.append(metric)
+ metrics.insert(2, {"label": "分析样本胜率", "format": "percent",
+ **win_rate_sample(analysis_outcomes(player.analysis).values())})
+ return metrics
class StatsService:
@@ -387,7 +420,7 @@ async def _report(self, request, player_id):
if getattr(exc, "code", "") in {"not_found", "not_recorded", "no_data"}:
continue
raise
- view = match_view(detail, player)
+ view = match_view(detail, player, recent_match=match)
view.update(freshness(player_result, result, detail))
return Response(view=view)
return Response(f"{player.name} · STB ID:{player.id}\n当前返回样本中暂无可用单局战报。\n{player.source_url or ''}")
@@ -404,10 +437,7 @@ async def _report(self, request, player_id):
if len(times) != len(rows):
view["scope"] += f"({len(times)}/{len(rows)} 场有开始时间)"
if view["kind"] == "overview":
- # The profile uses recent matches; the metric grid retains the full analysis sample.
- results = [r["outcome"] for r in rows[:20] if r["outcome_source"] == "analysis"]
- win_rate = 100 * results.count("win") / len(results) if results else None
- view["profile_rating"] = profile_rating(matches, player.id, player.analysis, win_rate)
+ view["profile_rating"] = profile_rating(matches, player.id, player.analysis)
view["metrics"] = overview_metrics(player, rows)
view["common_units"] = common_units(player, matches)
view["map_stats"] = [{"name": m["mapName"] or f"地图#{m['mapId']}",
diff --git a/templates/_macros.html b/templates/_macros.html
index ec8827a..7104e10 100644
--- a/templates/_macros.html
+++ b/templates/_macros.html
@@ -1,9 +1,19 @@
-{% macro exchange(metrics) %}
-
- {% for metric in metrics %}
-
{{ metric.label }}
{{ metric.value }}{% if metric.unit %}{{ metric.unit }}{% endif %}
+{% macro outcome(value) %}
{{ value.label }}{% endmacro %}
+
+{% macro comparison(rows, composition=false) %}
+
左 A 队{% if composition %}(深){% endif %}右 B 队{% if composition %}(浅){% endif %}
+
+ {% for row in rows %}
+ - {{ row.label }}
-
+
{{ row['values'][0] }}{{ row['values'][1] }}
+ {% if row.width is not none %}
+
+
+
+
+ {% endif %}
+ {% if row.notes and (row.notes[0] or row.notes[1]) %}{{ row.notes[0] }}{{ row.notes[1] }}
{% endif %}
+
{% endfor %}
-
+
{% endmacro %}
-
-{% macro outcome(value) %}{{ value.label }}{% endmacro %}
diff --git a/templates/base.html b/templates/base.html
index 8f57717..3194f81 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -34,7 +34,7 @@
a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.report { width: 100%; max-width: {{ view.width }}px; margin: 0 auto; padding: 24px; }
.brandline { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 8px 20px; margin-bottom: 24px; color: var(--muted); font-size: 14px; }
- .brand { color: var(--accent); font-size: 17px; font-weight: 700; letter-spacing: 2px; }
+ .brand { color: var(--accent); font-size: 17px; font-weight: 700; }
.identity { border-left: 4px solid var(--accent); padding-left: 18px; margin-bottom: 22px; }
h1, h2, h3, p { margin: 0; }
h1 { font-size: 34px; line-height: 1.3; font-weight: 700; overflow-wrap: anywhere; }
@@ -52,38 +52,36 @@
.metric-note { font-size: 13px; color: var(--muted); margin-top: 7px; overflow-wrap: anywhere; }
.section-heading { margin: 24px 0 12px; }
.empty { background: var(--panel); border: 1px solid var(--line); padding: 22px 20px; color: var(--muted); }
- .unit-list { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--line); }
- .unit-list li { display: flex; gap: 16px; justify-content: space-between; align-items: baseline; padding: 13px 0; border-bottom: 1px solid var(--line); }
- .unit-name { min-width: 0; overflow-wrap: anywhere; }
- .unit-count { flex-shrink: 0; font-weight: 650; }
- .recent-list, .player-list { list-style: none; margin: 0; padding: 0; }
+ .recent-list { list-style: none; margin: 0; padding: 0; }
.recent-card { background: var(--panel); border: 1px solid var(--line); padding: 18px 20px; margin-bottom: 14px; }
.row-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
.row-heading > :first-child { min-width: 0; }
.outcome { flex-shrink: 0; font-size: 14px; font-weight: 650; color: var(--muted); }
.outcome.win { color: var(--win); }
.outcome.loss { color: var(--loss); }
+ .outcome.conflict { color: var(--warning); }
.row-meta { display: flex; flex-wrap: wrap; gap: 5px 18px; color: var(--muted); font-size: 14px; margin-top: 7px; overflow-wrap: anywhere; }
- .row-id { color: var(--muted); font-size: 13px; overflow-wrap: anywhere; margin-top: 12px; }
- .exchange { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px 18px; margin-top: 15px; padding-top: 14px; border-top: 1px solid var(--line); }
- .exchange > div { min-width: 0; }
- .small-value { font-size: 20px; line-height: 1.3; margin-top: 2px; overflow-wrap: anywhere; }
- .small-value .metric-unit { font-size: 14px; }
- .match-meta { background: var(--panel); border: 1px solid var(--line); padding: 16px 20px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 20px; margin-bottom: 22px; }
- .match-meta > div { min-width: 0; overflow-wrap: anywhere; }
- .match-meta .value { margin-top: 3px; }
- .team { margin-top: 20px; }
- .team-heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 6px 18px; padding: 10px 0; border-bottom: 2px solid var(--line); }
- .team-heading h2 { min-width: 0; overflow-wrap: anywhere; }
.team-size { color: var(--muted); font-size: 14px; margin-left: 8px; font-weight: 400; }
- .participant { padding: 16px 18px; border-bottom: 1px solid var(--line); background: var(--panel); }
- .participant h3 { font-size: 19px; }
- .participant .exchange { grid-template-columns: repeat(4, minmax(0, 1fr)); }
- .participant-id { color: var(--muted); font-size: 13px; margin-top: 3px; overflow-wrap: anywhere; }
- .participant.target { border-left: 3px solid var(--accent); }
- .compact-line { display: flex; flex-wrap: wrap; gap: 4px 14px; margin-top: 7px; overflow-wrap: anywhere; }
- .compact-line span { min-width: 0; }
- .compact-line b { font-weight: 600; }
+ .roster { width: 100%; table-layout: fixed; border-collapse: collapse; }
+ .roster :is(th, td) { padding: 8px 10px; text-align: right; overflow-wrap: anywhere; }
+ .roster :is(th, td):first-child { text-align: left; }
+ .roster thead { color: var(--muted); font-size: 17px; border-bottom: 1px solid var(--line); }
+ .roster thead th:first-child { width: 29%; }
+ .roster thead th:nth-child(2) { width: 20%; }
+ .roster thead th:nth-child(3) { width: 12%; }
+ .roster thead th:nth-child(4) { width: 24%; }
+ .roster .team-heading { background: var(--subtle); border-top: 2px solid var(--side); font-size: 19px; }
+ .team-heading .outcome { margin-left: 10px; }
+ .roster .participant { background: var(--panel); border-top: 1px solid var(--line); font-size: 21px; }
+ .roster .participant-detail { background: var(--panel); color: var(--muted); font-size: 17px; }
+ .roster .participant-detail td { padding-top: 0; }
+ .roster .target { background: var(--team-a-panel); }
+ .roster .side-b ~ .target { background: var(--team-b-panel); }
+ .roster .target > :first-child { box-shadow: inset 3px 0 var(--accent); }
+ .target-label { display: inline-block; color: var(--accent); font-size: 15px; margin-inline-start: 8px; }
+ .compact-line { display: flex; flex-wrap: wrap; gap: 2px 14px; }
+ .compact-line b { color: var(--ink); font-weight: 600; }
+ .roster .narrow-only { display: none; }
.report-table { width: 100%; border-collapse: collapse; table-layout: auto; }
.report-table th, .report-table td { padding: 9px 5px; text-align: right; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
.report-table th { color: var(--muted); font-size: 13px; font-weight: 400; }
@@ -108,32 +106,39 @@
.profile-grade .score { display: block; margin: 2px 0; font-size: 30px; }
.profile-grade .score.is-missing { font-size: 22px; color: var(--muted); }
.grade-title { font-size: 14px; font-weight: 600; overflow-wrap: anywhere; }
- .radar-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 6px; }
- .radar { display: block; width: 100%; max-width: 452px; margin: 5px auto 0; }
- .radar-grid { fill: none; stroke: var(--muted); stroke-opacity: .45; }
+ .grade-sample { display: block; font-size: 14px; color: var(--muted); }
+ .radar-heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 4px 10px; }
+ .radar-key, .radar-sample, .radar-window { font-size: 14px; color: var(--muted); font-weight: 400; }
+ .radar-sample { text-align: center; }
+ .radar { display: block; width: 100%; max-width: 570px; margin: 7px auto 0; }
+ .radar-grid { fill: none; stroke: var(--muted); stroke-opacity: .38; }
+ .radar-grid .radar-mid { stroke-opacity: 1; stroke-width: 1.8; stroke-dasharray: 5 3; }
.radar-area { fill: var(--accent); fill-opacity: .17; stroke: var(--accent); stroke-width: 2; }
.radar-dot { fill: var(--accent); stroke: var(--canvas); stroke-width: 1.5; }
- .radar-label { fill: var(--muted); font-size: 17px; }
+ .radar-label { fill: var(--muted); font-size: 18px; }
.radar-value { fill: var(--ink); font-size: 20px; font-weight: 700; }
+ .profile-facts { margin: 6px 0 0; }
+ .profile-facts > div { display: flex; align-items: baseline; justify-content: space-between; gap: 5px 12px; padding: 4px 0; border-bottom: 1px solid var(--line); }
+ .profile-facts dt { color: var(--muted); }
+ .profile-facts dd { margin: 0; text-align: right; font-weight: 650; }
+ .profile-facts small { display: inline-block; margin-inline-start: 8px; color: var(--muted); font-weight: 400; }
.report-overview .section-heading { margin: 13px 0 5px; }
.report-overview .report-table :is(th, td) { padding-block: 5px; }
.style-list { display: flex; flex-wrap: wrap; gap: 3px 14px; list-style: none; padding: 0; margin: 0; overflow-wrap: anywhere; }
.style-list b { white-space: nowrap; }
.report-recent .pagination { margin-bottom: 8px; }
.report-recent .recent-card { padding: 9px 12px; margin-bottom: 7px; }
+ .report-recent .row-heading { justify-content: initial; }
.report-recent .row-heading h3 { flex: 1; min-width: 0; }
- .report-recent .row-heading .score { display: inline-flex; flex-direction: row; align-items: baseline; gap: 4px; min-width: 78px; white-space: nowrap; }
+ .report-recent .row-heading .score { display: inline-flex; flex-direction: row; align-items: baseline; gap: 4px; white-space: nowrap; }
.report-recent .row-heading .score small { margin: 0; font-size: 13px; }
.report-recent .row-heading .score.is-missing { font-size: 18px; color: var(--muted); }
.report-recent .row-meta { margin-top: 4px; gap: 2px 12px; }
- .report-recent .row-meta .numeric { white-space: nowrap; }
- .recent-metrics { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 10px; margin: 6px 0 0; }
- .recent-metrics > :last-child { grid-column: 1 / -1; }
- .recent-metrics dt { color: var(--muted); font-size: 14px; }
- .recent-metrics dd { margin: 0; font-weight: 650; }
- .recent-metrics .number { display: inline-block; white-space: nowrap; }
+ .row-meta span { min-width: 0; }
+ .row-meta b { color: var(--ink); font-weight: 600; }
+ .row-elo { font-size: 14px; color: var(--muted); white-space: nowrap; }
+ .row-elo b { color: var(--ink); }
.report-overview footer, .report-recent footer { margin-top: 14px; padding-top: 8px; }
- .compact-team { font-size: 14px; color: var(--muted); }
.score { display: inline-flex; flex-direction: column; font-size: 25px; font-weight: 700; line-height: 1.1; flex-shrink: 0; }
.score small { font-size: 11px; color: var(--muted); font-weight: 400; margin-bottom: 4px; }
.score.low { color: var(--loss); } .score.medium { color: var(--ink); } .score.high { color: var(--warning); }
@@ -169,7 +174,6 @@
.comparison-values b:last-child { text-align: right; }
.comparison-track { display: flex; height: 9px; margin-top: 5px; background: var(--subtle); }
.comparison-track .segment { display: block; height: 100%; background: var(--side); }
- .comparison-track.no-comparison { background: transparent; border-bottom: 1px solid var(--line); }
.comparison-notes { color: var(--muted); font-size: 12px; margin-top: 3px; }
.comparison-notes > :last-child { text-align: right; }
.composition-key { margin: 7px 0 16px; }
@@ -201,12 +205,7 @@
.metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.metric { padding: 14px 13px; }
.metric-number { font-size: 32px; }
- .recent-card { padding: 15px 14px; }
- .exchange { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 14px; }
- .participant { padding: 15px 14px; }
- .participant .exchange { grid-template-columns: repeat(2, minmax(0, 1fr)); }
- .match-meta { padding: 14px; grid-template-columns: 1fr; gap: 10px; }
- .metric-label, .row-id, .participant-id, .metric-note, footer { font-size: 14px; }
+ .metric-label, .metric-note, footer { font-size: 14px; }
.match-columns { grid-template-columns: 1fr; }
.team-summary { padding: 12px 10px; }
.summary-heading { flex-wrap: wrap; gap: 4px; }
@@ -215,12 +214,22 @@
.summary-metrics { grid-template-columns: 1fr; gap: 8px; }
.summary-metrics dd { font-size: 20px; }
.prediction-values { font-size: 20px; }
+ .roster thead th:first-child { width: 43%; }
+ .roster thead th:nth-child(2) { width: 34%; }
+ .roster thead th:nth-child(3) { width: 23%; }
+ .roster :is(th, td) { padding-inline: 7px; }
+ .roster thead, .roster .participant-detail { font-size: 14px; }
+ .roster .roster-wide { display: none; }
+ .roster tr.narrow-only { display: table-row; }
+ .roster span.narrow-only { display: inline; }
+ .roster .participant { font-size: 16px; }
}
@media (max-width: 520px) {
.report-overview, .report-recent { padding-inline: 14px; }
.report-overview h1, .report-recent h1 { font-size: 24px; }
.report-recent .row-heading { gap: 8px; }
.report-recent .row-heading h3 { font-size: 18px; }
+ .report-recent .row-heading .score { font-size: 20px; }
}
@media (min-width: 600px) {
.report-overview { font-size: 21px; line-height: 1.4; }
@@ -232,20 +241,18 @@
.report-overview .metric { padding: 6px 12px; }
.report-overview .metric-number, .profile-grade .score { font-size: 32px; }
.report-overview .metric-unit { font-size: 21px; }
+ .radar-key, .radar-sample, .radar-window, .grade-sample { font-size: 17px; }
}
@media (min-width: 760px) {
.report-recent { font-size: 24px; line-height: 1.3; }
.report-recent h1 { font-size: 36px; }
.report-recent :is(.brandline, .identity-meta, .scope, .pagination, .row-meta,
- .row-heading .score small, .recent-metrics dt, .synthetic,
+ .row-heading .score small, .row-elo, .synthetic,
footer, .attribution a) { font-size: 23px; }
.report-recent .brand { font-size: 26px; }
.report-recent .row-heading h3, .report-recent .row-heading .score { font-size: 32px; }
.report-recent .row-heading .score { min-width: 116px; gap: 6px; }
.report-recent .row-heading .score.is-missing, .report-recent .outcome { font-size: 25px; }
- .recent-metrics { grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr) minmax(0, 1.95fr); }
- .recent-metrics > :last-child { grid-column: auto; }
- .recent-metrics dd { font-size: 27px; }
}
diff --git a/templates/match.html b/templates/match.html
index 414d4b0..42d5f9f 100644
--- a/templates/match.html
+++ b/templates/match.html
@@ -1,5 +1,5 @@
{% extends "base.html" %}
-{% from "_macros.html" import exchange, outcome %}
+{% from "_macros.html" import comparison, outcome %}
{% block identity %}
{{ view.match.map_name }}
对局 ID:{{ view.match.id }}
@@ -7,66 +7,58 @@ {{ view.match.map_name }}
{{ view.match.started_at }} · {{ view.match.duration }}{% if view.match.mode != '暂无' %} · {{ view.match.mode }}{% endif %}{% if view.match.winner != '暂无' %} · 胜方 {{ view.match.winner }}{% endif %}
{% endblock %}
{% block content %}
-
-
-
赛前预测
- {% if view.prediction %}
A 队 {{ view.prediction.a }}%B 队 {{ view.prediction.b }}%
-
-
按赛前 ELO 估算
{% else %}
暂无完整赛前 ELO
{% endif %}
-
-
- {% for team in view.teams %}
-
- {{ team.name }}{{ team.players | length }} 人
{{ outcome(team.outcome) }}
- {% for metric in team.summary %}- {{ metric.label }}
- {{ metric.display }}
{% if metric.note %}{{ metric.note }}{% endif %}{% endfor %}
-
- {% endfor %}
-
+
+
赛前预测
+ {% if view.prediction %}
+
A 队 {{ view.prediction.a }}%B 队 {{ view.prediction.b }}%
+
+ {% endif %}
+
{{ view.prediction_note }}
+
+ {% if view.formal_teams %}
+
+ {% for team in view.formal_teams %}
+
+ {{ team.name }}{{ team.players | length }} 人
{{ outcome(team.outcome) }}
+ {% for metric in team.summary %}- {{ metric.label }}
- {{ metric.display }}
{% if metric.note %}{{ metric.note }}{% endif %}{% endfor %}
+
+ {% endfor %}
+
+ {% endif %}
-
兵种构成
按基础花费估算
- {% if view.composition_rows %}
- 左 {{ view.teams[0].name }}(深)· 右 {{ view.teams[1].name }}(浅)
-
- {% for row in view.composition_rows %}- {{ row.label }}
-
-
{{ row['values'][0] }}{{ row['values'][1] }}
-
- {% if row.width is not none %}{% endif %}
-
- {% endfor %}
-
+ 兵种构成
按基础出动价值估算
+ {% if view.composition_rows %}{{ comparison(view.composition_rows, true) }}
{% else %}暂无完整兵种构成
{% endif %}
- {% for team in view.teams %}{% if team.composition_note %}{{ team.name }}:{{ team.composition_note }}
{% endif %}{% endfor %}
+ {% for team in view.formal_teams %}{% if team.composition_note %}{{ team.name }}:{{ team.composition_note }}
{% endif %}{% endfor %}
双方对比
- {% if view.comparisons %}
- 左 {{ view.teams[0].name }}右 {{ view.teams[1].name }}
-
- {% for row in view.comparisons %}- {{ row.label }}
-
-
{{ row['values'][0] }}{{ row['values'][1] }}
-
- {% if row.width is not none %}{% endif %}
-
- {% if row.notes[0] or row.notes[1] %}{{ row.notes[0] }}{{ row.notes[1] }}
{% endif %}
- {% endfor %}
-
{% else %}暂无对比数据
{% endif %}
+ {% if view.comparisons %}{{ comparison(view.comparisons) }}{% else %}暂无对比数据
{% endif %}
-队伍玩家
-{% for team in view.teams %}
-
- {{ team.name }}{{ team.players | length }} 人
{% if team.outcome.key != 'unknown' %}{{ outcome(team.outcome) }}{% endif %}
- {% if team.players %}
-
+队伍玩家
+{% if view.teams %}
+
+ | 玩家 | ELO | 分值 K/D | 摧毁 / 损失 | 击杀 / 阵亡 |
+ {% for team in view.teams %}
+
+ | {{ team.name }}{{ team.players | length }} 人{% if team.outcome.key != 'unknown' %}{{ outcome(team.outcome) }}{% endif %} |
{% for player in team.players %}
- -
-
{{ player.name }}{% if player.is_target %}(查询玩家){% endif %}
- {% for metric in player.metrics %}{{ metric.label }} {{ metric.display }}{% endfor %}
-
- {% endfor %}
-
- {% else %}队员:暂无
{% endif %}
-
-{% else %}分队与玩家:暂无
{% endfor %}
+
+ | {{ player.name }}{% if player.is_target %}查询玩家{% endif %} |
+ {% for metric in player.metrics[:4] %} 2 %} class="roster-wide"{% endif %}>{{ metric.display }} | {% endfor %}
+
+ {% if player.is_target %}
+
+
+ {% for metric in player.metrics[2:] %}{{ metric.label }} {{ metric.display }}{% if metric.note %}({{ metric.note }}){% endif %}{% endfor %}
+ |
+
+ {% endif %}
+ {% else %}| 队员:暂无 |
{% endfor %}
+
+ {% endfor %}
+
+{% else %}分队与玩家:暂无
{% endif %}
{% endblock %}
diff --git a/templates/overview.html b/templates/overview.html
index c80c6d2..94d8a15 100644
--- a/templates/overview.html
+++ b/templates/overview.html
@@ -6,16 +6,19 @@
综合评分
{{ view.profile_rating.score }}
{% if view.profile_rating.title %}{{ view.profile_rating.title }}{% endif %}
+ {% if view.profile_rating.sample %}{{ view.profile_rating.sample }}{% endif %}
{% endblock %}
{% block content %}
{% set rating = view.profile_rating %}
- 五维表现
刻度 0–100
-
{% if view.categories or view.style_scope %}
{{ view.style_scope or '兵种风格' }}
diff --git a/templates/recent.html b/templates/recent.html
index 5d19af7..86559e8 100644
--- a/templates/recent.html
+++ b/templates/recent.html
@@ -5,13 +5,17 @@
{% for row in view.rows %}
-
-
评分{{ row.score }}
{{ row.map_name }}
{{ outcome(row.outcome) }}
- #{{ row.id }}{% if row.duration != '暂无' %}{{ row.duration }}{% endif %}{% if row.elo_delta != '暂无' %}ELO {{ row.elo_delta }}{% endif %}
-
- {% for metric in row.exchange %}
- - {{ metric.label }}
- {% for part in metric.display.split(' / ') %}{% if not loop.first %} {% endif %}{% if not loop.first %}/ {% endif %}{{ part }}{% endfor %}
- {% endfor %}
-
+
+ 评分{{ row.score }}
+
{{ row.map_name }}
+ {{ outcome(row.outcome) }}
+ ELO {{ row.elo_delta }}
+
+
+ 分值 K/D {{ row.kd }}
+ 时长 {{ row.duration }}
+ #{{ row.id }}
+
{% endfor %}
diff --git a/tests/test_models.py b/tests/test_models.py
index b38af70..9ac7ea5 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -5,7 +5,7 @@
import pytest
from models import (
- FetchResult, Match, Participant, Player, canonical_id, parse_match,
+ FetchResult, Match, Participant, Player, analysis_outcomes, canonical_id, parse_match,
parse_player, parse_recent, parse_search, utc_datetime,
)
@@ -56,9 +56,11 @@ def test_scoring_preserves_old_rating_and_unit_lifecycle_without_guessing_unit_a
def test_scoring_career_spend_and_unit_category_are_retained_when_supplied():
analysis = analysis_player({"matchCount": 1,
- "categoryPreferences": [{"categoryKey": "vehicles", "totalCost": 2000}],
- "highlightUnits": [{"unitId": 13, "categoryType": 2, "totalCost": 1500}],
+ "categoryPreferences": [{"totalCost": 99999}, {"categoryKey": "vehicles", "totalCost": 2000}],
+ "highlightUnits": [{"categoryType": 2, "totalCost": 99999},
+ {"unitId": 13, "categoryType": 2, "totalCost": 1500}],
}).analysis
+ assert len(analysis["categoryPreferences"]) == len(analysis["highlightUnits"]) == 1
assert analysis["categoryPreferences"][0]["totalCost"] == 2000
assert analysis["highlightUnits"][0]["categoryType"] == 2
assert analysis["highlightUnits"][0]["totalCost"] == 1500
@@ -277,13 +279,20 @@ def test_analysis_duplicate_match_ids_do_not_inflate_samples_or_hide_conflicts(v
rows = [{"matchId": 42 if i % 2 else "42", "endTime": 1700000000 + i,
**({"won": value} if value is not None else {})}
for i, value in enumerate(values)]
- rows.append({"matchId": "042", "won": False})
- points = analysis_player({"trend": {"points": rows}}).analysis["trend"]["points"]
- assert len(points) == 2
+ rows.extend([{"matchId": "042", "won": False}, {"won": True}])
+ analysis = analysis_player({"trend": {"points": rows}}).analysis
+ points = analysis["trend"]["points"]
+ assert len(points) == 3
assert points[0]["matchId"] == "42"
assert points[0]["won"] is expected
assert points[0]["endTime"] == utc_datetime(1700000000 + len(values) - 1)
assert points[1]["matchId"] == "042"
+ conflict = True in values and False in values
+ assert points[0].get("wonConflict", False) is conflict
+ expected_outcomes = {"042": "loss"}
+ if conflict or expected is not None:
+ expected_outcomes["42"] = "conflict" if conflict else ("win" if expected else "loss")
+ assert analysis_outcomes(analysis) == expected_outcomes
@pytest.mark.parametrize("analysis", [
diff --git a/tests/test_render.py b/tests/test_render.py
index 4ed0910..277f1d7 100644
--- a/tests/test_render.py
+++ b/tests/test_render.py
@@ -148,30 +148,26 @@ def test_missing_metric_is_unknown_without_fake_zero_or_unit(view, value):
def test_real_zero_and_unknown_stay_distinct(view):
view.update(kind="recent", rows=[{
- "id": "zero", "kills": 0, "losses": None, "destroyed_value": 0,
- "lost_value": None, "unit_exchange": None, "value_exchange": None,
+ "id": "zero", "value_exchange": None,
"duration_seconds": 0, "elo_delta": 0,
}])
- text = Renderer().text(view)
- assert "击杀 / 阵亡 0 / 暂无" in text
- assert "摧毁 / 损失 0 / 暂无" in text
- assert "分值 K/D 暂无" in text
- assert "胜负暂无" in text
- assert "0分00秒" in text
- assert "ELO +0" in text
+ renderer = Renderer()
+ for output in (renderer.text(view), VisibleHTML(renderer.template(view)).text):
+ for value in ("分值 K/D 暂无", "胜负暂无", "时长 0分00秒", "ELO +0"):
+ assert compact(value) in compact(output)
def test_exchange_values_are_separate_and_not_recalculated(view):
- view.update(kind="recent", rows=[{
+ view.update(kind="match", teams=[{"name": "A 队", "players": [{
"id": "ratios", "kills": 8, "losses": 2, "unit_exchange": 4,
- "destroyed_value": 2500.5, "lost_value": 2000.75, "value_exchange": 1.249,
- }])
+ "destroyed_value": 2500.5, "lost_value": 0, "value_exchange": 1.249,
+ }]}])
renderer = Renderer()
html_text = compact(VisibleHTML(renderer.template(view)).text)
text = renderer.text(view)
- for expected in ["击杀 / 阵亡 8 / 2", "摧毁 / 损失 2,500.5 / 2,000.75", "分值 K/D 1.25"]:
- assert expected in text
- assert compact(expected.replace(":", "")) in html_text
+ for label, value in [("击杀 / 阵亡", "8 / 2"), ("摧毁 / 损失", "2,500.5 / 0"), ("分值 K/D", "1.25")]:
+ assert f"{label}:{value}" in text
+ assert compact(value) in html_text
def test_stale_and_absent_timestamps_are_visible(view):
@@ -281,6 +277,7 @@ def test_analysis_units_maps_and_categories_share_values(view):
@pytest.fixture
def profile():
return {"score": 5.8, "title": "泯然众人", "tone": "medium", "sample_size": 4,
+ "win_rate_sample": {"value": 0, "wins": 0, "losses": 6, "sample_size": 6, "window_size": 8},
"dimensions": [{"key": key, "value": value}
for key, value in (("win_rate", 0), ("outcome", 71), ("obj", 16),
("contrib", 59), ("kd", 37))]}
@@ -292,10 +289,12 @@ def test_title_and_five_distinct_axes_belong_only_to_overview(view, profile, kin
renderer = Renderer()
parsed = VisibleHTML(renderer.template(view))
for output in (parsed.text, renderer.text(view)):
- for value in ("泯然众人", "五维表现", "分值 K/D 37", "摧毁贡献 59", "占点贡献 16", "胜负预期 71", "实际胜率 0%"):
+ for value in ("泯然众人", "4 场有效", "五维表现", "交换效率 37", "摧毁贡献 59",
+ "夺点表现 16", "赛果超预期 71", "实际胜率 0%", "近 8 场 · 0 胜 6 负 · 6 场有赛果"):
assert (compact(value) in compact(output)) == (kind == "overview")
assert sum(attrs.get("class") == "radar-area" for _, attrs in parsed.tags) == (kind == "overview")
assert sum(attrs.get("class") == "radar-dot" for _, attrs in parsed.tags) == (5 if kind == "overview" else 0)
+ assert sum(attrs.get("class") == "radar-mid" for _, attrs in parsed.tags) == (kind == "overview")
@pytest.mark.parametrize("value", [None, float("nan"), -1, 101])
@@ -307,46 +306,106 @@ def test_missing_radar_axis_keeps_real_zero_without_filling_polygon(view, profil
parsed = VisibleHTML(renderer.template(view))
for output in (parsed.text, renderer.text(view)):
assert "综合评分暂无" in compact(output)
- assert "胜负预期暂无" in compact(output) and "实际胜率0%" in compact(output)
+ assert "赛果超预期暂无" in compact(output) and "实际胜率0%" in compact(output)
assert profile["title"] not in output
assert not any(attrs.get("class") == "radar-area" for _, attrs in parsed.tags)
assert sum(attrs.get("class") == "radar-dot" for _, attrs in parsed.tags) == 4
-def test_recent_score_precedes_match_and_has_color_without_title(view):
- view.update(kind="recent", rows=[{"id":"42", "map_name":"Coast", "score":8.6, "score_band":"high"}])
+@pytest.mark.parametrize("sample", [1, 4, 5])
+def test_radar_win_rate_uses_its_own_known_results_and_threshold(view, profile, sample):
+ profile["win_rate_sample"].update(value=100, wins=sample, losses=0, sample_size=sample)
+ view["player"]["analysis"] = {"matchCount": 83}
+ view["style_scope"] = "近91场风格"
+ view.update(profile_rating=profile, metrics=[{"label": "分析样本胜率", "value": 60,
+ "wins": 12, "sample_size": 20, "format": "percent"}])
+ renderer = Renderer()
+ parsed = VisibleHTML(renderer.template(view))
+ assert sum(attrs.get("class") == "radar-dot" for _, attrs in parsed.tags) == (4 if sample < 5 else 5)
+ for output in (parsed.text, renderer.text(view)):
+ if sample < 5:
+ assert f"实际胜率{sample}胜0负" in compact(output)
+ assert "100%" not in output
+ assert f"{sample} 场有赛果" in output
+ else:
+ assert "实际胜率100%" in compact(output) and "5 胜 0 负 · 5 场有赛果" in output
+ for label in ("4 场有效", "近83场胜率", "12 胜 8 负 · 20 场有赛果", "近 8 场"):
+ assert label in output
+ assert "近91场胜率" not in output and "83 场有赛果" not in output
+
+
+def test_sparse_profile_uses_fact_list_and_retains_real_zero(view, profile):
+ profile["dimensions"] = [{"key": "kd", "value": 0}, {"key": "obj", "value": 25}]
+ view["profile_rating"] = profile
+ renderer = Renderer()
+ html = renderer.template(view)
+ assert 'class="profile-facts"' in html and 'class="radar"' not in html
+ for output in (VisibleHTML(html).text, renderer.text(view)):
+ for value in ("交换效率 0", "实际胜率 0%"):
+ assert compact(value) in compact(output)
+ assert "赛果超预期" not in output and "摧毁贡献" not in output
+
+
+def test_empty_profile_shows_one_unknown_line_without_axis_list(view, profile):
+ profile.update(dimensions=[], win_rate_sample={"sample_size": 0, "wins": 0}, score=None)
+ view["profile_rating"] = profile
renderer = Renderer()
html = renderer.template(view)
+ assert 'class="profile-facts"' not in html and 'class="radar"' not in html
+ for output in (VisibleHTML(html).text, renderer.text(view)):
+ assert output.count("五维表现:暂无数据") == 1
+ assert "实际胜率" not in output and "交换效率" not in output
+
+
+def test_recent_score_precedes_match_and_has_color_without_title(view):
+ view.update(kind="recent", metrics=[], rows=[{"id": "42", "map_name": "Coast", "score": 8.6, "score_band": "high",
+ "outcome": "win", "elo_delta": 15, "value_exchange": 1.42,
+ "duration_seconds": 90, "kills": 4, "losses": 0}])
+ renderer = Renderer()
+ page, = renderer.views(view)
+ html = renderer.template(page)
assert 'class="score high"' in html
- text = renderer.text(view)
- assert text.index("评分 8.6") < text.index("Coast") < text.index("#42")
- assert "龙蛆" not in text and "称号" not in text
+ text = renderer.text(page)
+ assert "评分 8.6 · Coast · 胜利 · ELO +15\n分值 K/D 1.42 · 时长 1分30秒 · #42" in text
+ for output in (text, VisibleHTML(html).text):
+ values = ["评分", "Coast", "胜利", "ELO", "分值 K/D", "时长", "#42"]
+ assert [output.index(value) for value in values] == sorted(output.index(value) for value in values)
+ assert all(output.count(value) == 1 for value in values)
+ assert "第 1/1 页" not in output and "击杀 / 阵亡" not in output
def test_match_retains_known_target_result_and_fractional_resource_values(view):
view.update(kind="match", match={"id": "42", "target_outcome": "loss"}, teams=[
{"name": "A 队", "players": [{"id": view["player"]["id"], "name": "查询玩家",
- "objectives": 3, "spawned_value": 1234.5, "supply": 12.5}]},
+ "objectives": 3, "spawned_value": 1234.5, "supply": 12.5},
+ {"id": "other", "name": "另一玩家", "spawned_value": 991171}]},
])
renderer = Renderer()
for output in (renderer.text(view), VisibleHTML(renderer.template(view)).text):
- for value in ("失利", "1234.50", "12.50", "占点"):
+ for value in ("失利", "1,234.5", "12.5", "占点"):
assert value in output
+ assert "另一玩家" in output and "991,171" not in output
+ assert renderer.template(view).count('class="participant-detail target"') == 1
+ direct = {key: value for key, value in view.items() if key != "player"}
+ assert 'class="participant-detail' not in renderer.template(direct)
+ assert "1,234.5" not in renderer.text(direct)
def test_match_sections_and_footer_are_shared_across_cards(view):
- view.update(kind="match", match={"id":"42"}, prediction={"a":64,"b":36}, teams=[
+ view.update(kind="match", match={"id":"42"}, prediction={"a":63.5,"b":36.5}, teams=[
{"name":"A 队", "metrics":[{"label":"击杀", "value":234,"format":"integer"}],
- "composition":[{"name":"步兵", "percentage":60}], "players":[{"id":"a","name":"甲"}]},
+ "composition":[{"name":"步兵", "percentage":60}], "players":[{"id":view["player"]["id"],"name":"甲","elo_before":1500}]},
{"name":"B 队", "metrics":[{"label":"击杀", "value":227,"format":"integer"}],
- "composition":[{"name":"装甲", "percentage":40}], "players":[{"id":"b","name":"乙"}]},
+ "composition":[{"name":"装甲", "percentage":40}], "players":[{"id":"b","name":"乙","elo_before":1400}]},
])
renderer = Renderer()
html = renderer.template(view)
assert html.index("赛前预测") < html.index("兵种构成") < html.index("双方对比") < html.index("队伍玩家") < html.index('class="team"')
assert 'class="match-columns"' in html
+ assert html.count("") == 1 and html.count('') == 2
+ assert html.count('class="participant target"') == 1
for output in (renderer.text(view), VisibleHTML(html).text):
- for value in ("64.00%", "36.00%", "234", "227", "步兵", "60.00%", "甲", "乙"):
+ for value in ("64%", "36%", "234", "227", "步兵", "60%", "甲", "乙", "查询玩家"):
assert value in output
assert "timeance/astrbot_plugin_BA_stats" in html and "数据来源 BATracer" in html
assert "data:image/svg+xml;base64," in html
@@ -378,59 +437,91 @@ def test_comparison_uses_one_continuous_bar_and_raw_denominator(view, values, ex
{"name": name, "metrics": [{"label": "伤害", "value": value}]}
for name, value in zip(("A 队", "B 队"), values)
])
- html = Renderer().template(view)
+ renderer = Renderer()
+ html = renderer.template(view)
tags = VisibleHTML(html).tags
tracks = [attrs for tag, attrs in tags if "comparison-track" in attrs.get("class", "").split()]
segments = [attrs for tag, attrs in tags if "segment" in attrs.get("class", "").split()]
- assert len(tracks) == 1
if expected is None:
- assert segments == [] and "no-comparison" in tracks[0]["class"]
+ assert not tracks and not segments
else:
+ assert len(tracks) == 1
widths = [float(attrs["style"].removeprefix("width:").removesuffix("%")) for attrs in segments]
assert widths == pytest.approx([expected, 100 - expected])
assert [attrs["class"] for attrs in segments] == ["segment side-a", "segment side-b"]
if None in values:
- assert "暂无" in tracks[0]["aria-label"]
+ assert f"伤害:{' / '.join('暂无' if value is None else str(value) for value in values)}" in renderer.text(view)
elif values == (0, 0):
- assert "A 队 0,B 队 0" in tracks[0]["aria-label"]
+ assert "伤害:0 / 0" in renderer.text(view)
+
+
+def test_partial_team_metric_keeps_values_and_coverage_but_has_no_bar(view):
+ view.update(kind="match", teams=[
+ {"id": "1", "name": "B 队", "metrics": [{"label": "伤害", "value": 40, "complete": True}]},
+ {"id": "0", "name": "A 队", "metrics": [{"label": "伤害", "value": 0, "complete": False, "note": "1/2 人有数据"}]},
+ ])
+ renderer = Renderer()
+ parsed = VisibleHTML(renderer.template(view))
+ assert not any(attrs.get("class") == "comparison-track" for _, attrs in parsed.tags)
+ assert "1/2 人有数据" in parsed.text
+ assert "伤害:0(1/2 人有数据) / 40" in renderer.text(view)
+
+
+@pytest.mark.parametrize("b_size,b_rating,roster_complete", [(0, 1700, None), (1, 1700, None), (2, None, None), (2, 1700, False)])
+def test_prediction_needs_equal_formal_rosters_and_all_ratings(view, b_size, b_rating, roster_complete):
+ spectator = {"id": "4", "name": "观战", "players": [{"name": "观战者", "elo_before": 1700}] * 2,
+ "metrics": [{"label": "伤害", "value": 987654}]}
+ team_a = {"id": "0", "name": "A 队", "players": [{"name": "A 玩家", "elo_before": 1550}] * 2,
+ "metrics": [{"label": "伤害", "value": 37}]}
+ teams = [spectator, team_a]
+ if b_size:
+ teams.insert(0, {"id": "1", "name": "B 队", "players": [{"name": "B 玩家", "elo_before": b_rating}] * b_size})
+ scope = "单局 · 详情收录 5 人 · 近期名单 7 人"
+ view.update(kind="match", teams=teams, prediction={"a": 60, "b": 40},
+ match={"roster_complete": roster_complete}, scope=scope)
+ renderer = Renderer()
+ html = renderer.template(view)
+ assert 'class="prediction-bar"' not in html
+ for output in (VisibleHTML(html).text, renderer.text(view)):
+ assert "暂无可用预测" in output and scope in output
+ assert "观战者" in output and "987654" not in output and "60%" not in output
+ assert "伤害:37 / 暂无" in renderer.text(view)
def test_composition_compares_each_original_share_with_one_shared_bar(view):
view.update(kind="match", teams=[
{"name": "A 队", "composition": [{"name": "装甲", "percentage": 40}, {"name": "步兵", "percentage": 60}]},
- {"name": "B 队", "composition": [{"name": "装甲", "percentage": 20}, {"name": "步兵", "percentage": 30}]},
+ {"name": "B 队", "composition": [{"name": "装甲", "percentage": 20}, {"name": "步兵", "percentage": 80}]},
])
html = Renderer().template(view)
tags = VisibleHTML(html).tags
- tracks = [attrs for _, attrs in tags if attrs.get("role") == "img"]
+ tracks = [attrs for _, attrs in tags if attrs.get("class") == "comparison-track"]
segments = [attrs for _, attrs in tags if "role-a" in attrs.get("class", "") or "role-b" in attrs.get("class", "")]
assert len(tracks) == 2 and len(segments) == 4
assert [attrs["class"] for attrs in segments] == ["segment role-armor role-a", "segment role-armor role-b",
"segment role-infantry role-a", "segment role-infantry role-b"]
widths = [float(attrs["style"].removeprefix("width:").removesuffix("%")) for attrs in segments]
- assert widths == pytest.approx([100 * 40 / 60, 100 * 20 / 60, 100 * 60 / 90, 100 * 30 / 90])
- assert "A 队 40.00%,B 队 20.00%" in tracks[0]["aria-label"]
- assert "A 队 60.00%,B 队 30.00%" in tracks[1]["aria-label"]
- assert "左 A 队(深)· 右 B 队(浅)" in VisibleHTML(html).text
- assert "composition-stack" not in html
+ assert widths == pytest.approx([100 * 40 / 60, 100 * 20 / 60, 100 * 60 / 140, 100 * 80 / 140])
+ assert "装甲:40% / 20%" in Renderer().text(view)
+ assert "步兵:60% / 80%" in Renderer().text(view)
+ assert "左A队(深)右B队(浅)" in compact(VisibleHTML(html).text)
@pytest.mark.parametrize("a,b,expected", [(0, 0, None), (None, 20, None), (20, None, None), (0, 20, 0)])
def test_composition_distinguishes_zero_and_missing_share(view, a, b, expected):
view.update(kind="match", teams=[
- {"name": name, "composition": [{"name": "装甲", "percentage": value}]}
+ {"name": name, "composition": [{"name": "装甲", "percentage": value}] +
+ ([{"name": "步兵", "percentage": 100 - value}] if value is not None else [])}
for name, value in zip(("A 队", "B 队"), (a, b))
])
tags = VisibleHTML(Renderer().template(view)).tags
- segments = [attrs for _, attrs in tags if "segment" in attrs.get("class", "").split()]
- track = next(attrs for _, attrs in tags if attrs.get("role") == "img")
+ segments = [attrs for _, attrs in tags if "role-armor" in attrs.get("class", "").split()]
if expected is None:
- assert not segments and "no-comparison" in track["class"]
+ assert not segments
else:
assert float(segments[0]["style"].removeprefix("width:").removesuffix("%")) == expected
- assert ("暂无" in track["aria-label"]) is (a is None or b is None)
- if a == b == 0:
- assert "A 队 0.00%,B 队 0.00%" in track["aria-label"]
+ expected_values = " / ".join(f"{value}%" if value is not None else "暂无" for value in (a, b))
+ assert f"装甲:{expected_values}" in Renderer().text(view)
def test_only_complete_composition_can_supply_an_omitted_zero_category(view):
@@ -438,9 +529,10 @@ def test_only_complete_composition_can_supply_an_omitted_zero_category(view):
{"name": "A 队", "composition": [{"name": "步兵", "percentage": 100}]},
{"name": "B 队", "composition": [{"name": "装甲", "percentage": 30}]},
])
- tracks = [attrs for _, attrs in VisibleHTML(Renderer().template(view)).tags if attrs.get("role") == "img"]
- assert "A 队 0.00%,B 队 30.00%" in tracks[0]["aria-label"]
- assert "A 队 100.00%,B 队 暂无" in tracks[1]["aria-label"]
+ renderer = Renderer()
+ assert not any(attrs.get("class") == "comparison-track" for _, attrs in VisibleHTML(renderer.template(view)).tags)
+ text = renderer.text(view)
+ assert "装甲:0% / 30%" in text and "步兵:100% / 暂无" in text
def test_unknown_composition_is_not_rendered_as_zero_or_renormalized(view):
diff --git a/tests/test_report_data.py b/tests/test_report_data.py
index 6695148..6521840 100644
--- a/tests/test_report_data.py
+++ b/tests/test_report_data.py
@@ -63,15 +63,18 @@ def metrics(view):
return {metric["label"]: metric for metric in view["metrics"]}
-async def test_overview_separates_analysis_denominator_recent_values_and_single_match_dmr(report):
+async def test_overview_uses_distinct_results_and_pairs_damage_in_the_recent_window(report):
player = report.player({"matchCount": 80, "trend": {"points": [
{"matchId": "win", "won": True, "dmr": 2.5, "endTime": "2026-11-16T00:00:00Z"},
{"matchId": "loss", "won": False, "dmr": 9, "endTime": "2026-11-15T00:00:00Z"},
{"matchId": "unknown", "endTime": "2026-11-14T00:00:00Z"},
{"matchId": "analysis-only", "won": True},
+ {"won": False},
]}})
matches = [recent(report, "win"), recent(report, "loss", destroyed=200, lost=75),
recent(report, "unmatched", destroyed=None, lost=999)]
+ for match, (dealt, received) in zip(matches, [(100, 20), (20, 40), (990, None)]):
+ match.players[0].damage_dealt, match.players[0].damage_received = dealt, received
original_player, original_matches = deepcopy(player), deepcopy(matches)
view = await report.run(player, matches)
data = metrics(view)
@@ -81,7 +84,10 @@ async def test_overview_separates_analysis_denominator_recent_values_and_single_
dims = {axis["key"]: axis["value"] for axis in view["profile_rating"]["dimensions"]}
assert dims["win_rate"] == 50 # Only the win and loss are in the recent sample.
assert dims["outcome"] is None # Team ELO is missing, but the actual outcomes are known.
- assert data["单局伤害交换比"]["value"] == 2.5
+ assert data["近期伤害交换比"]["value"] == 2 # (100 + 20) / (20 + 40), not the last match's dmr.
+ assert data["近期伤害交换比"]["sample_size"] == 2
+ assert data["分析样本胜率"]["sample_size"] == 3
+ assert view["profile_rating"]["win_rate_sample"] == {"wins": 1, "losses": 1, "sample_size": 2, "value": 50}
assert view["style_scope"] == "近80场风格"
assert view["scope"] == "近期3场 · 11-17—11-17"
assert [row["outcome"] for row in view["rows"]] == ["win", "loss", "unknown"]
@@ -149,7 +155,8 @@ async def test_analysis_empty_lists_remain_empty_without_inventing_statistics(re
assert view["common_units"] == view["map_stats"] == view["categories"] == []
assert metrics(view)["近期分值 K/D"]["value"] is None
assert metrics(view)["分析样本胜率"]["value"] is None
- assert metrics(view)["单局伤害交换比"]["value"] is None
+ assert "单局伤害交换比" not in metrics(view)
+ assert "近期伤害交换比" not in metrics(view)
assert view["style_scope"] == "近0场风格"
assert view["rows"][0]["map_name"] == "地图#20"
@@ -192,12 +199,13 @@ def test_match_team_metrics_sum_known_values_show_coverage_and_leave_missing_out
first = {item["label"]: item for item in view["teams"][0]["metrics"]}
assert {key: item["value"] for key, item in first.items()} == {
"摧毁分": 350, "损失分": 100, "赛后平均 ELO": 1100, "击杀": 5, "阵亡": 1, "伤害": 500,
- "出兵花费": 1000, "占点": 0, "补给": 10,
+ "出动价值": 1000, "占点": 0, "补给": 10,
}
assert first["伤害"]["note"] == "1/2 人有数据"
- assert first["出兵花费"]["note"] == first["占点"]["note"] == first["补给"]["note"] == "1/2 人有数据"
+ assert first["出动价值"]["note"] == first["占点"]["note"] == first["补给"]["note"] == "1/2 人有数据"
assert view["teams"][1]["metrics"] == []
a, b = view["teams"][0]["players"]
+ assert a["damage_exchange"] == "无承伤"
assert (a["damage_dealt"], a["damage_received"], a["objectives"], a["spawned_value"], a["supply"]) == (500, 0, 0, 1000, 10)
assert (b["damage_dealt"], b["damage_received"], b["objectives"], b["spawned_value"], b["supply"]) == (None,) * 5
@@ -268,7 +276,7 @@ async def test_overview_renders_aggregate_and_separate_observed_win_rate(report)
assert (rating["score"], rating["title"]) == (7.9, "有龙样")
assert [axis["value"] for axis in rating["dimensions"]] == [91, 53, 53, 92, 100]
for output in (Renderer().template(view), Renderer().text(view)):
- assert all(term in output for term in ("7.9", "有龙样", "胜负预期", "胜率", "100%"))
+ assert all(term in output for term in ("7.9", "有龙样", "赛果超预期", "胜率"))
report.client.match.assert_not_awaited()
@@ -288,7 +296,7 @@ def test_match_prediction_composition_and_a_b_order_reach_both_renderers(report)
assert "1 人缺单位数据" in view["teams"][2]["composition_note"]
renderer = Renderer()
for output in (renderer.template(view), renderer.text(view)):
- assert "35.99%" in output and "64.01%" in output
+ assert "36%" in output and "64%" in output
assert "装甲" in output and "步兵" in output
assert output.index("A 队") < output.index("B 队")
assert match == before
diff --git a/tests/test_scoring.py b/tests/test_scoring.py
index ecb6cd6..9f7f36a 100644
--- a/tests/test_scoring.py
+++ b/tests/test_scoring.py
@@ -139,9 +139,50 @@ def test_missing_teammate_financials_or_opponent_elo_do_not_make_up_a_score():
{"highlightUnits": [{"unitId": 13, "totalCost": 2000}]},
{"highlightUnits": [{"unitId": 13, "categoryType": 2}]},
])
-def test_incomplete_career_spend_is_unknown_not_percentage_substitution(analysis):
+def test_incomplete_career_spend_uses_the_prior_without_substituting_percentages(analysis):
match = normalized()
- assert recent_score(match, match.players[0], analysis) is None
+ assert recent_score(match, match.players[0], analysis) == recent_score(match, match.players[0], {}) == 9.9
+
+
+def test_partial_role_observations_keep_the_usable_spend():
+ match = normalized()
+ partial = deepcopy(SUPPORT_ANALYSIS)
+ partial["highlightUnits"].extend([
+ {"unitId": 13, "totalCost": 99999}, {"unitId": 57, "categoryType": 1},
+ ])
+ partial["categoryPreferences"].append({"categoryKey": "vehicles", "percentage": 100})
+ assert recent_score(match, match.players[0], partial) == 8.6
+
+
+def test_explicit_loss_overrides_positive_elo_and_conflict_blocks_the_fallback():
+ match = normalized()
+ me = match.players[0]
+ loss = {"matchId": match.id, "won": False}
+ analysis = {"trend": {"points": [loss, {"matchId": match.id}, loss]}}
+ assert recent_score(match, me, analysis) == 9.5
+ expected = profile_rating([match], me.player_id, analysis)
+ assert expected["sample_size"] == 1
+ assert expected["win_rate_sample"] == {"value": 0, "sample_size": 1, "wins": 0, "losses": 1}
+ for other in match.players[1:]:
+ other.elo = other.elo_delta = None
+ assert recent_score(match, me, analysis) == 9.5
+ assert profile_rating([match], me.player_id, analysis) == expected
+ analysis["trend"]["points"].append({**loss, "won": True})
+ assert recent_score(match, me, analysis) is None
+ blocked = profile_rating([match], me.player_id, analysis)
+ assert blocked["sample_size"] == blocked["win_rate_sample"]["sample_size"] == 0
+
+
+@pytest.mark.parametrize("post_elo", [1900, 1900.005, None])
+def test_explicit_win_does_not_admit_a_match_without_a_valid_elo_change(post_elo):
+ match = normalized()
+ me = match.players[0]
+ me.elo = post_elo
+ analysis = {"trend": {"points": [{"matchId": match.id, "won": True}]}}
+ assert recent_score(match, me, analysis) is None
+ profile = profile_rating([match], me.player_id, analysis)
+ assert profile["score"] is None and profile["sample_size"] == 0
+ assert profile["win_rate_sample"] == {"value": 100, "sample_size": 1, "wins": 1, "losses": 0}
def test_unrated_spectator_foreign_participant_and_missing_opposition_have_no_score():
@@ -193,6 +234,8 @@ def test_prediction_accepts_old_rating_without_new_rating_and_ignores_spectators
match.players.insert(0, Participant("observer", "Observer", team="2"))
match.players.reverse()
assert match_prediction(match) == expected
+ match.players = [p for p in match.players if p.player_id != "d"]
+ assert match_prediction(match) is None # Both sides exist, but one roster is short.
match.players = [p for p in match.players if p.team != "1"]
assert match_prediction(match) is None
assert match_prediction(Match("empty")) is None
@@ -290,13 +333,14 @@ def test_profile_matches_pinned_compute_dragon_score(indices, analysis, expected
raws = profile_sample()
matches = [parse_match({"matchInfo": raws[i]}, str(i)) for i in indices]
before = deepcopy(matches)
- profile = profile_rating(matches, "a", analysis, 0)
+ profile = profile_rating(matches, "a", analysis)
score, title, tone, parts = expected
assert profile == {
"score": score, "title": title, "tone": tone, "sample_size": len(matches),
+ "win_rate_sample": {"value": None, "sample_size": 0, "wins": 0, "losses": 0},
"dimensions": [dict(key=key, label=label, value=value) for key, label, value in zip(
("kd", "contrib", "obj", "outcome", "win_rate"),
- ("分值 K/D", "摧毁贡献", "占点贡献", "胜负预期", "实际胜率"), [*parts, 0])],
+ ("交换效率", "摧毁贡献", "夺点表现", "赛果超预期", "实际胜率"), [*parts, None])],
}
assert matches == before
@@ -313,47 +357,58 @@ def test_profile_caps_newest_valid_rows_after_normalizing_match_order():
}})
matches = parse_recent({"matches": raws[::2] + raws[1::2]})
assert [m.id for m in matches] == [str(i) for i in range(21, -1, -1)]
- profile = profile_rating(matches, "a", {}, None)
+ profile = profile_rating(matches, "a", {})
assert (profile["score"], profile["title"], profile["sample_size"]) == (10, "真龙", 20)
assert [d["value"] for d in profile["dimensions"]] == [99, 99, 83, 95, None]
+def test_win_rate_uses_newest_twenty_distinct_matches_independently_of_score():
+ matches = [Match(str(i), players=[Participant("a", "A", team="0")]) for i in range(21)]
+ analysis = {"trend": {"points": [
+ {"matchId": 0, "won": False}, {"matchId": 19, "won": True}, {"matchId": 20, "won": True},
+ ]}}
+ profile = profile_rating([matches[0], *matches], "a", analysis)
+ assert profile["score"] is None and profile["sample_size"] == 0
+ assert profile["dimensions"][-1]["value"] == 50
+ assert profile["win_rate_sample"] == {"value": 50, "sample_size": 2, "wins": 1, "losses": 1}
+
+
def test_missing_objectives_omit_only_unobserved_parts_and_never_supply_a_win():
short, _, afk = profile_sample()
short["Data"]["c"].pop("ObjectivesCaptured")
latest = parse_match({"matchInfo": short}, "latest")
earlier = parse_match({"matchInfo": afk}, "earlier")
- single = profile_rating([latest], "a", FRONT_ANALYSIS, None)
+ single = profile_rating([latest], "a", FRONT_ANALYSIS)
assert single["score"] == 7.8
assert [d["value"] for d in single["dimensions"]] == [100, 98, None, 95, None]
# Missing objectives for an inactive ally do not affect the active-team comparison.
- earlier_obj = profile_rating([earlier], "a", FRONT_ANALYSIS, None)["dimensions"][2]["value"]
+ earlier_obj = profile_rating([earlier], "a", FRONT_ANALYSIS)["dimensions"][2]["value"]
assert earlier_obj is not None
- both = profile_rating([latest, earlier], "a", FRONT_ANALYSIS, None)
+ both = profile_rating([latest, earlier], "a", FRONT_ANALYSIS)
assert both["sample_size"] == 2 and both["dimensions"][2]["value"] == earlier_obj
- empty = profile_rating([latest], "absent", {}, 100)
+ empty = profile_rating([latest], "absent", {"trend": {"points": [{"matchId": "latest", "won": True}]}})
assert (empty["sample_size"], empty["score"], empty["title"], empty["tone"]) == (0, None, None, None)
- assert [d["value"] for d in empty["dimensions"]] == [None, None, None, None, 100]
+ assert [d["value"] for d in empty["dimensions"]] == [None] * 5
def test_profile_distinguishes_explicit_zero_from_unknown_values():
raw = raw_match()
for player in raw["Data"].values():
player.update(DestructionScore=0, LossesScore=0, ObjectivesCaptured=0)
- zero = profile_rating([normalized(raw)], "a", {}, 0)
+ zero = profile_rating([normalized(raw)], "a", {})
# The TS oracle still scores the explicit zeros and returns an objective percentile.
assert (zero["score"], zero["title"], zero["sample_size"]) == (7.2, "泯然众人", 1)
- assert [d["value"] for d in zero["dimensions"]] == [61, 58, 54, 86, 0]
+ assert [d["value"] for d in zero["dimensions"]] == [61, 58, 54, 86, None]
raw["Data"]["a"].pop("DestructionScore") # Protobuf omits zero counters.
- assert profile_rating([normalized(raw)], "a", {}, 0) == zero
+ assert profile_rating([normalized(raw)], "a", {}) == zero
raw["Data"]["a"].pop("ObjectivesCaptured")
- missing = profile_rating([normalized(raw)], "a", {}, None)
+ missing = profile_rating([normalized(raw)], "a", {})
assert missing["score"] == zero["score"]
assert [d["value"] for d in missing["dimensions"]] == [61, 58, None, 86, None]
raw["Data"]["a"]["DestructionScore"] = None
- incomplete = profile_rating([normalized(raw)], "a", {}, 0)
+ incomplete = profile_rating([normalized(raw)], "a", {})
assert incomplete["score"] is None and incomplete["sample_size"] == 0
- assert [d["value"] for d in incomplete["dimensions"]] == [None, None, None, None, 0]
+ assert [d["value"] for d in incomplete["dimensions"]] == [None] * 5
def test_bundled_model_has_pinned_source_and_complete_mit_notice_without_match_awards():
diff --git a/tests/test_service.py b/tests/test_service.py
index bbb0bc3..1c8b52f 100644
--- a/tests/test_service.py
+++ b/tests/test_service.py
@@ -400,6 +400,87 @@ def handler(request):
await client.close()
+@pytest.mark.parametrize("case", ["missing", "wrong_team", "detail_superset"])
+async def test_last_checks_the_known_roster_on_each_side(h, case):
+ from render import Renderer
+
+ def player(pid, team, elo, points):
+ return {"Id": pid, "Name": f"Player {pid}", "TeamId": team, "OldRating": elo, "NewRating": elo + 10,
+ "DestructionScore": points, "UnitData": {"u": {"Id": 13}}}
+
+ a1, a2 = player("001", 0, 2500, 1000), player("003", 0, 1700, 8000)
+ b1, b2 = player("002", 1, 1700, 2000), player("004", 1, 2500, 1000)
+ observer = player("005", 4, 2000, 99999)
+ listed = [a1, b1, observer] if case == "detail_superset" else [a1, a2, b1, b2, observer]
+ shown = {
+ "missing": [a1, b1],
+ "wrong_team": [a1, b1, dict(a2, TeamId=1), dict(b2, TeamId=0)],
+ "detail_superset": [a1, a2, b1, b2],
+ }[case]
+
+ def match_data(players):
+ return {"StartTime": 1700000000, "EndTime": 1700001200,
+ "Data": {p["Id"]: p for p in players}}
+
+ responses = {
+ "/api/players/search": {"players": [{"id": "001", "name": "Synthetic Player"}]},
+ "/api/analysis/player": {"matchCount": 1, "trend": {"points": [{"matchId": "42", "won": True}]}},
+ "/api/players/matches": {"matches": [{"matchId": "42", "data": match_data(listed)}]},
+ "/api/match": {"matchInfo": match_data(shown)},
+ }
+ requests = []
+
+ def handler(request):
+ requests.append((request.url.path, dict(request.url.params)))
+ return httpx.Response(200, json=responses[request.url.path])
+
+ c = h.modules.client
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ client = c.BatraceClient(c.ClientConfig(
+ enabled=True, base_url="https://example.invalid", request_interval=0, retries=0,
+ ), storage=h.storage, http_client=http)
+ h.service.client = client
+ try:
+ view = (await h.run("last stb:001")).view
+ finally:
+ await client.close()
+
+ assert requests == [
+ ("/api/players/search", {"q": "001", "limit": "20"}),
+ ("/api/analysis/player", {"stbid": "001"}),
+ ("/api/players/matches", {"stbid": "001", "limit": "20"}),
+ ("/api/match", {"matchid": "42"}),
+ ]
+ assert view["match"]["target_outcome"] == "win"
+ assert view["scope"].startswith(f"单局 · 实际收录 {len(shown)} 名玩家")
+ for team in view["teams"]:
+ members = [p for p in shown if str(p["TeamId"]) == team["id"]]
+ assert {p["id"] for p in team["players"]} == {p["Id"] for p in members}
+ destroyed = next(metric for metric in team["metrics"] if metric["key"] == "destroyed_value")
+ assert destroyed["value"] == sum(p["DestructionScore"] for p in members)
+ assert destroyed["observed_count"] == destroyed["participant_count"] == len(members)
+
+ renderer = Renderer()
+ html, text = renderer.template(view), renderer.text(view)
+ if case == "detail_superset":
+ assert view["match"].get("roster_complete") is not False
+ assert view["prediction"] == {"a": 50, "b": 50}
+ assert 'class="comparison-track"' in html and "A 队 50%" in text
+ assert "同场已知名单覆盖" not in view["scope"]
+ else:
+ assert view["match"]["roster_complete"] is False
+ assert view["match"]["roster_coverage"] == {
+ team_id: {"matched": 1, "known": 2} for team_id in ("0", "1")
+ }
+ assert view["prediction"] is None
+ assert 'class="comparison-track"' not in html and 'class="prediction-bar"' not in html
+ for output in (html, text):
+ assert "同场已知名单覆盖:A 1/2、B 1/2" in output
+ assert "暂无可用预测" in output
+ a_points, b_points = (1000, 2000) if case == "missing" else (2000, 10000)
+ assert f"摧毁分:{a_points} / {b_points}" in text
+
+
async def test_empty_recent_rosters_remain_unavailable_without_identity_errors(h):
h.client.recent.return_value = h.result([h.m.Match("empty")])
assert (await h.run("recent stb:001")).view["rows"] == []
@@ -462,6 +543,8 @@ async def test_overview_uses_actual_sample_and_known_outcomes_only(h):
"search": {"players": [{"id": "001", "name": "Synthetic"}]},
"analysis": {"matchCount": 30, "trend": {"points": [
{"matchId": "0", "won": True}, {"matchId": "1", "won": False}, {"matchId": "2"},
+ {"matchId": "0", "won": True}, {"matchId": "3", "won": True},
+ {"matchId": "3", "won": False}, {"won": False}, {"matchId": "analysis-only", "won": True},
]}},
}, "001").analysis
h.client.recent.return_value = h.result([
@@ -472,12 +555,111 @@ async def test_overview_uses_actual_sample_and_known_outcomes_only(h):
metrics = {item["label"]: item for item in view["metrics"]}
assert len(view["rows"]) == 3
assert [row["outcome"] for row in view["rows"]] == ["win", "loss", "unknown"]
- assert metrics["分析样本胜率"]["value"] == 50
+ analysis_rate = metrics["分析样本胜率"]
+ assert analysis_rate["value"] == pytest.approx(200 / 3)
+ assert (analysis_rate["sample_size"], analysis_rate["wins"], analysis_rate["losses"]) == (3, 2, 1)
+ rating = view["profile_rating"]
+ assert rating["sample_size"] == 0
+ assert rating["win_rate_sample"] == {"value": 50, "sample_size": 2, "wins": 1, "losses": 1}
assert view["scope"] == "近期3场"
assert view["style_scope"] == "近30场风格"
assert view["stale"] is True
+async def test_recent_and_last_keep_analysis_authority_separate_from_scoring_inference(h):
+ h.player.analysis = h.m.parse_player({
+ "search": {"players": [{"id": h.player.id}]},
+ "analysis": {"trend": {"points": [
+ {"matchId": "loss", "won": False}, {"matchId": "loss", "won": False},
+ {"matchId": "conflict", "won": True}, {"matchId": "conflict", "won": False},
+ {"matchId": "inferred"}, {"matchId": "unrated", "won": True}, {"won": True},
+ ]}},
+ }, h.player.id).analysis
+
+ def match(mid):
+ return h.m.parse_match({"matchInfo": {"Data": {
+ "a": {"Id": h.player.id, "OldRating": 2000, "NewRating": 2000 if mid == "unrated" else 2010,
+ "DestructionScore": 2000, "LossesScore": 1000},
+ "b": {"Id": "002", "TeamId": 1, "OldRating": 2100, "NewRating": 2090,
+ "DestructionScore": 1000, "LossesScore": 2000},
+ }}}, mid)
+
+ matches = [match(mid) for mid in ("loss", "conflict", "inferred", "unrated")]
+ h.client.recent.return_value = h.result(matches)
+ recent = (await h.run("recent stb:001")).view["rows"]
+ assert [(row["outcome"], row["outcome_source"], row["outcome_conflict"], row["score_outcome_source"])
+ for row in recent] == [
+ ("loss", "analysis", False, "analysis"),
+ ("unknown", None, True, None),
+ ("unknown", None, False, "elo_delta"),
+ ("win", "analysis", False, None),
+ ]
+ assert recent[0]["score"] < recent[2]["score"]
+ assert recent[1]["score"] is recent[3]["score"] is None
+ rating = (await h.run("stats stb:001")).view["profile_rating"]
+ assert rating["sample_size"] == 2 # Explicit loss and Elo inference.
+ assert rating["win_rate_sample"] == {"value": 50, "sample_size": 2, "wins": 1, "losses": 1}
+ h.client.match.assert_not_awaited()
+
+ h.client.match.return_value = h.result(matches[0])
+ detail = (await h.run("last stb:001")).view
+ assert detail["match"]["target_outcome"] == "loss"
+ assert detail["match"]["target_outcome_source"] == "analysis"
+ assert detail["match"]["winner"] is None
+ assert all(team["outcome"] == "unknown" for team in detail["teams"])
+ assert detail["teams"][1]["players"][0]["outcome"] == "unknown"
+ h.client.match.assert_awaited_once_with("loss")
+
+
+async def test_damage_exchange_uses_recent_complete_pairs_and_analysis_dmr_only_in_matching_detail(h):
+ h.player.analysis = {"trend": {"points": [
+ {"matchId": "other", "dmr": 99}, {"matchId": "partial", "dmr": 3.5},
+ ]}}
+ matches = [
+ h.m.Match(mid, players=[h.m.Participant(h.player.id, "A", team="0",
+ damage_dealt=dealt, damage_received=received)])
+ for mid, dealt, received in (("partial", 5000, None), ("first", 300, 100), ("second", 100, 300))
+ ]
+ h.client.recent.return_value = h.result(matches)
+ overview = (await h.run("stats stb:001")).view
+ damage = next(metric for metric in overview["metrics"] if metric["label"] == "近期伤害交换比")
+ assert damage == {"label": "近期伤害交换比", "value": 1, "sample_size": 2,
+ "window_size": 3, "note": "2/3 场有数据"}
+ h.client.recent.return_value = h.result(matches[:1])
+ overview = (await h.run("stats stb:001")).view
+ assert not any("伤害交换比" in metric["label"] for metric in overview["metrics"])
+ h.client.match.assert_not_awaited()
+
+ raw, fallback, unrelated = (
+ h.modules.service.match_view(h.result(match), h.player)["match"]
+ for match in (matches[1], matches[0], h.m.Match("unrelated", players=matches[0].players))
+ )
+ for detail, value, source in ((raw, 3, "match"), (fallback, 3.5, "analysis"), (unrelated, None, None)):
+ assert (detail["target_damage_exchange"], detail["target_damage_exchange_source"]) == (value, source)
+
+
+def test_team_comparisons_use_only_both_playing_teams_and_expose_partial_coverage(modules):
+ m = modules.models
+ observer = m.Participant("obs", "Observer", team="4", damage_dealt=99999)
+ a1 = m.Participant("a1", "A1", team="0", damage_dealt=0)
+ a2 = m.Participant("a2", "A2", team="0")
+ b = m.Participant("b", "B", team="1", damage_dealt=400)
+ match = m.Match("sample", players=[observer, b, a1, a2], winner_team="0")
+ view = modules.service.match_view(m.FetchResult(match, NOW))
+ assert [team["id"] for team in view["teams"]] == ["0", "1", "4"]
+ assert view["comparison_team_ids"] == ["0", "1"]
+ a, b_metric = [next(metric for metric in team["metrics"] if metric["key"] == "damage_dealt")
+ for team in view["teams"][:2]]
+ assert (a["value"], a["observed_count"], a["participant_count"], a["complete"], a["note"]) == (
+ 0, 1, 2, False, "1/2 人有数据")
+ assert (b_metric["value"], b_metric["complete"]) == (400, True)
+ assert view["teams"][2]["outcome"] == "unknown"
+ match.players.remove(b)
+ view = modules.service.match_view(m.FetchResult(match, NOW))
+ assert view["comparison_team_ids"] == []
+ assert view["teams"][-1]["players"][0]["id"] == "obs"
+
+
async def test_service_real_client_pipeline_sorts_and_deduplicates_recent_samples(h, monkeypatch):
c = h.modules.client
client = c.BatraceClient(c.ClientConfig(
diff --git a/tools/render_previews.py b/tools/render_previews.py
index 5e25412..214c360 100644
--- a/tools/render_previews.py
+++ b/tools/render_previews.py
@@ -25,7 +25,7 @@
sys.dont_write_bytecode = True
REPOSITORY = Path(__file__).resolve().parents[1]
SESSION = REPOSITORY.parent
-OUTPUT = SESSION / "tmp" / "overview-v015" / "previews"
+OUTPUT = SESSION / "tmp" / "report-readability" / "previews"
sys.path.insert(0, str(REPOSITORY))
from render import Renderer
@@ -44,18 +44,20 @@ def sample_views() -> dict[str, dict]:
"synthetic": True,
}
overview = deepcopy(base)
+ overview["player"]["analysis"] = {"matchCount": 83}
overview.update(
kind="overview",
+ scope="近期12场 · 11-06—11-17",
metrics=[
{"label": "ELO", "value": 1854.02},
{"label": "近期分值 K/D", "value": 1.42},
- {"label": "分析样本胜率", "value": 40, "format": "percent"},
- {"label": "单局伤害交换比", "value": 1.3},
+ {"label": "分析样本胜率", "value": 40, "format": "percent", "wins": 20, "sample_size": 50},
+ {"label": "近期伤害交换比", "value": 1.3, "note": "8/10 场有数据"},
],
profile_rating={"score": 5.8, "title": "泯然众人", "tone": "medium", "sample_size": 4,
- "dimensions": [{"key": key, "label": label, "value": value} for key, label, value in
- (("kd", "分值 K/D", 37), ("contrib", "摧毁贡献", 59), ("obj", "占点贡献", 30),
- ("outcome", "胜负预期", 51), ("win_rate", "实际胜率", 60))]},
+ "win_rate_sample": {"value": 60, "wins": 6, "losses": 4, "sample_size": 10, "window_size": 12},
+ "dimensions": [{"key": key, "value": value} for key, value in
+ (("kd", 37), ("contrib", 59), ("obj", 30), ("outcome", 51), ("win_rate", 60))]},
common_units=[{"name": "Tu-95", "count": 72, "damage": 11682.87, "roi": 1.62},
{"name": "Mi-8AMTSh-VN Sapsan", "count": 165, "damage": 7074.14, "roi": .37}],
style_scope="近83场风格", categories=[{"name": name, "percentage": value} for name, value in
@@ -85,17 +87,17 @@ def sample_views() -> dict[str, dict]:
"started_at": "2026-11-17T02:20:00Z", "duration_seconds": 2700, "winner": "A 队", "target_outcome": "win"},
prediction={"a": 50, "b": 50},
teams=[
- {"name": name, "outcome": "win" if side == 0 else "loss",
+ {"id": str(side), "name": name, "outcome": "win" if side == 0 else "loss",
"metrics": [{"label": label, "value": values[side], "format": "decimal" if label == "赛后平均 ELO" else "integer"}
for label, values in [("摧毁分", (32960, 31000)), ("损失分", (31000, 32960)),
("赛后平均 ELO", (1833.25, 1816.75)), ("击杀", (234, 227)), ("阵亡", (227, 234)),
- ("伤害", (4983, 6480)), ("出兵花费", (40200, 43450)),
+ ("伤害", (4983, 6480)), ("出动价值", (40200, 43450)),
("占点", (15, 16)), ("补给消耗", (62685, 82319))]],
"composition": [{"name": role, "percentage": percentages[side]}
for role, percentages in [("装甲", (20, 17)), ("步兵", (13, 13)), ("侦察", (10, 8)),
("炮兵", (5, 7)), ("防空", (17, 19)), ("直升机", (10, 15)),
("固定翼", (24, 20)), ("后勤/运输", (1, 1))]],
- "composition_note":"合成样本", "players": [
+ "players": [
{"id": base["player"]["id"] if side == 0 and index == 1 else f"sample-{side}-{index}",
"name": match["player"]["name"] if side == 0 and index == 1 else f"合成队员 {side + 1}-{index + 1}",
"elo_before": 1800 + index * 12.5,
@@ -134,10 +136,13 @@ def sample_views() -> dict[str, dict]:
source_url=None, source_updated_at=None, stale=True, scope="已取得样本 · 覆盖范围暂无")
if kind == "overview":
missing["metrics"] = [dict(metric, value=None) for metric in overview["metrics"]]
+ missing["metrics"][2].update(wins=0, sample_size=0)
missing["profile_rating"] = deepcopy(overview["profile_rating"])
- missing["profile_rating"].update(score=None, title=None, tone=None, sample_size=0)
+ missing["profile_rating"].update(score=None, title=None, tone=None, sample_size=0,
+ win_rate_sample={"value": 0, "wins": 0, "losses": 5,
+ "sample_size": 5, "window_size": 8})
for axis in missing["profile_rating"]["dimensions"]:
- axis["value"] = 0 if axis["key"] == "win_rate" else None
+ axis["value"] = 0 if axis["key"] in ("kd", "win_rate") else None
missing["style_scope"] = "近0场风格"
missing["common_units"] = [{"name": "合成未完整单位", "count": 0, "roi": 0}]
missing["map_stats"] = [{"name": "合成未完整地图", "count": 2}]
@@ -148,6 +153,27 @@ def sample_views() -> dict[str, dict]:
missing["teams"] = [{"name": "合成未完整分队", "players": [{"id": "sample-player", "name": None}]},
{"name": "合成空分队", "players": []}]
samples[f"{kind}-missing"] = missing
+ small = deepcopy(overview)
+ small["profile_rating"]["win_rate_sample"] = {"value": 100, "wins": 1, "losses": 0,
+ "sample_size": 1, "window_size": 12}
+ samples["overview-small-sample"] = small
+ multi = deepcopy(recent)
+ multi["scope"] = "近期7场"
+ multi["rows"] += [dict(recent["rows"][i], id=f"sample-match-{i + 6:03d}") for i in range(2)]
+ samples["recent-multi"] = multi
+ partial = deepcopy(match)
+ partial["match"].update(roster_complete=False, target_outcome="unknown")
+ partial["scope"] = "单局 · 详情收录 9 人 · 近期名单 11 人"
+ partial["teams"][0]["players"].pop()
+ partial["teams"][1]["players"].pop()
+ partial["teams"][1].update(composition=[], composition_note="1 人缺单位数据,构成暂无")
+ partial["teams"][0]["metrics"][5].update(value=3062, complete=False, note="3/4 人有数据")
+ partial["teams"].append({"id": "4", "name": "观战", "players": [{"name": "合成观战者"}]})
+ samples["match-partial"] = partial
+ direct = deepcopy(match)
+ del direct["player"]
+ direct["match"].pop("target_outcome")
+ samples["match-direct"] = direct
return samples
@@ -184,10 +210,11 @@ async def screenshots(artifacts: list[dict]) -> list[dict]:
const bounds = report.getBoundingClientRect();
const numbers = report.querySelectorAll(
'.metric-number, .report-table td:not(:first-child), .score, .style-list b, ' +
- '.compact-line b, .recent-metrics dd, .row-meta .numeric, .summary-metrics dd, ' +
+ '.compact-line b, .row-meta b, .row-elo, .summary-metrics dd, .roster .participant td, ' +
'.comparison-values b, .prediction-values b'
);
const overflowingNumbers = [...numbers].filter(el => {
+ if (!el.getClientRects().length) return false;
if (el.clientWidth && el.scrollWidth > el.clientWidth + 1) return true;
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
@@ -210,13 +237,20 @@ async def screenshots(artifacts: list[dict]) -> list[dict]:
return box.left < frame.left || box.right > frame.right ||
box.top < frame.top || box.bottom > frame.bottom;
}).map(el => el.textContent.trim());
+ const roster = report.querySelector('.roster');
+ const rosterColumns = [...(roster?.querySelectorAll('thead th') ?? [])]
+ .filter(el => el.getClientRects().length).map(el => el.textContent.trim());
+ const badRoster = roster && (roster.tHead.rows.length !== 1 ||
+ rosterColumns.length !== (innerWidth <= 680 ? 3 : 5) ||
+ roster.querySelectorAll('.participant-detail').length !==
+ roster.querySelectorAll('.participant.target').length);
return {
width: innerWidth, documentWidth: document.documentElement.scrollWidth,
height: document.documentElement.scrollHeight,
reportWidth: bounds.width, reportHeight: bounds.height,
synthetic: report.querySelector('.synthetic')?.textContent,
font: getComputedStyle(document.body).fontFamily,
- overflowingNumbers, clippedRadarLabels
+ overflowingNumbers, clippedRadarLabels, rosterColumns, badRoster
};
}""")
name = f"{item['name']}-{width}.png"
@@ -225,8 +259,9 @@ async def screenshots(artifacts: list[dict]) -> list[dict]:
"external_requests": list(requests),
"passed": dimensions["reportWidth"] == width and dimensions["documentWidth"] == width
and not requests and not dimensions["overflowingNumbers"]
- and not dimensions["clippedRadarLabels"] and bool(dimensions["synthetic"])}
- if width != PHONE_WIDTH and item["kind"] in {"overview", "recent"}:
+ and not dimensions["clippedRadarLabels"] and not dimensions["badRoster"]
+ and bool(dimensions["synthetic"])}
+ if width != PHONE_WIDTH:
chat_image = f"{item['name']}-{width}-chat-{PHONE_WIDTH}.png"
with Image.open(OUTPUT / name) as image:
height = round(image.height * PHONE_WIDTH / image.width)
diff --git a/views/settings/index.html b/views/settings/index.html
index 53861bb..8ec2a2d 100644
--- a/views/settings/index.html
+++ b/views/settings/index.html
@@ -72,9 +72,9 @@ 断箭战报设置中心