From f27e0bf71445b24312f67e670594a00c39bfc838 Mon Sep 17 00:00:00 2001 From: cleverman1337 Date: Wed, 16 Oct 2024 00:28:16 +0300 Subject: [PATCH] =?UTF-8?q?8=20=D0=BB=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?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 36 +++++- .../CollectionInfo.cs | 80 +++++++++++++ .../ICollectionGenericObjects.cs | 13 ++- .../ListGenericObjects.cs | 50 ++++++-- .../MassiveGenericObjects.cs | 71 +++++++---- .../StorageCollection.cs | 110 ++++++++++-------- .../TankSharingService.cs | 2 +- .../Drawnings/DrawningTankCompareByColor.cs | 44 +++++++ .../Drawnings/DrawningTankCompareByType.cs | 32 +++++ .../Drawnings/DrawningTankEqutables.cs | 65 +++++++++++ .../ObjectAlreadyInCollectionException.cs | 25 ++++ .../FormTankCollection.Designer.cs | 61 ++++++---- .../FormTankCollection.cs | 82 ++++++++++--- 13 files changed, 544 insertions(+), 127 deletions(-) create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/CollectionInfo.cs create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByColor.cs create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByType.cs create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankEqutables.cs create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectAlreadyInCollectionException.cs diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs index 4c47e6e..d1d6d0e 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using SelfPropelledArtilleryUnit.Drawnings; +using SelfPropelledArtilleryUnit.Exceptions; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; @@ -56,7 +57,18 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTank tank) { - return company._collection.Insert(tank); + try + { + return company._collection.Insert(tank, 0, new DrawningTankEqutables()); + } + catch (ObjectAlreadyInCollectionException) + { + return -1; + } + catch (CollectionOverflowException) + { + return -1; + } } /// @@ -87,26 +99,38 @@ public abstract class AbstractCompany { Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); - DrawBackgound(graphics); + DrawBackground(graphics); SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningTank? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningTank? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) + { + continue; + } } return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод заднего фона /// /// - protected abstract void DrawBackgound(Graphics g); + protected abstract void DrawBackground(Graphics g); /// /// Расстановка объектов /// protected abstract void SetObjectsPosition(); -} +} \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/CollectionInfo.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..3e6c206 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs index f96840a..5023e0a 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using SelfPropelledArtilleryUnit.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -28,7 +29,8 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); + /// /// Добавление объекта в коллекцию на конкретную позицию @@ -36,7 +38,7 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -62,4 +64,9 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs index 84302d2..39a7d5e 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using SelfPropelledArtilleryUnit.Exceptions; +using SelfPropelledArtilleryUnit.Drawnings; +using SelfPropelledArtilleryUnit.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -51,17 +52,47 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T? obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - if (Count == _maxCount) throw new CollectionOverflowException(Count); + // TODO выброс ошибки, если переполнение + // TODO выброс ошибки, если такой объект есть в коллекции + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); + } + + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } + _collection.Add(obj); - return Count - 1; + return _collection.Count; } - public int Insert(T? obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (Count == _maxCount) throw new CollectionOverflowException(Count); - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (position < 0 || position > Count) + { + throw new PositionOutOfCollectionException(position); + } + + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); + } + + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } + _collection.Insert(position, obj); return position; } @@ -81,4 +112,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs index 3868250..b88f839 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using SelfPropelledArtilleryUnit.Exceptions; +using SelfPropelledArtilleryUnit.Drawnings; +using SelfPropelledArtilleryUnit.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -49,9 +50,17 @@ 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 < _collection.Length; i++) + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } + + for (int i = 0; i < Count; i++) { if (_collection[i] == null) { @@ -59,37 +68,51 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - throw new CollectionOverflowException(Count); ; + + throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position < 0 || position >= _collection.Length) throw new PositionOutOfCollectionException(position); + // TODO выброс ошибки, если выход за границы массива + // TODO выброс ошибки, если такой объект есть в коллекции + // TODO выброс ошибки, если переполнение + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } if (_collection[position] == null) { _collection[position] = obj; return position; } - else - { - for (int i = position + 1; i < _collection.Length; i++) - { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } - } - for (int i = position - 1; i >= 0; i--) + for (int i = position + 1; i < Count; i++) + { + if (_collection[i] == null) { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } + _collection[i] = obj; + return i; } } + + for (int i = position - 1; i >= 0; i--) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + throw new CollectionOverflowException(Count); } public T Remove(int position) @@ -113,4 +136,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs index f5abca9..86b2245 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs @@ -14,12 +14,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); private readonly string _collectionKey = "CollectionStorage"; @@ -31,7 +31,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -39,18 +39,21 @@ public class StorageCollection /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo info) { - if (string.IsNullOrEmpty(name)) return; - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - if (collectionType == CollectionType.Massive) + if (info == null || _storages.ContainsKey(info)) { - _storages[name] = new MassiveGenericObjects(); + return; } - else if (collectionType == CollectionType.List) + + if (info.CollectionType == CollectionType.Massive) { - _storages[name] = new ListGenericObjects(); + _storages.Add(info, new MassiveGenericObjects()); + } + + if (info.CollectionType == CollectionType.List) + { + _storages.Add(info, new ListGenericObjects()); } } @@ -58,12 +61,14 @@ public class StorageCollection /// Удаление коллекции /// /// Название коллекции - public void DelCollection(string name) + public void DelCollection(CollectionInfo info) { - if (_storages.ContainsKey(name)) + if (info == null || !_storages.ContainsKey(info)) { - _storages.Remove(name); + return; } + + _storages.Remove(info); } /// @@ -71,23 +76,24 @@ public class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo info] { get { - if (_storages.ContainsKey(name)) + if (_storages.ContainsKey(info)) { - return _storages[name]; + return _storages[info]; } + return null; } } + public void SaveData(string filename) { if (_storages.Count == 0) { - throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); - + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -96,21 +102,20 @@ 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); - // не сохраняем пустые коллекции + 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; @@ -123,61 +128,72 @@ public class StorageCollection } writer.Write(sb); } + } } - + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { if (!File.Exists(filename)) { throw new FileNotFoundException("Файл не существует"); } - using (StreamReader reader = File.OpenText(filename)) + + using (StreamReader sr = new(filename)) { - string str = reader.ReadLine(); - if (str == null || str.Length == 0) + string line = sr.ReadLine(); + + if (line == null || line.Length == 0) { - throw new InvalidOperationException("В файле нет данных"); + throw new FileFormatException("В файле нет данных"); } - if (!str.StartsWith(_collectionKey)) + if (!line.Equals(_collectionKey)) { - throw new InvalidOperationException("В файле не верные данные"); + throw new FileFormatException("В файле неверные данные"); } _storages.Clear(); - string strs = ""; - while ((strs = reader.ReadLine()) != null) + + while ((line = sr.ReadLine()) != null) { - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new InvalidOperationException("Не удалось создать коллекцию"); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); + + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningTank() is T tank) + if (elem?.CreateDrawningTank() is T warship) { try { - if (collection.Insert(tank)==-1) + if (collection.Insert(warship, new DrawningTankEqutables()) == -1) { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[3]); + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } } catch (CollectionOverflowException ex) { - throw new InvalidOperationException("Коллекция переполнена", ex); + throw new OverflowException("Коллекция переполнена", ex); + } + catch (ObjectAlreadyInCollectionException ex) + { + throw new InvalidOperationException("Объект уже присутствует в коллекции", ex); } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs index 34a3c78..c02c346 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs @@ -15,7 +15,7 @@ public class TankSharingService : AbstractCompany { } - protected override void DrawBackgound(Graphics g) + protected override void DrawBackground(Graphics g) { int width = _pictureWidth / _placeSizeWidth; int height = _pictureHeight / _placeSizeHeight; diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByColor.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByColor.cs new file mode 100644 index 0000000..51035b4 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByColor.cs @@ -0,0 +1,44 @@ +using SelfPropelledArtilleryUnit.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.Drawnings; + +public class DrawningTankCompareByColor : IComparer +{ + public int Compare(DrawningTank? x, DrawningTank? y) + { + // TODO прописать логику сравения по цветам, скорости, весу + if (x == null || x.EntityTank == null) + { + return 1; + } + if (y == null || y.EntityTank == null) + { + return -1; + } + var bodyColorCompare = y.EntityTank.BodyColor.Name.CompareTo(x.EntityTank.BodyColor.Name); + if (bodyColorCompare != 0) + { + return bodyColorCompare; + } + if (x is DrawningArtillery && y is DrawningArtillery) + { + var additionalColorCompare = (y.EntityTank as EntityArtillery).AdditionalColor.Name.CompareTo( + (x.EntityTank as EntityArtillery).AdditionalColor.Name); + if (additionalColorCompare != 0) + { + return additionalColorCompare; + } + } + var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight); + } +} \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByType.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByType.cs new file mode 100644 index 0000000..424eb46 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankCompareByType.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.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 y.GetType().Name.CompareTo(x.GetType().Name); + } + var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight); + } +} \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankEqutables.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankEqutables.cs new file mode 100644 index 0000000..ebddbd4 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/DrawningTankEqutables.cs @@ -0,0 +1,65 @@ +using SelfPropelledArtilleryUnit.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.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 DrawningArtillery && y is DrawningArtillery) + { + // TODO доделать логику сравнения дополнительных параметров + if ((x.EntityTank as EntityArtillery)?.AdditionalColor != + (y.EntityTank as EntityArtillery)?.AdditionalColor) + { + return false; + } + if ((x.EntityTank as EntityArtillery)?.Rocket != + (y.EntityTank as EntityArtillery)?.Rocket) + { + return false; + } + if ((x.EntityTank as EntityArtillery)?.Cannon != + (y.EntityTank as EntityArtillery)?.Cannon) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningTank? obj) + { + return obj.GetHashCode(); + } +} diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectAlreadyInCollectionException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectAlreadyInCollectionException.cs new file mode 100644 index 0000000..02fa889 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectAlreadyInCollectionException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class ObjectAlreadyInCollectionException : ApplicationException +{ + public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { } + + public ObjectAlreadyInCollectionException() : base() { } + + public ObjectAlreadyInCollectionException(string message) : base(message) { } + + public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { } + + protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.Designer.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.Designer.cs index 79d1c49..e6f087a 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.Designer.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.Designer.cs @@ -30,8 +30,9 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonAddTank = new Button(); - buttonAddArtillery = new Button(); buttonRefresh = new Button(); maskedTextBoxPosition = new MaskedTextBox(); buttonGoToCheak = new Button(); @@ -69,30 +70,53 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(715, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(200, 484); + groupBoxTools.Size = new Size(200, 528); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTank); - panelCompanyTools.Controls.Add(buttonAddArtillery); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonGoToCheak); panelCompanyTools.Controls.Add(buttonRemoveTank); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 276); + panelCompanyTools.Location = new Point(3, 297); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(194, 205); + panelCompanyTools.Size = new Size(194, 228); panelCompanyTools.TabIndex = 9; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(12, 196); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(170, 23); + 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(12, 165); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(170, 25); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // buttonAddTank // buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddTank.Location = new Point(12, 9); + buttonAddTank.Location = new Point(12, 0); buttonAddTank.Name = "buttonAddTank"; buttonAddTank.Size = new Size(170, 30); buttonAddTank.TabIndex = 2; @@ -100,20 +124,10 @@ buttonAddTank.UseVisualStyleBackColor = true; buttonAddTank.Click += ButtonAddTank_Click; // - // buttonAddArtillery - // - buttonAddArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddArtillery.Location = new Point(12, 45); - buttonAddArtillery.Name = "buttonAddArtillery"; - buttonAddArtillery.Size = new Size(170, 31); - buttonAddArtillery.TabIndex = 1; - buttonAddArtillery.Text = "Добавление сау"; - buttonAddArtillery.UseVisualStyleBackColor = true; - // // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(12, 174); + buttonRefresh.Location = new Point(12, 128); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(170, 23); buttonRefresh.TabIndex = 6; @@ -123,7 +137,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(12, 82); + maskedTextBoxPosition.Location = new Point(12, 36); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(176, 23); @@ -133,7 +147,7 @@ // buttonGoToCheak // buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheak.Location = new Point(12, 143); + buttonGoToCheak.Location = new Point(12, 97); buttonGoToCheak.Name = "buttonGoToCheak"; buttonGoToCheak.Size = new Size(170, 25); buttonGoToCheak.TabIndex = 5; @@ -144,7 +158,7 @@ // buttonRemoveTank // buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveTank.Location = new Point(12, 110); + buttonRemoveTank.Location = new Point(12, 64); buttonRemoveTank.Name = "buttonRemoveTank"; buttonRemoveTank.Size = new Size(170, 27); buttonRemoveTank.TabIndex = 4; @@ -261,7 +275,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(715, 484); + pictureBox.Size = new Size(715, 528); pictureBox.TabIndex = 1; pictureBox.TabStop = false; pictureBox.Click += pictureBox_Click; @@ -311,7 +325,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(915, 508); + ClientSize = new Size(915, 552); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -335,7 +349,6 @@ private GroupBox groupBoxTools; private ComboBox comboBoxSelectorCompany; private Button buttonAddTank; - private Button buttonAddArtillery; private MaskedTextBox maskedTextBoxPosition; private PictureBox pictureBox; private Button buttonRemoveTank; @@ -357,5 +370,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs index 178b1d8..3204b7b 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs @@ -48,17 +48,22 @@ public partial class FormTankCollection : Form /// private void SetTank(DrawningTank? tank) { - try { - if (_company == null || tank == null) + try { - return; - } + if (_company == null || tank == null) + { + return; + } - if (_company + tank != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: " + tank.GetDataForSave()); + if (_company + tank != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + tank.GetDataForSave()); + } + else + { + MessageBox.Show("Такой объект уже есть в коллекции"); } } catch (CollectionOverflowException ex) @@ -66,7 +71,11 @@ public partial class FormTankCollection : Form MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } - + catch (ArgumentException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } } /// @@ -156,12 +165,10 @@ public partial class FormTankCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: заполнены не все данные для добавления коллекции"); return; } try { - CollectionType collectionType = CollectionType.None; if (radioButtonMassive.Checked) { @@ -171,8 +178,9 @@ public partial class FormTankCollection : Form { collectionType = CollectionType.List; } + CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty); - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(collectionInfo); RerfreshListBoxItems(); _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } @@ -186,7 +194,7 @@ public partial class FormTankCollection : 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); @@ -207,7 +215,8 @@ public partial class FormTankCollection : Form { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + _storageCollection.DelCollection(collectionInfo); RerfreshListBoxItems(); _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); } @@ -225,7 +234,8 @@ public partial class FormTankCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + ICollectionGenericObjects? collection = _storageCollection[collectionInfo]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -249,15 +259,17 @@ public partial class FormTankCollection : Form private void RefreshListBoxItems() { listBoxCollection.Items.Clear(); - for (int i = 0; i < _storageCollection.Keys?.Count; i++) + 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); } } + } + private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) @@ -294,4 +306,38 @@ public partial class FormTankCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareTanks(new DrawningTankCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareTanks(new DrawningTankCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareTanks(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }