Skip to main content

nil_core/ranking/
mod.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4pub mod score;
5
6use crate::ruler::Ruler;
7use bon::Builder;
8use derive_more::Deref;
9use itertools::Itertools;
10use score::Score;
11use serde::{Deserialize, Serialize};
12
13#[derive(Clone, Debug, Default, Deref, Deserialize, Serialize)]
14pub struct Ranking(Vec<RankingEntry>);
15
16impl Ranking {
17  #[inline]
18  pub fn get(&self, ruler: &Ruler) -> Option<&RankingEntry> {
19    self
20      .0
21      .iter()
22      .find(|entry| &entry.ruler == ruler)
23  }
24
25  pub fn update<T>(&mut self, entries: T)
26  where
27    T: IntoIterator<Item = RankingEntry>,
28  {
29    self.0.clear();
30    let entries = entries
31      .into_iter()
32      .sorted_by_key(|it| it.score)
33      .rev()
34      .zip(1u32..)
35      .map(|(mut entry, rank)| {
36        entry.rank = Rank(rank);
37        entry
38      });
39
40    self.0.extend(entries);
41  }
42}
43
44#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct RankingEntry {
47  #[builder(skip)]
48  rank: Rank,
49
50  #[builder(into)]
51  ruler: Ruler,
52
53  #[builder(into)]
54  score: Score,
55
56  #[builder(into)]
57  cities: u32,
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
61pub struct Rank(u32);