Debian Codegraph @

src/scores/scores.rs

raw symbols SCIP
1 /*
2 * Copyright 2024 Andrey Kutejko <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
16 *
17 * For more details see the file COPYING.
18 */
19
20 use super::ROWS_TO_DISPLAY;
21 use super::new_score_dialog::new_score_dialog;
22 use super::scores_dialog::scores_dialog;
23 use crate::config::PACKAGE;
24 use crate::game::MoveSafety;
25 use crate::utils::{list_directory, now};
26 use gettextrs::gettext;
27 use gtk::{glib, prelude::*};
28 use std::cmp::Reverse;
29 use std::collections::BTreeMap;
30 use std::fs;
31 use std::io::{self, BufRead, Write};
32 use std::path::{Path, PathBuf};
33
34 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
35 pub struct Category {
36 pub key: String,
37 pub safety: MoveSafety,
38 }
39
40 impl Category {
41 fn from_game_type(game_type: &str) -> Self {
42 if let Some(key) = game_type.strip_suffix("-super-safe") {
43 Self {
44 key: key.to_owned(),
45 safety: MoveSafety::SuperSafe,
46 }
47 } else if let Some(key) = game_type.strip_suffix("-safe") {
48 Self {
49 key: key.to_owned(),
50 safety: MoveSafety::Safe,
51 }
52 } else {
53 Self {
54 key: game_type.to_owned(),
55 safety: MoveSafety::Unsafe,
56 }
57 }
58 }
59
60 fn game_type(&self) -> String {
61 match self.safety {
62 MoveSafety::Unsafe => self.key.replace(' ', "_").clone(),
63 MoveSafety::Safe => format!("{}-safe", self.key.replace(' ', "_")),
64 MoveSafety::SuperSafe => format!("{}-super-safe", self.key.replace(' ', "_")),
65 }
66 }
67
68 pub fn name(&self) -> Option<String> {
69 match (self.key.as_str(), self.safety) {
70 ("classic_robots", MoveSafety::Unsafe) => Some(gettext("Classic robots")),
71 ("classic_robots", MoveSafety::Safe) => Some(gettext("Classic robots with safe moves")),
72 ("classic_robots", MoveSafety::SuperSafe) => {
73 Some(gettext("Classic robots with super-safe moves"))
74 }
75 ("nightmare", MoveSafety::Unsafe) => Some(gettext("Nightmare")),
76 ("nightmare", MoveSafety::Safe) => Some(gettext("Nightmare with safe moves")),
77 ("nightmare", MoveSafety::SuperSafe) => {
78 Some(gettext("Nightmare with super-safe moves"))
79 }
80 ("robots2", MoveSafety::Unsafe) => Some(gettext("Robots2")),
81 ("robots2", MoveSafety::Safe) => Some(gettext("Robots2 with safe moves")),
82 ("robots2", MoveSafety::SuperSafe) => Some(gettext("Robots2 with super-safe moves")),
83 ("robots2_easy", MoveSafety::Unsafe) => Some(gettext("Robots2 easy")),
84 ("robots2_easy", MoveSafety::Safe) => Some(gettext("Robots2 easy with safe moves")),
85 ("robots2_easy", MoveSafety::SuperSafe) => {
86 Some(gettext("Robots2 easy with super-safe moves"))
87 }
88 ("robots_with_safe_teleport", MoveSafety::Unsafe) => {
89 Some(gettext("Robots with safe teleport"))
90 }
91 ("robots_with_safe_teleport", MoveSafety::Safe) => {
92 Some(gettext("Robots with safe teleport with safe moves"))
93 }
94 ("robots_with_safe_teleport", MoveSafety::SuperSafe) => {
95 Some(gettext("Robots with safe teleport with super-safe moves"))
96 }
97 _ => None,
98 }
99 }
100 }
101
102 #[derive(PartialEq, Eq, Clone, Debug)]
103 pub struct Score {
104 pub score: i64,
105 pub time: u64,
106 pub user: String,
107 }
108
109 impl Score {
110 fn from_line(line: &str, fallback_user: &str) -> Option<Self> {
111 let mut tokens = line.splitn(3, ' ');
112
113 let score = tokens.next()?.parse().ok()?;
114 let time = tokens.next()?.parse().ok()?;
115 let user = tokens.next().unwrap_or(fallback_user).to_owned();
116
117 Some(Self { score, time, user })
118 }
119
120 fn to_line(&self) -> String {
121 format!("{} {} {}", self.score, self.time, self.user)
122 }
123
124 fn rename(self, user: String) -> Self {
125 Self { user, ..self }
126 }
127 }
128
129 fn save_score_to_file(scores_dir: &Path, category: &Category, score: &Score) -> io::Result<()> {
130 fs::create_dir_all(scores_dir)?;
131
132 let filename = scores_dir.join(category.game_type());
133 let mut file = fs::OpenOptions::new()
134 .create(true)
135 .append(true)
136 .open(&filename)?;
137 writeln!(file, "{}", score.to_line())?;
138 Ok(())
139 }
140
141 #[derive(Default)]
142 pub struct ScoreList {
143 pub scores: Vec<Score>,
144 }
145
146 impl ScoreList {
147 pub fn load(path: &Path, fallback_user: &str) -> io::Result<Self> {
148 let mut scores = Vec::new();
149 let file = fs::OpenOptions::new().read(true).open(path)?;
150 for line in io::BufReader::new(file).lines() {
151 let line = line?;
152 match Score::from_line(&line, fallback_user) {
153 Some(score) => scores.push(score),
154 None => {
155 eprintln!(
156 "Failed to read malformed score {} in {}.",
157 line,
158 path.display()
159 )
160 }
161 }
162 }
163 scores.sort_by_key(|s| Reverse(s.score));
164 Ok(Self { scores })
165 }
166
167 pub fn high_scores(&self, n: usize) -> Vec<&Score> {
168 self.scores.iter().take(n).collect()
169 }
170
171 pub fn add(&mut self, score: Score) {
172 self.scores.push(score);
173 self.scores.sort_by_key(|s| Reverse(s.score));
174 }
175 }
176
177 #[derive(Default)]
178 pub struct Scores {
179 pub scores: BTreeMap<Category, ScoreList>,
180 }
181
182 impl Scores {
183 fn load(dir: &Path) -> io::Result<Self> {
184 let mut scores = BTreeMap::new();
185
186 let user = glib::real_name();
187 let user = user.to_string_lossy();
188
189 let files = list_directory(dir)?;
190 for file in files {
191 let Some(file_name) = file.file_name().and_then(|s| s.to_str()) else {
192 continue;
193 };
194
195 let category = Category::from_game_type(file_name);
196
197 if category.name().is_none() {
198 continue;
199 }
200
201 let scores_of_single_category = ScoreList::load(&file, &user)?;
202
203 scores.insert(category, scores_of_single_category);
204 }
205
206 Ok(Self { scores })
207 }
208 }
209
210 fn scores_dir() -> PathBuf {
211 glib::user_data_dir().join(PACKAGE).join("scores")
212 }
213
214 pub fn show_scores(category: Option<&Category>, parent_window: &impl IsA<gtk::Window>) {
215 let scores_dir = scores_dir();
216 let scores = Scores::load(&scores_dir).unwrap_or_else(|e| {
217 eprintln!("Failed to load scores: {}", e);
218 Default::default()
219 });
220 let dialog = scores_dialog(scores, category, parent_window.upcast_ref());
221 dialog.present();
222 }
223
224 pub async fn add_score(category: &Category, score: i64, parent_window: &gtk::Window) {
225 if category.name().is_none() {
226 eprintln!("Failed to add score for unknown game '{:?}'.", category);
227 };
228
229 let user = glib::real_name();
230 let user = user.to_string_lossy();
231
232 let score = Score {
233 score,
234 time: now(),
235 user: user.to_string(),
236 };
237
238 let scores_dir = scores_dir();
239 let mut score_list = ScoreList::load(&scores_dir.join(category.game_type()), &user)
240 .map_err(|err| {
241 eprintln!("Failed to read scores for {}: {}", category.key, err);
242 err
243 })
244 .unwrap_or_default();
245
246 let high_score_gained = {
247 let best_scores = score_list.high_scores(ROWS_TO_DISPLAY);
248 best_scores.len() < ROWS_TO_DISPLAY || score.score > best_scores.last().unwrap().score
249 };
250
251 if high_score_gained {
252 score_list.add(score.clone());
253
254 let new_name = new_score_dialog(&score, category, &score_list, parent_window).await;
255 if let Err(error) = save_score_to_file(&scores_dir, category, &score.rename(new_name)) {
256 eprint!("Failed to save scores for {}: {}", category.key, error);
257 }
258 }
259 }