From 2258c0b47ce9fc21d5aa723479a62c9841826f52 Mon Sep 17 00:00:00 2001 From: xom9kxom9k Date: Sun, 12 May 2024 14:52:01 +0400 Subject: [PATCH 1/2] =?UTF-8?q?1=20=D1=87=D0=B0=D1=81=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 11 ++- .../CollectionInfo.cs | 88 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 9 +- .../ListGenericObjects.cs | 29 +++++- .../MassiveGenericObjects.cs | 37 +++++++- .../StorageCollection.cs | 79 +++++++++-------- .../DrawningArmoredCarCompareByColor.cs | 44 ++++++++++ .../DrawningArmoredCarCompareByType.cs | 40 +++++++++ .../Drawnings/DrawningArmoredCarEqutables.cs | 66 ++++++++++++++ .../FormArmoredCarCollection.Designer.cs | 44 ++++++++-- AntiAircraftGun/FormArmoredCarCollection.cs | 34 ++++++- 11 files changed, 424 insertions(+), 57 deletions(-) create mode 100644 AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs create mode 100644 AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByColor.cs create mode 100644 AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByType.cs create mode 100644 AntiAircraftGun/Drawnings/DrawningArmoredCarEqutables.cs diff --git a/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs b/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs index 702b156..a907811 100644 --- a/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs +++ b/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs @@ -59,9 +59,10 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningArmoredCar airplan) + public static int operator +(AbstractCompany company, DrawningArmoredCar armoredCar) { - return company._collection.Insert(airplan); + return company._collection?.Insert(armoredCar, new DrawningArmoredCarEqutables()) ?? throw new DrawingEquitablesException(); + } /// @@ -108,6 +109,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => + _collection?.CollectionSort(comparer); /// /// Вывод заднего фона diff --git a/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs b/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..ad924f5 --- /dev/null +++ b/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.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/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs index 6ace662..6d6f1c5 100644 --- a/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -23,7 +23,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj,IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -31,7 +31,7 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,4 +56,9 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index ee171c0..08cef97 100644 --- a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -52,17 +52,38 @@ 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); + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(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 == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } _collection.Insert(position, obj); return position; } @@ -82,4 +103,8 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index f86f961..2bec6af 100644 --- a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -58,9 +58,19 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -73,10 +83,22 @@ 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 >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + if (_collection[position] == null) { _collection[position] = obj; @@ -123,4 +145,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + List lst = [.._collection]; + lst.Sort(comparer.Compare); + for (int i = 0; i < _collection.Length; ++i) + { + _collection[i] = lst[i]; + } + } } diff --git a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index 3274c35..b45e558 100644 --- a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -17,12 +17,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл /// @@ -43,7 +43,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -51,25 +51,26 @@ public class StorageCollection /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo collectionInfo) { - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); - else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo); + if (collectionInfo.CollectionType == CollectionType.None) + throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionInfo.CollectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionInfo.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); } /// @@ -77,12 +78,12 @@ public class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { - if (_storages.ContainsKey(name)) - return _storages[name]; + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -104,7 +105,7 @@ public class StorageCollection using (StreamWriter writer = new(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); @@ -143,7 +144,7 @@ public class StorageCollection { throw new FileNotFoundException($"{filename} не существует"); } - using (StreamReader reader = new(filename)) + using (StreamReader reader = File.OpenText(filename)) { string line = reader.ReadLine(); if (line == null || line.Length == 0) @@ -156,41 +157,41 @@ public class StorageCollection throw new IOException("В файле неверные данные"); } _storages.Clear(); - while ((line = reader.ReadLine()) != null) + string strs = ""; + while ((strs = reader.ReadLine()) != null) { - string[] record = line.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("Не удалось создать коллекцию"); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); + + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); + + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningArmoredCar() is T armoredCar) + if (elem?.CreateDrawningArmoredCar() is T ship) { try { - if (collection.Insert(armoredCar) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(ship); } - 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/AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByColor.cs b/AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByColor.cs new file mode 100644 index 0000000..7503115 --- /dev/null +++ b/AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByColor.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Drawnings; +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningArmoredCarCompareByColor : IComparer +{ + public int Compare(DrawningArmoredCar? x, DrawningArmoredCar? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityAircraftGun == null) + { + return 1; + } + + if (y == null || y.EntityAircraftGun == null) + { + return -1; + } + + if (ToHex(x.EntityAircraftGun.BodyColor) != ToHex(y.EntityAircraftGun.BodyColor)) + { + return String.Compare(ToHex(x.EntityAircraftGun.BodyColor), ToHex(y.EntityAircraftGun.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityAircraftGun.Speed.CompareTo(y.EntityAircraftGun.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityAircraftGun.Weight.CompareTo(y.EntityAircraftGun.Weight); + + + static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; + } +} diff --git a/AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByType.cs b/AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByType.cs new file mode 100644 index 0000000..1cd4a40 --- /dev/null +++ b/AntiAircraftGun/Drawnings/DrawningArmoredCarCompareByType.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Drawnings; +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningArmoredCarCompareByType : IComparer +{ + + public int Compare(DrawningArmoredCar? x, DrawningArmoredCar? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityAircraftGun == null) + { + return 1; + } + + if (y == null || y.EntityAircraftGun == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityAircraftGun.Speed.CompareTo(y.EntityAircraftGun.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityAircraftGun.Weight.CompareTo(y.EntityAircraftGun.Weight); + } +} diff --git a/AntiAircraftGun/Drawnings/DrawningArmoredCarEqutables.cs b/AntiAircraftGun/Drawnings/DrawningArmoredCarEqutables.cs new file mode 100644 index 0000000..ff003cb --- /dev/null +++ b/AntiAircraftGun/Drawnings/DrawningArmoredCarEqutables.cs @@ -0,0 +1,66 @@ +using AntiAircraftGun.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Drawnings; + +public class DrawningArmoredCarEqutables : IEqualityComparer +{ + public bool Equals(DrawningArmoredCar? x, DrawningArmoredCar? 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.EntityAircraftGun != null && y.EntityAircraftGun != null && x.EntityAircraftGun.Speed != y.EntityAircraftGun.Speed) + { + return false; + } + + if (x.EntityAircraftGun.Weight != y.EntityAircraftGun.Weight) + { + return false; + } + + if (x.EntityAircraftGun.BodyColor != y.EntityAircraftGun.BodyColor) + { + return false; + } + + if (x is DrawningAntiAircraftGun && y is DrawningAntiAircraftGun) + { + if (((EntityAntiAircraftGun)x.EntityAircraftGun).AdditionalColor != + ((EntityAntiAircraftGun)y.EntityAircraftGun).AdditionalColor) + { + return false; + } + if (((EntityAntiAircraftGun)x.EntityAircraftGun).Tower != + ((EntityAntiAircraftGun)y.EntityAircraftGun).Tower) + { + return false; + } + if (((EntityAntiAircraftGun)x.EntityAircraftGun).Radar != + ((EntityAntiAircraftGun)y.EntityAircraftGun).Radar) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningArmoredCar obj) + { + return obj.GetHashCode(); + + } +} diff --git a/AntiAircraftGun/FormArmoredCarCollection.Designer.cs b/AntiAircraftGun/FormArmoredCarCollection.Designer.cs index be62389..efa6ac6 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.Designer.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.Designer.cs @@ -30,6 +30,8 @@ { groupBoxToools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonAddArmoredCar = new Button(); maskedTextBox = new MaskedTextBox(); buttonRefresh = new Button(); @@ -68,13 +70,15 @@ groupBoxToools.Dock = DockStyle.Right; groupBoxToools.Location = new Point(1057, 24); groupBoxToools.Name = "groupBoxToools"; - groupBoxToools.Size = new Size(210, 612); + groupBoxToools.Size = new Size(210, 654); groupBoxToools.TabIndex = 0; groupBoxToools.TabStop = false; groupBoxToools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddArmoredCar); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -83,9 +87,31 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(6, 348); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(200, 261); + panelCompanyTools.Size = new Size(200, 306); panelCompanyTools.TabIndex = 8; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(7, 263); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(191, 39); + 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(7, 218); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(191, 39); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // buttonAddArmoredCar // buttonAddArmoredCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; @@ -99,7 +125,7 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(6, 94); + maskedTextBox.Location = new Point(6, 49); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(194, 23); @@ -109,7 +135,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(6, 216); + buttonRefresh.Location = new Point(7, 173); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(191, 39); buttonRefresh.TabIndex = 6; @@ -120,7 +146,7 @@ // buttonRemoveArmoredCar // buttonRemoveArmoredCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveArmoredCar.Location = new Point(6, 123); + buttonRemoveArmoredCar.Location = new Point(7, 78); buttonRemoveArmoredCar.Name = "buttonRemoveArmoredCar"; buttonRemoveArmoredCar.Size = new Size(191, 44); buttonRemoveArmoredCar.TabIndex = 4; @@ -131,7 +157,7 @@ // buttonGoToChek // buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToChek.Location = new Point(6, 171); + buttonGoToChek.Location = new Point(7, 128); buttonGoToChek.Name = "buttonGoToChek"; buttonGoToChek.Size = new Size(191, 39); buttonGoToChek.TabIndex = 5; @@ -248,7 +274,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1057, 612); + pictureBox.Size = new Size(1057, 654); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -296,7 +322,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1267, 636); + ClientSize = new Size(1267, 678); Controls.Add(pictureBox); Controls.Add(groupBoxToools); Controls.Add(menuStrip); @@ -341,5 +367,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/AntiAircraftGun/FormArmoredCarCollection.cs b/AntiAircraftGun/FormArmoredCarCollection.cs index cb74481..2afbe24 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.cs @@ -77,7 +77,7 @@ public partial class FormArmoredCarCollection : Form } } - + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); @@ -343,5 +343,37 @@ public partial class FormArmoredCarCollection : Form } } } + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new DrawningArmoredCarCompareByType()); + } + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new DrawningArmoredCarCompareByColor()); + } + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } -- 2.25.1 From a2301293b21fcdbf761a17c03644fb261a540e0c Mon Sep 17 00:00:00 2001 From: xom9kxom9k Date: Tue, 14 May 2024 19:49:41 +0400 Subject: [PATCH 2/2] =?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=20=E2=84=968?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ListGenericObjects.cs | 19 +++---- .../MassiveGenericObjects.cs | 54 ++++++++----------- .../StorageCollection.cs | 14 ++--- .../Exceptions/ObjectIsEqualException.cs | 21 ++++++++ AntiAircraftGun/FormArmoredCarCollection.cs | 31 +++++++---- 6 files changed, 79 insertions(+), 62 deletions(-) create mode 100644 AntiAircraftGun/Exceptions/ObjectIsEqualException.cs diff --git a/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs b/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs index a907811..550d1a5 100644 --- a/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs +++ b/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs @@ -61,7 +61,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningArmoredCar armoredCar) { - return company._collection?.Insert(armoredCar, new DrawningArmoredCarEqutables()) ?? throw new DrawingEquitablesException(); + return company._collection.Insert(armoredCar, new DrawningArmoredCarEqutables()); } diff --git a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index 08cef97..4e8e961 100644 --- a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -57,12 +57,9 @@ public class ListGenericObjects : ICollectionGenericObjects if (Count == _maxCount) throw new CollectionOverflowException(Count); if (comparer != null) { - for (int i = 0; i < Count; i++) + if (_collection.Contains(obj, comparer)) { - if (comparer.Equals(_collection[i], obj)) - { - throw new CollectionInsertException(obj); - } + throw new ObjectIsEqualException(obj); } } _collection.Add(obj); @@ -71,17 +68,13 @@ public class ListGenericObjects : ICollectionGenericObjects public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (Count == _maxCount) throw new CollectionOverflowException(Count); - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); - + if (Count == _maxCount) throw new CollectionOverflowException(); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); if (comparer != null) { - for (int i = 0; i < Count; i++) + if (_collection.Contains(obj, comparer)) { - if (comparer.Equals(_collection[i], obj)) - { - throw new CollectionInsertException(obj); - } + throw new ObjectIsEqualException(obj); } } _collection.Insert(position, obj); diff --git a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index 2bec6af..680c2ee 100644 --- a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -62,15 +62,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects { if (comparer != null) { - for (int i = 0; i < Count; i++) + foreach (T? i in _collection) { - if (comparer.Equals(_collection[i], obj)) + if (comparer.Equals(i, obj)) { - throw new CollectionInsertException(obj); + throw new ObjectIsEqualException(i); } } } - for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -79,22 +78,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - - throw new CollectionOverflowException(Count); + throw new CollectionOverflowException(); } public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); - - if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (comparer != null) { - for (int i = 0; i < Count; i++) + foreach (T? i in _collection) { - if (comparer.Equals(_collection[i], obj)) + if (comparer.Equals(i, obj)) { - throw new CollectionInsertException(obj); + throw new ObjectIsEqualException(i); } } } @@ -104,27 +101,27 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = obj; return position; } - int index = position + 1; - while (index < _collection.Length) + int temp = position + 1; + while (temp < Count) { - if (_collection[index] == null) + if (_collection[temp] == null) { - _collection[index] = obj; - return index; + _collection[temp] = obj; + return temp; } - ++index; + ++temp; } - index = position - 1; - while (index >= 0) + temp = position - 1; + while (temp >= 0) { - if (_collection[index] == null) + if (_collection[temp] == null) { - _collection[index] = obj; - return index; + _collection[temp] = obj; + return temp; } - --index; + --temp; } - throw new CollectionOverflowException(Count); + throw new CollectionOverflowException(); } public T? Remove(int position) @@ -145,13 +142,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } - public void CollectionSort(IComparer comparer) + void ICollectionGenericObjects.CollectionSort(IComparer comparer) { - List lst = [.._collection]; - lst.Sort(comparer.Compare); - for (int i = 0; i < _collection.Length; ++i) - { - _collection[i] = lst[i]; - } + Array.Sort(_collection, comparer); } } diff --git a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index b45e558..4a41f71 100644 --- a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -3,6 +3,7 @@ using AntiAircraftGun.CollectionGenereticObject; using AntiAircraftGun.Drawnings; using AntiAircraftGun.Exceptions; using System.Text; +using System.Xml.Linq; namespace AntiAircraftGun.CollectionGenericObjects; @@ -51,15 +52,14 @@ public class StorageCollection /// /// Название коллекции /// тип коллекции - public void AddCollection(CollectionInfo collectionInfo) + public void AddCollection(String name, CollectionType collectionType) { - - if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo); - if (collectionInfo.CollectionType == CollectionType.None) - throw new CollectionTypeException("Пустой тип коллекции"); - if (collectionInfo.CollectionType == CollectionType.Massive) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; + if (collectionType == CollectionType.None) return; + else if (collectionType == CollectionType.Massive) _storages[collectionInfo] = new MassiveGenericObjects(); - else if (collectionInfo.CollectionType == CollectionType.List) + else if (collectionType == CollectionType.List) _storages[collectionInfo] = new ListGenericObjects(); } diff --git a/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs b/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs new file mode 100644 index 0000000..5137708 --- /dev/null +++ b/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public class ObjectIsEqualException : ApplicationException +{ + public ObjectIsEqualException(object i) : base("В коллекции уже есть такой элемент " + i) { } + public ObjectIsEqualException() : base() { } + public ObjectIsEqualException(string message) : base(message) { } + public ObjectIsEqualException(string message, Exception exception) : base(message, exception) + { } + protected ObjectIsEqualException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/AntiAircraftGun/FormArmoredCarCollection.cs b/AntiAircraftGun/FormArmoredCarCollection.cs index 2afbe24..79beda9 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.cs @@ -69,20 +69,28 @@ public partial class FormArmoredCarCollection : Form { return; } - if (_company + armoredCar != -1) + if (_company + armoredCar < 32) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: {0}", armoredCar.GetDataForSave()); + _logger.LogInformation("Добавлен объект: " + armoredCar.GetDataForSave()); + } + else + { + MessageBox.Show("Не удалось добавить объект"); } - } - + catch (ObjectNotFoundException) { } catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } @@ -192,10 +200,10 @@ public partial class FormArmoredCarCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? col = _storageCollection.Keys?[i]; + if (!col!.IsEmpty()) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(col); } } @@ -245,14 +253,15 @@ public partial class FormArmoredCarCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } + try { if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); } catch (Exception ex) @@ -273,7 +282,9 @@ public partial class FormArmoredCarCollection : 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("Коллекция не проинициализирована"); -- 2.25.1