From 297b3a53953e2cd831c032a259a72c5e53a5050e Mon Sep 17 00:00:00 2001 From: Garifullin-Farid <95081032+Garifullin-Farid@users.noreply.github.com> Date: Tue, 21 May 2024 08:41:23 +0400 Subject: [PATCH] LabWork_8 --- .../AbstractCompany.cs | 9 +- .../CollectionInfo.cs | 85 ++++++++ .../ICollectionGenericObjects.cs | 17 +- .../ListGenericObjects.cs | 56 +++-- .../MassiveGenericObjects.cs | 197 +++++++++--------- .../StorageCollection.cs | 144 ++++++------- .../Drawning/DrawningTankCompareByColor.cs | 35 ++++ .../Drawning/DrawningTankCompareByType.cs | 33 +++ .../Drawning/DrawningTankEqutables.cs | 58 ++++++ .../ObjectAlreadyExistsException.cs | 19 ++ .../FormBattleTankCollection.Designer.cs | 46 +++- .../ProjectTank/FormBattleTankCollection.cs | 31 ++- 12 files changed, 511 insertions(+), 219 deletions(-) create mode 100644 ProjectTank/ProjectTank/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectTank/ProjectTank/Drawning/DrawningTankCompareByColor.cs create mode 100644 ProjectTank/ProjectTank/Drawning/DrawningTankCompareByType.cs create mode 100644 ProjectTank/ProjectTank/Drawning/DrawningTankEqutables.cs create mode 100644 ProjectTank/ProjectTank/Exceptions/ObjectAlreadyExistsException.cs diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs index 77e0f65..886a191 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs @@ -1,5 +1,6 @@ using ProjectTank.Drawning; using ProjectTank.CollectionGenericObjects; +using ProjectTank.Drawnings; /// /// Абстракция компании, хранящий Танковую базу @@ -58,7 +59,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTank tank) { - return company?._collection.Insert(tank)??-1; + return company._collection?.Insert(tank,new DrawningTankEqutables())??-1; } /// @@ -101,7 +102,11 @@ public abstract class AbstractCompany return bitmap; } - + /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод заднего фона /// diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionInfo.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..522342a --- /dev/null +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,85 @@ + +namespace ProjectTank.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 bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs index 3a42d62..fa04db2 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectTank.CollectionGenericObjects +using ProjectTank.Drawning; + +namespace ProjectTank.CollectionGenericObjects { /// /// Интерфейс описания действий для набора хранимых данных @@ -19,18 +21,20 @@ /// /// Добавление объекта в коллекцию - /// + /// /// Добавляемый объект + /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,5 +60,10 @@ /// /// Поэлементный вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer comparer); } } diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs index fa6605d..d5918cc 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs @@ -15,7 +15,6 @@ public class ListGenericObjects : ICollectionGenericObjects /// Список объектов, которые храним /// private readonly List _collection; - /// /// Максимально допустимое число объектов в списке /// @@ -47,53 +46,43 @@ public class ListGenericObjects : ICollectionGenericObjects { _collection = new(); } - - public T? Get(int position) { - // TODO проверка позиции - if (position >= Count || position < 0) - { - throw new PositionOutOfCollectionException(position); - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; } - - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // TODO проверка, что не превышено максимальное количество элементов - if (Count == _maxCount) + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) { - throw new CollectionOverflowException(Count); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(); + } } - // TODO вставка в конец набора _collection.Add(obj); - return _collection.Count; + return Count; + } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - // TODO проверка, что не превышено максимальное количество элементов - if (Count == _maxCount) + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (comparer != null) { - throw new CollectionOverflowException(Count); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(position); + } } - // TODO проверка позиции - if (position >= Count || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - // TODO вставка по позиции _collection.Insert(position, obj); return position; } public T? Remove(int position) { - // TODO проверка позиции - if (position >= Count || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - // TODO удаление объекта из списка + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T? obj = _collection[position]; _collection.RemoveAt(position); return obj; @@ -106,4 +95,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs index 228d8ea..02ab9a2 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs @@ -8,126 +8,125 @@ using ProjectTank.Exceptions; public class MassiveGenericObjects : ICollectionGenericObjects where T : class { - /// - /// Массив объектов, которые храним - /// - private T?[] _collection; - - public int Count => _collection.Length; - - public int MaxCount + /// + /// Массив объектов, которые храним + /// + private T?[] _collection; + public int Count => _collection.Length; + public int MaxCount + { + get { - get + return _collection.Length; + } + set + { + if (value > 0) { - return _collection.Length; - } - set - { - if (value > 0) + if (_collection.Length > 0) { - if (_collection.Length > 0) - { - Array.Resize(ref _collection, value); - } - else - { - _collection = new T?[value]; - } + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; } } } + } - public CollectionType GetCollectionType => CollectionType.Massive; - - /// - /// Конструктор - /// - public MassiveGenericObjects() + public CollectionType GetCollectionType => CollectionType.Massive; + /// + /// Конструктор + /// + public MassiveGenericObjects() + { + _collection = Array.Empty(); + } + public T? Get(int position) + { + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); + return _collection[position]; + } + public int Insert(T obj, IEqualityComparer? comparer = null) + { + if (comparer != null) { - _collection = Array.Empty(); - } - - public T? Get(int position) - { - // TODO проверка позиции - if (position < 0 || position > _collection.Length) + foreach (T? i in _collection) { - throw new PositionOutOfCollectionException(position); - } - if (position >= Count && _collection[position] == null) - { - throw new ObjectNotFoundException(position); - } - return _collection[position]; - } - - public int Insert(T obj) - { - - return Insert(obj,0); - throw new CollectionOverflowException(Count); - } - - public int Insert(T obj, int position) - { - // TODO проверка позиции - if (position > _collection.Length || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - if (_collection[position] == null) - { - _collection[position] = obj; - return position; - } - - for (int tmp = position + 1; tmp < _collection.Length; tmp++) - { - if (_collection[tmp] == null) + if (comparer.Equals(i, obj)) { - _collection[tmp] = obj; - return tmp; + throw new ObjectAlreadyExistsException(i); } } - - for (int tmp = position - 1; tmp >= 0; tmp--) + } + + return Insert(obj, 0); + throw new CollectionOverflowException(); + } + 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 (_collection[tmp] == null) + if (comparer.Equals(i, obj)) { - _collection[tmp] = obj; - return tmp; + throw new ObjectAlreadyExistsException(i); } } - - throw new CollectionOverflowException(Count); } - - public T? Remove(int position) + if (_collection[position] == null) { - // TODO проверка позиции - if (position < 0 || position > _collection.Length) - { - throw new PositionOutOfCollectionException(position); - } + _collection[position] = obj; + return position; - if (_collection[position] == null) - { - throw new ObjectNotFoundException(position); - } - T? tmp = _collection[position]; - _collection[position] = null; - // TODO удаление объекта из массива, присвоив элементу массива значение null - return tmp; } - - public IEnumerable GetItems() + int temp = position + 1; + while (temp < Count) { - for (int i = 0; i < _collection.Length; ++i) + if (_collection[temp] == null) { - yield return _collection[i]; + _collection[temp] = obj; + return temp; } + ++temp; } - } \ No newline at end of file + temp = position - 1; + while (temp >= 0) + { + if (_collection[temp] == null) + { + _collection[temp] = obj; + return temp; + } + --temp; + } + throw new CollectionOverflowException(); + } + public T? Remove(int position) + { + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) throw new ObjectNotFoundException(); + T? myObject = _collection[position]; + _collection[position] = null; + return myObject; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs index 97c8a9b..490c2e5 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs @@ -1,7 +1,8 @@ using ProjectTank.Drawning; using ProjectTank.Exceptions; -using System.Text; +using System.Data; + namespace ProjectTank.CollectionGenericObjects { @@ -15,16 +16,17 @@ namespace ProjectTank.CollectionGenericObjects /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; - /// - /// Возвращение списка названий коллекций - /// - public List Keys => _storages.Keys.ToList(); + readonly Dictionary> _storages; /// /// Ключевое слово, с которого должен начинаться файл /// - private readonly string _collectionKey = "CollectionStorage"; + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; /// /// Разделитель для записи ключа и значения элемента словаря @@ -32,15 +34,16 @@ namespace ProjectTank.CollectionGenericObjects private readonly string _separatorForKeyValue = "|"; /// - /// Разделитель для записей коллекции данных в файл + /// Возвращение списка названий коллекций /// - private readonly string _separatorItems = ";"; + public List Keys => _storages.Keys.ToList(); + /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -49,33 +52,34 @@ namespace ProjectTank.CollectionGenericObjects /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - // TODO Прописать логику для добавления - if (name == null || _storages.ContainsKey(name)) + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) return; switch (collectionType) { case CollectionType.None: return; case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); return; case CollectionType.List: - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); return; + default: break; } - } + /// /// Удаление коллекции /// /// Название коллекции public void DelCollection(string name) { - // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) - _storages.Remove(name); + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } + /// /// Доступ к коллекции /// @@ -85,61 +89,62 @@ namespace ProjectTank.CollectionGenericObjects { get { - // TODO Продумать логику получения объекта - if (name == null || !_storages.ContainsKey(name)) - return null; - return _storages[name]; + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; + return null; } } + + /// + /// Сохранение информации по лодкам в хранилище в файл + /// + /// + /// public void SaveData(string filename) { if (_storages.Count == 0) { throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения"); } - if (File.Exists(filename)) { File.Delete(filename); } - - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter sw = new StreamWriter(fs); - sw.WriteLine(_collectionKey); - foreach (KeyValuePair> value in _storages) + using (StreamWriter writer = new(filename)) { - sw.Write(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - sw.Write(value.Key); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.GetCollectionType); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.MaxCount); - sw.Write(_separatorForKeyValue); - - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); - sw.Write(data); - sw.Write(_separatorItems); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + writer.Write(data); + writer.Write(_separatorItems); + } } } } /// - /// Загрузка информации по локомотивам в хранилище из файла + /// Загрузка информации по лодкам в хранилище из файла /// - /// Путь и имя файла + /// >Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { @@ -147,63 +152,60 @@ namespace ProjectTank.CollectionGenericObjects { throw new FileNotFoundException("Файл не существует"); } - using (StreamReader reader = new(filename)) { string line = reader.ReadLine(); if (line == null || line.Length == 0) { - throw new InvalidDataException("В файле нет данных"); + throw new ArgumentException("В файле нет данных"); } if (!line.Equals(_collectionKey)) { - throw new InvalidOperationException("В файле неверные данные"); + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) { - string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string[] record = line.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + 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 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?.CreateDrawningTank() is T locomotive) + if (elem?.CreateDrawningTank() is T boat) { try { - if (collection.Insert(locomotive) == -1) + if (collection.Insert(boat) == -1) { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]); } } catch (CollectionOverflowException ex) { - throw new ArgumentOutOfRangeException("Коллекция переполнена", ex); + throw new DataException("Коллекция переполнена", ex); } } - } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } - /// - /// Создание коллекции по типа + /// Создание коллекции по типу /// /// /// @@ -213,8 +215,8 @@ namespace ProjectTank.CollectionGenericObjects { CollectionType.Massive => new MassiveGenericObjects(), CollectionType.List => new ListGenericObjects(), - _ => null + _ => null, }; } - } + } } diff --git a/ProjectTank/ProjectTank/Drawning/DrawningTankCompareByColor.cs b/ProjectTank/ProjectTank/Drawning/DrawningTankCompareByColor.cs new file mode 100644 index 0000000..2440fb0 --- /dev/null +++ b/ProjectTank/ProjectTank/Drawning/DrawningTankCompareByColor.cs @@ -0,0 +1,35 @@ +namespace ProjectTank.Drawning; + +public class DrawningTankCompareByColor : IComparer +{ + public int Compare(DrawningTank? x, DrawningTank? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityTank == null) + { + return 1; + } + + if (y == null || y.EntityTank== null) + { + return -1; + } + + if (ToHex(x.EntityTank.BodyColor) != ToHex(y.EntityTank.BodyColor)) + { + return String.Compare(ToHex(x.EntityTank.BodyColor), ToHex(y.EntityTank.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityTank.Speed.CompareTo(y.EntityTank.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTank.Weight.CompareTo(y.EntityTank.Weight); + } + static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; + +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/Drawning/DrawningTankCompareByType.cs b/ProjectTank/ProjectTank/Drawning/DrawningTankCompareByType.cs new file mode 100644 index 0000000..4704bae --- /dev/null +++ b/ProjectTank/ProjectTank/Drawning/DrawningTankCompareByType.cs @@ -0,0 +1,33 @@ + +using ProjectTank.Drawning; + +namespace ProjectTank.Drawnings; +/// +/// Сравнение по типу, скорости и весу +/// +public class DrawningTankCompareByType : IComparer +{ + public int Compare(DrawningTank? x, DrawningTank? y) + { + if (x == null || x.EntityTank == null) + { + return -1; + } + if (y == null || y.EntityTank == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityTank.Speed.CompareTo(y.EntityTank.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTank.Weight.CompareTo(y.EntityTank.Weight); + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/Drawning/DrawningTankEqutables.cs b/ProjectTank/ProjectTank/Drawning/DrawningTankEqutables.cs new file mode 100644 index 0000000..369a1e9 --- /dev/null +++ b/ProjectTank/ProjectTank/Drawning/DrawningTankEqutables.cs @@ -0,0 +1,58 @@ + +using ProjectTank.Drawning; +using System.Diagnostics.CodeAnalysis; +namespace ProjectTank.Drawnings; + +public class DrawningTankEqutables : IEqualityComparer +{ + public bool Equals(DrawningTank? x, DrawningTank? y) + { + if (x == null || x.EntityTank == null) + { + return false; + } + if (y == null || y.EntityTank == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityTank.Speed != y.EntityTank.Speed) + { + return false; + } + if (x.EntityTank.Weight != y.EntityTank.Weight) + { + return false; + } + if (x.EntityTank.BodyColor != y.EntityTank.BodyColor) + { + return false; + } + if (x is DrawningBattleTank && y is DrawningBattleTank) + { + EntityBattleTank entityX = (EntityBattleTank)x.EntityTank; + EntityBattleTank entityY = (EntityBattleTank)y.EntityTank; + if (entityX.MachinGun!= entityY.MachinGun) + { + return false; + } + if (entityX.Gun != entityY.Gun) + { + return false; + } + if (entityX.AdditionalColor != entityY.AdditionalColor) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningTank? obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/Exceptions/ObjectAlreadyExistsException.cs b/ProjectTank/ProjectTank/Exceptions/ObjectAlreadyExistsException.cs new file mode 100644 index 0000000..5357954 --- /dev/null +++ b/ProjectTank/ProjectTank/Exceptions/ObjectAlreadyExistsException.cs @@ -0,0 +1,19 @@ + +using System.Runtime.Serialization; + + +namespace ProjectTank.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) { } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs b/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs index 49d941c..8dd2a5e 100644 --- a/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs +++ b/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs @@ -54,6 +54,8 @@ namespace ProjectTank LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -70,13 +72,15 @@ namespace ProjectTank groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(824, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(187, 623); + groupBoxTools.Size = new Size(187, 652); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTank); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -85,7 +89,7 @@ namespace ProjectTank panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 372); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(184, 238); + panelCompanyTools.Size = new Size(184, 319); panelCompanyTools.TabIndex = 8; // // buttonAddTank @@ -101,7 +105,7 @@ namespace ProjectTank // // maskedTextBox // - maskedTextBox.Location = new Point(6, 85); + maskedTextBox.Location = new Point(6, 44); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(166, 23); @@ -111,7 +115,7 @@ namespace ProjectTank // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 200); + buttonRefresh.Location = new Point(3, 159); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(166, 35); buttonRefresh.TabIndex = 6; @@ -122,7 +126,7 @@ namespace ProjectTank // buttonRemoveTank // buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveTank.Location = new Point(3, 114); + buttonRemoveTank.Location = new Point(3, 73); buttonRemoveTank.Name = "buttonRemoveTank"; buttonRemoveTank.Size = new Size(169, 35); buttonRemoveTank.TabIndex = 4; @@ -133,9 +137,9 @@ namespace ProjectTank // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(6, 159); + buttonGoToCheck.Location = new Point(6, 118); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(159, 35); + buttonGoToCheck.Size = new Size(166, 35); buttonGoToCheck.TabIndex = 5; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -250,7 +254,7 @@ namespace ProjectTank pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(824, 623); + pictureBox.Size = new Size(824, 652); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -294,11 +298,33 @@ namespace ProjectTank // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 241); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(166, 35); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 200); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(166, 35); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormBattleTankCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1011, 647); + ClientSize = new Size(1011, 676); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -345,5 +371,7 @@ namespace ProjectTank private ToolStripMenuItem LoadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectTank/ProjectTank/FormBattleTankCollection.cs b/ProjectTank/ProjectTank/FormBattleTankCollection.cs index 39ddb6c..70b3368 100644 --- a/ProjectTank/ProjectTank/FormBattleTankCollection.cs +++ b/ProjectTank/ProjectTank/FormBattleTankCollection.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using ProjectTank.CollectionGenericObjects; using ProjectTank.Drawning; +using ProjectTank.Drawnings; using ProjectTank.Exceptions; namespace ProjectTank @@ -15,7 +16,7 @@ namespace ProjectTank /// private readonly StorageCollection _storageCollection; - + /// /// Компания /// @@ -72,6 +73,11 @@ namespace ProjectTank MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectAlreadyExistsException) + { + MessageBox.Show("Такой объект уже существует"); + _logger.LogError("Ошибка: такой объект уже существует {0}", tank); + } } /// @@ -91,7 +97,7 @@ namespace ProjectTank form.Show(); } - + private void buttonRemoveTank_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) @@ -247,7 +253,7 @@ namespace ProjectTank listBoxСollection.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)) { listBoxСollection.Items.Add(colName); @@ -327,5 +333,24 @@ namespace ProjectTank } } } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareTank(new DrawningTankCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareTank(new DrawningTankCompareByColor()); + } + private void CompareTank(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } } \ No newline at end of file