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] }}
- -
{% 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.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 %} -