From 9e2582cd3f5b2bf6f3e8c2d6434ab06ea97832a7 Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 7 May 2017 20:04:31 -0400 Subject: Implement a proper save system --- TimeHACK.Engine/SaveSystem.cs | 87 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 TimeHACK.Engine/SaveSystem.cs (limited to 'TimeHACK.Engine/SaveSystem.cs') diff --git a/TimeHACK.Engine/SaveSystem.cs b/TimeHACK.Engine/SaveSystem.cs new file mode 100644 index 0000000..c6e19a2 --- /dev/null +++ b/TimeHACK.Engine/SaveSystem.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace TimeHACK.Engine +{ + public static class SaveSystem + { + public static Save CurrentSave { get; private set; } + + public static string GameDirectory + { + get + { + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "TimeHACK"); + } + } + + public static string ProfileDirectory + { + get + { + return Path.Combine(GameDirectory, "Profiles"); + } + } + + public static bool LoadSave() + { + if(File.Exists(Path.Combine(ProfileDirectory, "user.save"))) + { + //Read base64 string from file + string b64 = File.ReadAllText(Path.Combine(ProfileDirectory, "user.save")); + //Get Unicode byte array + byte[] bytes = Convert.FromBase64String(b64); + //Decode the Unicode + string json = Encoding.UTF8.GetString(bytes); + //Deserialize save object. + CurrentSave = JsonConvert.DeserializeObject(json); + return true; + } + else + { + NewGame(); + return false; + } + } + + public static void NewGame() + { + //TODO: User must set a username....somehow + if (!Directory.Exists(GameDirectory)) + Directory.CreateDirectory(GameDirectory); + + if (!Directory.Exists(ProfileDirectory)) + Directory.CreateDirectory(ProfileDirectory); + + var save = new Save(); + save.ExperiencedStories = new List(); + save.InstalledPrograms = new Dictionary(); + CurrentSave = save; + SaveGame(); + } + + public static void SaveGame() + { + //Serialize the save to JSON. + string json = JsonConvert.SerializeObject(CurrentSave); + //Get JSON bytes (Unicode format). + var bytes = Encoding.UTF8.GetBytes(json); + //Encode the array into Base64. + string b64 = Convert.ToBase64String(bytes); + //Write to disk. + File.WriteAllText(Path.Combine(ProfileDirectory, "user.save"), b64); + } + } + + public class Save + { + public string Username { get; set; } + public Dictionary InstalledPrograms { get; set; } + public List ExperiencedStories { get; set; } + } +} -- cgit v1.2.3