From fccfd0c91acaf800b9846d31fb774de122cde1c1 Mon Sep 17 00:00:00 2001 From: nezui1 <104579567+nezui1@users.noreply.github.com> Date: Mon, 20 May 2024 21:23:21 +0400 Subject: [PATCH] =?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=E2=84=968?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 6 +- .../CollectionInfo.cs | 91 ++++++++++ .../ICollectionGenericObjects.cs | 9 +- .../ListGenericObjects.cs | 32 +++- .../MassiveGenericObjects.cs | 32 +++- .../StorageCollection.cs | 167 +++++++++--------- .../Drawning/DrawningCompareByColor.cs | 41 +++++ .../Drawning/DrawningCompareByType.cs | 33 ++++ .../Drawning/DrawningWarPlaneEqtubles.cs | 65 +++++++ .../Exceptions/EqualException.cs | 18 ++ .../FormWarPlaneCollection.Designer.cs | 52 ++++-- .../FormWarPlaneCollection.cs | 121 ++++++++----- .../FormWarPlaneCollection.resx | 3 + 13 files changed, 520 insertions(+), 150 deletions(-) create mode 100644 ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByColor.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByType.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlaneEqtubles.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Exceptions/EqualException.cs diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs index 3994b58..03c40fe 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -37,7 +37,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, которые можно разместить в окне /// - private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) + 1; + private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)); /// /// Конструктор @@ -61,7 +61,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningWarPlane warPlane) { - return company._collection.Insert(warPlane); + return company._collection.Insert(warPlane, new DrawningWarPlaneEqtubles()); } /// @@ -75,6 +75,8 @@ public abstract class AbstractCompany return company._collection.Remove(position); } + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Получение случайного объекта из коллекции /// diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..5ffa5f7 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,91 @@ +using ProjectAirFighter.CollectionGenericObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirFighter.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/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs index 3899ba4..0332285 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,5 +1,7 @@ using ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Drawning; using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; @@ -29,7 +31,7 @@ public interface ICollectionGenericObjects /// /// Добавляемы объект /// true - вставка прошла успешно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -37,7 +39,7 @@ public interface ICollectionGenericObjects /// Добавляемы объект /// Позиция /// true - вставка прошла успешно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -62,4 +64,7 @@ public interface ICollectionGenericObjects /// /// Поэлемениный вывод элементов коллекции IEnumerable GetItems(); + + + void CollectionSort(IComparer comparer); } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs index 9dba439..8a60fdc 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,6 +1,8 @@ -using ProjectAirFighter.CollectionGenericObject; +using Microsoft.VisualBasic.Devices; +using ProjectAirFighter.CollectionGenericObject; using ProjectAirFighter.Exceptions; using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; @@ -63,20 +65,27 @@ public class ListGenericObjects : ICollectionGenericObjects 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 EqualException(obj); + } + } + //вставка в конец набора _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); @@ -84,6 +93,14 @@ public class ListGenericObjects : ICollectionGenericObjects if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new EqualException(obj); + } + } + //вставка по позиции _collection.Insert(position,obj); return 1; @@ -106,4 +123,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index ef0fba0..784cabf 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,6 @@ using ProjectAirFighter.CollectionGenericObject; using ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Drawning; using ProjectAirFighter.Exceptions; using System; using System.Collections.Generic; @@ -66,8 +67,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new EqualException(i); + } + } + } for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -79,11 +90,23 @@ public class MassiveGenericObjects : ICollectionGenericObjects 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 > Count) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new EqualException(i); + } + } + } + if (_collection[position] == null) { _collection[position] = obj; @@ -137,4 +160,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index 5d3bf48..9986573 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using ProjectAirFighter.CollectionGenericObject; +using Microsoft.AspNetCore.Http; +using ProjectAirFighter.CollectionGenericObject; using ProjectAirFighter.Drawning; using ProjectAirFighter.Exceptions; using System; @@ -15,16 +16,18 @@ namespace ProjectAirFighter.CollectionGenericObjects; /// public class StorageCollection where T : DrawningWarPlane + + { /// /// Словарь (хранилище) с коллекциями /// - private Dictionary> _storages; + private Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -43,7 +46,7 @@ public class StorageCollection public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -53,33 +56,28 @@ public class StorageCollection /// public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + + if ( _storages.ContainsKey(collectionInfo)) { return; } - - switch(collectionType) - { - case CollectionType.None: - return; - case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); - return; - case CollectionType.List: - _storages[name] = new ListGenericObjects(); - return; - } + + if (collectionType == CollectionType.None) return; + else if (collectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); + } /// /// Удаление коллекции /// /// - public void DelCollection(string name) + public void DelCollection(CollectionInfo collectionInfo) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// @@ -87,59 +85,61 @@ public class StorageCollection /// /// /// - public ICollectionGenericObjects this[string name] + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { //логика получения объекта - if(name == null || !_storages.ContainsKey(name)) - return null; + if(_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; - return _storages[name]; + return null; } } - + public void SaveData(string filename) { if (_storages.Count == 0) - throw new Exception("В хранилище отсутсвуют коллекции для сохранения"); - - if (File.Exists(filename)) - File.Delete(filename); - - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter sw = new StreamWriter(fs); - sw.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) { - sw.Write(Environment.NewLine); - if (value.Value.Count == 0) - { - continue; - } + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); - 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()) + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter writer = new(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - 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.GetCollectionType); + 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); + } } } - } /// /// Загрузка информации по самолетам в хранилище из файла @@ -150,65 +150,60 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException($"{filename} не существует"); } - - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader reader = File.OpenText(filename)) { - using StreamReader sr = new StreamReader(fs); - - string str = sr.ReadLine(); - if (str == null || str.Length == 0) + string line = reader.ReadLine(); + if (line == null || line.Length == 0) { - throw new Exception("В файле нет данных"); + throw new IOException("Файл не подходит"); } - - if (!str.Equals(_collectionKey)) + if (!line.Equals(_collectionKey)) { - throw new Exception("В файле неверные данные"); + + throw new IOException("В файле неверные данные"); } _storages.Clear(); - - while (!sr.EndOfStream) + string strs = ""; + while ((strs = reader.ReadLine()) != null) { - string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string[] record = strs.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 Exception("Не удалось создать коллекцию"); - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); - collection.MaxCount = Convert.ToInt32(record[2]); + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningWarPlane() is T warPlane) { - try { - if (collection.Insert(warPlane) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(warPlane); } - catch(CollectionOverflowException ex) + catch (Exception ex) { - throw new Exception("Коллекция переполнена", ex); + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } } - + + } /// diff --git a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByColor.cs b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByColor.cs new file mode 100644 index 0000000..c8f9f53 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByColor.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirFighter.Drawning; + +public class DrawningCompareByColor : IComparer +{ + public int Compare(DrawningWarPlane? x, DrawningWarPlane? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityWarPlane == null) + { + return 1; + } + + if (y == null || y.EntityWarPlane == null) + { + return -1; + } + + if (ToHex(x.EntityWarPlane.BodyColor) != ToHex(y.EntityWarPlane.BodyColor)) + { + return String.Compare(ToHex(x.EntityWarPlane.BodyColor), ToHex(y.EntityWarPlane.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight); + } + static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; + +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByType.cs b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByType.cs new file mode 100644 index 0000000..735a83f --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningCompareByType.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirFighter.Drawning; + +public class DrawningCompareByType : IComparer +{ + public int Compare(DrawningWarPlane? x, DrawningWarPlane? y) + { + if (x == null || x.EntityWarPlane == null) + { + return -1; + } + if (y == null || y.EntityWarPlane == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight); + } +} diff --git a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlaneEqtubles.cs b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlaneEqtubles.cs new file mode 100644 index 0000000..7d5804a --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlaneEqtubles.cs @@ -0,0 +1,65 @@ +using ProjectAirFighter.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirFighter.Drawning; + +public class DrawningWarPlaneEqtubles : IEqualityComparer +{ + public bool Equals(DrawningWarPlane? x, DrawningWarPlane? y) + { + if (ReferenceEquals(x, null)) return false; + if (ReferenceEquals(y, null)) return false; + if (x.GetType() != y.GetType()) return false; + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityWarPlane != null && y.EntityWarPlane != null && x.EntityWarPlane.Speed != y.EntityWarPlane.Speed) + { + return false; + } + + if (x.EntityWarPlane.Weight != y.EntityWarPlane.Weight) + { + return false; + } + + if (x.EntityWarPlane.BodyColor != y.EntityWarPlane.BodyColor) + { + return false; + } + + if (x is DrawningAirFighter && y is DrawningAirFighter) + { + if (((EntityAirFighter)x.EntityWarPlane).AdditionalColor != + ((EntityAirFighter)y.EntityWarPlane).AdditionalColor) + { + return false; + } + if (((EntityAirFighter)x.EntityWarPlane).Rocket != + ((EntityAirFighter)y.EntityWarPlane).Rocket) + { + return false; + } + if (((EntityAirFighter)x.EntityWarPlane).AdditionalWing != + ((EntityAirFighter)y.EntityWarPlane).AdditionalWing) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningWarPlane? obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/EqualException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/EqualException.cs new file mode 100644 index 0000000..bef0d88 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/EqualException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirFighter.Exceptions; + +internal class EqualException : ApplicationException +{ + public EqualException(object i) : base("В коллекции уже есть такой элемент " + i) { } + public EqualException() : base() { } + public EqualException(string message) : base(message) { } + public EqualException(string message, Exception exception) : base(message, exception) + { } + protected EqualException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs index 674d827..bb5e41c 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBox1.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -61,6 +63,8 @@ // // groupBox1 // + groupBox1.Controls.Add(buttonSortByType); + groupBox1.Controls.Add(buttonSortByColor); groupBox1.Controls.Add(panelCompanyTools); groupBox1.Controls.Add(buttonCreateCompany); groupBox1.Controls.Add(panelStorage); @@ -68,7 +72,7 @@ groupBox1.Dock = DockStyle.Right; groupBox1.Location = new Point(659, 24); groupBox1.Name = "groupBox1"; - groupBox1.Size = new Size(174, 658); + groupBox1.Size = new Size(174, 739); groupBox1.TabIndex = 0; groupBox1.TabStop = false; groupBox1.Text = "Инструменты"; @@ -83,14 +87,14 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(0, 373); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(174, 278); + panelCompanyTools.Size = new Size(174, 262); panelCompanyTools.TabIndex = 9; // // buttonRemove // - buttonRemove.Location = new Point(6, 145); + buttonRemove.Location = new Point(6, 121); buttonRemove.Name = "buttonRemove"; - buttonRemove.Size = new Size(162, 44); + buttonRemove.Size = new Size(162, 48); buttonRemove.TabIndex = 4; buttonRemove.Text = "Удалить самолет"; buttonRemove.UseVisualStyleBackColor = true; @@ -98,9 +102,9 @@ // // buttonAddWarPlane // - buttonAddWarPlane.Location = new Point(6, 27); + buttonAddWarPlane.Location = new Point(6, 3); buttonAddWarPlane.Name = "buttonAddWarPlane"; - buttonAddWarPlane.Size = new Size(162, 52); + buttonAddWarPlane.Size = new Size(162, 56); buttonAddWarPlane.TabIndex = 1; buttonAddWarPlane.Text = "Добавление военного самолета"; buttonAddWarPlane.UseVisualStyleBackColor = true; @@ -108,9 +112,9 @@ // // button1 // - button1.Location = new Point(6, 245); + button1.Location = new Point(6, 221); button1.Name = "button1"; - button1.Size = new Size(162, 30); + button1.Size = new Size(162, 34); button1.TabIndex = 6; button1.Text = "Обновить"; button1.UseVisualStyleBackColor = true; @@ -118,7 +122,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(8, 111); + maskedTextBoxPosition.Location = new Point(8, 87); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(162, 23); @@ -127,9 +131,9 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(6, 195); + buttonGoToCheck.Location = new Point(6, 171); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(162, 44); + buttonGoToCheck.Size = new Size(162, 48); buttonGoToCheck.TabIndex = 5; buttonGoToCheck.Text = "Передать на тест"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -244,7 +248,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(659, 658); + pictureBox.Size = new Size(659, 739); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -288,11 +292,31 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Location = new Point(8, 644); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(162, 35); + buttonSortByType.TabIndex = 10; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(8, 685); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(160, 42); + buttonSortByColor.TabIndex = 11; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormWarPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(833, 682); + ClientSize = new Size(833, 763); Controls.Add(pictureBox); Controls.Add(groupBox1); Controls.Add(menuStrip); @@ -337,5 +361,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByType; + private Button buttonSortByColor; } } \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs index 2fc851a..5a700f0 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs @@ -3,6 +3,7 @@ using ProjectAirFighter.CollectionGenericObject; using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawning; using ProjectAirFighter.Exceptions; +using System.Runtime.Intrinsics.Arm; namespace ProjectAirFighter; @@ -19,9 +20,9 @@ public partial class FormWarPlaneCollection : Form /// private AbstractCompany? _company; - private readonly ILogger _logger; + private readonly ILogger _logger; + - /// /// Конструктор @@ -61,13 +62,18 @@ public partial class FormWarPlaneCollection : Form return; } - try { + try + { if (_company + warPlane != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); _logger.LogInformation("Объект добавлен: " + warPlane.GetDataForSave()); } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } catch (CollectionOverflowException ex) { @@ -80,7 +86,7 @@ public partial class FormWarPlaneCollection : Form MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } @@ -99,7 +105,8 @@ public partial class FormWarPlaneCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - try { + try + { if (_company - pos != null) { MessageBox.Show("Объект удален"); @@ -107,16 +114,17 @@ public partial class FormWarPlaneCollection : Form _logger.LogInformation("Объект удален на позиции: " + pos); } } - catch(ObjectNotFoundException ex) + catch (ObjectNotFoundException ex) { MessageBox.Show("Не удалось удалить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } - catch(PositionOutOfCollectionException ex) { + catch (PositionOutOfCollectionException ex) + { MessageBox.Show("Не удалось удалить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } private void ButtonGoToCheck_Click(object sender, EventArgs e) @@ -131,7 +139,8 @@ public partial class FormWarPlaneCollection : Form int counter = 100; while (warPlane == null) { - try { + try + { warPlane = _company.GetRandomObject(); counter--; if (counter <= 0) @@ -186,25 +195,26 @@ public partial class FormWarPlaneCollection : Form return; } - try { - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); _logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text); } catch (Exception ex) { _logger.LogError("Ошибка: {Massege}", ex.Message); } - } + } /// /// Обновление списка в listBoxCollection /// @@ -213,8 +223,8 @@ public partial class FormWarPlaneCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? colName = _storageCollection.Keys?[i]; + if (!colName!.IsEmpty()) { listBoxCollection.Items.Add(colName); } @@ -233,16 +243,18 @@ public partial class FormWarPlaneCollection : Form MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - try { + try + { if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); + _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); } - catch(Exception ex) { + catch (Exception ex) + { _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -259,24 +271,31 @@ public partial class FormWarPlaneCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; } - - switch (comboBoxSelectorCompany.Text) + try { - case "Хранилище": - _company = new WarPlaneBase(pictureBox.Width, - pictureBox.Height, collection); - break; + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new WarPlaneBase(pictureBox.Width, pictureBox.Height, collection); + break; + } + + } + catch (ObjectNotFoundException) + { + } panelCompanyTools.Enabled = true; RerfreshListBoxItems(); - } /// @@ -294,11 +313,12 @@ public partial class FormWarPlaneCollection : Form MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение в файл: {filname}", saveFileDialog.FileName); } - catch(Exception ex) { + catch (Exception ex) + { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } } @@ -308,7 +328,7 @@ public partial class FormWarPlaneCollection : Form /// /// /// - + private void LoadToolStripMenuItem_Click_1(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) @@ -326,9 +346,30 @@ public partial class FormWarPlaneCollection : Form _logger.LogError("Ошибка: {Message}", ex.Message); } - + } } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareWarPlanes(new DrawningCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareWarPlanes(new DrawningCompareByColor()); + } + + private void CompareWarPlanes(IComparer comparer) + { + if(_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx index 8b1dfa1..6ef9170 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx @@ -126,4 +126,7 @@ 261, 17 + + 46 + \ No newline at end of file -- 2.25.1