- opgg.ts: 세션 404 → 새 initialize 후 한 번 다시 (MCP 규격), 실패를 '경기 없음'과 나눠 meta.opgg.error · 화면 · 지시문에 반영 - rating.ts: 라인전을 LOL.PS 원문 정의대로 10 · 15분 맞라이너 CS · 골드 · 경험치 차로 - tools/opscore-fit/README.md: OP.GG(롤 · 발로란트) · LOL.PS 원문 인용과 구현 대응 - 테스트: 세션 재시작 · 503 · 일부 실패 · 서버 메타, 라인전 10/15분 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
212 lines
11 KiB
TypeScript
212 lines
11 KiB
TypeScript
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 라인전 점수의 입력과 같은 10 · 15분 맞라이너 골드 · 경험치 · CS 차 (LOL.PS 점수 자체는 AI 추론이라 공개되지 않아
|
||
* 점수로 바꾸지 않고 차이 값만 보여 준다. 원문 · 근거: tools/opscore-fit/README.md)
|
||
* 계수는 tools/opscore-fit (OP.GG 공식 MCP 로 받은 실제 경기) 에서 만든다. 승패 · MVP/ACE 표시도 OP.GG 와 같다.
|
||
*/
|
||
|
||
export interface RatingPart {
|
||
/** 화면 · AI 자료용 짧은 글 ("KAST 82%") */
|
||
text: string;
|
||
/** 점수를 올린 지표인가 (true = 강점, false = 약점) */
|
||
good: boolean;
|
||
}
|
||
|
||
export interface LaneDiff {
|
||
cs: number;
|
||
gold: number;
|
||
xp: number;
|
||
}
|
||
|
||
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[];
|
||
/** 롤 10 · 15분 맞라이너와의 차 (LOL.PS 라인전 점수의 입력). 맞상대를 모르면 없음, 그 시각 기록이 없으면 그 칸만 없음 */
|
||
lane?: { vs: string; at10?: LaneDiff; at15?: LaneDiff };
|
||
/** 추가 지표 없이 기본 기록(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);
|
||
// 기록이 깨진 경기(값 없는 선수)는 점수를 내지 않는다
|
||
if (!rounded.every(Number.isFinite)) return out;
|
||
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 ?? 0) / n,
|
||
dpr: (p.deaths ?? 0) / n,
|
||
apr: (p.assists ?? 0) / 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): 같은 포지션 상대가 딱 한 명이면 10 · 15분 차이
|
||
const diff = (a?: LaneDiff, b?: LaneDiff): LaneDiff | undefined => (a && b ? { cs: a.cs - b.cs, gold: a.gold - b.gold, xp: a.xp - b.xp } : undefined);
|
||
for (const p of players) {
|
||
const role = p.stats?.role;
|
||
const r = out.get(p.puuid);
|
||
if (!r || !role || !LANES.has(role)) continue;
|
||
const opp = players.filter((q) => q.team !== p.team && q.stats?.role === role);
|
||
if (opp.length !== 1) continue;
|
||
const at10 = diff(p.stats?.at10, opp[0].stats?.at10);
|
||
const at15 = diff(p.stats?.at15, opp[0].stats?.at15);
|
||
if (at10 || at15) r.lane = { vs: opp[0].puuid, ...(at10 ? { at10 } : {}), ...(at15 ? { at15 } : {}) };
|
||
}
|
||
return out;
|
||
}
|