Уже чтото

This commit is contained in:
Kirill 2024-02-12 22:41:27 +04:00
parent 6747efcf15
commit 52f3762b15
8 changed files with 276 additions and 52 deletions

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
using ProjectTractor.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectTractor.Generics
{
internal class DrawningTractorEqutables : IEqualityComparer<DrawningTractor?>
{
public bool Equals(DrawningTractor? x, DrawningTractor? y)
{
if (x == null || x.EntityTractor == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTractor == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTractor.Speed != y.EntityTractor.Speed)
{
return false;
}
if (x.EntityTractor.Weight != y.EntityTractor.Weight)
{
return false;
}
if (x.EntityTractor.BodyColor != y.EntityTractor.BodyColor)
{
return false;
}
if (x is DrawningBulldoser && y is DrawningBulldoser)
{
EntityBulldoser EntityX = (EntityBulldoser)x.EntityTractor;
EntityBulldoser EntityY = (EntityBulldoser)y.EntityTractor;
if (EntityX.Blade != EntityY.Blade)
return false;
if (EntityX.WheelsOrnament != EntityY.WheelsOrnament)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTractor obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -275,6 +275,8 @@ namespace ProjectTractor
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBox = new System.Windows.Forms.GroupBox();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.ButtonDelObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
@ -306,6 +308,8 @@ namespace ProjectTractor
//
// groupBox
//
this.groupBox.Controls.Add(this.buttonSortByColor);
this.groupBox.Controls.Add(this.buttonSortByType);
this.groupBox.Controls.Add(this.groupBox1);
this.groupBox.Controls.Add(this.ButtonRefreshCollection);
this.groupBox.Controls.Add(this.ButtonRemoveTractor);
@ -319,6 +323,26 @@ namespace ProjectTractor
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(28, 321);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(203, 34);
this.buttonSortByColor.TabIndex = 12;
this.buttonSortByColor.Text = "Сортировка по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(28, 279);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(203, 34);
this.buttonSortByType.TabIndex = 11;
this.buttonSortByType.Text = "Сортировка по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.ButtonDelObject);
@ -327,14 +351,14 @@ namespace ProjectTractor
this.groupBox1.Controls.Add(this.textBoxStorageName);
this.groupBox1.Location = new System.Drawing.Point(16, 54);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(224, 279);
this.groupBox1.Size = new System.Drawing.Size(224, 229);
this.groupBox1.TabIndex = 9;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Наборы";
//
// ButtonDelObject
//
this.ButtonDelObject.Location = new System.Drawing.Point(12, 227);
this.ButtonDelObject.Location = new System.Drawing.Point(12, 184);
this.ButtonDelObject.Name = "ButtonDelObject";
this.ButtonDelObject.Size = new System.Drawing.Size(203, 35);
this.ButtonDelObject.TabIndex = 3;
@ -346,7 +370,7 @@ namespace ProjectTractor
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 20;
this.listBoxStorages.Location = new System.Drawing.Point(12, 116);
this.listBoxStorages.Location = new System.Drawing.Point(12, 94);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(203, 84);
this.listBoxStorages.TabIndex = 2;
@ -371,7 +395,7 @@ namespace ProjectTractor
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(28, 463);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(28, 473);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(203, 35);
this.ButtonRefreshCollection.TabIndex = 8;
@ -381,7 +405,7 @@ namespace ProjectTractor
//
// ButtonRemoveTractor
//
this.ButtonRemoveTractor.Location = new System.Drawing.Point(28, 410);
this.ButtonRemoveTractor.Location = new System.Drawing.Point(28, 434);
this.ButtonRemoveTractor.Name = "ButtonRemoveTractor";
this.ButtonRemoveTractor.Size = new System.Drawing.Size(203, 33);
this.ButtonRemoveTractor.TabIndex = 7;
@ -391,7 +415,7 @@ namespace ProjectTractor
//
// ButtonAddTractor
//
this.ButtonAddTractor.Location = new System.Drawing.Point(28, 337);
this.ButtonAddTractor.Location = new System.Drawing.Point(28, 361);
this.ButtonAddTractor.Name = "ButtonAddTractor";
this.ButtonAddTractor.Size = new System.Drawing.Size(203, 34);
this.ButtonAddTractor.TabIndex = 6;
@ -401,7 +425,7 @@ namespace ProjectTractor
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 377);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 401);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(203, 27);
this.maskedTextBoxNumber.TabIndex = 5;
@ -477,6 +501,43 @@ namespace ProjectTractor
private ToolStripMenuItem toolStripMenuItemload;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
private PictureBox pictureBoxCollection;
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareTractors(IComparer<DrawningTractor?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTractors();
}
}
}

View File

@ -33,16 +33,20 @@ namespace ProjectTractor.Generics
_places = new List<T?>(count);
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="tractor">Добавляемый трактор</param>
/// <returns></returns>
public bool Insert(T tractor)
public void Insert(T tractor, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(tractor, 0);
return true;
Insert(tractor, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@ -50,12 +54,17 @@ namespace ProjectTractor.Generics
/// <param name="tractor">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public void Insert(T tractor, int position)
public void Insert(T tractor, int position, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
throw new Exception("Неверная позиция для вставки");
if (equal != null)
{
if (_places.Contains(tractor, equal))
throw new ArgumentException(nameof(tractor));
}
_places.Insert(position, tractor);
}
/// <summary>

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
namespace ProjectTractor.Generics
{
internal class TractorCompareByColor : IComparer<DrawningTractor?>
{
public int Compare(DrawningTractor? x, DrawningTractor? y)
{
if (x == null || x.EntityTractor == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityTractor == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityTractor.BodyColor.Name != y.EntityTractor.BodyColor.Name)
{
return x.EntityTractor.BodyColor.Name.CompareTo(y.EntityTractor.BodyColor.Name);
}
var speedCompare = x.EntityTractor.Speed.CompareTo(y.EntityTractor.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityTractor.Weight.CompareTo(y.EntityTractor.Weight);
}
}
}

View File

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

View File

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

View File

@ -65,11 +65,10 @@ namespace ProjectTractor.Generics
public static bool operator +(TractorsGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
if (obj == null || collect == null)
return false;
}
return collect?._collection.Insert(obj) ?? false;
collect?._collection.Insert(obj, new DrawningTractorEqutables());
return true;
}
/// <summary>
/// Перегрузка оператора вычитания
@ -151,6 +150,13 @@ namespace ProjectTractor.Generics
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) =>
_collection.SortSet(comparer);
}
}

View File

@ -18,11 +18,11 @@ namespace ProjectTractor
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>> _tractorStorages;
readonly Dictionary<TractorsCollectionInfo, TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>> _tractorStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _tractorStorages.Keys.ToList();
public List<TractorsCollectionInfo> Keys => _tractorStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -50,7 +50,7 @@ namespace ProjectTractor
/// <param name="pictureHeight"></param>
public TractorsGenericStorage(int pictureWidth, int pictureHeight)
{
_tractorStorages = new Dictionary<string,
_tractorStorages = new Dictionary<TractorsCollectionInfo,
TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
@ -61,19 +61,8 @@ namespace ProjectTractor
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
try
{
if (_tractorStorages.ContainsKey(name))
throw new CollectionCreationErrorException(name);
_tractorStorages.Add(name,
new TractorsGenericCollection<DrawningTractor,
DrawningObjectTractor>(_pictureWidth, _pictureHeight));
}
catch
{
throw new CollectionCreationErrorException(name);
}
_tractorStorages.Add(new TractorsCollectionInfo(name, string.Empty), new TractorsGenericCollection<DrawningTractor,
DrawningObjectTractor>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
@ -81,9 +70,9 @@ namespace ProjectTractor
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_tractorStorages.ContainsKey(name))
if (!_tractorStorages.ContainsKey(new TractorsCollectionInfo(name, string.Empty)))
return;
_tractorStorages.Remove(name);
_tractorStorages.Remove(new TractorsCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@ -95,8 +84,9 @@ namespace ProjectTractor
{
get
{
if (_tractorStorages.ContainsKey(ind))
return _tractorStorages[ind];
TractorsCollectionInfo indObj = new TractorsCollectionInfo(ind, string.Empty);
if (_tractorStorages.ContainsKey(indObj))
return _tractorStorages[indObj];
return null;
}
}
@ -106,14 +96,14 @@ namespace ProjectTractor
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
foreach (KeyValuePair<TractorsCollectionInfo,
TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>> record in _tractorStorages)
{
StringBuilder records = new();
@ -121,40 +111,40 @@ namespace ProjectTractor
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
throw new IOException("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter streamWriter = new(filename))
{
streamWriter.WriteLine($"TractorStorage{Environment.NewLine}{data}");
streamWriter.WriteLine($"TractorStorages{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
throw new IOException("Файл не найден");
}
using (StreamReader streamReader = new(filename))
{
string str = streamReader.ReadLine();
string[] strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
var strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strings == null || strings.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strings[0].StartsWith("TractorStorage"))
if (!strings[0].StartsWith("BusStorages"))
{
//если нет такой записи, то это не те данные
throw new IOException("Неверный формат данных");
}
_tractorStorages.Clear();
@ -170,20 +160,19 @@ namespace ProjectTractor
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningTractor? tractor = elem?.CreateDrawningTractor(_separatorForObject, _pictureWidth, _pictureHeight);
if (tractor != null)
DrawningTractor? bus = elem?.CreateDrawningTractor(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (!(collection + tractor))
if (!(collection + bus))
{
throw new ArgumentNullException("Ошибка добавления в коллекцию");
throw new IOException("Ошибка добавления в коллекцию");
}
}
}
_tractorStorages.Add(record[0], collection);
_tractorStorages.Add(new TractorsCollectionInfo(record[0], string.Empty), collection);
str = streamReader.ReadLine();
} while (str != null);
}
return true;
}
}
}