범인찾기 C4: 기록 점수 (OP.GG OP스코어 방식) + LOL.PS 라인전

- packages/shared/src/rating.ts: 발로란트(라운드 승률 · KAST · ACS · 피해 격차) · 롤(킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드) 0~10 점수, 경기/팀 순위, MVP · ACE, 점수를 올리고 깎은 지표, 롤 15분 맞라인 비교
- 계수: OP.GG 공식 MCP 로 받은 실제 경기의 OP스코어에 맞춤 (tools/opscore-fit). 교차 검증 발로란트 상관 0.968 · 오차 0.49, 롤 상관 0.943 · 오차 0.60 · 팀 최하위 일치 85%
- 발로란트 경기 상세에 KAST 라운드 수(5초 트레이드) · 받은 피해 저장
- AI 자료에 '# 기록 점수' 칸, 참가자 줄에 KAST · 피해 격차, OP.GG 에서 경기를 찾을 정보(lookup), 참가자에 태그 · 기록 점수

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 15:29:59 +09:00
parent 685e6a7ebe
commit f8916829e1
21 changed files with 2053 additions and 6 deletions

View File

@@ -0,0 +1,200 @@
import type { MatchPlayer, MatchRound } from './protocol.js';
import { LOL_MODEL, VALORANT_MODEL, type LinearModel } from './rating-model.js';
/**
* 기록 점수 (범인찾기, 0~10): 전적 사이트 점수를 우리 기록으로 다시 계산한 값.
* - 발로란트: OP.GG OP스코어. OP.GG 가 밝힌 입력(라운드 승률 · KAST · ACS · 피해량 격차)을 실제 OP.GG 점수에 맞춘 선형 모델
* - 롤: OP.GG OP스코어. 킬 관여 · 데스 · 딜/받은 피해 비중 · 골드 · CS · 레벨 · CC · 와드를 실제 OP.GG 점수에 맞춘 선형 모델
* (포지션별로 나눠도 나아지지 않았다. 딜 · 받은 피해 · 와드 비중이 포지션 차이를 담고, 내전은 포지션 추정이 틀릴 수 있다)
* - 롤 라인전: LOL.PS 처럼 15분 맞라인 상대와 CS · 골드 · 경험치 차 (점수에는 넣지 않고 따로 보여 준다)
* 계수는 tools/opscore-fit (OP.GG 공식 MCP 로 받은 실제 경기) 에서 만든다. 승패 · MVP/ACE 표시도 OP.GG 와 같다.
*/
export interface RatingPart {
/** 화면 · AI 자료용 짧은 글 ("KAST 82%") */
text: string;
/** 점수를 올린 지표인가 (true = 강점, false = 약점) */
good: boolean;
}
export interface PlayerRating {
/** 0~10, 0.1 단위 */
score: number;
/** 경기 10명 중 순위 (1 = 최고) */
rank: number;
/** 팀 안 순위 */
teamRank: number;
/** OP.GG 처럼 이긴 팀 1등 = MVP, 진 팀 1등 = ACE */
badge: 'MVP' | 'ACE' | null;
/** 점수를 가장 많이 올리고 깎은 지표 (각각 최대 2개) */
parts: RatingPart[];
/** 롤 15분 맞라인 비교 (LOL.PS 라인전 지표). 맞상대를 모르면 없음 */
lane?: { vs: string; cs: number; gold: number; xp: number };
/** 추가 지표 없이 기본 기록(K/D/A 등)만으로 낸 점수 */
basic: boolean;
}
type Feat = Record<string, number>;
interface FeatInfo {
/** 이 지표가 크면 좋은가 (+1) 나쁜가 (-1). 0 = 설명에 쓰지 않음 (팀 전체 값 등) */
dir: 1 | -1 | 0;
label: (v: number) => string;
}
const pct = (v: number) => `${Math.round(v * 100)}%`;
const signed = (v: number, d = 0) => `${v >= 0 ? '+' : ''}${v.toFixed(d)}`;
const VAL_INFO: Record<string, FeatInfo> = {
rwr: { dir: 0, label: (v) => `라운드 승률 ${pct(v)}` },
kast: { dir: 1, label: (v) => `KAST ${pct(v)}` },
acs: { dir: 1, label: (v) => `ACS ${Math.round(v)}` },
ddd: { dir: 1, label: (v) => `피해 격차 ${signed(v)}/라운드` },
kpr: { dir: 1, label: (v) => `라운드당 킬 ${v.toFixed(2)}` },
dpr: { dir: -1, label: (v) => `라운드당 데스 ${v.toFixed(2)}` },
apr: { dir: 1, label: (v) => `라운드당 어시 ${v.toFixed(2)}` },
};
const LOL_INFO: Record<string, FeatInfo> = {
win: { dir: 0, label: () => '' },
kp: { dir: 1, label: (v) => `킬 관여 ${pct(v)}` },
death_share: { dir: -1, label: (v) => `상대 킬의 ${pct(v)}가 이 사람` },
dpm: { dir: -1, label: (v) => `분당 데스 ${v.toFixed(2)}` },
kda: { dir: 1, label: (v) => `KDA ${Math.expm1(v).toFixed(1)}` },
dmg_share: { dir: 1, label: (v) => `팀 딜 비중 ${pct(v)}` },
dmg_rel: { dir: 1, label: (v) => `딜량 평균의 ${v.toFixed(1)}배` },
taken_share: { dir: 1, label: (v) => `받은 피해 비중 ${pct(v)}` },
gold_share: { dir: 1, label: (v) => `팀 골드 비중 ${pct(v)}` },
gold_rel: { dir: 1, label: (v) => `골드 평균의 ${v.toFixed(1)}배` },
cspm: { dir: 1, label: (v) => `분당 CS ${v.toFixed(1)}` },
lvl_diff: { dir: 1, label: (v) => `레벨 평균 ${signed(v, 1)}` },
ccpm: { dir: 1, label: (v) => `분당 CC ${v.toFixed(1)}초` },
wardpm: { dir: 1, label: (v) => `분당 와드 ${v.toFixed(2)}` },
cwpm: { dir: 1, label: (v) => `분당 제어 와드 ${v.toFixed(2)}` },
};
/** 라인전 비교를 하는 포지션 (바텀 = 원딜/서폿을 모름 → 비교 안 함) */
const LANES = new Set(['탑', '정글', '미드', '원딜', '서폿']);
function apply(m: LinearModel, f: Feat): number {
let s = m.intercept;
m.features.forEach((k, i) => (s += m.coef[i] * (f[k] ?? 0)));
return Math.min(10, Math.max(0, s));
}
/** 경기 평균과 비교해 점수를 가장 많이 올리고 깎은 지표 (모델 계수 × 평균과의 차) */
function explain(m: LinearModel, f: Feat, mean: Feat, info: Record<string, FeatInfo>): RatingPart[] {
const contrib = m.features
.map((k, i) => ({ k, c: m.coef[i] * ((f[k] ?? 0) - (mean[k] ?? 0)) }))
// 계수 부호가 상식과 반대인 지표(다른 지표와 겹쳐 생긴 것)는 설명에 쓰지 않는다
.filter(({ k }) => info[k] && info[k].dir !== 0 && Math.sign(m.coef[m.features.indexOf(k)]) === info[k].dir);
const ups = contrib.filter((x) => x.c >= 0.25).sort((a, b) => b.c - a.c).slice(0, 2);
const downs = contrib.filter((x) => x.c <= -0.25).sort((a, b) => a.c - b.c).slice(0, 2);
return [...ups.map((x) => ({ text: info[x.k].label(f[x.k]), good: true })), ...downs.map((x) => ({ text: info[x.k].label(f[x.k]), good: false }))];
}
function meanOf(fs: Feat[]): Feat {
const out: Feat = {};
for (const f of fs) for (const [k, v] of Object.entries(f)) out[k] = (out[k] ?? 0) + v / fs.length;
return out;
}
function finish(players: MatchPlayer[], scores: number[], parts: RatingPart[][], basic: boolean, teamWin: (p: MatchPlayer) => boolean | null): Map<string, PlayerRating> {
const out = new Map<string, PlayerRating>();
const rounded = scores.map((s) => Math.round(s * 10) / 10);
const order = rounded.map((s, i) => ({ s, i })).sort((a, b) => b.s - a.s);
players.forEach((p, i) => {
const mates = players.map((q, j) => ({ q, j })).filter(({ q }) => q.team === p.team);
const teamOrder = [...mates].sort((a, b) => rounded[b.j] - rounded[a.j]);
const teamRank = teamOrder.findIndex((x) => x.j === i) + 1;
const win = teamWin(p);
out.set(p.puuid, {
score: rounded[i],
rank: order.findIndex((x) => x.i === i) + 1,
teamRank,
badge: teamRank === 1 && win !== null ? (win ? 'MVP' : 'ACE') : null,
parts: parts[i],
basic,
});
});
return out;
}
/** 발로란트 기록 점수. rounds = 경기 라운드 기록(우리 팀 기준 승패) */
export function rateValorant(players: MatchPlayer[], rounds: MatchRound[]): Map<string, PlayerRating> {
if (!players.length) return new Map();
const total = rounds.length;
const allyWon = rounds.filter((r) => r.win).length;
const full = players.every((p) => p.stats?.kastRounds !== undefined && p.stats?.damageTaken !== undefined && p.stats?.damage !== undefined);
const model = full ? VALORANT_MODEL.full : VALORANT_MODEL.basic;
const feats: Feat[] = players.map((p) => {
const n = p.stats?.rounds || total || 1;
const won = p.ally ? allyWon : total - allyWon;
return {
rwr: total ? won / total : 0.5,
kast: (p.stats?.kastRounds ?? 0) / n,
acs: (p.score ?? 0) / n,
ddd: ((p.stats?.damage ?? 0) - (p.stats?.damageTaken ?? 0)) / n,
kpr: p.kills / n,
dpr: p.deaths / n,
apr: p.assists / n,
};
});
const mean = meanOf(feats);
const scores = feats.map((f) => apply(model, f));
const parts = feats.map((f) => explain(model, f, mean, VAL_INFO));
return finish(players, scores, parts, !full, (p) => (total ? (p.ally ? allyWon * 2 > total : allyWon * 2 < total) : null));
}
/** 롤 기록 점수. minutes = 경기 시간(분), allyWin = 우리 팀 승리 여부 */
export function rateLol(players: MatchPlayer[], minutes: number, allyWin: boolean | null): Map<string, PlayerRating> {
if (!players.length) return new Map();
const m = Math.max(1, minutes);
const full = players.every((p) => p.stats?.damage !== undefined && p.stats?.damageTaken !== undefined);
const sum = (xs: MatchPlayer[], f: (p: MatchPlayer) => number) => xs.reduce((n, p) => n + f(p), 0);
const avgLevel = sum(players, (p) => p.level ?? 0) / players.length;
const lobbyDmg = Math.max(1, sum(players, (p) => p.stats?.damage ?? 0) / players.length);
const lobbyGold = Math.max(1, sum(players, (p) => p.gold ?? 0) / players.length);
const feats: Feat[] = players.map((p) => {
const mates = players.filter((q) => q.team === p.team);
const foes = players.filter((q) => q.team !== p.team);
const tk = Math.max(1, sum(mates, (q) => q.kills));
const ek = Math.max(1, sum(foes, (q) => q.kills));
const tdmg = Math.max(1, sum(mates, (q) => q.stats?.damage ?? 0));
const ttaken = Math.max(1, sum(mates, (q) => q.stats?.damageTaken ?? 0));
const tgold = Math.max(1, sum(mates, (q) => q.gold ?? 0));
const win = allyWin === null ? 0.5 : p.ally === allyWin ? 1 : 0;
return {
win,
kp: (p.kills + p.assists) / tk,
death_share: p.deaths / ek,
dpm: p.deaths / m,
kda: Math.log1p((p.kills + p.assists) / Math.max(1, p.deaths)),
dmg_share: (p.stats?.damage ?? 0) / tdmg,
dmg_rel: (p.stats?.damage ?? 0) / lobbyDmg,
taken_share: (p.stats?.damageTaken ?? 0) / ttaken,
gold_share: (p.gold ?? 0) / tgold,
gold_rel: (p.gold ?? 0) / lobbyGold,
cspm: (p.cs ?? 0) / m,
lvl_diff: (p.level ?? 0) - avgLevel,
ccpm: (p.stats?.ccSeconds ?? 0) / m,
wardpm: (p.stats?.wardsPlaced ?? 0) / m,
cwpm: (p.stats?.controlWards ?? 0) / m,
};
});
const model = full ? LOL_MODEL.full : LOL_MODEL.basic;
const mean = meanOf(feats);
const scores = feats.map((f) => apply(model, f));
const parts = feats.map((f) => explain(model, f, mean, LOL_INFO));
const out = finish(players, scores, parts, !full, (p) => (allyWin === null ? null : p.ally === allyWin));
// 라인전 (LOL.PS): 같은 포지션 상대가 딱 한 명이면 15분 차이
for (const p of players) {
const role = p.stats?.role;
const a = p.stats?.at15;
if (!role || !LANES.has(role) || !a) continue;
const opp = players.filter((q) => q.team !== p.team && q.stats?.role === role);
const b = opp.length === 1 ? opp[0].stats?.at15 : undefined;
if (!b) continue;
out.get(p.puuid)!.lane = { vs: opp[0].puuid, cs: a.cs - b.cs, gold: a.gold - b.gold, xp: a.xp - b.xp };
}
return out;
}