Save/Load

- added save/load functions to json
This commit is contained in:
2024-05-14 12:43:05 +02:00
parent 64ee4bf732
commit d07f22713d
2 changed files with 24 additions and 0 deletions

View File

@@ -9,6 +9,7 @@ edition = "2021"
rand = "0.8.5"
rand_pcg = { version = "0.3.1", features = ["serde1"] }
serde = { version = "1.0.197", features = ["derive", "rc"] }
serde_json = "1.0.117"
typetag = "0.2.16"
dyn-clone = "1.0.17"
console = "0.15.8"

View File

@@ -7,6 +7,10 @@ use super::{
use rand::{RngCore, SeedableRng};
use rand_pcg::Pcg32;
use serde::{Deserialize, Serialize};
use std::{
fs::File,
io::{self, BufReader, BufWriter},
};
/// Rappresenta un Dungeon in stile RogueLike.\
/// In esso possiamo trovare dei piani generati casualmente
@@ -35,6 +39,25 @@ impl Dungeon {
game
}
/// Carica il dungeon da un file.\
/// Il file deve essere formattato tramite json, altrimenti viene ritornato un errore.
pub fn load(filename: &str) -> io::Result<Self> {
let file = File::open(filename)?;
let reader = BufReader::new(file);
let dungeon: Self = serde_json::from_reader(reader)?;
Ok(dungeon)
}
/// Salva il dungeon corrente nel file indicato.\
/// Il salvataggio viene fatto tramite serializzazione JSON in modo che sia facile da vedere.\
/// Nel caso in cui ci siano problemi con I/O, viene ritornato un errore.
pub fn save(&mut self, filename: &str) -> io::Result<()> {
let file = File::create(filename)?;
let writer = BufWriter::new(file);
let _ = serde_json::to_writer_pretty(writer, self)?;
Ok(())
}
/// Aggiunge un giocatore al Dungeon, esso avrà le statistiche di base assegnate
/// ad esso tramite la configurazione indicata nel costruttore.\
/// Il giocatore appena inserito si troverà al piano 0.