ISEbd-21. Gruzdev A.P. Lab work 08. #9

Closed
y3nnn wants to merge 1 commits from lab08 into lab07
10 changed files with 279 additions and 21 deletions
Showing only changes of commit 63f5950f5c - Show all commits

View File

@ -0,0 +1,65 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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 _warshipX = (EntityWarmlyShip)x.EntityShip;
EntityWarmlyShip _warshipY = (EntityWarmlyShip)y.EntityShip;
if (_warshipX.ShipPipes != _warshipY.ShipPipes)
{
return false;
}
if (_warshipX.ShipFuel != _warshipY.ShipFuel)
{
return false;
}
if (_warshipX.AdditionalColor != _warshipY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -30,6 +30,8 @@
{ {
pictureBoxCollection = new PictureBox(); pictureBoxCollection = new PictureBox();
groupBox1 = new GroupBox(); groupBox1 = new GroupBox();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
maskedTextBoxNumber = new MaskedTextBox(); maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button(); buttonRefreshCollection = new Button();
buttonRemoveShip = new Button(); buttonRemoveShip = new Button();
@ -63,6 +65,8 @@
// //
// groupBox1 // groupBox1
// //
groupBox1.Controls.Add(ButtonSortByColor);
groupBox1.Controls.Add(ButtonSortByType);
groupBox1.Controls.Add(maskedTextBoxNumber); groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonRefreshCollection); groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(buttonRemoveShip); groupBox1.Controls.Add(buttonRemoveShip);
@ -74,6 +78,26 @@
groupBox1.TabStop = false; groupBox1.TabStop = false;
groupBox1.Text = "Инструменты"; groupBox1.Text = "Инструменты";
// //
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(16, 298);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(136, 23);
ButtonSortByColor.TabIndex = 5;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(16, 269);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(136, 23);
ButtonSortByType.TabIndex = 4;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(16, 357); maskedTextBoxNumber.Location = new Point(16, 357);
@ -119,14 +143,14 @@
groupBox2.Controls.Add(textBoxStorageName); groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Location = new Point(625, 22); groupBox2.Location = new Point(625, 22);
groupBox2.Name = "groupBox2"; groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(175, 300); groupBox2.Size = new Size(175, 241);
groupBox2.TabIndex = 4; groupBox2.TabIndex = 4;
groupBox2.TabStop = false; groupBox2.TabStop = false;
groupBox2.Text = "Наборы"; groupBox2.Text = "Наборы";
// //
// buttonDelObject // buttonDelObject
// //
buttonDelObject.Location = new Point(16, 240); buttonDelObject.Location = new Point(16, 213);
buttonDelObject.Name = "buttonDelObject"; buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(136, 23); buttonDelObject.Size = new Size(136, 23);
buttonDelObject.TabIndex = 3; buttonDelObject.TabIndex = 3;
@ -171,14 +195,14 @@
// сохранениеToolStripMenuItem // сохранениеToolStripMenuItem
// //
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new Size(180, 22); сохранениеToolStripMenuItem.Size = new Size(141, 22);
сохранениеToolStripMenuItem.Text = "Сохранение"; сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// загрузкаToolStripMenuItem // загрузкаToolStripMenuItem
// //
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem"; загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new Size(180, 22); загрузкаToolStripMenuItem.Size = new Size(141, 22);
загрузкаToolStripMenuItem.Text = "Загрузка"; загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
@ -237,5 +261,7 @@
private MenuStrip menuStrip; private MenuStrip menuStrip;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
} }
} }

View File

@ -45,9 +45,9 @@ namespace ProjectWarmlyShip
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
foreach (var key in _storage.Keys) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(key); 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))
@ -146,6 +146,11 @@ namespace ProjectWarmlyShip
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
catch (ArgumentException ex)
{
_logger.LogWarning($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
}); });
form.AddEvent(ShipDelegate); form.AddEvent(ShipDelegate);
form.Show(); form.Show();
@ -267,5 +272,31 @@ namespace ProjectWarmlyShip
} }
} }
} }
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareShips(IComparer<DrawningShip?> 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

@ -41,7 +41,7 @@ namespace ProjectWarmlyShip
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger); option.AddSerilog(logger);
});<EFBFBD> });
} }
} }
} }

View File

@ -36,14 +36,15 @@ namespace ProjectWarmlyShip.Generics
_maxCount = count; _maxCount = count;
_places = new List<T?>(count); _places = new List<T?>(count);
} }
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 bool Insert(T ship) public bool Insert(T ship, IEqualityComparer<T?>? equal = null)
{ {
return Insert(ship, 0); return Insert(ship, 0, equal);
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -51,13 +52,17 @@ namespace ProjectWarmlyShip.Generics
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</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)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
throw new ShipNotFoundException(position); throw new ShipNotFoundException(position);
if (Count >= _maxCount) if (Count >= _maxCount)
throw new StorageOverflowException(Count); throw new StorageOverflowException(Count);
if (equal != null && _places.Contains(ship, equal))
{
throw new ArgumentException("Добавляемый объект уже сущесвует в коллекции");
}
_places.Insert(0, ship); _places.Insert(0, ship);
return true; return true;

View File

@ -0,0 +1,51 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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);
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
if (x.GetType().Name == y.GetType().Name && x is DrawningWarmlyShip)
{
EntityWarmlyShip _warshipX = (EntityWarmlyShip)x.EntityShip;
EntityWarmlyShip _warshipY = (EntityWarmlyShip)y.EntityShip;
if (_warshipX.AdditionalColor.Name != _warshipY.AdditionalColor.Name)
{
return _warshipX.AdditionalColor.Name.CompareTo(_warshipY.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 ProjectWarmlyShip.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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)
{
// TODO прописать логику сравнения по свойству Name
if (this.Name == other?.Name)
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -17,6 +17,7 @@ namespace ProjectWarmlyShip.Generics
where T : DrawningShip where T : DrawningShip
where U : IMoveableObject where U : IMoveableObject
{ {
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary> /// <summary>
/// Ширина окна прорисовки /// Ширина окна прорисовки
/// </summary> /// </summary>
@ -63,7 +64,7 @@ namespace ProjectWarmlyShip.Generics
{ {
return false; return false;
} }
return (bool)collect?._collection.Insert(obj); return (bool)collect?._collection.Insert(obj, new DrawiningShipEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания

View File

@ -19,11 +19,11 @@ namespace ProjectWarmlyShip
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> _shipStorages; readonly Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> _shipStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _shipStorages.Keys.ToList(); public List<ShipsCollectionInfo> Keys => _shipStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -51,7 +51,7 @@ namespace ProjectWarmlyShip
/// /// <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;
} }
@ -62,8 +62,16 @@ namespace ProjectWarmlyShip
public void AddSet(string name) public void AddSet(string name)
{ {
// TODO Прописать логику для добавления // TODO Прописать логику для добавления
if (_shipStorages.ContainsKey(name)) return; if (_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
_shipStorages[name] = new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight); {
MessageBox.Show("Словарь уже содержит набор с таким названием", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
_shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight));
}
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -72,8 +80,11 @@ namespace ProjectWarmlyShip
public void DelSet(string name) public void DelSet(string name)
{ {
// TODO Прописать логику для удаления // TODO Прописать логику для удаления
if (!_shipStorages.ContainsKey(name)) return; ShipsGenericCollection<DrawningShip, DrawningObjectShip> ship;
_shipStorages.Remove(name); if (_shipStorages.TryGetValue(new ShipsCollectionInfo(name, string.Empty), out ship))
{
_shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
}
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
@ -86,7 +97,8 @@ namespace ProjectWarmlyShip
get get
{ {
// TODO Продумать логику получения набора // TODO Продумать логику получения набора
if (_shipStorages.ContainsKey(ind)) return _shipStorages[ind]; ShipsCollectionInfo infShip = new ShipsCollectionInfo(ind, string.Empty);
if (_shipStorages.ContainsKey(infShip)) return _shipStorages[infShip];
return null; return null;
} }
} }
@ -102,7 +114,7 @@ namespace ProjectWarmlyShip
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, foreach (KeyValuePair<ShipsCollectionInfo,
ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages) ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
@ -178,7 +190,7 @@ namespace ProjectWarmlyShip
} }
} }
} }
_shipStorages.Add(name, collection); _shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), collection);
} }
} }
} }