CI / core (pull_request) Successful in 1m50s
- The core reads the champion played in the client's gameflow session (champion selections, else the teams, by the summoner's client PUUID) and follows the Live Match from one read to the next: it starts with an Arena game in progress and lasts through that game's end-of-game screen. - The follower tells the page the Live Match on each change, before the champ select's end, so the end of a champ select that launched a game shows « En partie » instead of « Défi », without computing the statistics again. - « En partie »: the banner with the champion's splash, the Season and the count, its tick of the ring lit and the stake (« Un top 1 validerait X : 88 / 172 », or the day it was validated); « Champion en cours d’identification » until the client says it. Under it, the card's sheet and the champion's 5 latest Matches of the Season, read at low priority. - A Live Match is a phase like the champ select: the signed-in Account and the current Season, the Account selector greyed, « Paramètres » closed, and a minimised or hidden window shown again without the focus, never raised. - Its end-of-game block ends it and #129 decides the screen; without a block, the lobby shows « Défi ». A screen gone with its tab falls back to « Défi ». - Tests with the simulated client: launch from the champ select, a client met in a game, the champion identified late, the end with and without a block, a game outside Arena. docs/interface.md and the guide are updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0192He3BEKJ9v922udzup4Qn
491 lines
18 KiB
Rust
491 lines
18 KiB
Rust
//! Challenge figures and champion statistics, computed on demand from stored Matches.
|
|
mod rows;
|
|
|
|
pub(crate) use rows::collate;
|
|
pub use rows::{Column, StateFilter, sort_rows};
|
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
|
use std::ffi::OsStr;
|
|
use std::ops::Range;
|
|
use std::path::PathBuf;
|
|
|
|
use crate::champions::{Champion, card_portrait_path, cards_dir, file_names};
|
|
use crate::date::Date;
|
|
use crate::error::Error;
|
|
use crate::model::{FollowedMatch, Format, Match, MatchEnd};
|
|
use crate::seasons::{Season, period};
|
|
use crate::splash::{Splash, cached_splashes, splashes_dir};
|
|
use crate::tracker::Tracker;
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum SeasonScope {
|
|
/// By Season name.
|
|
Season(String),
|
|
AllSeasons,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Scope {
|
|
pub season: SeasonScope,
|
|
/// `None` = all Formats. Filters statistics only, never the Challenge.
|
|
pub format: Option<Format>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Statistics {
|
|
/// `None` in the all-Seasons view.
|
|
pub challenge: Option<ChallengeSummary>,
|
|
/// One per champion in the game, ordered by champion name.
|
|
pub rows: Vec<ChampionRow>,
|
|
pub charts: Charts,
|
|
/// Distinct Formats among all stored Matches of the Account, for the filter.
|
|
pub formats: Vec<Format>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct ChallengeSummary {
|
|
pub completed: usize,
|
|
pub total: usize,
|
|
/// All Attempts, including those on champions not yet Completed.
|
|
pub attempts: usize,
|
|
/// Over Completed champions only.
|
|
pub average_attempts: Option<f64>,
|
|
pub first_tries: usize,
|
|
/// The Completed champions' ids in the order of their first top 1, the earliest first.
|
|
pub completion_order: Vec<u32>,
|
|
/// The Season's latest Match, all Formats; `None` without any Match in the Season.
|
|
pub last_match: Option<LastMatch>,
|
|
}
|
|
|
|
/// A Match as the Challenge saw it.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct LastMatch {
|
|
pub champion_id: u32,
|
|
pub placement: u8,
|
|
pub outcome: MatchOutcome,
|
|
}
|
|
|
|
/// What a Match did to its champion's Challenge.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum MatchOutcome {
|
|
/// The champion's Attempt of that number (1 for the first), which did not complete it.
|
|
Attempt(usize),
|
|
/// The champion's first top 1, after that many Attempts (1 for a First Try).
|
|
Completed(usize),
|
|
/// Played once the champion was already Completed: not an Attempt.
|
|
AfterCompletion,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum ChampionState {
|
|
Completed,
|
|
InProgress,
|
|
NeverPlayed,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct ChampionRow {
|
|
pub champion: Champion,
|
|
/// Only when the file exists in the portraits dir.
|
|
pub portrait: Option<PathBuf>,
|
|
/// Only when the file exists in the portraits dir's `cards` folder.
|
|
pub card_portrait: Option<PathBuf>,
|
|
pub splash: Option<Splash>,
|
|
// In scope (Season and Format filter):
|
|
pub matches: usize,
|
|
pub best_placement: Option<u8>,
|
|
pub top1: usize,
|
|
pub wins: usize,
|
|
pub average_placement: Option<f64>,
|
|
pub last_match_ms: Option<i64>,
|
|
/// Season scope only, and not affected by the Format filter.
|
|
pub attempts: Option<usize>,
|
|
/// Season scope: always `Some`, not affected by the Format filter. All Seasons:
|
|
/// `Some(NeverPlayed)` for a champion with no stored Match, otherwise `None`.
|
|
pub state: Option<ChampionState>,
|
|
/// Season scope: always `Some`, zeros for a champion never played. All Seasons: `None`.
|
|
/// Not affected by the Format filter.
|
|
pub challenge: Option<ChampionChallenge>,
|
|
/// The Account's Mastery Points on this champion. `None` = unknown for this Account (the
|
|
/// points were never fetched); `Some(0)` = known, no points. Not affected by the Season
|
|
/// nor the Format.
|
|
pub mastery_points: Option<u64>,
|
|
}
|
|
|
|
/// What the champion card shows: the Challenge figures of one champion for one Account and
|
|
/// one Season, all Formats together. The statistics' Format filter never changes them.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
|
pub struct ChampionChallenge {
|
|
/// Matches in the Season, all Formats.
|
|
pub matches: usize,
|
|
/// Wins in the Season, all Formats.
|
|
pub wins: usize,
|
|
/// Best Placement in the Season, all Formats.
|
|
pub best_placement: Option<u8>,
|
|
/// The day of the first top 1 of the Season, by start time. Same day as the matching point
|
|
/// of `Charts::completed_over_time`. A later top 1 never changes it.
|
|
pub completed_on: Option<Date>,
|
|
}
|
|
|
|
/// The three Marks of the Challenge on a champion.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct Marks {
|
|
/// At least one Match.
|
|
pub played: bool,
|
|
/// At least one Win. A top 1 is always a Win.
|
|
pub won: bool,
|
|
/// At least one top 1: the champion is Completed.
|
|
pub completed: bool,
|
|
}
|
|
|
|
impl ChampionChallenge {
|
|
/// The figures of a champion's progress; zeros for a champion never played.
|
|
fn of(progress: Option<&Progress>) -> ChampionChallenge {
|
|
progress.map_or_else(ChampionChallenge::default, |p| ChampionChallenge {
|
|
matches: p.matches,
|
|
wins: p.wins,
|
|
best_placement: p.best_placement,
|
|
completed_on: p.completed_at_ms.map(Date::from_ms),
|
|
})
|
|
}
|
|
|
|
pub fn marks(&self) -> Marks {
|
|
let completed = self.completed_on.is_some();
|
|
Marks {
|
|
played: self.matches > 0,
|
|
won: self.wins > 0 || completed,
|
|
completed,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Charts {
|
|
/// In scope: one entry per Placement from 1 to the highest seen, zero counts included.
|
|
pub placements: Vec<(u8, usize)>,
|
|
/// Season scope: the cumulative Completed count on each day a champion became Completed.
|
|
pub completed_over_time: Vec<(Date, usize)>,
|
|
/// Season scope: Completed champions that took 1, 2, 3, 4 and 5-or-more Attempts.
|
|
pub attempts_to_complete: [usize; 5],
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Progress {
|
|
attempts: usize,
|
|
completed_at_ms: Option<i64>,
|
|
/// Over every Match given, not only up to the first top 1.
|
|
matches: usize,
|
|
wins: usize,
|
|
best_placement: Option<u8>,
|
|
}
|
|
|
|
/// What one chronological pass over the Season's Matches gives the Challenge.
|
|
#[derive(Default)]
|
|
struct ChallengePass {
|
|
progress: HashMap<u32, Progress>,
|
|
completion_order: Vec<u32>,
|
|
last_match: Option<LastMatch>,
|
|
}
|
|
|
|
/// Progress per champion from Matches in chronological order: a champion's Attempts count
|
|
/// its Matches up to and including its first top 1; the other figures count them all.
|
|
fn challenge_pass(matches: &[&Match]) -> ChallengePass {
|
|
let mut pass = ChallengePass::default();
|
|
for m in matches {
|
|
let p = pass.progress.entry(m.champion_id).or_default();
|
|
p.matches += 1;
|
|
p.wins += usize::from(m.win);
|
|
p.best_placement = Some(p.best_placement.map_or(m.placement, |b| b.min(m.placement)));
|
|
let outcome = if p.completed_at_ms.is_some() {
|
|
MatchOutcome::AfterCompletion
|
|
} else {
|
|
p.attempts += 1;
|
|
if m.placement == 1 {
|
|
p.completed_at_ms = Some(m.started_at_ms);
|
|
pass.completion_order.push(m.champion_id);
|
|
MatchOutcome::Completed(p.attempts)
|
|
} else {
|
|
MatchOutcome::Attempt(p.attempts)
|
|
}
|
|
};
|
|
pass.last_match = Some(LastMatch {
|
|
champion_id: m.champion_id,
|
|
placement: m.placement,
|
|
outcome,
|
|
});
|
|
}
|
|
pass
|
|
}
|
|
|
|
/// What the Match `match_id` brought its champion's Challenge. `matches` are that champion's
|
|
/// Matches of one Season, oldest first, the Match included: its Marks with them all are compared
|
|
/// with its Marks without it.
|
|
pub(crate) fn match_end(matches: &[Match], match_id: &str) -> MatchEnd {
|
|
let marks = |matches: Vec<&Match>| {
|
|
let pass = challenge_pass(&matches);
|
|
ChampionChallenge::of(pass.progress.values().next()).marks()
|
|
};
|
|
MatchEnd::between(
|
|
marks(matches.iter().filter(|m| m.match_id != match_id).collect()),
|
|
marks(matches.iter().collect()),
|
|
)
|
|
}
|
|
|
|
/// `matches` are all the Account's stored Matches, oldest first. `period` is the Season's
|
|
/// period (`None` = all Seasons). The Challenge only ever looks at the Season, never at `format`.
|
|
pub(crate) fn compute(
|
|
catalog: Vec<Champion>,
|
|
matches: &[Match],
|
|
period: Option<Range<i64>>,
|
|
format: Option<Format>,
|
|
) -> Statistics {
|
|
// A champion played but missing from the catalog still counts.
|
|
let mut champions = catalog;
|
|
let mut known: HashSet<u32> = champions.iter().map(|c| c.id).collect();
|
|
for m in matches {
|
|
if known.insert(m.champion_id) {
|
|
champions.push(Champion {
|
|
id: m.champion_id,
|
|
key: m.champion_name.clone(),
|
|
name: m.champion_name.clone(),
|
|
});
|
|
}
|
|
}
|
|
champions.sort_by_cached_key(|c| (collate(&c.name), c.id));
|
|
|
|
let in_period: Vec<&Match> = matches
|
|
.iter()
|
|
.filter(|m| period.as_ref().is_none_or(|p| p.contains(&m.started_at_ms)))
|
|
.collect();
|
|
let in_scope: Vec<&Match> = in_period
|
|
.iter()
|
|
.copied()
|
|
.filter(|m| format.is_none_or(|f| m.format == f))
|
|
.collect();
|
|
let mut by_champion: HashMap<u32, Vec<&Match>> = HashMap::new();
|
|
for m in &in_scope {
|
|
by_champion.entry(m.champion_id).or_default().push(m);
|
|
}
|
|
let mut pass = period.is_some().then(|| challenge_pass(&in_period));
|
|
let ever_played: HashSet<u32> = matches.iter().map(|m| m.champion_id).collect();
|
|
|
|
let rows: Vec<ChampionRow> = champions
|
|
.into_iter()
|
|
.map(|champion| {
|
|
let mine = by_champion.get(&champion.id).map_or(&[][..], Vec::as_slice);
|
|
let (attempts, state, challenge) = match &pass {
|
|
Some(pass) => {
|
|
let p = pass.progress.get(&champion.id);
|
|
let state = match p {
|
|
Some(Progress {
|
|
completed_at_ms: Some(_),
|
|
..
|
|
}) => ChampionState::Completed,
|
|
Some(_) => ChampionState::InProgress,
|
|
None => ChampionState::NeverPlayed,
|
|
};
|
|
let challenge = ChampionChallenge::of(p);
|
|
(
|
|
Some(p.map_or(0, |p| p.attempts)),
|
|
Some(state),
|
|
Some(challenge),
|
|
)
|
|
}
|
|
None => (
|
|
None,
|
|
(!ever_played.contains(&champion.id)).then_some(ChampionState::NeverPlayed),
|
|
None,
|
|
),
|
|
};
|
|
ChampionRow {
|
|
portrait: None,
|
|
card_portrait: None,
|
|
splash: None,
|
|
matches: mine.len(),
|
|
best_placement: mine.iter().map(|m| m.placement).min(),
|
|
top1: mine.iter().filter(|m| m.placement == 1).count(),
|
|
wins: mine.iter().filter(|m| m.win).count(),
|
|
average_placement: (!mine.is_empty()).then(|| {
|
|
mine.iter().map(|m| f64::from(m.placement)).sum::<f64>() / mine.len() as f64
|
|
}),
|
|
last_match_ms: mine.iter().map(|m| m.started_at_ms).max(),
|
|
attempts,
|
|
state,
|
|
challenge,
|
|
mastery_points: None,
|
|
champion,
|
|
}
|
|
})
|
|
.collect();
|
|
|
|
let highest = in_scope.iter().map(|m| m.placement).max().unwrap_or(0);
|
|
let placements = (1..=highest)
|
|
.map(|p| (p, in_scope.iter().filter(|m| m.placement == p).count()))
|
|
.collect();
|
|
|
|
let mut challenge = None;
|
|
let mut completed_over_time = Vec::new();
|
|
let mut attempts_to_complete = [0; 5];
|
|
if let Some(pass) = &mut pass {
|
|
let progress = &pass.progress;
|
|
let completed: Vec<(usize, i64)> = progress
|
|
.values()
|
|
.filter_map(|p| Some((p.attempts, p.completed_at_ms?)))
|
|
.collect();
|
|
challenge = Some(ChallengeSummary {
|
|
completed: completed.len(),
|
|
total: rows.len(),
|
|
attempts: progress.values().map(|p| p.attempts).sum(),
|
|
average_attempts: (!completed.is_empty()).then(|| {
|
|
completed.iter().map(|(n, _)| n).sum::<usize>() as f64 / completed.len() as f64
|
|
}),
|
|
first_tries: completed.iter().filter(|(n, _)| *n == 1).count(),
|
|
completion_order: std::mem::take(&mut pass.completion_order),
|
|
last_match: pass.last_match,
|
|
});
|
|
let mut per_day: BTreeMap<Date, usize> = BTreeMap::new();
|
|
for &(attempts, ms) in &completed {
|
|
*per_day.entry(Date::from_ms(ms)).or_default() += 1;
|
|
attempts_to_complete[attempts.min(5) - 1] += 1;
|
|
}
|
|
let mut cumulative = 0;
|
|
completed_over_time = per_day
|
|
.into_iter()
|
|
.map(|(day, n)| {
|
|
cumulative += n;
|
|
(day, cumulative)
|
|
})
|
|
.collect();
|
|
}
|
|
|
|
let mut formats: Vec<Format> = matches.iter().map(|m| m.format).collect();
|
|
formats.sort();
|
|
formats.dedup();
|
|
|
|
Statistics {
|
|
challenge,
|
|
rows,
|
|
charts: Charts {
|
|
placements,
|
|
completed_over_time,
|
|
attempts_to_complete,
|
|
},
|
|
formats,
|
|
}
|
|
}
|
|
|
|
impl Tracker {
|
|
/// Replaces the Season table; Matches are assigned to Seasons on demand, so already
|
|
/// stored Matches move accordingly.
|
|
pub fn with_seasons(mut self, mut seasons: Vec<Season>) -> Tracker {
|
|
seasons.sort_by_key(|s| s.start);
|
|
self.seasons = seasons;
|
|
self
|
|
}
|
|
|
|
/// Oldest first.
|
|
pub fn seasons(&self) -> Vec<Season> {
|
|
self.seasons.clone()
|
|
}
|
|
|
|
/// The Season containing `now_ms`.
|
|
pub fn current_season(&self, now_ms: i64) -> Option<Season> {
|
|
self.seasons
|
|
.iter()
|
|
.rev()
|
|
.find(|s| s.start.start_ms() <= now_ms)
|
|
.cloned()
|
|
}
|
|
|
|
/// The stored Match `match_id` as the live follow reports it: what it brought its champion's
|
|
/// Challenge in its Season, nothing when no Season holds it. `None` when it is not stored.
|
|
pub(crate) fn followed_match(
|
|
&self,
|
|
puuid: &str,
|
|
match_id: &str,
|
|
) -> Result<Option<FollowedMatch>, Error> {
|
|
let Some(m) = self.stored_match(puuid, match_id)? else {
|
|
return Ok(None);
|
|
};
|
|
let season = self.current_season(m.started_at_ms).map(|s| s.name);
|
|
let end = match &season {
|
|
Some(name) => {
|
|
let range = period(&self.seasons, name).expect("a Season of the table");
|
|
match_end(
|
|
&self.champion_matches(puuid, m.champion_id, range)?,
|
|
match_id,
|
|
)
|
|
}
|
|
None => MatchEnd::Nothing,
|
|
};
|
|
Ok(Some(FollowedMatch {
|
|
puuid: puuid.into(),
|
|
match_id: match_id.into(),
|
|
provisional: m.provisional,
|
|
// Riot's Match id is the platform and the client's game id.
|
|
game_id: match_id
|
|
.rsplit_once('_')
|
|
.and_then(|(_, id)| id.parse().ok()),
|
|
season,
|
|
format: m.format,
|
|
champion_id: m.champion_id,
|
|
started_at_ms: m.started_at_ms,
|
|
end,
|
|
}))
|
|
}
|
|
|
|
/// The Account's latest `limit` Matches with one champion in the Season named `season`,
|
|
/// newest first: what « En partie » lists (#109).
|
|
pub fn recent_champion_matches(
|
|
&self,
|
|
puuid: &str,
|
|
champion_id: u32,
|
|
season: &str,
|
|
limit: usize,
|
|
) -> Result<Vec<Match>, Error> {
|
|
let range =
|
|
period(&self.seasons, season).ok_or_else(|| Error::UnknownSeason(season.into()))?;
|
|
let mut matches = self.champion_matches(puuid, champion_id, range)?;
|
|
matches.reverse();
|
|
matches.truncate(limit);
|
|
Ok(matches)
|
|
}
|
|
|
|
pub fn statistics(&self, puuid: &str, scope: &Scope) -> Result<Statistics, Error> {
|
|
let season_period = match &scope.season {
|
|
SeasonScope::AllSeasons => None,
|
|
SeasonScope::Season(name) => Some(
|
|
period(&self.seasons, name).ok_or_else(|| Error::UnknownSeason(name.clone()))?,
|
|
),
|
|
};
|
|
let mut stats = compute(
|
|
self.cached_champions()?,
|
|
&self.matches(puuid)?,
|
|
season_period,
|
|
scope.format,
|
|
);
|
|
// A read error leaves the points unknown rather than failing the statistics.
|
|
if let Ok(Some(points)) = self.mastery(puuid) {
|
|
for row in &mut stats.rows {
|
|
row.mastery_points = Some(points.get(&row.champion.id).copied().unwrap_or(0));
|
|
}
|
|
}
|
|
if let Some((_, dir)) = &self.champions {
|
|
// One read of each folder rather than a file check per champion and per portrait.
|
|
let squares: HashSet<_> = file_names(dir).collect();
|
|
let cards: HashSet<_> = file_names(&cards_dir(dir)).collect();
|
|
let mut splashes = cached_splashes(&splashes_dir(dir));
|
|
for row in &mut stats.rows {
|
|
row.splash = splashes.remove(&row.champion.key);
|
|
let name = format!("{}.png", row.champion.key);
|
|
row.portrait = squares.contains(OsStr::new(&name)).then(|| dir.join(name));
|
|
let card = card_portrait_path(dir, &row.champion.key);
|
|
row.card_portrait = card
|
|
.file_name()
|
|
.is_some_and(|name| cards.contains(name))
|
|
.then_some(card);
|
|
}
|
|
}
|
|
Ok(stats)
|
|
}
|
|
}
|