From d07f22713d19081cf4db5c22f8e2829bedae3e53 Mon Sep 17 00:00:00 2001 From: Berack96 Date: Tue, 14 May 2024 12:43:05 +0200 Subject: [PATCH] Save/Load - added save/load functions to json --- Cargo.toml | 1 + src/es03_game/game.rs | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 403b5d7..dbf7ec4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/es03_game/game.rs b/src/es03_game/game.rs index db3929d..fa1732c 100644 --- a/src/es03_game/game.rs +++ b/src/es03_game/game.rs @@ -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 { + 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.