From 88cbd86febf5bf5e8b99de040ad83e60fe6ada8a Mon Sep 17 00:00:00 2001 From: SAliulov <146759803+SAliulov@users.noreply.github.com> Date: Mon, 17 Jun 2024 08:09:00 +0300 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 24 +++-- .../CollectionInfo.cs | 76 ++++++++++++++ .../ICollectionGenericObjects.cs | 98 ++++++++++--------- .../ListGenericObjects.cs | 32 ++++-- .../MassiveGenericObjects.cs | 67 ++++++++----- .../StorageCollection.cs | 52 +++++----- .../Drawnings/DrawningBomber.cs | 5 - .../Drawnings/DrawningBomberCompareByColor.cs | 27 +++++ .../Drawnings/DrawningBomberCompareByType.cs | 31 ++++++ .../Drawnings/DrawningBomberEqutables.cs | 68 +++++++++++++ .../ObjectAlreadyExistsException.cs | 16 +++ .../PositionOutOfCollectionException.cs | 3 +- .../FormBomberCollection.Designer.cs | 59 +++++++++-- .../ProjectAirBomber/FormBomberCollection.cs | 53 +++++++--- .../FormBomberCollection.resx | 3 + 15 files changed, 475 insertions(+), 139 deletions(-) create mode 100644 ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByColor.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByType.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs create mode 100644 ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectAlreadyExistsException.cs diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs index f94729e..a9aa58d 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs @@ -52,15 +52,15 @@ public abstract class AbstractCompany _collection.MaxCount = GetMaxCount; } - /// - /// Перегрузка оператора сложения для класса - /// - /// Компания - /// Добавляемый объект - /// - public static int operator +(AbstractCompany company, DrawningBomber bomber) - { - return company._collection.Insert(bomber); + /// + /// Перегрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static int operator +(AbstractCompany company, DrawningBomber bomber) + { + return company._collection.Insert(bomber, new DrawningAirCraftEqutables()); } /// @@ -110,6 +110,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/CollectionInfo.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..2751e18 --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +namespace ProjectAirBomber.CollectionGenericObjects; + +/// +/// Класс, хранящиий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + + return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs index 1e630c8..3a2da36 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,61 +1,71 @@ -using ProjectAirBomber.Drawnings; - -namespace ProjectAirBomber.CollectionGenericObjects; +using ProjectAirBomber.CollectionGenericObjects; +/// +/// Интерфейс описания действий для набора хранимых объектов +/// +/// Параметр: ограничение - ссылочный тип /// /// Интерфейс описания действий для набора хранимых объектов /// /// Параметр: ограничение - ссылочный тип public interface ICollectionGenericObjects - where T : class + where T : class { - /// - /// Количество объектов в коллекции - /// - int Count { get; } - - /// - /// Установка максимального количества элементов - /// - int MaxCount { get; set; } - - /// - /// Добавление объекта в коллекцию - /// - /// Добавляемый объект - /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); - - /// - /// Добавление объекта в коллекцию на конкретную позицию - /// - /// Добавляемый объект - /// Позиция - /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); - - /// - /// Удаление объекта из коллекции с конкретной позиции - /// - /// Позиция - /// true - удаление прошло удачно, false - удаление не удалось - T? Remove(int position); - - /// - /// Получение объекта по позиции - /// - /// Позиция - /// Объект - T? Get(int position); + /// + /// Количество объектов в коллекции + /// + int Count { get; } /// - /// Получение типа коллекции + /// Установка максимального количества элементов /// - CollectionType GetCollectionType { get; } + int MaxCount { get; set; } + + /// + /// Добавление объекта в коллекцию + /// + /// Добавляемый объект + /// Cравнение двух объектов + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj, IEqualityComparer? comparer = null); + + /// + /// Добавление объекта в коллекцию на конкретную позицию + /// + /// Добавляемый объект + /// Позиция + /// Cравнение двух объектов + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj, int position, IEqualityComparer? comparer = null); + + /// + /// Удаление объекта из коллекции с конкретной позиции + /// + /// Позиция + /// true - удаление прошло удачно, false - удаление не удалось + T? Remove(int position); + + /// + /// Получение объекта по позиции + /// + /// Позиция + /// Объект + T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } /// /// Получение объектов коллекции по одному /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs index 2f87eab..d57eddf 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs @@ -1,9 +1,4 @@ using ProjectAirBomber.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ProjectAirBomber.CollectionGenericObjects; @@ -24,9 +19,6 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; public int Count => _collection.Count; - - public CollectionType GetCollectionType => CollectionType.List; - public int MaxCount { get @@ -42,6 +34,8 @@ public class ListGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -55,16 +49,30 @@ public class ListGenericObjects : ICollectionGenericObjects if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(); + } + } _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(position); + } + } _collection.Insert(position, obj); return position; } @@ -83,4 +91,8 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs index 814e124..e8ef852 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,6 +1,7 @@ -using System.Runtime.Remoting; -using ProjectAirBomber.Drawnings; + +using ProjectAirBomber.CollectionGenericObjects; using ProjectAirBomber.Exceptions; + namespace ProjectAirBomber.CollectionGenericObjects; /// @@ -9,7 +10,6 @@ namespace ProjectAirBomber.CollectionGenericObjects; /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects where T : class - { /// /// Массив объектов, которые храним @@ -45,6 +45,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// /// Конструктор /// + public MassiveGenericObjects() { _collection = Array.Empty(); @@ -57,29 +58,40 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // вставка в свободное место набора - for (int i = 0; i < Count; i++) + if (comparer != null) { - if (_collection[i] == null) + foreach (T? i in _collection) { - _collection[i] = obj; - return i; + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } + return Insert(obj, 0); + } + + public int Insert(T obj, int position, IEqualityComparer? comparer = null) + { + + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(); + } + + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } } } - throw new CollectionOverflowException(Count); - } - - public int Insert(T obj, int position) - { - // проверка позиции - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - - // проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до if (_collection[position] != null) { bool pushed = false; @@ -112,23 +124,19 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - // вставка _collection[position] = obj; return position; } - public T? Remove(int position) { - // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) throw new ObjectNotFoundException(position); - T? temp = _collection[position]; _collection[position] = null; return temp; } + public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; ++i) @@ -136,4 +144,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + List lst = [.. _collection]; + lst.Sort(comparer.Compare); + for (int i = 0; i < _collection.Length; ++i) + { + _collection[i] = lst[i]; + } + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs index 508fe55..468f73b 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,5 @@ -using ProjectAirBomber.Drawnings; -using ProjectAirBomber.Exceptions; +using ProjectAirBomber.Exceptions; +using ProjectAirBomber.Drawnings; using System.Data; using System.Text; @@ -10,17 +10,17 @@ namespace ProjectAirBomber.CollectionGenericObjects; /// /// public class StorageCollection - where T : DrawningBomber + where T : DrawningAirBomber { /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -42,7 +42,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -52,13 +52,13 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - - if (_storages.ContainsKey(name)) return; + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; if (collectionType == CollectionType.None) return; else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); } /// @@ -67,8 +67,9 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - _storages.Remove(name); + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// @@ -80,8 +81,9 @@ public class StorageCollection { get { - if (_storages.ContainsKey(name)) - return _storages[name]; + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -105,7 +107,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -118,10 +120,9 @@ public class StorageCollection 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; @@ -134,6 +135,7 @@ public class StorageCollection } writer.Write(sb); } + } } @@ -164,18 +166,20 @@ public class StorageCollection while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции" + record[0]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); if (collection == null) { - throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); + throw new InvalidOperationException("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningBomber() is T bomber) @@ -184,7 +188,7 @@ public class StorageCollection { if (collection.Insert(bomber) == -1) { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]); } } catch (CollectionOverflowException ex) @@ -193,7 +197,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs index e01b9e1..076a511 100644 --- a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs @@ -1,9 +1,4 @@ using ProjectAirBomber.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ProjectAirBomber.Drawnings; diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByColor.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByColor.cs new file mode 100644 index 0000000..66727cc --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByColor.cs @@ -0,0 +1,27 @@ +namespace ProjectAirBomber.Drawnings; +public class DrawningBomberCompareByColor : IComparer +{ + public int Compare(DrawningBomber? x, DrawningBomber? y) + { + if (x == null || x.EntityBomber == null) + { + return 1; + } + + if (y == null || y.EntityBomber == null) + { + return -1; + } + var bodycolorCompare = x.EntityBomber.BodyColor.Name.CompareTo(y.EntityBomber.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityBomber.Speed.CompareTo(y.EntityBomber.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBomber.Weight.CompareTo(y.EntityBomber.Weight); + } +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByType.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByType.cs new file mode 100644 index 0000000..e3a3191 --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberCompareByType.cs @@ -0,0 +1,31 @@ +using ProjectAirBomber.Drawnings; + +public class DrawingBomberCompareByType : IComparer +{ + public int Compare(DrawningBomber? x, DrawningBomber? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityBomber == null) + { + return 1; + } + + if (y == null || y.EntityBomber == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityBomber.Speed.CompareTo(y.EntityBomber.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBomber.Weight.CompareTo(y.EntityBomber.Weight); + } +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs new file mode 100644 index 0000000..3dd981c --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs @@ -0,0 +1,68 @@ +using ProjectAirBomber.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectAirBomber.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningAirCraftEqutables : IEqualityComparer +{ + public bool Equals(DrawningBomber? x, DrawningBomber? y) + { + if (x == null || x.EntityBomber == null) + { + return false; + } + + if (y == null || y.EntityBomber == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityBomber.Speed != y.EntityBomber.Speed) + { + return false; + } + + if (x.EntityBomber.Weight != y.EntityBomber.Weight) + { + return false; + } + + if (x.EntityBomber.BodyColor != y.EntityBomber.BodyColor) + { + return false; + } + + if (x is DrawningAirBomber && y is DrawningAirBomber) + { + EntityAirBomber entityX = (EntityAirBomber)x.EntityBomber; + EntityAirBomber entityY = (EntityAirBomber)y.EntityBomber; + if (entityX.FuelTanks != entityY.FuelTanks) + { + return false; + } + if (entityX.Bombs != entityY.Bombs) + { + return false; + } + if (entityX.AdditionalColor != entityY.AdditionalColor) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningBomber obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectAlreadyExistsException.cs b/ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectAlreadyExistsException.cs new file mode 100644 index 0000000..50e7b6f --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Exceptions/ObjectAlreadyExistsException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectAirBomber.Exceptions; +/// +/// Класс, описывающий ошибку, что в коллекции уже есть такой элемент +/// +[Serializable] +public class ObjectAlreadyExistsException : ApplicationException +{ + public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { } + public ObjectAlreadyExistsException() : base() { } + public ObjectAlreadyExistsException(string message) : base(message) { } + public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception) + { } + protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs index 2afd4b5..15323e2 100644 --- a/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectAirBomber/ProjectAirBomber/Exceptions/PositionOutOfCollectionException.cs @@ -1,5 +1,4 @@ - -using System.Runtime.Serialization; +using System.Runtime.Serialization; namespace ProjectAirBomber.Exceptions; diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs index 29914ad..a7b4b64 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs @@ -30,6 +30,7 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByType = new Button(); buttonAddBomber = new Button(); maskedTextBoxPosition = new MaskedTextBox(); buttonRefresh = new Button(); @@ -52,6 +53,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + button2 = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -75,6 +78,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddBomber); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -82,15 +87,26 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 521); + panelCompanyTools.Location = new Point(3, 491); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(262, 285); + panelCompanyTools.Size = new Size(262, 315); panelCompanyTools.TabIndex = 9; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 225); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(253, 42); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // buttonAddBomber // buttonAddBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBomber.Location = new Point(3, 3); + buttonAddBomber.Location = new Point(3, 0); buttonAddBomber.Name = "buttonAddBomber"; buttonAddBomber.Size = new Size(253, 42); buttonAddBomber.TabIndex = 1; @@ -100,7 +116,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 99); + maskedTextBoxPosition.Location = new Point(3, 48); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(253, 23); @@ -110,7 +126,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 228); + buttonRefresh.Location = new Point(3, 177); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(253, 42); buttonRefresh.TabIndex = 6; @@ -121,7 +137,7 @@ // buttonRemoveBomber // buttonRemoveBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveBomber.Location = new Point(3, 128); + buttonRemoveBomber.Location = new Point(3, 77); buttonRemoveBomber.Name = "buttonRemoveBomber"; buttonRemoveBomber.Size = new Size(253, 42); buttonRemoveBomber.TabIndex = 4; @@ -132,7 +148,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 176); + buttonGoToCheck.Location = new Point(3, 125); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(253, 46); buttonGoToCheck.TabIndex = 5; @@ -142,7 +158,7 @@ // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(3, 481); + buttonCreateCompany.Location = new Point(3, 448); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(262, 44); buttonCreateCompany.TabIndex = 8; @@ -238,7 +254,7 @@ comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(3, 438); + comboBoxSelectorCompany.Location = new Point(3, 419); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(262, 23); comboBoxSelectorCompany.TabIndex = 0; @@ -294,6 +310,27 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file|*.txt"; // + // button2 + // + button2.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + button2.Location = new Point(3, 225); + button2.Name = "button2"; + button2.Size = new Size(253, 46); + button2.TabIndex = 7; + button2.Text = "Передать на тесты"; + button2.UseVisualStyleBackColor = true; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 270); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(253, 42); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormBomberCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -305,6 +342,7 @@ MainMenuStrip = menuStrip; Name = "FormBomberCollection"; Text = "Коллекция самолетов"; + Load += FormBomberCollection_Load; groupBoxTools.ResumeLayout(false); panelCompanyTools.ResumeLayout(false); panelCompanyTools.PerformLayout(); @@ -345,5 +383,8 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByType; + private Button button2; + private Button buttonSortByColor; } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs index 5d279c5..cc1256c 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs @@ -2,15 +2,6 @@ using ProjectAirBomber.CollectionGenericObjects; using ProjectAirBomber.Drawnings; using ProjectAirBomber.Exceptions; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; namespace ProjectAirBomber; @@ -72,7 +63,7 @@ public partial class FormBomberCollection : Form /// /// Добавление военного самолёта в коллекцию /// - /// + /// private void SetBomber(DrawningBomber? bomber) { if (_company == null || bomber == null) @@ -245,7 +236,7 @@ public partial class FormBomberCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -329,4 +320,44 @@ public partial class FormBomberCollection : Form } } } + + private void FormBomberCollection_Load(object sender, EventArgs e) + { + + } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareBomber(new DrawingBomberCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareBomber(new DrawningBomberCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareBomber(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx index 8b1dfa1..ca20953 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx @@ -126,4 +126,7 @@ 261, 17 + + 25 + \ No newline at end of file -- 2.25.1 From 27d8385bad0ef2e4add2ececa16cda3b7f1531d9 Mon Sep 17 00:00:00 2001 From: SAliulov <146759803+SAliulov@users.noreply.github.com> Date: Mon, 17 Jun 2024 11:42:34 +0300 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9D=D0=B5=D0=BA=D0=BE=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D1=8B=D0=B5=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../MassiveGenericObjects.cs | 3 +- .../Drawnings/DrawningBomberEqutables.cs | 2 +- .../ProjectAirBomber/FormBomberCollection.cs | 37 +++++++++++++------ 4 files changed, 29 insertions(+), 15 deletions(-) diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs index a9aa58d..9f19b6b 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs @@ -60,7 +60,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningBomber bomber) { - return company._collection.Insert(bomber, new DrawningAirCraftEqutables()); + return company._collection.Insert(bomber, new DrawningBomberEqutables()); } /// diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs index e8ef852..c7f49a9 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs @@ -146,7 +146,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public void CollectionSort(IComparer comparer) { - List lst = [.. _collection]; + List value = [.. _collection]; + List lst = value; lst.Sort(comparer.Compare); for (int i = 0; i < _collection.Length; ++i) { diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs index 3dd981c..76d41d9 100644 --- a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomberEqutables.cs @@ -6,7 +6,7 @@ namespace ProjectAirBomber.Drawnings; /// /// Реализация сравнения двух объектов класса-прорисовки /// -public class DrawningAirCraftEqutables : IEqualityComparer +public class DrawningBomberEqutables : IEqualityComparer { public bool Equals(DrawningBomber? x, DrawningBomber? y) { diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs index cc1256c..32855ce 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs @@ -2,6 +2,7 @@ using ProjectAirBomber.CollectionGenericObjects; using ProjectAirBomber.Drawnings; using ProjectAirBomber.Exceptions; +using System.Xml.Linq; namespace ProjectAirBomber; @@ -81,7 +82,12 @@ public partial class FormBomberCollection : Form catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); - _logger.LogError($"Не удалось добавить объект: {ex.Message}"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + } + catch (ObjectAlreadyExistsException) + { + MessageBox.Show("Такой объект уже существует"); + _logger.LogError("Ошибка: такой объект уже существует {0}", bomber); } } @@ -109,18 +115,18 @@ public partial class FormBomberCollection : Form { object decrementObject = _company - pos; MessageBox.Show("Объект удален"); - _logger.LogInformation($"Удален объект по позиции {pos}"); + _logger.LogInformation($"Удален по позиции {pos}"); pictureBox.Image = _company.Show(); } - catch (ObjectNotFoundException) + catch (ObjectNotFoundException ex) { MessageBox.Show("Объект не найден"); - _logger.LogError($"Удаление не найденного объекта в позиции {pos} "); + _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} "); } catch (PositionOutOfCollectionException) { MessageBox.Show("Удаление вне рамках коллекции"); - _logger.LogError($"Удаление объекта за пределами коллекции {pos} "); + _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} "); } } @@ -135,7 +141,6 @@ public partial class FormBomberCollection : Form { return; } - try { DrawningBomber? bomber = null; @@ -190,8 +195,8 @@ public partial class FormBomberCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Не заполненная коллекция"); return; } CollectionType collectionType = CollectionType.None; @@ -203,8 +208,8 @@ public partial class FormBomberCollection : Form { collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, - collectionType); + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); RerfreshListBoxItems(); } /// @@ -217,14 +222,17 @@ public partial class FormBomberCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogError("Удаление невыбранной коллекции"); return; } + string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция: {name}"); RerfreshListBoxItems(); } @@ -254,20 +262,25 @@ public partial class FormBomberCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogError("Создание компании невыбранной коллекции"); return; } + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogError("Не удалось инициализировать коллекцию"); return; } + switch (comboBoxSelectorCompany.Text) { - case "Хранилище": + case "Ангар": _company = new BomberHungarService(pictureBox.Width, pictureBox.Height, collection); break; } + panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } @@ -323,7 +336,7 @@ public partial class FormBomberCollection : Form private void FormBomberCollection_Load(object sender, EventArgs e) { - + } /// -- 2.25.1 From 60f0b8f1061f336c623ff3e68ca43a302aa48e62 Mon Sep 17 00:00:00 2001 From: SAliulov <146759803+SAliulov@users.noreply.github.com> Date: Mon, 17 Jun 2024 17:14:31 +0300 Subject: [PATCH 3/3] =?UTF-8?q?net8.0,=20=20=D0=B2=20StorageCollection=20?= =?UTF-8?q?=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2=D1=8B=D0=B9=20=D0=BE=D0=B1=D1=8A?= =?UTF-8?q?=D0=B5=D0=BA=D1=82,=20=D0=B2=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D0=B5=20=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BF=D0=B0=D0=BD=D0=B8=D0=B8=20"=D0=90?= =?UTF-8?q?=D0=BD=D0=B3=D0=B0=D1=80"=20=D0=B7=D0=B0=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BD=D0=B0=20"=D0=A5=D1=80=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=D1=89=D0=B5"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionGenericObjects/StorageCollection.cs | 2 +- ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs | 4 ++-- ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs index 468f73b..47b74c8 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs @@ -10,7 +10,7 @@ namespace ProjectAirBomber.CollectionGenericObjects; /// /// public class StorageCollection - where T : DrawningAirBomber + where T : DrawningBomber { /// /// Словарь (хранилище) с коллекциями diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs index 32855ce..94252e1 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs @@ -166,7 +166,7 @@ public partial class FormBomberCollection : Form } catch (ObjectNotFoundException) { - _logger.LogError("Ошибка при передаче объекта на FormAirFighter"); + _logger.LogError("Ошибка при передаче объекта на FormAirBomber"); } } @@ -276,7 +276,7 @@ public partial class FormBomberCollection : Form switch (comboBoxSelectorCompany.Text) { - case "Ангар": + case "Хранилище": _company = new BomberHungarService(pictureBox.Width, pictureBox.Height, collection); break; } diff --git a/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj b/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj index 228b2c7..36a7753 100644 --- a/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj +++ b/ProjectAirBomber/ProjectAirBomber/ProjectAirBomber.csproj @@ -2,7 +2,7 @@ WinExe - net7.0-windows + net8.0-windows7.0 enable true enable -- 2.25.1