This commit is contained in:
Timourka 2023-12-16 18:17:57 +04:00
parent 21c9ff5017
commit 1b6c637413
9 changed files with 264 additions and 26 deletions

View File

@ -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<DrawingTrain?>
{
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();
}
}
}

View File

@ -45,6 +45,8 @@
loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog = new System.Windows.Forms.OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog(); 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(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panel1.SuspendLayout(); panel1.SuspendLayout();
panel2.SuspendLayout(); panel2.SuspendLayout();
@ -64,6 +66,8 @@
// panel1 // panel1
// //
panel1.AccessibleName = ""; panel1.AccessibleName = "";
panel1.Controls.Add(sort_by_color);
panel1.Controls.Add(sort_by_type);
panel1.Controls.Add(panel2); panel1.Controls.Add(panel2);
panel1.Controls.Add(maskedTextBoxNumber); panel1.Controls.Add(maskedTextBoxNumber);
panel1.Controls.Add(ButtonAddTrain); panel1.Controls.Add(ButtonAddTrain);
@ -191,14 +195,14 @@
// saveToolStripMenuItem // saveToolStripMenuItem
// //
saveToolStripMenuItem.Name = "saveToolStripMenuItem"; saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); saveToolStripMenuItem.Size = new System.Drawing.Size(100, 22);
saveToolStripMenuItem.Text = "Save"; saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// loadToolStripMenuItem // loadToolStripMenuItem
// //
loadToolStripMenuItem.Name = "loadToolStripMenuItem"; loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); loadToolStripMenuItem.Size = new System.Drawing.Size(100, 22);
loadToolStripMenuItem.Text = "Load"; loadToolStripMenuItem.Text = "Load";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
@ -212,6 +216,26 @@
saveFileDialog.FileName = "TrainSave.txt"; saveFileDialog.FileName = "TrainSave.txt";
saveFileDialog.Filter = "txt file | *.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 // FormTrainCollection
// //
AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -252,5 +276,7 @@
private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.Button sort_by_color;
private System.Windows.Forms.Button sort_by_type;
} }
} }

View File

@ -44,7 +44,7 @@ namespace Laba1Loco
listBoxStorage.Items.Clear(); listBoxStorage.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) 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)) if (listBoxStorage.Items.Count > 0 && (index == -1 || index >= listBoxStorage.Items.Count))
{ {
@ -81,7 +81,7 @@ namespace Laba1Loco
_logger.LogWarning($"добавление поезда неуспешно"); _logger.LogWarning($"добавление поезда неуспешно");
} }
} }
catch(ApplicationException ex) catch (ApplicationException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"добавление поезда неуспешно {ex.Message}"); _logger.LogWarning($"добавление поезда неуспешно {ex.Message}");
@ -145,7 +145,8 @@ namespace Laba1Loco
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try { try
{
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
@ -224,7 +225,7 @@ namespace Laba1Loco
_logger.LogWarning($"удаление набора неуспешно индекс вне"); _logger.LogWarning($"удаление набора неуспешно индекс вне");
return; 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; String name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
_storage.DelSet(name); _storage.DelSet(name);
@ -264,7 +265,7 @@ namespace Laba1Loco
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try try
{ {
_storage.LoadData(openFileDialog.FileName); _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
@ -281,5 +282,31 @@ namespace Laba1Loco
ReloadObjects(); 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());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareTrains(IComparer<DrawingTrain?> 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();
}
} }
} }

View File

@ -39,10 +39,12 @@ namespace Laba1Loco
/// </summary> /// </summary>
/// <param name="train">Добавляемый поезд</param> /// <param name="train">Добавляемый поезд</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T train) public int Insert(T train, IEqualityComparer<T?> equal = null)
{ {
if (_places.Count >= _maxCount) if (_places.Count >= _maxCount)
throw new StorageOverflowException(_places.Count); throw new StorageOverflowException(_places.Count);
if (equal != null && _places.Contains<T>(train, equal))
throw new ApplicationException("already exist");
_places.Insert(0, train); _places.Insert(0, train);
return 0; return 0;
} }
@ -52,7 +54,7 @@ namespace Laba1Loco
/// <param name="train">Добавляемый поезд</param> /// <param name="train">Добавляемый поезд</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T train, int position) public bool Insert(T train, int position, IEqualityComparer<T?> equal = null)
{ {
if (_places.Count >= _maxCount) if (_places.Count >= _maxCount)
throw new StorageOverflowException(_places.Count); throw new StorageOverflowException(_places.Count);
@ -60,6 +62,9 @@ namespace Laba1Loco
if (position < 0 || position > _places.Count) if (position < 0 || position > _places.Count)
throw new TrainNotFoundException(position); throw new TrainNotFoundException(position);
if (equal != null && _places.Contains<T>(train, equal))
throw new Exception("already exist");
if (position == _places.Count) if (position == _places.Count)
_places.Add(train); _places.Add(train);
else else
@ -107,7 +112,7 @@ namespace Laba1Loco
{ {
try try
{ {
Insert(value, position); Insert(value, position, (IEqualityComparer<T>)new DrawiningTrainEqutables());
} }
catch catch
{ {
@ -115,7 +120,11 @@ namespace Laba1Loco
} }
} }
} }
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary> /// <summary>
/// Проход по списку /// Проход по списку
/// </summary> /// </summary>

View File

@ -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<DrawingTrain?>
{
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);
}
}
}

View File

@ -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<DrawingTrain?>
{
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);
}
}
}

View File

@ -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<TrainsCollectionInfo>
{
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;
}
}
}

View File

@ -49,6 +49,11 @@ where U : IMoveableObject
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(width * height);
} }
/// <summary> /// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Перегрузка оператора сложения /// Перегрузка оператора сложения
/// </summary> /// </summary>
/// <param name="collect"></param> /// <param name="collect"></param>
@ -61,7 +66,7 @@ where U : IMoveableObject
return -1; return -1;
} }
return collect?._collection.Insert(obj) ?? -1; return collect?._collection.Insert(obj, new DrawiningTrainEqutables()) ?? -1;
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания

View File

@ -5,6 +5,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq;
using static System.Runtime.InteropServices.JavaScript.JSType; using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Laba1Loco namespace Laba1Loco
@ -36,14 +37,14 @@ namespace Laba1Loco
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
foreach (KeyValuePair<string, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> record in _trainStorages) foreach (KeyValuePair<TrainsCollectionInfo, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> record in _trainStorages)
{ {
StringBuilder records = new StringBuilder(); StringBuilder records = new StringBuilder();
foreach (DrawingTrain elem in record.Value.GetTrains) foreach (DrawingTrain elem in record.Value.GetTrains)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
{ {
@ -100,18 +101,18 @@ namespace Laba1Loco
} }
} }
} }
_trainStorages.Add(record[0], collection); _trainStorages.Add(new TrainsCollectionInfo(record[0], string.Empty), collection);
} }
} }
} }
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> _trainStorages; readonly Dictionary<TrainsCollectionInfo, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> _trainStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _trainStorages.Keys.ToList(); public List<TrainsCollectionInfo> Keys => _trainStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -127,7 +128,7 @@ namespace Laba1Loco
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public TrainsGenericStorage(int pictureWidth, int pictureHeight) public TrainsGenericStorage(int pictureWidth, int pictureHeight)
{ {
_trainStorages = new Dictionary<string, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>>(); _trainStorages = new Dictionary<TrainsCollectionInfo, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -137,9 +138,10 @@ namespace Laba1Loco
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
if (_trainStorages.ContainsKey(name)) TrainsCollectionInfo tInfo = new TrainsCollectionInfo(name, string.Empty);
if (_trainStorages.ContainsKey(tInfo))
return; return;
_trainStorages[name] = new TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>(_pictureWidth, _pictureHeight); _trainStorages[tInfo] = new TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>(_pictureWidth, _pictureHeight);
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -147,22 +149,23 @@ namespace Laba1Loco
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_trainStorages.ContainsKey(name)) TrainsCollectionInfo tInfo = new TrainsCollectionInfo(name, string.Empty);
if (!_trainStorages.ContainsKey(tInfo))
return; return;
_trainStorages.Remove(name); _trainStorages.Remove(tInfo);
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
/// </summary> /// </summary>
/// <param name="ind"></param> /// <param name="ind"></param>
/// <returns></returns> /// <returns></returns>
public TrainsGenericCollection<DrawingTrain, DrawningObjectTrain> public TrainsGenericCollection<DrawingTrain, DrawningObjectTrain> this[string ind]
this[string ind]
{ {
get get
{ {
if (_trainStorages.ContainsKey(ind)) TrainsCollectionInfo tInfo = new TrainsCollectionInfo(ind, string.Empty);
return _trainStorages[ind]; if (_trainStorages.ContainsKey(tInfo))
return _trainStorages[tInfo];
return null; return null;
} }
} }