This commit is contained in:
илья 2024-08-29 21:09:09 +04:00
parent 4511d78c10
commit abc3034fa0
10 changed files with 309 additions and 13 deletions

View File

@ -49,7 +49,7 @@ namespace ProjectLocomotive.CollectionGenericObjects
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>

View File

@ -14,7 +14,7 @@
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
@ -40,6 +40,17 @@
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
} }
} }

View File

@ -16,7 +16,19 @@
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; 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;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -61,5 +73,12 @@
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
} }
} }

View File

@ -15,8 +15,12 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -33,6 +37,8 @@ namespace ProjectLocomotive.CollectionGenericObjects
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -112,5 +118,13 @@ namespace ProjectLocomotive.CollectionGenericObjects
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }
} }

View File

@ -1,10 +1,13 @@
namespace ProjectLocomotive.CollectionGenericObjects using ProjectLocomotive.Drawnings;
using System.Text;
namespace ProjectLocomotive.CollectionGenericObjects
{ {
// Класс-хранилище коллекций // Класс-хранилище коллекций
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningLocomotive
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
@ -16,6 +19,21 @@
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -69,5 +87,125 @@
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
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<string, ICollectionGenericObjects<T>> 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;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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<T>? collection = StorageCollection<T>.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;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }
} }

View File

@ -10,7 +10,7 @@ public class DrawningLocomotive
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityLocomotiev? EntityLocomotive { get; protected set; } public EntityLocomotive? EntityLocomotive { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
@ -58,7 +58,7 @@ public class DrawningLocomotive
/// <summary> /// <summary>
/// Пустой онструктор /// Пустой онструктор
/// </summary> /// </summary>
private DrawningLocomotive() public DrawningLocomotive()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
@ -74,7 +74,7 @@ public class DrawningLocomotive
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
public DrawningLocomotive(int speed, double weight, Color bodyColor) : this() public DrawningLocomotive(int speed, double weight, Color bodyColor) : this()
{ {
EntityLocomotive = new EntityLocomotiev(speed, weight, bodyColor); EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
} }
/// <summary> /// <summary>
/// Конструктор для наследников /// Конструктор для наследников
@ -87,6 +87,15 @@ public class DrawningLocomotive
_pictureHeight = drawningCarHeight; _pictureHeight = drawningCarHeight;
} }
/// <summary>
/// конструктор
/// </summary>
/// <param name="entityLocomotive"></param>
public DrawningLocomotive(EntityLocomotive entityLocomotive)
{
EntityLocomotive = entityLocomotive;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>

View File

@ -22,7 +22,13 @@ namespace ProjectLocomotive.Drawnings
{ {
EntityLocomotive = new EntityTLocomotive(speed, weight, bodyColor, additionalColor, pipe, fueltank, headlight); 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) public override void DrawTransport(Graphics g)
{ {
if (EntityLocomotive == null || EntityLocomotive is not EntityTLocomotive entityTLocomotive || !_startPosX.HasValue || if (EntityLocomotive == null || EntityLocomotive is not EntityTLocomotive entityTLocomotive || !_startPosX.HasValue ||

View File

@ -0,0 +1,50 @@
using ProjectLocomotive.Entities;
namespace ProjectLocomotive.Drawnings
{
public static class ExtentionDrawningLocomotive
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLocomotive">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningLocomotive drawningLocomotive)
{
string[]? array = drawningLocomotive?.EntityLocomotive?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}
}

View File

@ -3,7 +3,7 @@
/// <summary> /// <summary>
/// Класс-сущность "поезд" /// Класс-сущность "поезд"
/// </summary> /// </summary>
public class EntityLocomotiev public class EntityLocomotive
{ {
//свойства //свойства
/// <summary> /// <summary>
@ -32,10 +32,34 @@ public class EntityLocomotiev
/// <param name="speed">скорость</param> /// <param name="speed">скорость</param>
/// <param name="weight">вес</param> /// <param name="weight">вес</param>
/// <param name="bodyColor">основной цвет</param> /// <param name="bodyColor">основной цвет</param>
public EntityLocomotiev(int speed, double weight, Color bodyColor) public EntityLocomotive(int speed, double weight, Color bodyColor)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
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]));
}
} }

View File

@ -1,6 +1,6 @@
namespace ProjectLocomotive.Entities namespace ProjectLocomotive.Entities
{ {
internal class EntityTLocomotive : EntityLocomotiev internal class EntityTLocomotive : EntityLocomotive
{ {
/// <summary> /// <summary>
/// Признак (опция) наличие трубы /// Признак (опция) наличие трубы
@ -29,5 +29,30 @@
Fueltank = fueltank; Fueltank = fueltank;
Headlight = headlight; Headlight = headlight;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Pipe.ToString(), Fueltank.ToString(), Headlight.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
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]));
}
} }
} }