155 lines
6.1 KiB
C#
155 lines
6.1 KiB
C#
using Battleship.DrawningObjects;
|
|
using Battleship.MovementStrategy;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Battleship.Generics
|
|
{
|
|
internal class ShipsGenericStorage
|
|
{
|
|
readonly Dictionary<string, ShipGenericCollection<DrawningShip,
|
|
DrawningObjectShip>> _shipStorages;
|
|
|
|
public List<string> Keys => _shipStorages.Keys.ToList();
|
|
|
|
private readonly int _pictureWidth;
|
|
|
|
private readonly int _pictureHeight;
|
|
/// <summary>
|
|
/// Разделитель для записи ключа и значения элемента словаря
|
|
/// </summary>
|
|
private static readonly char _separatorForKeyValue = '|';
|
|
/// <summary>
|
|
/// Разделитель для записей коллекции данных в файл
|
|
/// </summary>
|
|
private readonly char _separatorRecords = ';';
|
|
/// <summary>
|
|
/// Разделитель для записи информации по объекту в файл
|
|
/// </summary>
|
|
private static readonly char _separatorForObject = ':';
|
|
|
|
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
|
|
{
|
|
_shipStorages = new Dictionary<string,
|
|
ShipGenericCollection<DrawningShip, DrawningObjectShip>>();
|
|
_pictureWidth = pictureWidth;
|
|
_pictureHeight = pictureHeight;
|
|
}
|
|
|
|
public void AddSet(string name)
|
|
{
|
|
if (_shipStorages.ContainsKey(name))
|
|
return;
|
|
_shipStorages[name] = new ShipGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight);
|
|
}
|
|
|
|
public void DelSet(string name)
|
|
{
|
|
if (!_shipStorages.ContainsKey(name))
|
|
return;
|
|
_shipStorages.Remove(name);
|
|
}
|
|
|
|
public ShipGenericCollection<DrawningShip, DrawningObjectShip>?
|
|
this[string ind]
|
|
{
|
|
get
|
|
{
|
|
if (_shipStorages.ContainsKey(ind))
|
|
return _shipStorages[ind];
|
|
return null;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Сохранение информации по автомобилям в хранилище в файл
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
|
public void SaveData(string filename)
|
|
{
|
|
if (File.Exists(filename))
|
|
{
|
|
File.Delete(filename);
|
|
}
|
|
StringBuilder data = new();
|
|
foreach (KeyValuePair<string, ShipGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
|
|
{
|
|
StringBuilder records = new();
|
|
foreach (DrawningShip? elem in record.Value.GetShips)
|
|
{
|
|
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
|
}
|
|
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
|
|
}
|
|
if (data.Length == 0)
|
|
{
|
|
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
|
|
}
|
|
using (StreamWriter writer = new StreamWriter(filename))
|
|
{
|
|
writer.Write($"ShipStorage{Environment.NewLine}{data}");
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Загрузка информации по кораблям в хранилище из файла
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
|
|
|
public void LoadData(string filename)
|
|
{
|
|
if (!File.Exists(filename))
|
|
{
|
|
throw new FileNotFoundException($"Файл {filename} не найден");
|
|
}
|
|
|
|
using (StreamReader fs = File.OpenText(filename))
|
|
{
|
|
string str = fs.ReadLine();
|
|
if (str == null || str.Length == 0)
|
|
{
|
|
throw new NullReferenceException("Нет данных для загрузки");
|
|
}
|
|
if (!str.StartsWith("ShipStorage"))
|
|
{
|
|
throw new FormatException("Неверный формат данных");
|
|
}
|
|
|
|
_shipStorages.Clear();
|
|
string strs = "";
|
|
while ((strs = fs.ReadLine()) != null)
|
|
{
|
|
if (strs == null)
|
|
{
|
|
throw new NullReferenceException("Нет данных для загрузки");
|
|
}
|
|
|
|
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
|
if (record.Length != 2)
|
|
{
|
|
continue;
|
|
}
|
|
ShipGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
|
|
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
|
foreach (string elem in set)
|
|
{
|
|
DrawningShip? plane = elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
|
|
if (plane != null)
|
|
{
|
|
if (!(collection + plane))
|
|
{
|
|
throw new InvalidOperationException("Ошибка добавления в коллекцию");
|
|
}
|
|
}
|
|
}
|
|
_shipStorages.Add(record[0], collection);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|