diff --git a/AirBomber/CollectionGenericObjects/AbstractCompany.cs b/AirBomber/CollectionGenericObjects/AbstractCompany.cs
index 0c9b413..ab94fa9 100644
--- a/AirBomber/CollectionGenericObjects/AbstractCompany.cs
+++ b/AirBomber/CollectionGenericObjects/AbstractCompany.cs
@@ -53,7 +53,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
- _collection.SetMaxCount = GetMaxCount;
+ _collection.MaxCount = GetMaxCount;
}
///
diff --git a/AirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs b/AirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs
index 5bd7242..9fbf04c 100644
--- a/AirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/AirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using AirBomber.CollectionGenericObjects;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -15,7 +16,7 @@ public interface ICollectionGenericObjects
///
/// Установка максимального количества элементов
///
- int SetMaxCount { set; }
+ int MaxCount { get; set; }
///
/// Добавление объекта в коллекцию
@@ -45,4 +46,15 @@ public interface ICollectionGenericObjects
/// Позиция
/// Объект
T? Get(int position);
+
+ ///
+ /// Получение типа коллекции
+ ///
+ CollectionType GetCollectionType { get; }
+
+ ///
+ /// Поэлементный вывод элементов коллекции
+ ///
+ ///
+ IEnumerable GetItems();
}
diff --git a/AirBomber/CollectionGenericObjects/ListGenericObjects.cs b/AirBomber/CollectionGenericObjects/ListGenericObjects.cs
index 994f56e..0095cd6 100644
--- a/AirBomber/CollectionGenericObjects/ListGenericObjects.cs
+++ b/AirBomber/CollectionGenericObjects/ListGenericObjects.cs
@@ -16,7 +16,19 @@ public class ListGenericObjects : ICollectionGenericObjects
private int _maxCount;
public int Count => _collection.Count;
- public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
+ public int MaxCount
+ {
+ get => _maxCount;
+ set
+ {
+ if (value > 0)
+ {
+ _maxCount = value;
+ }
+ }
+ }
+
+ public CollectionType GetCollectionType => CollectionType.List;
///
/// Конструктор
@@ -64,4 +76,12 @@ public class ListGenericObjects : ICollectionGenericObjects
_collection.RemoveAt(position);
return obj;
}
+
+ public IEnumerable GetItems()
+ {
+ for (int i = 0; i < _collection.Count; ++i)
+ {
+ yield return _collection[i];
+ }
+ }
}
\ No newline at end of file
diff --git a/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs
index 51ce63d..83c40dc 100644
--- a/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -15,8 +15,12 @@ where T : class
public int Count => _collection.Length;
- public int SetMaxCount
+ public int MaxCount
{
+ get
+ {
+ return _collection.Length;
+ }
set
{
if (value > 0)
@@ -33,6 +37,8 @@ where T : class
}
}
+ public CollectionType GetCollectionType => CollectionType.Massive;
+
///
/// Конструктор
///
@@ -106,4 +112,12 @@ where T : class
_collection[position] = null;
return obj;
}
+
+ public IEnumerable GetItems()
+ {
+ for (int i = 0; i < _collection.Length; ++i)
+ {
+ yield return _collection[i];
+ }
+ }
}
\ No newline at end of file
diff --git a/AirBomber/CollectionGenericObjects/StorageCollection.cs b/AirBomber/CollectionGenericObjects/StorageCollection.cs
index affbd6d..0939a98 100644
--- a/AirBomber/CollectionGenericObjects/StorageCollection.cs
+++ b/AirBomber/CollectionGenericObjects/StorageCollection.cs
@@ -1,4 +1,5 @@
-using System;
+using AirBomber.Drawnings;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -10,7 +11,7 @@ namespace AirBomber.CollectionGenericObjects;
///
///
public class StorageCollection
- where T : class
+ where T : DrawningAirPlane
{
///
/// Словарь (хранилище) с коллекциями
@@ -22,6 +23,21 @@ public class StorageCollection
///
public List Keys => _storages.Keys.ToList();
+ ///
+ /// Ключевое слово, с которого должен начинаться файл
+ ///
+ private readonly string _collectionKey = "CollectionsStorage";
+
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private readonly string _separatorForKeyValue = "|";
+
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly string _separatorItems = ";";
+
///
/// Конструктор
///
@@ -83,4 +99,118 @@ public class StorageCollection
return null;
}
}
+
+ ///
+ /// Сохранение информации по автомобилям в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public bool SaveData(string filename)
+ {
+ if (_storages.Count == 0)
+ {
+ return false;
+ }
+
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+
+ StringBuilder sb = new();
+
+ using (StreamWriter sw = new StreamWriter(filename))
+ {
+ sw.WriteLine(_collectionKey.ToString());
+ foreach (KeyValuePair> kvpair in _storages)
+ {
+ // не сохраняем пустые коллекции
+ if (kvpair.Value.Count == 0)
+ continue;
+ sb.Append(kvpair.Key);
+ sb.Append(_separatorForKeyValue);
+ sb.Append(kvpair.Value.GetCollectionType);
+ sb.Append(_separatorForKeyValue);
+ sb.Append(kvpair.Value.MaxCount);
+ sb.Append(_separatorForKeyValue);
+ foreach (T? item in kvpair.Value.GetItems())
+ {
+ string data = item?.GetDataForSave() ?? string.Empty;
+ if (string.IsNullOrEmpty(data))
+ continue;
+ sb.Append(data);
+ sb.Append(_separatorItems);
+ }
+ sw.WriteLine(sb.ToString());
+ sb.Clear();
+ }
+ }
+ return true;
+ }
+
+ ///
+ /// Загрузка информации по автомобилям в хранилище из файла
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public bool LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ return false;
+ }
+
+ using (StreamReader sr = new StreamReader(filename))
+ {
+ string? str;
+ str = sr.ReadLine();
+ if (str != _collectionKey.ToString())
+ return false;
+ _storages.Clear();
+ while ((str = sr.ReadLine()) != null)
+ {
+ string[] record = str.Split(_separatorForKeyValue);
+ if (record.Length != 4)
+ {
+ continue;
+ }
+ CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
+ ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
+ if (collection == null)
+ {
+ return false;
+ }
+
+ collection.MaxCount = Convert.ToInt32(record[2]);
+
+ string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
+ {
+ if (elem?.CreateDrawningAirPlane() is T boat)
+ {
+ if (collection.Insert(boat) == -1)
+ return false;
+ }
+ }
+ _storages.Add(record[0], collection);
+ }
+ }
+
+ return true;
+ }
+
+ ///
+ /// Создание коллекции по типу
+ ///
+ ///
+ ///
+ private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
+ {
+ return collectionType switch
+ {
+ CollectionType.Massive => new MassiveGenericObjects(),
+ CollectionType.List => new ListGenericObjects(),
+ _ => null,
+ };
+ }
}
\ No newline at end of file
diff --git a/AirBomber/Drawnings/DrawningAirBomber.cs b/AirBomber/Drawnings/DrawningAirBomber.cs
index 5ed5eb7..f303fd4 100644
--- a/AirBomber/Drawnings/DrawningAirBomber.cs
+++ b/AirBomber/Drawnings/DrawningAirBomber.cs
@@ -28,6 +28,14 @@ public class DrawningAirBomber : DrawningAirPlane
EntityAirPlane = new EntityAirBomber(speed, weight, bodyColor, additionalColor, bombs, fuelTanks);
}
+ ///
+ /// Конструктор через сущность
+ ///
+ ///
+ public DrawningAirBomber(EntityAirPlane entityAirPlane) : base()
+ {
+ EntityAirPlane = entityAirPlane;
+ }
public override void DrawTransport(Graphics g)
{
if (EntityAirPlane == null || EntityAirPlane is not EntityAirBomber airbomber || !_startPosX.HasValue || !_startPosY.HasValue)
diff --git a/AirBomber/Drawnings/DrawningAirPlane.cs b/AirBomber/Drawnings/DrawningAirPlane.cs
index 460ebed..9a27fc1 100644
--- a/AirBomber/Drawnings/DrawningAirPlane.cs
+++ b/AirBomber/Drawnings/DrawningAirPlane.cs
@@ -69,7 +69,7 @@ public class DrawningAirPlane
/// Пустой конструктор
///
///
- private DrawningAirPlane()
+ protected DrawningAirPlane()
{
_pictureHeight = null;
_pictureHeight = null;
@@ -92,11 +92,20 @@ public class DrawningAirPlane
///
/// Ширина прорисовки самолета
/// Высота прорисовки самолета
- protected DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
+ public DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
{
_drawningAirPlaneHeight = drawningAirBomberHeight;
_drawningAirPlaneWidth = drawningAirBomberWidth;
}
+
+ ///
+ /// Конструктор через сущность
+ ///
+ ///
+ public DrawningAirPlane(EntityAirPlane entityAirPlane) : base()
+ {
+ EntityAirPlane = entityAirPlane;
+ }
///
/// Установка границ поля
diff --git a/AirBomber/Drawnings/ExtentionDrawningAirPlane.cs b/AirBomber/Drawnings/ExtentionDrawningAirPlane.cs
new file mode 100644
index 0000000..0edb02c
--- /dev/null
+++ b/AirBomber/Drawnings/ExtentionDrawningAirPlane.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using AirBomber.Entities;
+
+namespace AirBomber.Drawnings;
+
+public static class ExtentionDrawningAirPlane
+{
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly string _separatorForObject = ":";
+
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка с данными для создания объекта
+ /// Объект
+ public static DrawningAirPlane? CreateDrawningAirPlane(this string info)
+ {
+ string[] strs = info.Split(_separatorForObject);
+ EntityAirPlane? airPlane = EntityAirBomber.CreateEntityAirBomber(strs);
+ if (airPlane != null)
+ {
+ return new DrawningAirBomber(airPlane);
+ }
+
+ airPlane = EntityAirPlane.CreateEntityAirPlane(strs);
+ if (airPlane != null)
+ {
+ return new DrawningAirPlane(airPlane);
+ }
+
+ return null;
+ }
+
+ ///
+ /// Получение данных для сохранения в файл
+ ///
+ /// Сохраняемый объект
+ /// Строка с данными по объекту
+ public static string GetDataForSave(this DrawningAirPlane drawningAirPlane)
+ {
+ string[]? array = drawningAirPlane?.EntityAirPlane?.GetStringRepresentation();
+
+ if (array == null)
+ {
+ return string.Empty;
+ }
+
+ return string.Join(_separatorForObject, array);
+ }
+}
diff --git a/AirBomber/Entities/EntityAirBomber.cs b/AirBomber/Entities/EntityAirBomber.cs
index 370aaf2..bcaf3bc 100644
--- a/AirBomber/Entities/EntityAirBomber.cs
+++ b/AirBomber/Entities/EntityAirBomber.cs
@@ -4,38 +4,52 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
-namespace AirBomber.Entities
+namespace AirBomber.Entities;
+
+public class EntityAirBomber : EntityAirPlane
{
- public class EntityAirBomber : EntityAirPlane
+ public Color AdditionalColor { get; private set; }
+
+ public void SetAdditionalColor(Color color) => AdditionalColor = color;
+
+ ///
+ /// Признак (опция) наличия бомб
+ ///
+ public bool Bombs { get; private set; }
+ ///
+ /// Признак (опция) наличия дополнительных топливных баков
+ ///
+ public bool FuelTanks { get; private set; }
+
+ ///
+ ///
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ /// Дополнительный цвет
+ /// Признак наличия бомб
+ /// Признак наличия дополнительных топливных баков
+ public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(speed, weight, bodyColor)
{
- public Color AdditionalColor { get; private set; }
- public void SetAdditionalColor(Color color) => AdditionalColor = color;
+ AdditionalColor = additionalColor;
+ Bombs = bombs;
+ FuelTanks = fuelTanks;
+ }
- ///
- /// Признак (опция) наличия бомб
- ///
- public bool Bombs { get; private set; }
- ///
- /// Признак (опция) наличия дополнительных топливных баков
- ///
- public bool FuelTanks { get; private set; }
+ public override string[] GetStringRepresentation()
+ {
+ return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), FuelTanks.ToString() };
+ }
- ///
- ///
- ///
- /// Скорость
- /// Вес
- /// Основной цвет
- /// Дополнительный цвет
- /// Признак наличия бомб
- /// Признак наличия дополнительных топливных баков
- public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(speed, weight, bodyColor)
+ public static EntityAirBomber? CreateEntityAirBomber(string[] strs)
+ {
+ if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber))
{
-
- AdditionalColor = additionalColor;
- Bombs = bombs;
- FuelTanks = fuelTanks;
+ return null;
}
+ return new EntityAirBomber(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]),
+ Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}
diff --git a/AirBomber/Entities/EntityAirPlane.cs b/AirBomber/Entities/EntityAirPlane.cs
index f358d6c..cafec64 100644
--- a/AirBomber/Entities/EntityAirPlane.cs
+++ b/AirBomber/Entities/EntityAirPlane.cs
@@ -42,4 +42,28 @@ public class EntityAirPlane
Weight = weight;
BodyColor = bodyColor;
}
+
+ ///
+ /// Получение строк со значениями свойств объекта класса-сущности
+ ///
+ ///
+ public virtual string[] GetStringRepresentation()
+ {
+ return new[] { nameof(EntityAirPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
+ }
+
+ ///
+ /// Создание объекта из массива строк
+ ///
+ ///
+ ///
+ public static EntityAirPlane? CreateEntityAirPlane(string[] strs)
+ {
+ if (strs.Length != 4 || strs[0] != nameof(EntityAirPlane))
+ {
+ return null;
+ }
+
+ return new EntityAirPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
+ }
}