195 lines
7.6 KiB
C#
195 lines
7.6 KiB
C#
using WarmlyShip.DrawningObjects;
|
|
using WarmlyShip.MovementStrategy;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace WarmlyShip.Generics
|
|
{
|
|
/// <summary>
|
|
/// Класс для хранения коллекции
|
|
/// </summary>
|
|
internal class ShipsGenericStorage
|
|
{
|
|
/// <summary>
|
|
/// Словарь (хранилище)
|
|
/// </summary>
|
|
readonly Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip,
|
|
DrawningObjectShip>> _shipStorages;
|
|
|
|
/// <summary>
|
|
/// Возвращение списка названий наборов
|
|
/// </summary>
|
|
public List<ShipsCollectionInfo> Keys => _shipStorages.Keys.ToList();
|
|
|
|
/// <summary>
|
|
/// Ширина окна отрисовки
|
|
/// </summary>
|
|
private readonly int _pictureWidth;
|
|
|
|
/// <summary>
|
|
/// Высота окна отрисовки
|
|
/// </summary>
|
|
private readonly int _pictureHeight;
|
|
|
|
/// <summary>
|
|
/// Разделитель для записи ключа и значения элемента словаря
|
|
/// </summary>
|
|
private static readonly char _separatorForKeyValue = '|';
|
|
/// <summary>
|
|
/// Разделитель для записей коллекции данных в файл
|
|
/// </summary>
|
|
private readonly char _separatorRecords = ';';
|
|
/// <summary>
|
|
/// Разделитель для записи информации по объекту в файл
|
|
/// </summary>
|
|
private static readonly char _separatorForObject = ':';
|
|
|
|
/// <summary>
|
|
/// Конструктор
|
|
/// </summary>
|
|
/// <param name="pictureWidth"></param>
|
|
/// <param name="pictureHeight"></param>
|
|
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
|
|
{
|
|
_shipStorages = new Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>();
|
|
_pictureWidth = pictureWidth;
|
|
_pictureHeight = pictureHeight;
|
|
}
|
|
|
|
/// <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<ShipsCollectionInfo, ShipsGenericCollection<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.Name}{_separatorForKeyValue}{records}");
|
|
}
|
|
|
|
if (data.Length == 0)
|
|
{
|
|
throw new IOException("Невалидная операция, нет данных для сохранения");
|
|
}
|
|
string toWrite = $"ShipStorage{Environment.NewLine}{data}";
|
|
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
using (StreamWriter sw = new(filename))
|
|
{
|
|
foreach (var str in strs)
|
|
{
|
|
sw.WriteLine(str);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Загрузка информации по кораблям в хранилище из файла
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
|
public void LoadData(string filename)
|
|
{
|
|
if (!File.Exists(filename))
|
|
{
|
|
throw new IOException("Файл не найден");
|
|
}
|
|
using (StreamReader sr = new(filename))
|
|
{
|
|
string str = sr.ReadLine();
|
|
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
|
if (strs == null || strs.Length == 0)
|
|
{
|
|
throw new IOException("Нет данных для загрузки");
|
|
}
|
|
if (!strs[0].StartsWith("ShipStorage"))
|
|
{
|
|
throw new IOException("Неверный формат данных");
|
|
}
|
|
_shipStorages.Clear();
|
|
do
|
|
{
|
|
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
|
if (record.Length != 2)
|
|
{
|
|
str = sr.ReadLine();
|
|
continue;
|
|
}
|
|
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
|
|
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
|
foreach (string elem in set)
|
|
{
|
|
DrawningShip? ship =
|
|
elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
|
|
if (ship != null)
|
|
{
|
|
if (!(collection + ship))
|
|
{
|
|
throw new IOException("Ошибка добавления в коллекцию");
|
|
}
|
|
}
|
|
}
|
|
_shipStorages.Add(new ShipsCollectionInfo(record[0], string.Empty), collection);
|
|
|
|
str = sr.ReadLine();
|
|
} while (str != null);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Добавление набора
|
|
/// </summary>
|
|
/// <param name="name">Название набора</param>
|
|
public void AddSet(string name)
|
|
{
|
|
_shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Удаление набора
|
|
/// </summary>
|
|
/// <param name="name">Название набора</param>
|
|
public void DelSet(string name)
|
|
{
|
|
if (!_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
|
|
{
|
|
return;
|
|
}
|
|
|
|
_shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Доступ к набору
|
|
/// </summary>
|
|
/// <param name="ind"></param>
|
|
/// <returns></returns>
|
|
public ShipsGenericCollection<DrawningShip, DrawningObjectShip>? this[string ind]
|
|
{
|
|
get
|
|
{
|
|
ShipsCollectionInfo indObj = new ShipsCollectionInfo(ind, string.Empty);
|
|
if (_shipStorages.ContainsKey(indObj))
|
|
{
|
|
return _shipStorages[indObj];
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
}
|