Готовая 8

This commit is contained in:
Софья Якобчук 2023-12-27 21:57:53 +04:00
parent 75133affd5
commit ea87423301
10 changed files with 264 additions and 49 deletions

View File

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.Entities;
namespace Sailboat.Generics
{
internal class BoatCompareByColor : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityBoat is EntitySailboat xEntitySailboat && y.EntityBoat is EntitySailboat yEntitySailboat)
{
var dumpBoxColorCompare = xEntitySailboat.BodyColor.Name.CompareTo(yEntitySailboat.BodyColor.Name);
if (dumpBoxColorCompare != 0)
{
return dumpBoxColorCompare;
}
var tentColorCompare = xEntitySailboat.AdditionalColor.Name.CompareTo(yEntitySailboat.AdditionalColor.Name);
if (tentColorCompare != 0)
{
return tentColorCompare;
}
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}
}

View File

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

View File

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

View File

@ -38,6 +38,7 @@ namespace Sailboat.Generics
/// </summary> /// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetBoats => _collection.GetBoats(); public IEnumerable<T?> GetBoats => _collection.GetBoats();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -63,7 +64,7 @@ namespace Sailboat.Generics
{ {
return false; return false;
} }
return (bool)collect?._collection.Insert(obj); return (bool)collect?._collection.Insert(obj, new DrawingBoatEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -140,4 +141,4 @@ namespace Sailboat.Generics
} }
} }
} }
} }

View File

@ -15,11 +15,11 @@ namespace Sailboat.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages; readonly Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _boatStorages.Keys.ToList(); public List<BoatsCollectionInfo> Keys => _boatStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -47,7 +47,7 @@ namespace Sailboat.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public BoatsGenericStorage(int pictureWidth, int pictureHeight) public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{ {
_boatStorages = new Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>(); _boatStorages = new Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -57,11 +57,7 @@ namespace Sailboat.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
if (_boatStorages.ContainsKey(name)) _boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight));
{
return;
}
_boatStorages[name] = new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight);
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -69,11 +65,9 @@ namespace Sailboat.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_boatStorages.ContainsKey(name)) if (!_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty)))
{
return; return;
} _boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty));
_boatStorages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
@ -84,10 +78,9 @@ namespace Sailboat.Generics
{ {
get get
{ {
if (_boatStorages.ContainsKey(ind)) BoatsCollectionInfo indObj = new BoatsCollectionInfo(ind, string.Empty);
{ if (_boatStorages.ContainsKey(indObj))
return _boatStorages[ind]; return _boatStorages[indObj];
}
return null; return null;
} }
} }
@ -105,15 +98,14 @@ namespace Sailboat.Generics
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages) foreach (KeyValuePair<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats) foreach (DrawingBoat? elem in record.Value.GetBoats)
{ {
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)
{ {
@ -180,7 +172,7 @@ namespace Sailboat.Generics
} }
} }
} }
_boatStorages.Add(name, collection); _boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), collection);
} }
} }
} }

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.Entities;
namespace Sailboat.Generics
{
internal class DrawingBoatEqutables : IEqualityComparer<DrawingBoat?>
{
public bool Equals(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBoat.Speed != y.EntityBoat.Speed)
{
return false;
}
if (x.EntityBoat.Weight != y.EntityBoat.Weight)
{
return false;
}
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor)
{
return false;
}
if (x is DrawingSailboat && y is DrawingSailboat)
{
EntitySailboat EntityX = (EntitySailboat)x.EntityBoat;
EntitySailboat EntityY = (EntitySailboat)y.EntityBoat;
if (EntityX.Sail != EntityY.Sail)
return false;
if (EntityX.Hull != EntityY.Hull)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBoat obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -25,7 +25,8 @@ namespace Sailboat.DrawingObjects
/// <param name="sail">Признак наличия паруса</param> /// <param name="sail">Признак наличия паруса</param>
/// <param name="width">Ширина картинки</param> /// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param> /// <param name="height">Высота картинки</param>
public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) : base(speed, weight, bodyColor, width, height, 200, 160) public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) :
base(speed, weight, bodyColor, width, height, 200, 160)
{ {
if (EntityBoat != null) if (EntityBoat != null)
{ {

View File

@ -34,6 +34,8 @@
buttonRefreshCollection = new Button(); buttonRefreshCollection = new Button();
maskedTextBoxNumber = new MaskedTextBox(); maskedTextBoxNumber = new MaskedTextBox();
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxCollection = new GroupBox(); groupBoxCollection = new GroupBox();
textBoxStorageName = new TextBox(); textBoxStorageName = new TextBox();
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
@ -99,6 +101,8 @@
// //
// groupBoxTools // groupBoxTools
// //
groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(groupBoxCollection); groupBoxTools.Controls.Add(groupBoxCollection);
groupBoxTools.Controls.Add(buttonAddBoat); groupBoxTools.Controls.Add(buttonAddBoat);
groupBoxTools.Controls.Add(buttonRefreshCollection); groupBoxTools.Controls.Add(buttonRefreshCollection);
@ -112,15 +116,35 @@
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// buttonSortByColor
//
buttonSortByColor.Location = new Point(12, 367);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(184, 29);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(12, 335);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(184, 29);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// groupBoxCollection // groupBoxCollection
// //
groupBoxCollection.Controls.Add(textBoxStorageName); groupBoxCollection.Controls.Add(textBoxStorageName);
groupBoxCollection.Controls.Add(listBoxStorages); groupBoxCollection.Controls.Add(listBoxStorages);
groupBoxCollection.Controls.Add(buttonDelObject); groupBoxCollection.Controls.Add(buttonDelObject);
groupBoxCollection.Controls.Add(buttonAddObject); groupBoxCollection.Controls.Add(buttonAddObject);
groupBoxCollection.Location = new Point(6, 75); groupBoxCollection.Location = new Point(6, 54);
groupBoxCollection.Name = "groupBoxCollection"; groupBoxCollection.Name = "groupBoxCollection";
groupBoxCollection.Size = new Size(196, 299); groupBoxCollection.Size = new Size(196, 275);
groupBoxCollection.TabIndex = 5; groupBoxCollection.TabIndex = 5;
groupBoxCollection.TabStop = false; groupBoxCollection.TabStop = false;
groupBoxCollection.Text = "Наборы"; groupBoxCollection.Text = "Наборы";
@ -144,9 +168,9 @@
// //
// buttonDelObject // buttonDelObject
// //
buttonDelObject.Location = new Point(5, 256); buttonDelObject.Location = new Point(6, 231);
buttonDelObject.Name = "buttonDelObject"; buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(191, 37); buttonDelObject.Size = new Size(184, 37);
buttonDelObject.TabIndex = 1; buttonDelObject.TabIndex = 1;
buttonDelObject.Text = "Удалить набор"; buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true; buttonDelObject.UseVisualStyleBackColor = true;
@ -182,14 +206,14 @@
// SaveToolStripMenuItem // SaveToolStripMenuItem
// //
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(224, 26); SaveToolStripMenuItem.Size = new Size(177, 26);
SaveToolStripMenuItem.Text = "Сохранение"; SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// LoadToolStripMenuItem // LoadToolStripMenuItem
// //
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(224, 26); LoadToolStripMenuItem.Size = new Size(177, 26);
LoadToolStripMenuItem.Text = "Загрузка"; LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
@ -241,5 +265,7 @@
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -33,7 +33,7 @@ namespace Sailboat
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))
@ -90,6 +90,10 @@ namespace Sailboat
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
} }
private void buttonRemoveBoat_Click(object sender, EventArgs e) private void buttonRemoveBoat_Click(object sender, EventArgs e)
@ -219,5 +223,25 @@ namespace Sailboat
} }
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType());
private void CompareBoats(IComparer<DrawingBoat?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBoats();
}
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor());
} }
} }

View File

@ -1,10 +1,10 @@
using System; using System;
using Sailboat.Exceptions;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms;
using Sailboat.Exceptions;
namespace Sailboat.Generics namespace Sailboat.Generics
{ {
@ -22,6 +22,7 @@ namespace Sailboat.Generics
/// Максимальное количество объектов в списке /// Максимальное количество объектов в списке
/// </summary> /// </summary>
private readonly int _maxCount; private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -36,14 +37,9 @@ namespace Sailboat.Generics
/// </summary> /// </summary>
/// <param name="boat">Добавляемая лодка</param> /// <param name="boat">Добавляемая лодка</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T boat) public bool Insert(T boat, IEqualityComparer<T?>? equal = null)
{ {
if (_places.Count == _maxCount) return Insert(boat, 0, equal);
{
throw new StorageOverflowException(_maxCount);
}
Insert(boat, 0);
return true;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -51,15 +47,17 @@ namespace Sailboat.Generics
/// <param name="boat">Добавляемая лодка</param> /// <param name="boat">Добавляемая лодка</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T boat, int position) public bool Insert(T boat, int position, IEqualityComparer<T?>? equal = null)
{ {
if (_places.Count == _maxCount) if (position < 0 || position >= _maxCount)
throw new BoatNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
{ if (equal != null && _places.Contains(boat, equal))
return false; throw new ArgumentException("Данный объект уже есть в коллекции");
} _places.Insert(0, boat);
_places.Insert(position, boat);
return true; return true;
} }
/// <summary> /// <summary>
@ -69,10 +67,9 @@ namespace Sailboat.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position > _maxCount || position >= Count)
{
throw new BoatNotFoundException(position); throw new BoatNotFoundException(position);
}
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }