This commit is contained in:
Robert 2024-03-02 01:53:48 +04:00
parent 4fdfba0b2e
commit fa98258a03
9 changed files with 273 additions and 32 deletions

View File

@ -0,0 +1,58 @@
using DumpTruck.DrawningObjects;
using DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class DrawiningCarEqutables : IEqualityComparer<DrawningTruck?>
{
public bool Equals(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTruck == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTruck.Speed != y.EntityTruck.Speed)
{
return false;
}
if (x.EntityTruck.Weight != y.EntityTruck.Weight)
{
return false;
}
if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor)
{
return false;
}
if (x is DrawningDumpTruck && y is DrawningDumpTruck)
{
EntityDumpTruck xDumpTruck = (EntityDumpTruck)x.EntityTruck;
EntityDumpTruck yDumpTruck = (EntityDumpTruck)y.EntityTruck;
if (xDumpTruck.Trailer != yDumpTruck.Trailer)
return false;
if (xDumpTruck.AdditionalColor != yDumpTruck.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTruck obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -29,6 +29,8 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBox1 = new GroupBox(); groupBox1 = new GroupBox();
buttonSortbyColor = new Button();
buttonSortbyType = new Button();
groupBox2 = new GroupBox(); groupBox2 = new GroupBox();
textBoxStorageName = new TextBox(); textBoxStorageName = new TextBox();
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
@ -53,12 +55,13 @@
// //
// groupBox1 // groupBox1
// //
groupBox1.Controls.Add(buttonSortbyColor);
groupBox1.Controls.Add(buttonSortbyType);
groupBox1.Controls.Add(groupBox2); groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(maskedTextBoxNumber); groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonRefreshCollection); groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(buttonRemoveTruck); groupBox1.Controls.Add(buttonRemoveTruck);
groupBox1.Controls.Add(buttonAddTruck); groupBox1.Controls.Add(buttonAddTruck);
groupBox1.Controls.Add(menuStrip);
groupBox1.Location = new Point(689, 16); groupBox1.Location = new Point(689, 16);
groupBox1.Margin = new Padding(3, 4, 3, 4); groupBox1.Margin = new Padding(3, 4, 3, 4);
groupBox1.Name = "groupBox1"; groupBox1.Name = "groupBox1";
@ -68,6 +71,26 @@
groupBox1.TabStop = false; groupBox1.TabStop = false;
groupBox1.Text = "Инструменты"; groupBox1.Text = "Инструменты";
// //
// buttonSortbyColor
//
buttonSortbyColor.Location = new Point(4, 339);
buttonSortbyColor.Name = "buttonSortbyColor";
buttonSortbyColor.Size = new Size(211, 36);
buttonSortbyColor.TabIndex = 7;
buttonSortbyColor.Text = "Сортировка по цвету";
buttonSortbyColor.UseVisualStyleBackColor = true;
buttonSortbyColor.Click += ButtonSortByColor_Click;
//
// buttonSortbyType
//
buttonSortbyType.Location = new Point(3, 297);
buttonSortbyType.Name = "buttonSortbyType";
buttonSortbyType.Size = new Size(211, 36);
buttonSortbyType.TabIndex = 6;
buttonSortbyType.Text = "Сортировка по типу";
buttonSortbyType.UseVisualStyleBackColor = true;
buttonSortbyType.Click += ButtonSortByType_Click;
//
// groupBox2 // groupBox2
// //
groupBox2.Controls.Add(textBoxStorageName); groupBox2.Controls.Add(textBoxStorageName);
@ -164,10 +187,10 @@
menuStrip.Dock = DockStyle.None; menuStrip.Dock = DockStyle.None;
menuStrip.ImageScalingSize = new Size(20, 20); menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1 }); menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1 });
menuStrip.Location = new Point(7, 314); menuStrip.Location = new Point(11, 9);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.RenderMode = ToolStripRenderMode.Professional; menuStrip.RenderMode = ToolStripRenderMode.Professional;
menuStrip.Size = new Size(223, 47); menuStrip.Size = new Size(223, 29);
menuStrip.TabIndex = 6; menuStrip.TabIndex = 6;
menuStrip.Tag = ""; menuStrip.Tag = "";
menuStrip.Text = "menuStrip"; menuStrip.Text = "menuStrip";
@ -176,29 +199,29 @@
// //
toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItemLoad, toolStripMenuItemSave }); toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItemLoad, toolStripMenuItemSave });
toolStripMenuItem1.Name = "toolStripMenuItem1"; toolStripMenuItem1.Name = "toolStripMenuItem1";
toolStripMenuItem1.Size = new Size(44, 43); toolStripMenuItem1.Size = new Size(44, 25);
toolStripMenuItem1.Text = "file"; toolStripMenuItem1.Text = "file";
// //
// toolStripMenuItemLoad // toolStripMenuItemLoad
// //
toolStripMenuItemLoad.Name = "toolStripMenuItemLoad"; toolStripMenuItemLoad.Name = "toolStripMenuItemLoad";
toolStripMenuItemLoad.Size = new Size(224, 26); toolStripMenuItemLoad.Size = new Size(125, 26);
toolStripMenuItemLoad.Text = "Load"; toolStripMenuItemLoad.Text = "Load";
toolStripMenuItemLoad.Click += LoadStripMenuItem_Click; toolStripMenuItemLoad.Click += LoadStripMenuItem_Click;
// //
// toolStripMenuItemSave // toolStripMenuItemSave
// //
toolStripMenuItemSave.Name = "toolStripMenuItemSave"; toolStripMenuItemSave.Name = "toolStripMenuItemSave";
toolStripMenuItemSave.Size = new Size(224, 26); toolStripMenuItemSave.Size = new Size(125, 26);
toolStripMenuItemSave.Text = "Save"; toolStripMenuItemSave.Text = "Save";
toolStripMenuItemSave.Click += SaveStripMenuItem_Click; toolStripMenuItemSave.Click += SaveStripMenuItem_Click;
// //
// pictureBoxCollection // pictureBoxCollection
// //
pictureBoxCollection.Location = new Point(11, 16); pictureBoxCollection.Location = new Point(11, 40);
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4); pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(672, 568); pictureBoxCollection.Size = new Size(672, 544);
pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
// //
@ -218,6 +241,7 @@
ClientSize = new Size(935, 611); ClientSize = new Size(935, 611);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Controls.Add(groupBox1); Controls.Add(groupBox1);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Margin = new Padding(3, 4, 3, 4); Margin = new Padding(3, 4, 3, 4);
Name = "FormTruckCollection"; Name = "FormTruckCollection";
@ -251,5 +275,7 @@
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private ToolStripMenuItem toolStripMenuItemLoad; private ToolStripMenuItem toolStripMenuItemLoad;
private ToolStripMenuItem toolStripMenuItemSave; private ToolStripMenuItem toolStripMenuItemSave;
private Button buttonSortbyType;
private Button buttonSortbyColor;
} }
} }

View File

@ -40,7 +40,7 @@ namespace DumpTruck
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i].Name);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count)) >= listBoxStorages.Items.Count))
@ -159,6 +159,11 @@ namespace DumpTruck
System.Windows.Forms.MessageBox.Show(ex.Message); System.Windows.Forms.MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
catch (ArgumentException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
} }
private void buttonAddTruck_Click(object sender, EventArgs e) private void buttonAddTruck_Click(object sender, EventArgs e)
{ {
@ -240,5 +245,35 @@ namespace DumpTruck
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTrucks(new TruckCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTrucks(new TruckCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareTrucks(IComparer<DrawningTruck?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTrucks();
}
} }
} }

View File

@ -31,6 +31,7 @@ namespace DumpTruck.Generics
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="count"></param> /// <param name="count"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public SetGeneric(int count) public SetGeneric(int count)
{ {
_maxCount = count; _maxCount = count;
@ -41,9 +42,9 @@ namespace DumpTruck.Generics
/// </summary> /// </summary>
/// <param name="truck">Добавляемый автомобиль</param> /// <param name="truck">Добавляемый автомобиль</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T truck) public int Insert(T truck, IEqualityComparer<T?>? equal = null)
{ {
return Insert(truck, 0); return Insert(truck, equal);
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -51,13 +52,15 @@ namespace DumpTruck.Generics
/// <param name="truck">Добавляемый автомобиль</param> /// <param name="truck">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T truck, int position) public int Insert(T truck, int position, IEqualityComparer<T?>? equal = null)
{ {
// Проверка позиции // Проверка позиции
if (position < 0 || position > Count) if (position < 0 || position > Count)
throw new TruckNotFoundException(position); throw new TruckNotFoundException(position);
if (Count >= _maxCount) if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(truck, equal))
throw new ArgumentException("Данный объект уже есть в коллекции");
// Вставка по позиции // Вставка по позиции
_places.Insert(position, truck); _places.Insert(position, truck);
return position; return position;

View File

@ -0,0 +1,44 @@
using DumpTruck.DrawningObjects;
using DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class TruckCompareByColor : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTruck == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityTruck.BodyColor.Name.CompareTo(y.EntityTruck.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityTruck is EntityDumpTruck xEntityDumpTruck && y.EntityTruck is EntityDumpTruck yEntityDumpTruck)
{
var tentColorCompare = xEntityDumpTruck.AdditionalColor.Name.CompareTo(yEntityDumpTruck.AdditionalColor.Name);
if (tentColorCompare != 0)
{
return tentColorCompare;
}
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}
}

View File

@ -0,0 +1,39 @@
using DumpTruck.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class TruckCompareByType : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTruck == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
var weightCompare = x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
if (weightCompare != 0)
{
return weightCompare;
}
}
}
}

View File

@ -17,11 +17,11 @@ namespace DumpTruck.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> _truckStorages; readonly Dictionary<TrucksCollectionInfo, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> _truckStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _truckStorages.Keys.ToList(); public List<TrucksCollectionInfo> Keys => _truckStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -49,7 +49,7 @@ namespace DumpTruck.Generics
/// /// <param name="pictureHeight"></param> /// /// <param name="pictureHeight"></param>
public TrucksGenericStorage(int pictureWidth, int pictureHeight) public TrucksGenericStorage(int pictureWidth, int pictureHeight)
{ {
_truckStorages = new Dictionary<string, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>>(); _truckStorages = new Dictionary<TrucksCollectionInfo, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -60,7 +60,7 @@ namespace DumpTruck.Generics
public void AddSet(string name) public void AddSet(string name)
{ {
// TODO Прописать логику для добавления // TODO Прописать логику для добавления
_truckStorages.Add(name, new TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight)); if (!_truckStorages.ContainsKey(new TrucksCollectionInfo(name, string.Empty))) _truckStorages.Add(new TrucksCollectionInfo(name, string.Empty), new TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight));
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -69,8 +69,7 @@ namespace DumpTruck.Generics
public void DelSet(string name) public void DelSet(string name)
{ {
// TODO Прописать логику для удаления // TODO Прописать логику для удаления
if (_truckStorages.ContainsKey(name)) if (_truckStorages.ContainsKey(new TrucksCollectionInfo(name, string.Empty))) _truckStorages.Remove(new TrucksCollectionInfo(name, string.Empty));
_truckStorages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
@ -82,8 +81,8 @@ namespace DumpTruck.Generics
get get
{ {
// TODO Продумать логику получения набора // TODO Продумать логику получения набора
if (_truckStorages.ContainsKey(ind)) if (_truckStorages.ContainsKey(new TrucksCollectionInfo(ind, string.Empty)))
return _truckStorages[ind]; return _truckStorages[new TrucksCollectionInfo(ind, string.Empty)];
return null; return null;
} }
} }
@ -99,14 +98,14 @@ namespace DumpTruck.Generics
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> record in _truckStorages) foreach (KeyValuePair<TrucksCollectionInfo, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> record in _truckStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawningTruck? elem in record.Value.GetTrucks) foreach (DrawningTruck? elem in record.Value.GetTrucks)
{ {
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)
{ {
@ -158,7 +157,7 @@ namespace DumpTruck.Generics
} }
} }
} }
_truckStorages.Add(record[0], collection); _truckStorages.Add(new TrucksCollectionInfo(record[0], string.Empty), collection);
} }
} }
} }

View File

@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class TrucksCollectionInfo : IEquatable<TrucksCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public TrucksCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(TrucksCollectionInfo? other)
{
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -36,7 +36,15 @@ namespace DumpTruck.Generics
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="picWidth"></param> /// <param name="picWidth"></param>
/// <param name="picHeight"></param> /// <param name="picHeight"></param>
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public TrucksGenericCollection(int picWidth, int picHeight) public TrucksGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
@ -45,6 +53,11 @@ namespace DumpTruck.Generics
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(width * height);
} }
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTrucks => _collection.GetTrucks();
/// <summary> /// <summary>
/// Перегрузка оператора сложения /// Перегрузка оператора сложения
/// </summary> /// </summary>
@ -57,7 +70,7 @@ namespace DumpTruck.Generics
{ {
return -1; return -1;
} }
return collect._collection.Insert(obj); return collect._collection.Insert(obj,new DrawiningCarEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -132,10 +145,5 @@ namespace DumpTruck.Generics
truck.DrawTransport(g); truck.DrawTransport(g);
} }
} }
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTrucks => _collection.GetTrucks();
} }
} }