This commit is contained in:
AnnaLioness 2023-12-16 18:22:14 +04:00
parent 3eceaaf9b2
commit 69bc174b89
10 changed files with 275 additions and 28 deletions

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using Lab1ContainersShip.DrawingObjects;
using Lab1ContainersShip.Entities;
namespace Lab1ContainersShip
{
public class DrawiningShipEqutables : IEqualityComparer<DrawingShip?>
{
public bool Equals(DrawingShip? x, DrawingShip? 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 DrawingContainerShip && y is DrawingContainerShip)
{
EntityContainerShip _shipX = (EntityContainerShip)x.EntityShip;
EntityContainerShip _shipY = (EntityContainerShip)y.EntityShip;
if (_shipX.Crane != _shipY.Crane)
{
return false;
}
if (_shipX.Conteiners != _shipY.Conteiners)
{
return false;
}
if (_shipX.AdditionalColor != _shipY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingShip obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -29,6 +29,8 @@
private void InitializeComponent() private void InitializeComponent()
{ {
this.panel1 = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.textBoxStorageName = new System.Windows.Forms.TextBox(); this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.ButtonAddObject = new System.Windows.Forms.Button(); this.ButtonAddObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox(); this.listBoxStorages = new System.Windows.Forms.ListBox();
@ -51,6 +53,8 @@
// //
// panel1 // panel1
// //
this.panel1.Controls.Add(this.ButtonSortByColor);
this.panel1.Controls.Add(this.ButtonSortByType);
this.panel1.Controls.Add(this.textBoxStorageName); this.panel1.Controls.Add(this.textBoxStorageName);
this.panel1.Controls.Add(this.ButtonAddObject); this.panel1.Controls.Add(this.ButtonAddObject);
this.panel1.Controls.Add(this.listBoxStorages); this.panel1.Controls.Add(this.listBoxStorages);
@ -66,6 +70,26 @@
this.panel1.Size = new System.Drawing.Size(183, 518); this.panel1.Size = new System.Drawing.Size(183, 518);
this.panel1.TabIndex = 1; this.panel1.TabIndex = 1;
// //
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(21, 286);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(139, 23);
this.ButtonSortByColor.TabIndex = 7;
this.ButtonSortByColor.Text = "сортировка по цвету";
this.ButtonSortByColor.UseVisualStyleBackColor = true;
this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// ButtonSortByType
//
this.ButtonSortByType.Location = new System.Drawing.Point(21, 257);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(139, 23);
this.ButtonSortByType.TabIndex = 2;
this.ButtonSortByType.Text = "сортировка по типу";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// textBoxStorageName // textBoxStorageName
// //
this.textBoxStorageName.Location = new System.Drawing.Point(21, 29); this.textBoxStorageName.Location = new System.Drawing.Point(21, 29);
@ -236,5 +260,7 @@
private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.Button ButtonSortByType;
private System.Windows.Forms.Button ButtonSortByColor;
} }
} }

View File

@ -35,7 +35,7 @@ namespace Lab1ContainersShip
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 >= listBoxStorages.Items.Count)) if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{ {
@ -98,20 +98,26 @@ namespace Lab1ContainersShip
_logger.LogWarning("Добавление пустого объекта"); _logger.LogWarning("Добавление пустого объекта");
return; return;
} }
try try
{ {
_ = obj + drawningShip; if (_ = obj + drawningShip) {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}"); _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
} }
catch (ApplicationException ex) catch (ApplicationException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
@ -224,5 +230,21 @@ namespace Lab1ContainersShip
} }
ReloadObjects(); ReloadObjects();
} }
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<DrawingShip?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowShips();
}
} }
} }

View File

@ -66,4 +66,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>430, 31</value> <value>430, 31</value>
</metadata> </metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>

View File

@ -34,7 +34,7 @@ namespace Lab1ContainersShip
/// </summary> /// </summary>
/// <param name="car">Добавляемый автомобиль</param> /// <param name="car">Добавляемый автомобиль</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T ship) /*public int Insert(T ship)
{ {
// TODO вставка в начало набора // TODO вставка в начало набора
if(_places.Count >= _maxCount) if(_places.Count >= _maxCount)
@ -48,14 +48,20 @@ namespace Lab1ContainersShip
_places.Insert(0, ship); _places.Insert(0, ship);
return 0; return 0;
} }
}*/
public bool Insert(T ship, IEqualityComparer<T?>? equal = null)
{
return Insert(ship, 0, equal);
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
/// </summary> /// </summary>
/// <param name="car">Добавляемый автомобиль</param> /// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T ship, int position) public bool Insert(T ship, int position, IEqualityComparer<T?>? equal = null)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, // TODO проверка, что элемент массива по этой позиции пустой,
@ -73,14 +79,19 @@ namespace Lab1ContainersShip
{ {
throw new ShipNotFoundException(position); throw new ShipNotFoundException(position);
} }
if(position == _places.Count) /*if(position == _places.Count)
{ {
_places.Add(ship); _places.Add(ship);
} }
else else
{ {
_places.Insert(position, ship); _places.Insert(position, ship);
}*/
if (equal != null && _places.Contains(ship, equal))
{
throw new ApplicationException("уже есть");
} }
_places.Insert(position, ship);
return true; return true;
} }
/// <summary> /// <summary>
@ -159,7 +170,6 @@ namespace Lab1ContainersShip
} }
} }
} }
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
} }
} }

View File

@ -0,0 +1,56 @@
using Lab1ContainersShip.DrawingObjects;
using Lab1ContainersShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab1ContainersShip
{
internal class ShipCompareByColor : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? 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);
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is DrawingShip)
{
return -1;
}
else
{
return 1;
}
}
if (x.GetType().Name == y.GetType().Name && x is DrawingContainerShip)
{
EntityContainerShip _X = (EntityContainerShip)x.EntityShip;
EntityContainerShip _Y = (EntityContainerShip)y.EntityShip;
if (_X.AdditionalColor.Name != _Y.AdditionalColor.Name)
{
return _X.AdditionalColor.Name.CompareTo(_Y.AdditionalColor.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,34 @@
using Lab1ContainersShip.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab1ContainersShip
{
internal class ShipCompareByType : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? 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

@ -53,15 +53,16 @@ namespace Lab1ContainersShip
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
public static int operator +(ShipGenericCollection<T, U> collect, T public static bool operator +(ShipGenericCollection<T, U> collect, T
obj) obj)
{ {
if (obj == null) if (obj == null)
{ {
return -1; return false;
} }
return collect?._collection.Insert(obj) ?? -1; //return collect?._collection.Insert(obj) ?? -1;
return (bool)collect?._collection.Insert(obj, new DrawiningShipEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -144,6 +145,8 @@ namespace Lab1ContainersShip
// TODO прорисовка объекта // TODO прорисовка объекта
} }
} }
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
} }
} }

View File

@ -14,7 +14,7 @@ namespace Lab1ContainersShip
{ {
internal class ShipGenericStorage internal class ShipGenericStorage
{ {
readonly Dictionary<string, ShipGenericCollection<DrawingShip, readonly Dictionary<ShipsCollectionInfo, ShipGenericCollection<DrawingShip,
DrawningObjectShip>> _shipStorages; DrawningObjectShip>> _shipStorages;
/// <summary> /// <summary>
/// Разделитель для записи ключа и значения элемента словаря /// Разделитель для записи ключа и значения элемента словаря
@ -31,7 +31,7 @@ DrawningObjectShip>> _shipStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _shipStorages.Keys.ToList(); public List<ShipsCollectionInfo> Keys => _shipStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -47,7 +47,7 @@ DrawningObjectShip>> _shipStorages;
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public ShipGenericStorage(int pictureWidth, int pictureHeight) public ShipGenericStorage(int pictureWidth, int pictureHeight)
{ {
_shipStorages = new Dictionary<string, ShipGenericCollection<DrawingShip, _shipStorages = new Dictionary<ShipsCollectionInfo, ShipGenericCollection<DrawingShip,
DrawningObjectShip>>(); DrawningObjectShip>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
@ -59,13 +59,13 @@ DrawningObjectShip>>();
public void AddSet(string name) public void AddSet(string name)
{ {
// TODO Прописать логику для добавления // TODO Прописать логику для добавления
if (_shipStorages.ContainsKey(name)) if (_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
{ {
return; return;
} }
else else
{ {
_shipStorages[name] = new ShipGenericCollection<DrawingShip, DrawningObjectShip>(_pictureWidth, _pictureHeight); _shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), new ShipGenericCollection<DrawingShip, DrawningObjectShip>(_pictureWidth, _pictureHeight));
} }
} }
/// <summary> /// <summary>
@ -74,13 +74,13 @@ DrawningObjectShip>>();
/// <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;
} }
else else
{ {
_shipStorages.Remove(name); _shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
} }
// TODO Прописать логику для удаления // TODO Прописать логику для удаления
} }
@ -94,10 +94,11 @@ DrawningObjectShip>>();
{ {
get get
{ {
ShipsCollectionInfo indOb = new ShipsCollectionInfo(ind, string.Empty);
// TODO Продумать логику получения набора // TODO Продумать логику получения набора
if (_shipStorages.ContainsKey(ind)) if (_shipStorages.ContainsKey(indOb))
{ {
return _shipStorages[ind]; return _shipStorages[indOb];
} }
else else
{ {
@ -118,7 +119,7 @@ public void SaveData(string filename)
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
foreach (KeyValuePair<string, foreach (KeyValuePair<ShipsCollectionInfo,
ShipGenericCollection<DrawingShip, DrawningObjectShip>> record in _shipStorages) ShipGenericCollection<DrawingShip, DrawningObjectShip>> record in _shipStorages)
{ {
StringBuilder records = new StringBuilder(); StringBuilder records = new StringBuilder();
@ -182,7 +183,7 @@ public void SaveData(string filename)
{ {
try try
{ {
int t = collection + ship; bool t = collection + ship;
} }
catch (ApplicationException ex) catch (ApplicationException ex)
{ {
@ -190,7 +191,7 @@ public void SaveData(string filename)
} }
} }
} }
_shipStorages.Add(record[0], collection); _shipStorages.Add(new ShipsCollectionInfo(record[0], string.Empty), collection);
} }
} }
} }

View File

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