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 {
|
2024-10-06 22:24:37 +02:00
|
|
|
pub cycles: usize,
|
|
|
|
pub tiles: usize,
|
|
|
|
pub area: usize,
|
2024-10-06 12:39:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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 23:30:59 +02:00
|
|
|
board: level.init_board().unwrap_or(String::from(" ")),
|
2024-10-06 12:39:36 +02:00
|
|
|
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();
|
2024-10-06 23:37:21 +02:00
|
|
|
let path = dir.join(format!("{}.json", &self.solution_id));
|
2024-10-06 16:29:45 +02:00
|
|
|
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|