marble-machinations/src/solution.rs

70 lines
1.4 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-13 01:23:56 +02:00
solution_id: usize,
level_id: String,
2024-10-06 12:39:36 +02:00
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: usize,
pub tiles: usize,
pub area: usize,
2024-10-06 12:39:36 +02:00
}
impl Solution {
2024-10-13 01:23:56 +02:00
pub fn new(level: &Level, id: usize) -> Self {
2024-10-06 12:39:36 +02:00
Self {
2024-10-13 01:23:56 +02:00
solution_id: id,
2024-10-06 16:00:12 +02:00
level_id: level.id().to_owned(),
2024-10-13 01:23:56 +02:00
name: format!("Unnamed {id}"),
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-13 01:23:56 +02:00
pub fn new_copy(&self, id: usize) -> Self {
let mut new = self.clone();
new.solution_id = id;
new.score = None;
new
}
pub fn id(&self) -> usize {
self.solution_id
2024-10-07 18:43:24 +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!("solution_{}.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 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()
}
}
}