diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs index a7df920..2847d3c 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs @@ -50,7 +50,8 @@ public abstract class AbstractCompany /// Ширина окна /// Высота окна /// Коллекция поездов - public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + public AbstractCompany(int picWidth, int picHeight, + ICollectionGenericObjects collection) { _pictureWidth = picWidth; _pictureHeight = picHeight; @@ -64,9 +65,10 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningTrain train) + public static int operator +(AbstractCompany company, DrawningTrain trans) { - return company._collection.Insert(train); + return company._collection?.Insert(trans, new DrawingTransEquitables()) ?? + throw new DrawingEquitablesException(); } /// @@ -79,7 +81,9 @@ public abstract class AbstractCompany { return company._collection?.Remove(position); } - + + public void Sort(IComparer comparer) => + _collection?.CollectionSort(comparer); /// /// Получение случайного объекта из коллекции diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/CollectionInfo.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..85ce834 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.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(); + } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/DrawingTransEquitables.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/DrawingTransEquitables.cs new file mode 100644 index 0000000..4661594 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/DrawingTransEquitables.cs @@ -0,0 +1,65 @@ +using ProjectRoadTrain.Drawnings; +using ProjectRoadTrain.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.CollectionGenericObjects; + +public class DrawingTrainEquitables : IEqualityComparer +{ + public bool Equals(DrawningTrain? x, DrawningTrain? 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.EntityTrain != null && y.EntityTrain != null && x.EntityTrain.Speed != y.EntityTrain.Speed) + { + return false; + } + + if (x.EntityTrain.Weight != y.EntityTrain.Weight) + { + return false; + } + + if (x.EntityTrain.BodyColor != y.EntityTrain.BodyColor) + { + return false; + } + if (x is DrawningRoadTrain && y is DrawningRoadTrain) + { + if (((EntityRoadTrain)x.EntityTrain).BodyTankColor != + ((EntityRoadTrain)y.EntityTrain).BodyTankColor) + { + return false; + } + if (((EntityRoadTrain)x.EntityTrain).WaterTank != + ((EntityRoadTrain)y.EntityTrain).WaterTank) + { + return false; + } + if (((EntityRoadTrain)x.EntityTrain).CleanBrush != + ((EntityRoadTrain)y.EntityTrain).CleanBrush) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrain obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs index bcb6538..2307ca8 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; - +namespace ProjectRoadTrain.CollectionGenericObjects; public interface ICollectionGenericObjects where T : class { @@ -22,7 +22,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -30,7 +30,7 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -51,4 +51,5 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + void CollectionSort(IComparer comparer); } diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs index e84d42b..ce84317 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs @@ -48,9 +48,20 @@ 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; } @@ -61,13 +72,29 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } - 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; } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } public T Remove(int position) { diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs index 6d70ac0..e79a731 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs @@ -51,8 +51,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - 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++) { @@ -66,14 +78,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 < 0 || position >= Count) 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) { bool pushed = false; @@ -106,7 +126,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - // вставка _collection[position] = obj; return position; } @@ -130,4 +149,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs index 219d840..6143565 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,4 @@ -using ProjectRoadTrain.CollectionGenericObjects; + using ProjectRoadTrain.Drawnings; using ProjectRoadTrain.Exceptions; using System; @@ -6,43 +6,43 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +namespace ProjectRoadTrain.CollectionGenericObjects; public class StorageCollection where T : DrawningTrain { - readonly Dictionary> _storages; + readonly Dictionary> _storages; - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } - - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo collectionInfo) { - if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name); - if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции"); - 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); } - 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; } } @@ -70,7 +70,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -110,11 +110,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException(filename); } using (StreamReader fs = File.OpenText(filename)) @@ -122,8 +122,7 @@ public class StorageCollection string str = fs.ReadLine(); if (string.IsNullOrEmpty(str)) { - throw new FileNotFoundException(filename); - + throw new EmptyFileExeption(filename); } if (!str.StartsWith(_collectionKey)) @@ -136,20 +135,21 @@ public class StorageCollection while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateTrain() is T ship) @@ -165,11 +165,8 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } - - return true; - } } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) diff --git a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingEquitablesException.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingEquitablesException.cs new file mode 100644 index 0000000..cdc3927 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingEquitablesException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Drawnings; + +public class DrawningEquitablesException : Exception +{ + public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { } + public DrawningEquitablesException(string message) : base(message) { } + public DrawningEquitablesException(string message, Exception exception) : + base(message, exception) + { } + protected DrawningEquitablesException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTrainEquitables.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTrainEquitables.cs new file mode 100644 index 0000000..705585a --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTrainEquitables.cs @@ -0,0 +1,64 @@ +using ProjectRoadTrain.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Drawnings; + +public class DrawingTransEquitables : IEqualityComparer +{ + public bool Equals(DrawningTrain? x, DrawningTrain? 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.EntityTrain != null && y.EntityTrain != null && x.EntityTrain.Speed != y.EntityTrain.Speed) + { + return false; + } + + if (x.EntityTrain.Weight != y.EntityTrain.Weight) + { + return false; + } + + if (x.EntityTrain.BodyColor != y.EntityTrain.BodyColor) + { + return false; + } + if (x is DrawningRoadTrain && y is DrawningRoadTrain) + { + if (((EntityRoadTrain)x.EntityTrain).BodyTankColor != + ((EntityRoadTrain)y.EntityTrain).BodyTankColor) + { + return false; + } + if (((EntityRoadTrain)x.EntityTrain).WaterTank != + ((EntityRoadTrain)y.EntityTrain).WaterTank) + { + return false; + } + if (((EntityRoadTrain)x.EntityTrain).CleanBrush != + ((EntityRoadTrain)y.EntityTrain).CleanBrush) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrain obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTransCompareByColor.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTransCompareByColor.cs new file mode 100644 index 0000000..f3dcf02 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTransCompareByColor.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Drawnings; + +public class DrawingTransCompareByColor : IComparer +{ + public int Compare(DrawningTrain? x, DrawningTrain? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityTrain == null) + { + return 1; + } + + if (y == null || y.EntityTrain == null) + { + return -1; + } + + if (ToHex(x.EntityTrain.BodyColor) != ToHex(y.EntityTrain.BodyColor)) + { + return String.Compare(ToHex(x.EntityTrain.BodyColor), ToHex(y.EntityTrain.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight); + } + + private static String ToHex(Color c) + => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTransCompareByType.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTransCompareByType.cs new file mode 100644 index 0000000..602219a --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawingTransCompareByType.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Drawnings; + +public class DrawingTransCompareByType : IComparer +{ + public int Compare(DrawningTrain? x, DrawningTrain y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityTrain == null) + { + return 1; + } + + if (y == null || y.EntityTrain == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight); + } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs index 1e3e9f8..ea94ef6 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs @@ -1,4 +1,5 @@ -using System; +using ProjectRoadTrain.CollectionGenericObjects; +using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; @@ -10,7 +11,7 @@ namespace ProjectRoadTrain.Exceptions; public class CollectionAlreadyExistsException : Exception { public CollectionAlreadyExistsException() : base() { } - public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } + public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } public CollectionAlreadyExistsException(string name, Exception exception) : base($"Коллекция {name} уже существует!", exception) { } diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInfoException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInfoException.cs new file mode 100644 index 0000000..8c2e85f --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInfoException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; + +public class CollectionInfoException : Exception +{ + public CollectionInfoException() : base() { } + public CollectionInfoException(string message) : base(message) { } + public CollectionInfoException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionInfoException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs index c9bbd3b..b75fe4d 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs @@ -9,6 +9,7 @@ namespace ProjectRoadTrain.Exceptions; public class CollectionInsertException : Exception { + public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { } public CollectionInsertException() : base() { } public CollectionInsertException(string message) : base(message) { } public CollectionInsertException(string message, Exception exception) : diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/DrawingEquitablesException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/DrawingEquitablesException.cs new file mode 100644 index 0000000..636fd83 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/DrawingEquitablesException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; + +public class DrawingEquitablesException : Exception +{ + public DrawingEquitablesException() : base("Объекты прорисовки одинаковые") { } + public DrawingEquitablesException(string message) : base(message) { } + public DrawingEquitablesException(string message, Exception exception) : + base(message, exception) + { } + protected DrawingEquitablesException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs index 50010c3..97dec93 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs @@ -54,6 +54,8 @@ namespace ProjectRoadTrain loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -70,13 +72,15 @@ namespace ProjectRoadTrain groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(952, 0); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(218, 780); + groupBoxTools.Size = new Size(218, 842); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTrain); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -86,7 +90,7 @@ namespace ProjectRoadTrain panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 407); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(212, 370); + panelCompanyTools.Size = new Size(212, 432); panelCompanyTools.TabIndex = 8; // // buttonAddTrain @@ -102,7 +106,7 @@ namespace ProjectRoadTrain // // maskedTextBox // - maskedTextBox.Location = new Point(3, 137); + maskedTextBox.Location = new Point(3, 104); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(244, 27); @@ -112,9 +116,9 @@ namespace ProjectRoadTrain // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 294); + buttonRefresh.Location = new Point(3, 264); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(206, 56); + buttonRefresh.Size = new Size(206, 55); buttonRefresh.TabIndex = 6; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -123,7 +127,7 @@ namespace ProjectRoadTrain // buttonDelTrain // buttonDelTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonDelTrain.Location = new Point(3, 170); + buttonDelTrain.Location = new Point(3, 137); buttonDelTrain.Name = "buttonDelTrain"; buttonDelTrain.Size = new Size(206, 56); buttonDelTrain.TabIndex = 4; @@ -134,7 +138,7 @@ namespace ProjectRoadTrain // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 232); + buttonGoToCheck.Location = new Point(3, 199); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(206, 56); buttonGoToCheck.TabIndex = 5; @@ -251,7 +255,7 @@ namespace ProjectRoadTrain pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 0); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(952, 780); + pictureBox.Size = new Size(952, 842); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -296,11 +300,33 @@ namespace ProjectRoadTrain // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 328); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(206, 42); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 376); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(206, 53); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // // FormTrainCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1170, 780); + ClientSize = new Size(1170, 842); Controls.Add(menuStrip); Controls.Add(pictureBox); Controls.Add(groupBoxTools); @@ -345,5 +371,7 @@ namespace ProjectRoadTrain private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByType; + private Button buttonSortByColor; } } \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs index f267c7d..832149f 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs @@ -30,20 +30,19 @@ public partial class FormTrainCollection : 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); } } - } private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e) { switch (comboBoxSelectCompany.Text) { - case "Хранилище": + case "хранилище": _company = new AutoParkService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); break; } @@ -201,7 +200,7 @@ public partial class FormTrainCollection : Form try { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } @@ -210,7 +209,6 @@ public partial class FormTrainCollection : Form MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } - } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { @@ -273,11 +271,11 @@ public partial class FormTrainCollection : Form return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } - private void ButtonCreateCompany_Click(object sender, EventArgs e) { if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) @@ -287,7 +285,9 @@ public partial class FormTrainCollection : Form } ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -296,7 +296,7 @@ public partial class FormTrainCollection : Form switch (comboBoxSelectCompany.Text) { - case "хранилище": + case "ъранилище": _company = new AutoParkService(pictureBox.Width, pictureBox.Height, collection); _logger.LogInformation("Компания создана"); break; @@ -305,5 +305,39 @@ public partial class FormTrainCollection : Form panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new DrawingTransCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new DrawingTransCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }