diff --git a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/AbstractCompany.cs
index 3ea6809..2669826 100644
--- a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/AbstractCompany.cs
+++ b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/AbstractCompany.cs
@@ -49,7 +49,7 @@ namespace ProjectLocomotive.CollectionGenericObjects
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
- _collection.SetMaxCount = GetMaxCount;
+ _collection.MaxCount = GetMaxCount;
}
///
diff --git a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs
index 21475a1..6956c55 100644
--- a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -14,7 +14,7 @@
///
/// Установка максимального количества элементов
///
- int SetMaxCount { set; }
+ int MaxCount { get; set; }
///
/// Добавление объекта в коллекцию
///
@@ -40,6 +40,17 @@
/// Позиция
/// Объект
T? Get(int position);
+
+ ///
+ /// Получение типа коллекции
+ ///
+ CollectionType GetCollectionType { get; }
+ ///
+ /// Получение объектов коллекции по одному
+ ///
+ /// Поэлементый вывод элементов коллекции
+ IEnumerable GetItems();
+
}
}
diff --git a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ListGenericObjects.cs
index c7b734a..e8150a9 100644
--- a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/ListGenericObjects.cs
@@ -16,7 +16,19 @@
///
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;
///
/// Конструктор
///
@@ -61,5 +73,12 @@
_collection.RemoveAt(position);
return obj;
}
+ public IEnumerable GetItems()
+ {
+ for (int i = 0; i < _collection.Count; ++i)
+ {
+ yield return _collection[i];
+ }
+ }
}
}
diff --git a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs
index cbd8184..cc3649a 100644
--- a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -15,8 +15,12 @@ namespace ProjectLocomotive.CollectionGenericObjects
///
private T?[] _collection;
public int Count => _collection.Length;
- public int SetMaxCount
+ public int MaxCount
{
+ get
+ {
+ return _collection.Length;
+ }
set
{
if (value > 0)
@@ -33,6 +37,8 @@ namespace ProjectLocomotive.CollectionGenericObjects
}
}
+ public CollectionType GetCollectionType => CollectionType.Massive;
+
///
/// Конструктор
///
@@ -112,5 +118,13 @@ namespace ProjectLocomotive.CollectionGenericObjects
_collection[position] = null;
return obj;
}
+
+ public IEnumerable GetItems()
+ {
+ for (int i = 0; i < _collection.Length; ++i)
+ {
+ yield return _collection[i];
+ }
+ }
}
}
diff --git a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/StorageCollection.cs
index 6178778..da0bb29 100644
--- a/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectLocomotive/ProjectLocomotive/CollectionGenericObjects/StorageCollection.cs
@@ -1,10 +1,13 @@
-namespace ProjectLocomotive.CollectionGenericObjects
+using ProjectLocomotive.Drawnings;
+using System.Text;
+
+namespace ProjectLocomotive.CollectionGenericObjects
{
// Класс-хранилище коллекций
///
///
public class StorageCollection
- where T : class
+ where T : DrawningLocomotive
{
///
/// Словарь (хранилище) с коллекциями
@@ -16,6 +19,21 @@
///
public List Keys => _storages.Keys.ToList();
+ ///
+ /// Ключевое слово, с которого должен начинаться файл
+ ///
+ private readonly string _collectionKey = "CollectionsStorage";
+
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private readonly string _separatorForKeyValue = "|";
+
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly string _separatorItems = ";";
+
///
/// Конструктор
///
@@ -69,5 +87,125 @@
return null;
}
}
+ ///
+ /// Сохранение информации по автомобилям в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public bool SaveData(string filename)
+ {
+ if (_storages.Count == 0)
+ {
+ return false;
+ }
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+ using (StreamWriter writer = new StreamWriter(filename))
+ {
+ writer.Write(_collectionKey);
+ foreach (KeyValuePair> value in _storages)
+ {
+ StringBuilder sb = new();
+ sb.Append(Environment.NewLine);
+ // не сохраняем пустые коллекции
+ if (value.Value.Count == 0)
+ {
+ continue;
+ }
+
+ sb.Append(value.Key);
+ sb.Append(_separatorForKeyValue);
+ sb.Append(value.Value.GetCollectionType);
+ sb.Append(_separatorForKeyValue);
+ sb.Append(value.Value.MaxCount);
+ sb.Append(_separatorForKeyValue);
+ foreach (T? item in value.Value.GetItems())
+ {
+ string data = item?.GetDataForSave() ?? string.Empty;
+ if (string.IsNullOrEmpty(data))
+ {
+ continue;
+ }
+ sb.Append(data);
+ sb.Append(_separatorItems);
+ }
+ writer.Write(sb);
+ }
+ }
+ return true;
+ }
+
+ ///
+ /// Загрузка информации по автомобилям в хранилище из файла
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public bool LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ return false;
+ }
+ using (StreamReader fs = File.OpenText(filename))
+ {
+ string str = fs.ReadLine();
+ if (str == null || str.Length == 0)
+ {
+ return false;
+ }
+ if (!str.StartsWith(_collectionKey))
+ {
+ return false;
+ }
+ _storages.Clear();
+ string strs = "";
+ while ((strs = fs.ReadLine()) != null)
+ {
+ string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ 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?.CreateDrawningLocomotive() is T locomotive)
+ {
+ if (collection.Insert(locomotive) == -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,
+ };
+ }
}
}
diff --git a/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs
index 684178b..afb7741 100644
--- a/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs
+++ b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs
@@ -10,7 +10,7 @@ public class DrawningLocomotive
///
/// Класс-сущность
///
- public EntityLocomotiev? EntityLocomotive { get; protected set; }
+ public EntityLocomotive? EntityLocomotive { get; protected set; }
///
/// Ширина окна
///
@@ -58,7 +58,7 @@ public class DrawningLocomotive
///
/// Пустой онструктор
///
- private DrawningLocomotive()
+ public DrawningLocomotive()
{
_pictureWidth = null;
_pictureHeight = null;
@@ -74,7 +74,7 @@ public class DrawningLocomotive
/// Основной цвет
public DrawningLocomotive(int speed, double weight, Color bodyColor) : this()
{
- EntityLocomotive = new EntityLocomotiev(speed, weight, bodyColor);
+ EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
///
/// Конструктор для наследников
@@ -87,6 +87,15 @@ public class DrawningLocomotive
_pictureHeight = drawningCarHeight;
}
+ ///
+ /// конструктор
+ ///
+ ///
+ public DrawningLocomotive(EntityLocomotive entityLocomotive)
+ {
+ EntityLocomotive = entityLocomotive;
+ }
+
///
/// Установка границ поля
///
diff --git a/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs
index 310360e..0b175be 100644
--- a/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs
+++ b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs
@@ -22,7 +22,13 @@ namespace ProjectLocomotive.Drawnings
{
EntityLocomotive = new EntityTLocomotive(speed, weight, bodyColor, additionalColor, pipe, fueltank, headlight);
}
-
+ public DrawningTLocomotive(EntityLocomotive entityLocomotive)
+ {
+ if (entityLocomotive != null)
+ {
+ EntityLocomotive = entityLocomotive;
+ }
+ }
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive == null || EntityLocomotive is not EntityTLocomotive entityTLocomotive || !_startPosX.HasValue ||
diff --git a/ProjectLocomotive/ProjectLocomotive/Drawnings/ExtentionDrawningArtilleryUnit.cs b/ProjectLocomotive/ProjectLocomotive/Drawnings/ExtentionDrawningArtilleryUnit.cs
new file mode 100644
index 0000000..1509afb
--- /dev/null
+++ b/ProjectLocomotive/ProjectLocomotive/Drawnings/ExtentionDrawningArtilleryUnit.cs
@@ -0,0 +1,50 @@
+using ProjectLocomotive.Entities;
+
+namespace ProjectLocomotive.Drawnings
+{
+ public static class ExtentionDrawningLocomotive
+ {
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly string _separatorForObject = ":";
+
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка с данными для создания объекта
+ /// Объект
+ public static DrawningLocomotive? CreateDrawningLocomotive(this string info)
+ {
+ string[] strs = info.Split(_separatorForObject);
+ EntityLocomotive? locomotive = EntityTLocomotive.CreateEntityTLocomotive(strs);
+ if (locomotive != null)
+ {
+ return new DrawningTLocomotive(locomotive);
+ }
+
+ locomotive = EntityLocomotive.CreateEntityLocomotive(strs);
+ if (locomotive != null)
+ {
+ return new DrawningLocomotive(locomotive);
+ }
+ return null;
+ }
+
+ ///
+ /// Получение данных для сохранения в файл
+ ///
+ /// Сохраняемый объект
+ /// Строка с данными по объекту
+ public static string GetDataForSave(this DrawningLocomotive drawningLocomotive)
+ {
+ string[]? array = drawningLocomotive?.EntityLocomotive?.GetStringRepresentation();
+ if (array == null)
+ {
+ return string.Empty;
+ }
+ return string.Join(_separatorForObject, array);
+ }
+
+ }
+}
diff --git a/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs b/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotive.cs
similarity index 53%
rename from ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs
rename to ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotive.cs
index fb9bc9d..9dbe0f3 100644
--- a/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs
+++ b/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotive.cs
@@ -3,7 +3,7 @@
///
/// Класс-сущность "поезд"
///
-public class EntityLocomotiev
+public class EntityLocomotive
{
//свойства
///
@@ -32,10 +32,34 @@ public class EntityLocomotiev
/// скорость
/// вес
/// основной цвет
- public EntityLocomotiev(int speed, double weight, Color bodyColor)
+ public EntityLocomotive(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
+
+ ///
+ /// Получение строк со значениями свойств объекта класса-сущности
+ ///
+ ///
+ public virtual string[] GetStringRepresentation()
+ {
+ return new[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name };
+ }
+
+ ///
+ /// Создание объекта из массива строк
+ ///
+ ///
+ ///
+ public static EntityLocomotive? CreateEntityLocomotive(string[] strs)
+ {
+ if (strs.Length != 4 || strs[0] != nameof(EntityLocomotive))
+ {
+ return null;
+ }
+
+ return new EntityLocomotive(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
+ }
}
diff --git a/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs
index e81b07d..3559d97 100644
--- a/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs
+++ b/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs
@@ -1,6 +1,6 @@
namespace ProjectLocomotive.Entities
{
- internal class EntityTLocomotive : EntityLocomotiev
+ internal class EntityTLocomotive : EntityLocomotive
{
///
/// Признак (опция) наличие трубы
@@ -29,5 +29,30 @@
Fueltank = fueltank;
Headlight = headlight;
}
+
+ ///
+ /// Получение строк со значениями свойств объекта класса-сущности
+ ///
+ ///
+ public override string[] GetStringRepresentation()
+ {
+ return new[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
+ Pipe.ToString(), Fueltank.ToString(), Headlight.ToString() };
+ }
+
+ ///
+ /// Создание объекта из массива строк
+ ///
+ ///
+ ///
+ public static EntityLocomotive? CreateEntityTLocomotive(string[] strs)
+ {
+ if (strs.Length != 8 || strs[0] != nameof(EntityLocomotive))
+ {
+ return null;
+ }
+ return new EntityTLocomotive(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
+ Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
+ }
}
}