marble-machinations/src/solution.rs

66 lines
1.5 KiB
Rust
Raw Normal View History

2024-10-06 16:29:45 +02:00
use std::{
fs::{self, File},
io::Write,
};
2024-10-06 12:39:36 +02:00
use serde::{Deserialize, Serialize};
2024-10-06 16:29:45 +02:00
use crate::{level::Level, userdata_dir};
2024-10-06 16:00:12 +02:00
#[derive(Debug, Clone, Serialize, Deserialize)]
2024-10-06 12:39:36 +02:00
pub struct Solution {
2024-10-06 16:29:45 +02:00
solution_id: String,
2024-10-06 12:39:36 +02:00
level_id: String, // redundant?
pub name: String,
pub board: String,
2024-10-06 16:29:45 +02:00
#[serde(default)]
2024-10-06 12:39:36 +02:00
pub score: Option<Score>,
}
2024-10-06 16:00:12 +02:00
#[derive(Debug, Clone, Serialize, Deserialize)]
2024-10-06 12:39:36 +02:00
pub struct Score {
pub cycles: u32,
pub tiles: u32,
pub area: u32,
}
impl Solution {
2024-10-06 16:00:12 +02:00
pub fn new(level: &Level, number: usize) -> Self {
2024-10-06 12:39:36 +02:00
Self {
2024-10-06 16:29:45 +02:00
solution_id: format!("solution_{number}"),
2024-10-06 16:00:12 +02:00
level_id: level.id().to_owned(),
2024-10-06 12:39:36 +02:00
name: format!("Unnamed {number}"),
2024-10-06 16:00:12 +02:00
board: level
.init_board()
.unwrap_or_else(|| " \n".repeat(20)), // todo remove when auto resizing is implemented
2024-10-06 12:39:36 +02:00
// score: Some(Score { cycles: 5, tiles: 88, area: 987 }),
score: None,
}
}
2024-10-06 16:00:12 +02:00
2024-10-06 16:29:45 +02:00
pub fn save(&self) {
let dir = userdata_dir().join("solutions").join(&self.level_id);
fs::create_dir_all(&dir).unwrap();
let path = dir.join(&format!("{}.json", &self.solution_id));
let json = serde_json::to_string_pretty(self).unwrap();
let mut file = File::create(path).unwrap();
file.write_all(json.as_bytes()).unwrap();
}
2024-10-06 16:00:12 +02:00
pub fn level_id(&self) -> &str {
&self.level_id
}
2024-10-06 12:39:36 +02:00
pub fn score_text(&self) -> String {
if let Some(score) = &self.score {
format!(
"C: {} T: {} A: {}",
score.cycles, score.tiles, score.area
)
} else {
"unsolved".into()
}
}
}