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();
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;
}
}

View File

@ -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());
}
/// <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>
/// <param name="train">Добавляемый поезд</param>
/// <returns></returns>
public int Insert(T train)
public int Insert(T train, IEqualityComparer<T?> equal = null)
{
if (_places.Count >= _maxCount)
throw new StorageOverflowException(_places.Count);
if (equal != null && _places.Contains<T>(train, equal))
throw new ApplicationException("already exist");
_places.Insert(0, train);
return 0;
}
@ -52,7 +54,7 @@ namespace Laba1Loco
/// <param name="train">Добавляемый поезд</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T train, int position)
public bool Insert(T train, int position, IEqualityComparer<T?> 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<T>(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<T>)new DrawiningTrainEqutables());
}
catch
{
@ -115,7 +120,11 @@ namespace Laba1Loco
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <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);
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
@ -61,7 +66,7 @@ where U : IMoveableObject
return -1;
}
return collect?._collection.Insert(obj) ?? -1;
return collect?._collection.Insert(obj, new DrawiningTrainEqutables()) ?? -1;
}
/// <summary>
/// Перегрузка оператора вычитания

View File

@ -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<string, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> record in _trainStorages)
foreach (KeyValuePair<TrainsCollectionInfo, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> 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);
}
}
}
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> _trainStorages;
readonly Dictionary<TrainsCollectionInfo, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>> _trainStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _trainStorages.Keys.ToList();
public List<TrainsCollectionInfo> Keys => _trainStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -127,7 +128,7 @@ namespace Laba1Loco
/// <param name="pictureHeight"></param>
public TrainsGenericStorage(int pictureWidth, int pictureHeight)
{
_trainStorages = new Dictionary<string, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>>();
_trainStorages = new Dictionary<TrainsCollectionInfo, TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -137,9 +138,10 @@ namespace Laba1Loco
/// <param name="name">Название набора</param>
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<DrawingTrain, DrawningObjectTrain>(_pictureWidth, _pictureHeight);
_trainStorages[tInfo] = new TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
@ -147,22 +149,23 @@ namespace Laba1Loco
/// <param name="name">Название набора</param>
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);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>
this[string ind]
public TrainsGenericCollection<DrawingTrain, DrawningObjectTrain> 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;
}
}