This commit is contained in:
Dasha 2023-12-30 13:14:20 +04:00
parent 3e75f73a19
commit b17f2d743d
9 changed files with 260 additions and 28 deletions

View File

@ -45,8 +45,10 @@
FileToolStripMenuItem = new ToolStripMenuItem(); FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem(); SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog(); saveFileDialog = new SaveFileDialog();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
toolsPanel.SuspendLayout(); toolsPanel.SuspendLayout();
panelSets.SuspendLayout(); panelSets.SuspendLayout();
@ -63,6 +65,8 @@
// //
// toolsPanel // toolsPanel
// //
toolsPanel.Controls.Add(ButtonSortByType);
toolsPanel.Controls.Add(ButtonSortByColor);
toolsPanel.Controls.Add(LabelSets); toolsPanel.Controls.Add(LabelSets);
toolsPanel.Controls.Add(panelSets); toolsPanel.Controls.Add(panelSets);
toolsPanel.Controls.Add(LabelTools); toolsPanel.Controls.Add(LabelTools);
@ -71,7 +75,7 @@
toolsPanel.Controls.Add(maskedTextBoxNumber); toolsPanel.Controls.Add(maskedTextBoxNumber);
toolsPanel.Controls.Add(ButtonAddShip); toolsPanel.Controls.Add(ButtonAddShip);
toolsPanel.Location = new Point(660, 12); toolsPanel.Location = new Point(660, 12);
toolsPanel.Name = "toolsLabel"; toolsPanel.Name = "toolsPanel";
toolsPanel.Size = new Size(230, 495); toolsPanel.Size = new Size(230, 495);
toolsPanel.TabIndex = 0; toolsPanel.TabIndex = 0;
// //
@ -143,7 +147,7 @@
// //
// ButtonRefreshCollection // ButtonRefreshCollection
// //
ButtonRefreshCollection.Location = new Point(45, 432); ButtonRefreshCollection.Location = new Point(45, 453);
ButtonRefreshCollection.Name = "ButtonRefreshCollection"; ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(142, 37); ButtonRefreshCollection.Size = new Size(142, 37);
ButtonRefreshCollection.TabIndex = 2; ButtonRefreshCollection.TabIndex = 2;
@ -153,7 +157,7 @@
// //
// ButtonDeleteShip // ButtonDeleteShip
// //
ButtonDeleteShip.Location = new Point(45, 369); ButtonDeleteShip.Location = new Point(45, 410);
ButtonDeleteShip.Name = "ButtonDeleteShip"; ButtonDeleteShip.Name = "ButtonDeleteShip";
ButtonDeleteShip.Size = new Size(142, 37); ButtonDeleteShip.Size = new Size(142, 37);
ButtonDeleteShip.TabIndex = 2; ButtonDeleteShip.TabIndex = 2;
@ -163,14 +167,14 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(68, 340); maskedTextBoxNumber.Location = new Point(68, 381);
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(100, 23); maskedTextBoxNumber.Size = new Size(100, 23);
maskedTextBoxNumber.TabIndex = 2; maskedTextBoxNumber.TabIndex = 2;
// //
// ButtonAddShip // ButtonAddShip
// //
ButtonAddShip.Location = new Point(45, 274); ButtonAddShip.Location = new Point(45, 339);
ButtonAddShip.Name = "ButtonAddShip"; ButtonAddShip.Name = "ButtonAddShip";
ButtonAddShip.Size = new Size(142, 36); ButtonAddShip.Size = new Size(142, 36);
ButtonAddShip.TabIndex = 2; ButtonAddShip.TabIndex = 2;
@ -218,6 +222,26 @@
// //
saveFileDialog.Filter = "txt file | *.txt"; saveFileDialog.Filter = "txt file | *.txt";
// //
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(45, 306);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(142, 27);
ButtonSortByColor.TabIndex = 4;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(45, 273);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(142, 27);
ButtonSortByType.TabIndex = 5;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -266,5 +290,7 @@
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button ButtonSortByType;
private Button ButtonSortByColor;
} }
} }

View File

@ -46,7 +46,7 @@ namespace WarmlyShip
ListBoxObjects.Items.Clear(); ListBoxObjects.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
ListBoxObjects.Items.Add(_storage.Keys[i]); ListBoxObjects.Items.Add(_storage.Keys[i].Name);
} }
if (ListBoxObjects.Items.Count > 0 && (index == -1 || index >= ListBoxObjects.Items.Count)) if (ListBoxObjects.Items.Count > 0 && (index == -1 || index >= ListBoxObjects.Items.Count))
@ -137,10 +137,10 @@ namespace WarmlyShip
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
Log.Information($"Добавлен объект в коллекцию {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}"); Log.Information($"Добавлен объект в коллекцию {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
} }
catch (StorageOverflowException ex) catch (ArgumentException ex)
{ {
Log.Warning($"Коллекция {ListBoxObjects.SelectedItem.ToString() ?? string.Empty} переполнена"); Log.Warning($"Добавляемый объект уже существует в коллекции {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message); MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
} }
}); });
form.AddEvent(shipDelegate); form.AddEvent(shipDelegate);
@ -258,5 +258,22 @@ namespace WarmlyShip
} }
} }
} }
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByColor());
private void CompareShips(IComparer<DrawningShip?> comparer)
{
if (ListBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[ListBoxObjects.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowShips();
}
} }
} }

View File

@ -0,0 +1,66 @@
using WarmlyShip.DrawningObjects;
using WarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
internal class DrawiningShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityShip == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is DrawningWarmlyShip && y is DrawningWarmlyShip)
{
EntityWarmlyShip EntityX = (EntityWarmlyShip)x.EntityShip;
EntityWarmlyShip EntityY = (EntityWarmlyShip)y.EntityShip;
if (EntityX.Pipe != EntityY.Pipe)
{
return false;
}
if (EntityX.FuelCompartment != EntityY.FuelCompartment)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -39,19 +39,24 @@ namespace WarmlyShip.Generics
_places = new List<T?>(count); _places = new List<T?>(count);
} }
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
/// </summary> /// </summary>
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <returns></returns> /// <returns></returns>
public void Insert(T ship) public void Insert(T ship, IEqualityComparer<T>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
{ {
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
} }
Insert(ship, 0, equal);
Insert(ship, 0);
} }
/// <summary> /// <summary>
@ -60,7 +65,7 @@ namespace WarmlyShip.Generics
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public void Insert(T ship, int position) public void Insert(T ship, int position, IEqualityComparer<T>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
{ {
@ -70,7 +75,13 @@ namespace WarmlyShip.Generics
{ {
throw new Exception("Неверная позиция для вставки"); throw new Exception("Неверная позиция для вставки");
} }
if (equal != null)
{
if (_places.Contains(ship, equal))
{
throw new ArgumentException(nameof(ship));
}
}
_places.Insert(position, ship); _places.Insert(position, ship);
} }

View File

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

View File

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

View File

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

View File

@ -23,6 +23,12 @@ namespace WarmlyShip.Generics
/// </summary> /// </summary>
public IEnumerable<T?> GetShips => _collection.GetShips(); public IEnumerable<T?> GetShips => _collection.GetShips();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary> /// <summary>
/// Ширина окна прорисовки /// Ширина окна прорисовки
/// </summary> /// </summary>
@ -74,7 +80,7 @@ namespace WarmlyShip.Generics
{ {
return false; return false;
} }
collect?._collection.Insert(obj); collect?._collection.Insert(obj, new DrawiningShipEqutables());
return true; return true;
} }

View File

@ -16,13 +16,13 @@ namespace WarmlyShip.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawningShip, readonly Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip,
DrawningObjectShip>> _shipStorages; DrawningObjectShip>> _shipStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _shipStorages.Keys.ToList(); public List<ShipsCollectionInfo> Keys => _shipStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
@ -54,7 +54,7 @@ namespace WarmlyShip.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public ShipsGenericStorage(int pictureWidth, int pictureHeight) public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{ {
_shipStorages = new Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>(); _shipStorages = new Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -71,14 +71,14 @@ namespace WarmlyShip.Generics
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages) foreach (KeyValuePair<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawningShip? elem in record.Value.GetShips) foreach (DrawningShip? elem in record.Value.GetShips)
{ {
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)
@ -143,7 +143,7 @@ namespace WarmlyShip.Generics
} }
} }
} }
_shipStorages.Add(record[0], collection); _shipStorages.Add(new ShipsCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine(); str = sr.ReadLine();
} while (str != null); } while (str != null);
@ -156,7 +156,7 @@ namespace WarmlyShip.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
_shipStorages.Add(name, new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight)); _shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight));
} }
/// <summary> /// <summary>
@ -165,12 +165,12 @@ namespace WarmlyShip.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_shipStorages.ContainsKey(name)) if (!_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
{ {
return; return;
} }
_shipStorages.Remove(name); _shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
} }
/// <summary> /// <summary>
@ -182,9 +182,10 @@ namespace WarmlyShip.Generics
{ {
get get
{ {
if (_shipStorages.ContainsKey(ind)) ShipsCollectionInfo indObj = new ShipsCollectionInfo(ind, string.Empty);
if (_shipStorages.ContainsKey(indObj))
{ {
return _shipStorages[ind]; return _shipStorages[indObj];
} }
return null; return null;
} }