rust_warrior/
profile.rs

1//! contains the struct for saving player name and current level
2
3use base64;
4use serde_derive::{Deserialize, Serialize};
5use std::str;
6
7/// The player's profile tracks their game progress. It is saved in .profile at
8/// the root of the player's generated project.
9#[derive(Deserialize, Serialize)]
10pub struct Profile {
11    /// The name the player has chosen
12    pub name: String,
13    /// The level of the player's warrior
14    pub level: usize,
15    /// Whether the player has successfully completed the final floor
16    pub maximus_oxidus: bool,
17}
18
19impl Profile {
20    /// create new Profile for player with given `name`
21    pub fn new(name: String) -> Profile {
22        Profile {
23            name,
24            level: 1,
25            maximus_oxidus: false,
26        }
27    }
28
29    pub fn increment_level(&mut self) {
30        self.level += 1;
31    }
32
33    /// load Profile from base64 encoded TOML String
34    pub fn from_toml(contents: &str) -> Profile {
35        let err = "failed to parse .profile";
36        let bytes = base64::decode(contents).expect(err);
37        let decoded = str::from_utf8(&bytes).expect(err);
38        toml::from_str(decoded).expect(err)
39    }
40
41    /// convert Profile to base64 encoded TOML String
42    pub fn to_toml(&self) -> String {
43        let profile_toml = toml::to_string(&self).unwrap();
44        base64::encode(&profile_toml.as_bytes())
45    }
46
47    pub fn directory(&self) -> String {
48        self.name.to_lowercase().replace(r"[^a-z0-9]+", "-")
49    }
50}