Лаба8

This commit is contained in:
Владимир Данилов 2023-12-25 04:48:10 +04:00
parent 3795138c04
commit a491451e01
10 changed files with 269 additions and 31 deletions

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_DumpTruck.DrawningObjects;
using Project_DumpTruck.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Project_DumpTruck.Generics
{
internal class DrawningTruckEqutables: 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 EntityX = x.EntityTruck as EntityDumpTruck;
EntityDumpTruck EntityY = y.EntityTruck as EntityDumpTruck;
if (EntityX.BodyKit != EntityY.BodyKit)
return false;
if (EntityX.Tent != EntityY.Tent)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTruck obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -45,6 +45,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBox1.SuspendLayout();
groupBoxStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
@ -53,6 +55,8 @@
//
// groupBox1
//
groupBox1.Controls.Add(buttonSortByColor);
groupBox1.Controls.Add(buttonSortByType);
groupBox1.Controls.Add(groupBoxStorage);
groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonRefreshCollection);
@ -60,7 +64,7 @@
groupBox1.Controls.Add(buttonAddTruck);
groupBox1.Location = new Point(588, 27);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(200, 426);
groupBox1.Size = new Size(200, 526);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
@ -117,14 +121,14 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(52, 284);
maskedTextBoxNumber.Location = new Point(52, 384);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(100, 23);
maskedTextBoxNumber.TabIndex = 4;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(6, 387);
buttonRefreshCollection.Location = new Point(6, 487);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(188, 33);
buttonRefreshCollection.TabIndex = 3;
@ -134,7 +138,7 @@
//
// buttonRemoveTruck
//
buttonRemoveTruck.Location = new Point(6, 313);
buttonRemoveTruck.Location = new Point(6, 413);
buttonRemoveTruck.Name = "buttonRemoveTruck";
buttonRemoveTruck.Size = new Size(188, 34);
buttonRemoveTruck.TabIndex = 2;
@ -144,7 +148,7 @@
//
// buttonAddTruck
//
buttonAddTruck.Location = new Point(6, 247);
buttonAddTruck.Location = new Point(6, 347);
buttonAddTruck.Name = "buttonAddTruck";
buttonAddTruck.Size = new Size(188, 31);
buttonAddTruck.TabIndex = 1;
@ -156,7 +160,7 @@
//
pictureBoxCollection.Location = new Point(12, 27);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(570, 426);
pictureBoxCollection.Size = new Size(570, 526);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
@ -179,14 +183,14 @@
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(180, 22);
SaveToolStripMenuItem.Size = new Size(141, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(180, 22);
LoadToolStripMenuItem.Size = new Size(141, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@ -199,11 +203,31 @@
//
saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(6, 248);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(188, 31);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(6, 285);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(188, 31);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировать по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormTruckCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 468);
ClientSize = new Size(800, 565);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBox1);
Controls.Add(menuStrip1);
@ -240,5 +264,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -42,7 +42,7 @@ namespace Project_DumpTruck
listBoxStorages.Items.Clear();
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
>= listBoxStorages.Items.Count))
@ -80,7 +80,7 @@ namespace Project_DumpTruck
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Обьект добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
}
catch(StorageOverflowException ex)
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Обьект не добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
@ -126,7 +126,7 @@ namespace Project_DumpTruck
_logger.LogWarning($"Обьект не удален из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch(TruckNotFoundException ex)
catch (TruckNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Обьект не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
@ -210,7 +210,7 @@ namespace Project_DumpTruck
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}");
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show($"Не сохранено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не удалось");
@ -234,12 +234,46 @@ namespace Project_DumpTruck
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName}");
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show($"Не удалось загрузить данные: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не удалось");
}
}
}
/// <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

@ -28,6 +28,11 @@ namespace Project_DumpTruck.Generics
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
@ -41,9 +46,9 @@ namespace Project_DumpTruck.Generics
/// </summary>
/// <param name="truck">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T truck)
public int Insert(T truck, IEqualityComparer<T?>? equal = null)
{
return Insert(truck, 0);
return Insert(truck, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@ -51,7 +56,7 @@ namespace Project_DumpTruck.Generics
/// <param name="truck">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T truck, int position)
public int Insert(T truck, int position, IEqualityComparer<T?>? equal = null)
{
// Проверка позиции
if (position < 0 || position >= _maxCount)
@ -62,6 +67,8 @@ namespace Project_DumpTruck.Generics
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(truck, equal))
throw new StorageOverflowException("Обьект уже есть в коллекции");
_places.Insert(position, truck);
return position;
}
@ -125,6 +132,5 @@ namespace Project_DumpTruck.Generics
}
}
}
}
}

View File

@ -0,0 +1,45 @@
using Project_DumpTruck.DrawningObjects;
using Project_DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_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));
}
if (x.EntityTruck.BodyColor.Name != y.EntityTruck.BodyColor.Name)
{
return x.EntityTruck.BodyColor.Name.CompareTo(y.EntityTruck.BodyColor.Name);
}
if (x.GetType().Name == y.GetType().Name && x is DrawningDumpTruck)
{
EntityDumpTruck EntityX = x.EntityTruck as EntityDumpTruck;
EntityDumpTruck EntityY = y.EntityTruck as EntityDumpTruck;
if (EntityX.AdditionalColor.Name != EntityY.AdditionalColor.Name)
{
return EntityX.AdditionalColor.Name.CompareTo(EntityY.AdditionalColor.Name);
}
}
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,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck.DrawningObjects
{
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;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_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 (other == null)
return false;
return other.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -37,6 +37,11 @@ namespace Project_DumpTruck.Generics
/// </summary>
public IEnumerable<T?> GetCars => _collection.GetTrucks();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
@ -62,7 +67,7 @@ namespace Project_DumpTruck.Generics
{
return -1;
}
return collect._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawningTruckEqutables());
}
/// <summary>
/// Перегрузка оператора вычитания

View File

@ -14,11 +14,11 @@ namespace Project_DumpTruck.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> _truckStorages;
readonly Dictionary<TrucksCollectionInfo, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> _truckStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _truckStorages.Keys.ToList();
public List<TrucksCollectionInfo> Keys => _truckStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -46,7 +46,7 @@ namespace Project_DumpTruck.Generics
/// /// <param name="pictureHeight"></param>
public TrucksGenericStorage(int pictureWidth, int pictureHeight)
{
_truckStorages = new Dictionary<string, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>>();
_truckStorages = new Dictionary<TrucksCollectionInfo, TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -56,7 +56,8 @@ namespace Project_DumpTruck.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_truckStorages.Add(name, new TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight));
if (_truckStorages.ContainsKey(new TrucksCollectionInfo(name, string.Empty))) return;
_truckStorages.Add(new TrucksCollectionInfo(name, string.Empty), new TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
@ -64,8 +65,8 @@ namespace Project_DumpTruck.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_truckStorages.ContainsKey(name))
_truckStorages.Remove(name);
if (_truckStorages.ContainsKey(new TrucksCollectionInfo(name, string.Empty)))
_truckStorages.Remove(new TrucksCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@ -76,9 +77,9 @@ namespace Project_DumpTruck.Generics
{
get
{
// TODO Продумать логику получения набора
if (_truckStorages.ContainsKey(ind))
return _truckStorages[ind];
TrucksCollectionInfo indObj = new TrucksCollectionInfo(ind, string.Empty);
if (_truckStorages.ContainsKey(indObj))
return _truckStorages[indObj];
return null;
}
}
@ -95,7 +96,7 @@ namespace Project_DumpTruck.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
foreach (KeyValuePair<TrucksCollectionInfo,
TrucksGenericCollection<DrawningTruck, DrawningObjectTruck>> record in _truckStorages)
{
StringBuilder records = new();
@ -167,7 +168,7 @@ namespace Project_DumpTruck.Generics
}
}
}
_truckStorages.Add(record[0], collection);
_truckStorages.Add(new TrucksCollectionInfo(record[0], string.Empty), collection);
}
}
return true;