diff --git a/Laba1Loco/Laba1Loco/DrawiningTrainEqutables.cs b/Laba1Loco/Laba1Loco/DrawiningTrainEqutables.cs new file mode 100644 index 0000000..1db1df0 --- /dev/null +++ b/Laba1Loco/Laba1Loco/DrawiningTrainEqutables.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Laba1Loco +{ + internal class DrawiningTrainEqutables : IEqualityComparer + { + public bool Equals(DrawingTrain? x, DrawingTrain? y) + { + if (x == null || x.EntityTrain == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityTrain == null) + { + throw new ArgumentNullException(nameof(y)); + } + 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 DrawingLoco && y is DrawingLoco) + { + if (x.EntityTrain as EntityLoco == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y.EntityTrain as EntityLoco == null) + { + throw new ArgumentNullException(nameof(y)); + } + if ((x.EntityTrain as EntityLoco).LocoLine != (y.EntityTrain as EntityLoco).LocoLine) + { + return false; + } + if ((x.EntityTrain as EntityLoco).FuelTank != (y.EntityTrain as EntityLoco).FuelTank) + { + return false; + } + if ((x.EntityTrain as EntityLoco).Tube != (y.EntityTrain as EntityLoco).Tube) + { + return false; + } + if ((x.EntityTrain as EntityLoco).AdditionalColor != (y.EntityTrain as EntityLoco).AdditionalColor) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawingTrain obj) + { + return obj.GetHashCode(); + } + + } +} diff --git a/Laba1Loco/Laba1Loco/FormTrainCollection.Designer.cs b/Laba1Loco/Laba1Loco/FormTrainCollection.Designer.cs index f33b15a..9ae1b56 100644 --- a/Laba1Loco/Laba1Loco/FormTrainCollection.Designer.cs +++ b/Laba1Loco/Laba1Loco/FormTrainCollection.Designer.cs @@ -45,6 +45,8 @@ loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); openFileDialog = new System.Windows.Forms.OpenFileDialog(); saveFileDialog = new System.Windows.Forms.SaveFileDialog(); + sort_by_type = new System.Windows.Forms.Button(); + sort_by_color = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); panel1.SuspendLayout(); panel2.SuspendLayout(); @@ -64,6 +66,8 @@ // panel1 // panel1.AccessibleName = ""; + panel1.Controls.Add(sort_by_color); + panel1.Controls.Add(sort_by_type); panel1.Controls.Add(panel2); panel1.Controls.Add(maskedTextBoxNumber); panel1.Controls.Add(ButtonAddTrain); @@ -191,14 +195,14 @@ // saveToolStripMenuItem // saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - saveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + saveToolStripMenuItem.Size = new System.Drawing.Size(100, 22); saveToolStripMenuItem.Text = "Save"; saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // // loadToolStripMenuItem // loadToolStripMenuItem.Name = "loadToolStripMenuItem"; - loadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + loadToolStripMenuItem.Size = new System.Drawing.Size(100, 22); loadToolStripMenuItem.Text = "Load"; loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // @@ -212,6 +216,26 @@ saveFileDialog.FileName = "TrainSave.txt"; saveFileDialog.Filter = "txt file | *.txt"; // + // sort_by_type + // + sort_by_type.Location = new System.Drawing.Point(18, 43); + sort_by_type.Name = "sort_by_type"; + sort_by_type.Size = new System.Drawing.Size(163, 23); + sort_by_type.TabIndex = 7; + sort_by_type.Text = "Sort by type"; + sort_by_type.UseVisualStyleBackColor = true; + sort_by_type.Click += sort_by_type_Click; + // + // sort_by_color + // + sort_by_color.Location = new System.Drawing.Point(18, 69); + sort_by_color.Name = "sort_by_color"; + sort_by_color.Size = new System.Drawing.Size(163, 23); + sort_by_color.TabIndex = 8; + sort_by_color.Text = "Sort by color"; + sort_by_color.UseVisualStyleBackColor = true; + sort_by_color.Click += sort_by_color_Click; + // // FormTrainCollection // AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -252,5 +276,7 @@ private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; + private System.Windows.Forms.Button sort_by_color; + private System.Windows.Forms.Button sort_by_type; } } \ No newline at end of file diff --git a/Laba1Loco/Laba1Loco/FormTrainCollection.cs b/Laba1Loco/Laba1Loco/FormTrainCollection.cs index 9b01adb..1d8b182 100644 --- a/Laba1Loco/Laba1Loco/FormTrainCollection.cs +++ b/Laba1Loco/Laba1Loco/FormTrainCollection.cs @@ -44,7 +44,7 @@ namespace Laba1Loco listBoxStorage.Items.Clear(); for (int i = 0; i < _storage.Keys.Count; i++) { - listBoxStorage.Items.Add(_storage.Keys[i]); + listBoxStorage.Items.Add(_storage.Keys[i].Name); } if (listBoxStorage.Items.Count > 0 && (index == -1 || index >= listBoxStorage.Items.Count)) { @@ -81,7 +81,7 @@ namespace Laba1Loco _logger.LogWarning($"добавление поезда неуспешно"); } } - catch(ApplicationException ex) + catch (ApplicationException ex) { MessageBox.Show(ex.Message); _logger.LogWarning($"добавление поезда неуспешно {ex.Message}"); @@ -145,7 +145,8 @@ namespace Laba1Loco return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - try { + try + { if (obj - pos != null) { MessageBox.Show("Объект удален"); @@ -224,7 +225,7 @@ namespace Laba1Loco _logger.LogWarning($"удаление набора неуспешно индекс вне"); return; } - if (MessageBox.Show($"Удалить объект { listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { String name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; _storage.DelSet(name); @@ -264,7 +265,7 @@ namespace Laba1Loco { if (openFileDialog.ShowDialog() == DialogResult.OK) { - try + try { _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", @@ -281,5 +282,31 @@ namespace Laba1Loco ReloadObjects(); } + private void sort_by_type_Click(object sender, EventArgs e) + { + CompareTrains(new TrainCompareByType()); + } + + private void sort_by_color_Click(object sender, EventArgs e) + { + CompareTrains(new TrainCompareByColor()); + } + /// + /// Сортировка по сравнителю + /// + /// + private void CompareTrains(IComparer comparer) + { + if (listBoxStorage.SelectedIndex == -1) + return; + + var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + return; + + obj.Sort(comparer); + + pictureBoxCollection.Image = obj.ShowTrains(); + } } } diff --git a/Laba1Loco/Laba1Loco/SetGeneric.cs b/Laba1Loco/Laba1Loco/SetGeneric.cs index 4fcdf85..29bddc7 100644 --- a/Laba1Loco/Laba1Loco/SetGeneric.cs +++ b/Laba1Loco/Laba1Loco/SetGeneric.cs @@ -39,10 +39,12 @@ namespace Laba1Loco /// /// Добавляемый поезд /// - public int Insert(T train) + public int Insert(T train, IEqualityComparer equal = null) { if (_places.Count >= _maxCount) throw new StorageOverflowException(_places.Count); + if (equal != null && _places.Contains(train, equal)) + throw new ApplicationException("already exist"); _places.Insert(0, train); return 0; } @@ -52,7 +54,7 @@ namespace Laba1Loco /// Добавляемый поезд /// Позиция /// - public bool Insert(T train, int position) + public bool Insert(T train, int position, IEqualityComparer equal = null) { if (_places.Count >= _maxCount) throw new StorageOverflowException(_places.Count); @@ -60,6 +62,9 @@ namespace Laba1Loco if (position < 0 || position > _places.Count) throw new TrainNotFoundException(position); + if (equal != null && _places.Contains(train, equal)) + throw new Exception("already exist"); + if (position == _places.Count) _places.Add(train); else @@ -107,7 +112,7 @@ namespace Laba1Loco { try { - Insert(value, position); + Insert(value, position, (IEqualityComparer)new DrawiningTrainEqutables()); } catch { @@ -115,7 +120,11 @@ namespace Laba1Loco } } } - + /// + /// Сортировка набора объектов + /// + /// + public void SortSet(IComparer comparer) => _places.Sort(comparer); /// /// Проход по списку /// diff --git a/Laba1Loco/Laba1Loco/TrainCompareByColor.cs b/Laba1Loco/Laba1Loco/TrainCompareByColor.cs new file mode 100644 index 0000000..511926c --- /dev/null +++ b/Laba1Loco/Laba1Loco/TrainCompareByColor.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Laba1Loco +{ + internal class TrainCompareByColor : IComparer + { + public int Compare(DrawingTrain? x, DrawingTrain? y) + { + if (x == null || x.EntityTrain == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityTrain == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.EntityTrain.BodyColor != y.EntityTrain.BodyColor) + { + return x.EntityTrain.BodyColor.Name.CompareTo(y.EntityTrain.BodyColor.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/Laba1Loco/Laba1Loco/TrainCompareByType.cs b/Laba1Loco/Laba1Loco/TrainCompareByType.cs new file mode 100644 index 0000000..1480e05 --- /dev/null +++ b/Laba1Loco/Laba1Loco/TrainCompareByType.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Laba1Loco +{ + internal class TrainCompareByType : IComparer + { + public int Compare(DrawingTrain? x, DrawingTrain? y) + { + if (x == null || x.EntityTrain == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityTrain == null) + { + throw new ArgumentNullException(nameof(y)); + } + 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/Laba1Loco/Laba1Loco/TrainsCollectionInfo.cs b/Laba1Loco/Laba1Loco/TrainsCollectionInfo.cs new file mode 100644 index 0000000..915fd58 --- /dev/null +++ b/Laba1Loco/Laba1Loco/TrainsCollectionInfo.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Laba1Loco +{ + internal class TrainsCollectionInfo : IEquatable + { + public string Name { get; private set; } + public string Description { get; private set; } + public TrainsCollectionInfo(string name, string description) + { + Name = name; + Description = description; + } + public bool Equals(TrainsCollectionInfo? other) + { + return Name.Equals(other.Name); + } + public override int GetHashCode() + { + return Name?.GetHashCode() ?? 0; + } + } +} diff --git a/Laba1Loco/Laba1Loco/TrainsGenericCollection.cs b/Laba1Loco/Laba1Loco/TrainsGenericCollection.cs index 28e4cc4..e273eef 100644 --- a/Laba1Loco/Laba1Loco/TrainsGenericCollection.cs +++ b/Laba1Loco/Laba1Loco/TrainsGenericCollection.cs @@ -49,6 +49,11 @@ where U : IMoveableObject _collection = new SetGeneric(width * height); } /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => _collection.SortSet(comparer); + /// /// Перегрузка оператора сложения /// /// @@ -61,7 +66,7 @@ where U : IMoveableObject return -1; } - return collect?._collection.Insert(obj) ?? -1; + return collect?._collection.Insert(obj, new DrawiningTrainEqutables()) ?? -1; } /// /// Перегрузка оператора вычитания diff --git a/Laba1Loco/Laba1Loco/TrainsGenericStorage.cs b/Laba1Loco/Laba1Loco/TrainsGenericStorage.cs index d939eab..443248b 100644 --- a/Laba1Loco/Laba1Loco/TrainsGenericStorage.cs +++ b/Laba1Loco/Laba1Loco/TrainsGenericStorage.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using System.Xml.Linq; using static System.Runtime.InteropServices.JavaScript.JSType; namespace Laba1Loco @@ -36,14 +37,14 @@ namespace Laba1Loco File.Delete(filename); } StringBuilder data = new StringBuilder(); - foreach (KeyValuePair> record in _trainStorages) + foreach (KeyValuePair> record in _trainStorages) { StringBuilder records = new StringBuilder(); foreach (DrawingTrain elem in record.Value.GetTrains) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { @@ -100,18 +101,18 @@ namespace Laba1Loco } } } - _trainStorages.Add(record[0], collection); + _trainStorages.Add(new TrainsCollectionInfo(record[0], string.Empty), collection); } } } /// /// Словарь (хранилище) /// - readonly Dictionary> _trainStorages; + readonly Dictionary> _trainStorages; /// /// Возвращение списка названий наборов /// - public List Keys => _trainStorages.Keys.ToList(); + public List Keys => _trainStorages.Keys.ToList(); /// /// Ширина окна отрисовки /// @@ -127,7 +128,7 @@ namespace Laba1Loco /// public TrainsGenericStorage(int pictureWidth, int pictureHeight) { - _trainStorages = new Dictionary>(); + _trainStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -137,9 +138,10 @@ namespace Laba1Loco /// Название набора public void AddSet(string name) { - if (_trainStorages.ContainsKey(name)) + TrainsCollectionInfo tInfo = new TrainsCollectionInfo(name, string.Empty); + if (_trainStorages.ContainsKey(tInfo)) return; - _trainStorages[name] = new TrainsGenericCollection(_pictureWidth, _pictureHeight); + _trainStorages[tInfo] = new TrainsGenericCollection(_pictureWidth, _pictureHeight); } /// /// Удаление набора @@ -147,22 +149,23 @@ namespace Laba1Loco /// Название набора public void DelSet(string name) { - if (!_trainStorages.ContainsKey(name)) + TrainsCollectionInfo tInfo = new TrainsCollectionInfo(name, string.Empty); + if (!_trainStorages.ContainsKey(tInfo)) return; - _trainStorages.Remove(name); + _trainStorages.Remove(tInfo); } /// /// Доступ к набору /// /// /// - public TrainsGenericCollection - this[string ind] + public TrainsGenericCollection this[string ind] { get { - if (_trainStorages.ContainsKey(ind)) - return _trainStorages[ind]; + TrainsCollectionInfo tInfo = new TrainsCollectionInfo(ind, string.Empty); + if (_trainStorages.ContainsKey(tInfo)) + return _trainStorages[tInfo]; return null; } }