use std::{ fs::{self, File}, io::Write, }; use serde::{Deserialize, Serialize}; use crate::{level::Level, userdata_dir}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Solution { solution_id: String, level_id: String, // redundant? pub name: String, pub board: String, #[serde(default)] pub score: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Score { pub cycles: usize, pub tiles: usize, pub area: usize, } impl Solution { pub fn new(level: &Level, number: usize) -> Self { Self { solution_id: format!("solution_{number}"), level_id: level.id().to_owned(), name: format!("Unnamed {number}"), board: level.init_board().unwrap_or(String::from(" ")), score: None, } } 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(); } pub fn level_id(&self) -> &str { &self.level_id } 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() } } }