PIbd-23_Polevoy_S.V._SelfPr.../SelfPropelledArtilleryUnit/MapsCollection.cs

114 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Artilleries
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetArtilleriesGeneric<DrawingObjectArtillery, AbstractMap>> _mapsStorage;
public List<string> Keys => _mapsStorage.Keys.ToList();
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<string, MapWithSetArtilleriesGeneric<DrawingObjectArtillery, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddMap(string name, AbstractMap map)
{
if (!_mapsStorage.ContainsKey(name))
{
_mapsStorage.Add(name, new MapWithSetArtilleriesGeneric<DrawingObjectArtillery, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
}
public void DelMap(string name)
{
if (_mapsStorage.ContainsKey(name))
{
_mapsStorage.Remove(name);
}
}
public MapWithSetArtilleriesGeneric<DrawingObjectArtillery, AbstractMap> this[string index]
{
get
{
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<DrawingObjectArtillery, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapsStorage[elements[0]].LoadData(elements[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}
}