diff --git a/SelfPropelledArtilleryUnit/MapsCollection.cs b/SelfPropelledArtilleryUnit/MapsCollection.cs index cdd47ac..7a6cd83 100644 --- a/SelfPropelledArtilleryUnit/MapsCollection.cs +++ b/SelfPropelledArtilleryUnit/MapsCollection.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -14,6 +15,9 @@ namespace Artilleries private readonly int _pictureWidth; private readonly int _pictureHeight; + private readonly char separatorDict = '|'; + private readonly char separatorData = ';'; + public MapsCollection(int pictureWidth, int pictureHeight) { _mapsStorage = new Dictionary>(); @@ -44,5 +48,66 @@ namespace Artilleries return _mapsStorage.ContainsKey(index) ? _mapsStorage[index] : null; } } + + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + + using (FileStream fs = new FileStream(filename, FileMode.Create)) + using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) + { + sw.WriteLine("MapsCollection"); + foreach (var storage in _mapsStorage) + { + sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"); + } + } + + return true; + } + + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (FileStream fs = new FileStream(filename, FileMode.Open)) + using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) + { + string current_line = sr.ReadLine(); + + if (current_line == null || !current_line.Contains("MapsCollection")) + { + return false; + } + + _mapsStorage.Clear(); + while ((current_line = sr.ReadLine()) != null) + { + var elements = current_line.Split(separatorDict); + AbstractMap map = null; + + switch (elements[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "ForestMap": + map = new ForestMap(); + break; + } + + _mapsStorage.Add(elements[0], new MapWithSetArtilleriesGeneric(_pictureWidth, _pictureHeight, map)); + _mapsStorage[elements[0]].LoadData(elements[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + + return true; + } + } } }