diff options
author | metamuffin <metamuffin@disroot.org> | 2024-09-02 01:41:33 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2024-09-02 01:41:37 +0200 |
commit | 6c4fb2a9d5bf0fde77a6633cb244828852559b04 (patch) | |
tree | e39555afb74c2fdc561679cac9567ef0a4519b03 /server/src/scoreboard.rs | |
parent | 52e7384c955d6fcfe5d522c3c4d5258de38f3507 (diff) | |
download | hurrycurry-6c4fb2a9d5bf0fde77a6633cb244828852559b04.tar hurrycurry-6c4fb2a9d5bf0fde77a6633cb244828852559b04.tar.bz2 hurrycurry-6c4fb2a9d5bf0fde77a6633cb244828852559b04.tar.zst |
move things around, add scoreboards load/save module
Diffstat (limited to 'server/src/scoreboard.rs')
-rw-r--r-- | server/src/scoreboard.rs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/server/src/scoreboard.rs b/server/src/scoreboard.rs new file mode 100644 index 00000000..e7b97b8d --- /dev/null +++ b/server/src/scoreboard.rs @@ -0,0 +1,65 @@ +/* + Hurry Curry! - a game about cooking + Copyright 2024 metamuffin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +*/ +use anyhow::Result; +use hurrycurry_protocol::Score; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use tokio::{ + fs::{read_to_string, rename, File}, + io::AsyncWriteExt, +}; + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +pub struct ScoreboardStore { + maps: HashMap<String, Scoreboard>, +} +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct Scoreboard { + plays: usize, + best: Vec<ScoreboardEntry>, +} +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct ScoreboardEntry { + players: Vec<String>, + score: Score, +} + +impl ScoreboardStore { + pub async fn load() -> Result<Self> { + let path = + xdg::BaseDirectories::with_prefix("hurrycurry")?.place_data_file("scoreboards.json")?; + // TOCTOU because its easier that way + if !path.exists() { + ScoreboardStore::default().save().await?; + } + let s = read_to_string(path).await?; + Ok(serde_json::from_str(&s)?) + } + pub async fn save(&self) -> Result<()> { + let path = + xdg::BaseDirectories::with_prefix("hurrycurry")?.place_data_file("scoreboards.json")?; + let buffer_path = xdg::BaseDirectories::with_prefix("hurrycurry")? + .place_data_file("scoreboards.json~")?; + File::create(&buffer_path) + .await? + .write_all(serde_json::to_string(self)?.as_bytes()) + .await?; + rename(buffer_path, path).await?; + Ok(()) + } +} |