From 23202f62c4244f560ff010bbffdae4140a744d2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC?= Date: Thu, 29 Aug 2024 03:35:38 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 14 +++- .../CollectionInfo.cs | 75 +++++++++++++++++ .../ICollectionGenericObjects.cs | 17 +++- .../ListGenericObjects.cs | 34 ++++++-- .../MassiveGenericObjects.cs | 42 +++++++--- .../StorageCollection.cs | 81 +++++++++++-------- .../DrawiningArtilleryUnitEqutables.cs | 54 +++++++++++++ .../DrawningArtilleryUnitCompareByColor.cs | 34 ++++++++ .../DrawningArtilleryUnitCompareByType.cs | 35 ++++++++ .../ProjertTrain/Drawnings/DrawningTrain.cs | 2 +- .../ObjectAlreadyInCollectionException.cs | 22 +++++ .../ProjertTrain/FormTrainConfing.Designer.cs | 3 +- ProjertTrain/ProjertTrain/FormTrainConfing.cs | 19 ++--- .../FormTrainsCollection.Designer.cs | 54 ++++++++++--- .../ProjertTrain/FormTrainsCollection.cs | 65 +++++++++++---- .../MovementStrategy/MoveableTrain.cs | 22 ++--- 16 files changed, 464 insertions(+), 109 deletions(-) create mode 100644 ProjertTrain/ProjertTrain/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjertTrain/ProjertTrain/Drawnings/DrawiningArtilleryUnitEqutables.cs create mode 100644 ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByColor.cs create mode 100644 ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByType.cs create mode 100644 ProjertTrain/ProjertTrain/Exceptions/ObjectAlreadyInCollectionException.cs diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs index a825f54..a120b5d 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs @@ -57,11 +57,11 @@ namespace ProjectTrain.CollectionGenericObjects /// Перегрузка оператора сложения для класса /// /// Компания - /// Добавляемый объект + /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningTrain сruiser) + public static int operator +(AbstractCompany company, DrawningTrain train) { - return company._collection.Insert(сruiser); + return company._collection.Insert(train, new DrawiningTrainEqutables()); } /// @@ -109,6 +109,14 @@ namespace ProjectTrain.CollectionGenericObjects } return bitmap; } + + + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/CollectionInfo.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..8fe0ca4 --- /dev/null +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,75 @@ +namespace ProjectTrain.CollectionGenericObjects; + +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string + description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + + return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } + +} diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs index 25bf1b0..6258d9f 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectTrain.CollectionGenericObjects +using ProjectTrain.Drawnings; + +namespace ProjectTrain.CollectionGenericObjects { /// /// Интерфейс описания действий для набора хранимых объектов @@ -19,15 +21,18 @@ /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); + /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); + /// /// Удаление объекта из коллекции с конкретной позиции /// @@ -51,6 +56,12 @@ /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + } } diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs index 2f012b4..d07dc9c 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -using ProjectTrain.Exceptions; +using ProjectTrain.Drawnings; + +using ProjectTrain.Exceptions; namespace ProjectTrain.CollectionGenericObjects { @@ -47,23 +49,38 @@ namespace ProjectTrain.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO выбром позиций, если переполнение + // TODO выброc позиций, если такой объект есть в коллекции // TODO вставка в конец набора + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i); + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // TODO проверка, что не превышено максимальное количество элементов + // TODO выброc позиций, если такой объект есть в коллекции // TODO проверка позиции // TODO вставка по позиции + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i); + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + _collection.Insert(position, obj); return position; @@ -72,13 +89,15 @@ namespace ProjectTrain.CollectionGenericObjects public T Remove(int position) { // TODO проверка позиции - // TODO удаление объекта из списка // TODO выбром позиций, если выход за границы массива + // TODO удаление объекта из списка if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); return obj; } + public IEnumerable GetItems() { for (int i = 0; i < _collection.Count; ++i) @@ -86,5 +105,10 @@ namespace ProjectTrain.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } -} +} \ No newline at end of file diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs index 34f5955..5c36596 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,7 @@ -using ProjectTrain.Exceptions; - +using ProjectTrain.Drawnings; +using ProjectTrain.Exceptions; +using ProjectTrain.CollectionGenericObjects; +using ProjectTrain.Exceptions; namespace ProjectTrain.CollectionGenericObjects { @@ -36,6 +38,7 @@ namespace ProjectTrain.CollectionGenericObjects } } } + public CollectionType GetCollectionType => CollectionType.Massive; /// @@ -55,34 +58,44 @@ namespace ProjectTrain.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO вставка в свободное место набора // TODO выброc позиций, если переполнение - int index = 0; - while (index < Count && _collection[index] != null) + // TODO выброc позиций, если такой объект есть в коллекции + for (int i = 0; i < Count; i++) { - index++; + if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i); } - if (index < Count) + for (int i = 0; i < Count; i++) { - _collection[index] = obj; - return index; + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } } throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + // TODO выброc позиций, если такой объект есть в коллекции // TODO проверка позиции + // TODO выбром позиций, если выход за границы массива // TODO проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до - // TODO вставка // TODO выбром позиций, если переполнение - // TODO выбром позиций, если выход за границы массива + // TODO вставка + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i); + + } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] != null) @@ -143,5 +156,10 @@ namespace ProjectTrain.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } } diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs index 50c8ea9..31498d3 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,7 @@ -using ProjectTrain.Exceptions; -using ProjectTrain.Drawnings; +using ProjectTrain.Drawnings; +using ProjectTrain.Exceptions; +using ProjectTrain.CollectionGenericObjects; +using ProjectTrain.Exceptions; using System.Text; namespace ProjectTrain.CollectionGenericObjects @@ -13,12 +15,12 @@ namespace ProjectTrain.CollectionGenericObjects /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -40,7 +42,7 @@ namespace ProjectTrain.CollectionGenericObjects /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -48,29 +50,40 @@ namespace ProjectTrain.CollectionGenericObjects /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo name) { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; + if (name == null || _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 (name.CollectionType == CollectionType.Massive) + { + _storages.Add(name, new MassiveGenericObjects()); + } + + if (name.CollectionType == CollectionType.List) + { + _storages.Add(name, new ListGenericObjects()); + } } /// /// Удаление коллекции /// /// Название коллекции - public void DelCollection(string name) + public void DelCollection(CollectionInfo name) { // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) - _storages.Remove(name); + if (name == null || !_storages.ContainsKey(name)) + { + return; + } + + _storages.Remove(name); } /// @@ -78,18 +91,22 @@ namespace ProjectTrain.CollectionGenericObjects /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo name] { get { // TODO Продумать логику получения объекта if (_storages.ContainsKey(name)) + { return _storages[name]; + } + return null; } } + /// - /// Сохранение информации по автомобилям в хранилище в файл + /// Сохранение информации по самолетам в хранилище в файл /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных @@ -110,7 +127,7 @@ namespace ProjectTrain.CollectionGenericObjects using StreamWriter streamWriter = new StreamWriter(fs); streamWriter.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { streamWriter.Write(Environment.NewLine); @@ -121,8 +138,6 @@ namespace ProjectTrain.CollectionGenericObjects streamWriter.Write(value.Key); streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); streamWriter.Write(value.Value.MaxCount); streamWriter.Write(_separatorForKeyValue); @@ -163,27 +178,25 @@ namespace ProjectTrain.CollectionGenericObjects while ((str = sr.ReadLine()) != null) { string[] record = str.Split(_separatorForKeyValue); - 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 InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); + collection.MaxCount = Convert.ToInt32(record[1]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningTrain() is T aircraft) + if (elem?.CreateDrawningTrain() is T train) { try { - if (collection.Insert(aircraft) == -1) + if (collection.Insert(train, new DrawiningTrainEqutables()) == -1) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } @@ -192,9 +205,13 @@ namespace ProjectTrain.CollectionGenericObjects { throw new CollectionOverflowException("Коллекция переполнена", ex); } + catch (ObjectAlreadyInCollectionException ex) + { + throw new InvalidOperationException("Объект уже присутствует в коллекции", ex); + } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjertTrain/ProjertTrain/Drawnings/DrawiningArtilleryUnitEqutables.cs b/ProjertTrain/ProjertTrain/Drawnings/DrawiningArtilleryUnitEqutables.cs new file mode 100644 index 0000000..b9c3382 --- /dev/null +++ b/ProjertTrain/ProjertTrain/Drawnings/DrawiningArtilleryUnitEqutables.cs @@ -0,0 +1,54 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ProjectTrain.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawiningTrainEqutables : IEqualityComparer +{ + public bool Equals(DrawningTrain? x, DrawningTrain? y) + { + if (x == null || x.EntityTrain == null) + { + return false; + } + + if (y == null || y.EntityTrain == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (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 DrawningElectroTrain && y is DrawningElectroTrain) + { + // TODO доделать логику сравнения дополнительных параметров + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrain obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByColor.cs b/ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByColor.cs new file mode 100644 index 0000000..c7dca50 --- /dev/null +++ b/ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByColor.cs @@ -0,0 +1,34 @@ +using ProjectTrain.Entities; + +namespace ProjectTrain.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningTrainCompareByColor : IComparer +{ + public int Compare(DrawningTrain? x, DrawningTrain? y) + { + // TODO прописать логику сравения по цветам, скорости, весу + if (x == null || x.EntityTrain == null) + { + return 1; + } + + if (y == null || y.EntityTrain == null) + { + return -1; + } + var bodycolorCompare = x.EntityTrain.BodyColor.Name.CompareTo(y.EntityTrain.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight); + } +} diff --git a/ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByType.cs b/ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByType.cs new file mode 100644 index 0000000..f32de1c --- /dev/null +++ b/ProjertTrain/ProjertTrain/Drawnings/DrawningArtilleryUnitCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectTrain.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningTrainCompareByType : IComparer +{ + public int Compare(DrawningTrain? x, DrawningTrain? y) + { + 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); + } +} diff --git a/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs b/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs index 2e8957f..ea7c414 100644 --- a/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs +++ b/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs @@ -215,7 +215,7 @@ public class DrawningTrain //Brush additionalBrush = new SolidBrush(entityElectroTrain.AdditionalColor); Brush bodyBrush = new SolidBrush(EntityTrain.BodyColor); - //границы круисера + //границы поезда Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) }; //g.FillPolygon(additionalBrush, points); diff --git a/ProjertTrain/ProjertTrain/Exceptions/ObjectAlreadyInCollectionException.cs b/ProjertTrain/ProjertTrain/Exceptions/ObjectAlreadyInCollectionException.cs new file mode 100644 index 0000000..a22461c --- /dev/null +++ b/ProjertTrain/ProjertTrain/Exceptions/ObjectAlreadyInCollectionException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectTrain.Exceptions; + +[Serializable] +internal class ObjectAlreadyInCollectionException : ApplicationException +{ + public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { } + + public ObjectAlreadyInCollectionException() : base() { } + + public ObjectAlreadyInCollectionException(string message) : base(message) { } + + public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { } + + protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjertTrain/ProjertTrain/FormTrainConfing.Designer.cs b/ProjertTrain/ProjertTrain/FormTrainConfing.Designer.cs index 8f80d47..2f81593 100644 --- a/ProjertTrain/ProjertTrain/FormTrainConfing.Designer.cs +++ b/ProjertTrain/ProjertTrain/FormTrainConfing.Designer.cs @@ -184,6 +184,7 @@ checkBoxHeadlight.TabIndex = 8; checkBoxHeadlight.Text = "Признак наличие фонаря"; checkBoxHeadlight.UseVisualStyleBackColor = true; + checkBoxHeadlight.CheckedChanged += checkBoxHeadlight_CheckedChanged; // // checkBoxElectro // @@ -195,7 +196,6 @@ checkBoxElectro.TabIndex = 7; checkBoxElectro.Text = "Признак наличие батареи"; checkBoxElectro.UseVisualStyleBackColor = true; - checkBoxElectro.CheckedChanged += checkBoxElectro_CheckedChanged; // // checkBoxHorns // @@ -258,7 +258,6 @@ labelModifiedObject.TabIndex = 1; labelModifiedObject.Text = "Продвинутый"; labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter; - labelModifiedObject.Click += labelModifiedObject_Click; labelModifiedObject.MouseDown += labelObject_MouseDown; // // labelSimpleObject diff --git a/ProjertTrain/ProjertTrain/FormTrainConfing.cs b/ProjertTrain/ProjertTrain/FormTrainConfing.cs index 1413cf4..32a9cdb 100644 --- a/ProjertTrain/ProjertTrain/FormTrainConfing.cs +++ b/ProjertTrain/ProjertTrain/FormTrainConfing.cs @@ -152,9 +152,9 @@ namespace ProjectTrain private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e) { - if (_train.EntityTrain is EntityElectroTrain militaryTrain) + if (_train.EntityTrain is EntityElectroTrain electroTrain) { - militaryTrain.setAdditionalColor((Color)e.Data.GetData(typeof(Color))); + electroTrain.setAdditionalColor((Color)e.Data.GetData(typeof(Color))); } DrawObject(); } @@ -173,19 +173,14 @@ namespace ProjectTrain } } - private void checkBoxElectro_CheckedChanged(object sender, EventArgs e) - { - - } - - private void labelModifiedObject_Click(object sender, EventArgs e) - { - - } - private void checkBoxHorns_CheckedChanged(object sender, EventArgs e) { } + + private void checkBoxHeadlight_CheckedChanged(object sender, EventArgs e) + { + + } } } diff --git a/ProjertTrain/ProjertTrain/FormTrainsCollection.Designer.cs b/ProjertTrain/ProjertTrain/FormTrainsCollection.Designer.cs index a206208..ac5ac90 100644 --- a/ProjertTrain/ProjertTrain/FormTrainsCollection.Designer.cs +++ b/ProjertTrain/ProjertTrain/FormTrainsCollection.Designer.cs @@ -40,6 +40,8 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); ButtonAddTrain = new Button(); buttonRefresh = new Button(); ButtonRemoveTrain = new Button(); @@ -70,7 +72,7 @@ groupBoxTools.Margin = new Padding(3, 2, 3, 2); groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Padding = new Padding(3, 2, 3, 2); - groupBoxTools.Size = new Size(194, 485); + groupBoxTools.Size = new Size(194, 492); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; @@ -189,6 +191,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(ButtonAddTrain); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(ButtonRemoveTrain); @@ -201,6 +205,30 @@ panelCompanyTools.Size = new Size(189, 206); panelCompanyTools.TabIndex = 8; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonSortByColor.Location = new Point(17, 181); + buttonSortByColor.Margin = new Padding(3, 2, 3, 2); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(163, 23); + buttonSortByColor.TabIndex = 7; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Right; + buttonSortByType.Location = new Point(17, 149); + buttonSortByType.Margin = new Padding(3, 2, 3, 2); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(163, 28); + buttonSortByType.TabIndex = 6; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // ButtonAddTrain // ButtonAddTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; @@ -208,7 +236,7 @@ ButtonAddTrain.Location = new Point(16, 2); ButtonAddTrain.Margin = new Padding(3, 2, 3, 2); ButtonAddTrain.Name = "ButtonAddTrain"; - ButtonAddTrain.Size = new Size(163, 30); + ButtonAddTrain.Size = new Size(163, 39); ButtonAddTrain.TabIndex = 1; ButtonAddTrain.Text = "добваление поезда"; ButtonAddTrain.UseVisualStyleBackColor = true; @@ -217,10 +245,10 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonRefresh.Location = new Point(16, 170); + buttonRefresh.Location = new Point(17, 123); buttonRefresh.Margin = new Padding(3, 2, 3, 2); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(163, 31); + buttonRefresh.Size = new Size(163, 22); buttonRefresh.TabIndex = 5; buttonRefresh.Text = "обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -229,10 +257,10 @@ // ButtonRemoveTrain // ButtonRemoveTrain.Anchor = AnchorStyles.Right; - ButtonRemoveTrain.Location = new Point(16, 104); + ButtonRemoveTrain.Location = new Point(17, 74); ButtonRemoveTrain.Margin = new Padding(3, 2, 3, 2); ButtonRemoveTrain.Name = "ButtonRemoveTrain"; - ButtonRemoveTrain.Size = new Size(163, 30); + ButtonRemoveTrain.Size = new Size(163, 21); ButtonRemoveTrain.TabIndex = 3; ButtonRemoveTrain.Text = "удалить поезд"; ButtonRemoveTrain.UseVisualStyleBackColor = true; @@ -240,7 +268,7 @@ // // maskedTextBoxPosision // - maskedTextBoxPosision.Location = new Point(15, 79); + maskedTextBoxPosision.Location = new Point(16, 45); maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2); maskedTextBoxPosision.Mask = "00"; maskedTextBoxPosision.Name = "maskedTextBoxPosision"; @@ -251,10 +279,10 @@ // buttonGetToTest // buttonGetToTest.Anchor = AnchorStyles.Right; - buttonGetToTest.Location = new Point(16, 138); + buttonGetToTest.Location = new Point(16, 99); buttonGetToTest.Margin = new Padding(3, 2, 3, 2); buttonGetToTest.Name = "buttonGetToTest"; - buttonGetToTest.Size = new Size(163, 30); + buttonGetToTest.Size = new Size(163, 20); buttonGetToTest.TabIndex = 4; buttonGetToTest.Text = "передать на тесты"; buttonGetToTest.UseVisualStyleBackColor = true; @@ -266,10 +294,9 @@ pictureBoxTrain.Location = new Point(0, 24); pictureBoxTrain.Margin = new Padding(3, 2, 3, 2); pictureBoxTrain.Name = "pictureBoxTrain"; - pictureBoxTrain.Size = new Size(552, 485); + pictureBoxTrain.Size = new Size(552, 492); pictureBoxTrain.TabIndex = 1; pictureBoxTrain.TabStop = false; - pictureBoxTrain.Click += pictureBoxTrain_Click; // // menuStrip // @@ -317,7 +344,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(746, 509); + ClientSize = new Size(746, 516); Controls.Add(pictureBoxTrain); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -325,6 +352,7 @@ Margin = new Padding(3, 2, 3, 2); Name = "FormTrainsCollection"; Text = "FormTrainsCollection"; + Load += FormTrainsCollection_Load; groupBoxTools.ResumeLayout(false); panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); @@ -363,5 +391,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/ProjertTrain/ProjertTrain/FormTrainsCollection.cs b/ProjertTrain/ProjertTrain/FormTrainsCollection.cs index 00be967..cbaefc0 100644 --- a/ProjertTrain/ProjertTrain/FormTrainsCollection.cs +++ b/ProjertTrain/ProjertTrain/FormTrainsCollection.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using ProjectTrain.CollectionGenericObjects; using ProjectTrain.Drawnings; +using System.Windows.Forms; namespace ProjectTrain { @@ -174,17 +175,11 @@ namespace ProjectTrain collectionType = CollectionType.List; } - try - { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - _logger.LogInformation("Добавление коллекции"); - RerfreshListBoxItems(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError($"Ошибка: {ex.Message}", ex.Message); - } + CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty); + + _storageCollection.AddCollection(collectionInfo); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); } /// @@ -203,7 +198,10 @@ namespace ProjectTrain { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + + _storageCollection.DelCollection(collectionInfo); _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -216,7 +214,7 @@ namespace ProjectTrain listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -237,8 +235,8 @@ namespace ProjectTrain return; } - ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + ICollectionGenericObjects? collection = _storageCollection[collectionInfo]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -253,6 +251,7 @@ namespace ProjectTrain break; } panelCompanyTools.Enabled = true; + RerfreshListBoxItems(); } @@ -303,7 +302,41 @@ namespace ProjectTrain } } - private void pictureBoxTrain_Click(object sender, EventArgs e) + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareTrains(new DrawningTrainCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareTrains(new DrawningTrainCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareTrains(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBoxTrain.Image = _company.Show(); + } + + private void FormTrainsCollection_Load(object sender, EventArgs e) { } diff --git a/ProjertTrain/ProjertTrain/MovementStrategy/MoveableTrain.cs b/ProjertTrain/ProjertTrain/MovementStrategy/MoveableTrain.cs index 66e952a..1605aab 100644 --- a/ProjertTrain/ProjertTrain/MovementStrategy/MoveableTrain.cs +++ b/ProjertTrain/ProjertTrain/MovementStrategy/MoveableTrain.cs @@ -10,36 +10,36 @@ namespace ProjectTrain.MovementStrategy /// /// Поле-объект класса DrawningTrain или его наследника /// - private readonly DrawningTrain? _cruiser = null; + private readonly DrawningTrain? _train = null; /// /// Конструктор /// - /// Объект класса DrawningTrain - public MoveableTrain(DrawningTrain cruiser) + /// Объект класса DrawningTrain + public MoveableTrain(DrawningTrain train) { - _cruiser = cruiser; + _train = train; } public ObjectParameters? GetObjectPosition { get { - if (_cruiser == null || _cruiser.EntityTrain == null || - !_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue) + if (_train == null || _train.EntityTrain == null || + !_train.GetPosX.HasValue || !_train.GetPosY.HasValue) { return null; } - return new ObjectParameters(_cruiser.GetPosX.Value, - _cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight); + return new ObjectParameters(_train.GetPosX.Value, + _train.GetPosY.Value, _train.GetWidth, _train.GetHeight); } } - public int GetStep => (int)(_cruiser?.EntityTrain?.Step ?? 0); + public int GetStep => (int)(_train?.EntityTrain?.Step ?? 0); public bool TryMoveObject(MovementDirection direction) { - if (_cruiser == null || _cruiser.EntityTrain == null) + if (_train == null || _train.EntityTrain == null) { return false; } - return _cruiser.MoveTransport(GetDirectionType(direction)); + return _train.MoveTransport(GetDirectionType(direction)); } /// /// Конвертация из MovementDirection в DirectionType