lab 8 done

This commit is contained in:
ZakenChannel 2024-05-13 19:40:12 +04:00
parent 6213fef9d6
commit e03badef02
12 changed files with 398 additions and 41 deletions

View File

@ -64,7 +64,7 @@ public abstract class AbstractCompany
{ {
return -1; return -1;
} }
return company._collection.Insert(plane); return company._collection.Insert(plane, new DrawiningPlaneEqutables());
} }
/// <summary> /// <summary>
@ -114,6 +114,12 @@ public abstract class AbstractCompany
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningWarPlane?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -0,0 +1,76 @@
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,4 +1,6 @@
namespace ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary> /// <summary>
/// Интерфейс описания действий для набора хранимых объектов /// Интерфейс описания действий для набора хранимых объектов
@ -21,16 +23,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -56,4 +60,10 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,5 +1,7 @@
 
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System.Linq;
namespace ProjectAirFighter.CollectionGenericObjects; namespace ProjectAirFighter.CollectionGenericObjects;
@ -54,16 +56,32 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer)
{ {
if (comparer == null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); } if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); }
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer)
{ {
if (comparer == null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
if (Count == _maxCount) throw new CollectionOverflowException(); if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Insert(position, obj); _collection.Insert(position, obj);
@ -88,4 +106,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,4 +1,5 @@
 
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects; namespace ProjectAirFighter.CollectionGenericObjects;
@ -66,12 +67,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer)
{ {
return Insert(obj, 0); return Insert(obj, 0, comparer);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
@ -84,6 +85,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position; return position;
} }
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningWarPlane>).Equals(obj as DrawningWarPlane, item as DrawningWarPlane))
throw new ObjectNotUniqueException();
}
}
for (int i = position + 1; i < Count; i++) for (int i = position + 1; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -129,4 +139,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -1,6 +1,8 @@
using ProjectAirFighter.Drawnings; using Microsoft.AspNetCore.Http;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System.Text; using System.Text;
using System.Xml.Linq;
namespace ProjectAirFighter.CollectionGenericObjects; namespace ProjectAirFighter.CollectionGenericObjects;
@ -14,12 +16,12 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -42,7 +44,7 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -52,17 +54,18 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (name == null || _storages.ContainsKey(name)) { return; } CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(collectionInfo)) { return; }
switch (collectionType) switch (collectionType)
{ {
case CollectionType.None: case CollectionType.None:
return; return;
case CollectionType.Massive: case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { }); _storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return; return;
case CollectionType.List: case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { }); _storages.Add(collectionInfo, new ListGenericObjects<T> { });
return; return;
} }
@ -74,8 +77,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (name == null || !_storages.ContainsKey(name)) { return; } CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
_storages.Remove(name); if (name == null || !_storages.ContainsKey(collectionInfo)) { return; }
_storages.Remove(collectionInfo);
} }
/// <summary> /// <summary>
@ -87,8 +91,9 @@ public class StorageCollection<T>
{ {
get get
{ {
if (name == null || !_storages.ContainsKey(name)) { return null; } CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
return _storages[name]; if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
} }
} }
@ -113,17 +118,16 @@ public class StorageCollection<T>
using (StreamWriter sw = new StreamWriter(filename)) using (StreamWriter sw = new StreamWriter(filename))
{ {
sw.WriteLine(_collectionKey.ToString()); sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages) foreach (KeyValuePair< CollectionInfo, ICollectionGenericObjects <T>> kvpair in _storages)
{ {
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (kvpair.Value.Count == 0) if (kvpair.Value.Count == 0)
continue; continue;
sb.Append(kvpair.Key); sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount); sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems()) foreach (T? item in kvpair.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -159,20 +163,25 @@ public class StorageCollection<T>
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
string[] record = str.Split(_separatorForKeyValue); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
if (collection == null) if (collection == null)
{ {
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningPlane() is T plane) if (elem?.CreateDrawningPlane() is T plane)
@ -187,7 +196,7 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }

View File

@ -0,0 +1,68 @@
using ProjectAirFighter.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningPlaneEqutables : IEqualityComparer<DrawningWarPlane?>
{
public bool Equals(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityFighter == null)
{
return false;
}
if (y == null || y.EntityFighter == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityFighter.Speed != y.EntityFighter.Speed)
{
return false;
}
if (x.EntityFighter.Weight != y.EntityFighter.Weight)
{
return false;
}
if (x.EntityFighter.BodyColor != y.EntityFighter.BodyColor)
{
return false;
}
if (x is DrawningAirFighter && y is DrawningAirFighter)
{
EntityAirFighter _x = (EntityAirFighter) x.EntityFighter;
EntityAirFighter _y = (EntityAirFighter) x.EntityFighter;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.BodyRockets != _y.BodyRockets)
{
return false;
}
if (_x.AdditionalWings != _y.AdditionalWings)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningWarPlane obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,34 @@
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningPlaneCompareByColor : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityFighter == null)
{
return 1;
}
if (y == null || y.EntityFighter == null)
{
return -1;
}
var bodycolorCompare = y.EntityFighter.BodyColor.Name.CompareTo(x.EntityFighter.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = y.EntityFighter.Speed.CompareTo(x.EntityFighter.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityFighter.Weight.CompareTo(x.EntityFighter.Weight);
}
}

View File

@ -0,0 +1,33 @@
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningPlaneCompareByType : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityFighter == null)
{
return 1;
}
if (y == null || y.EntityFighter == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityFighter.Speed.CompareTo(x.EntityFighter.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityFighter.Weight.CompareTo(x.EntityFighter.Weight);
}
}

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку наличия такого же объекта в коллекции
/// </summary>
[Serializable]
internal class ObjectNotUniqueException : ApplicationException
{
public ObjectNotUniqueException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectNotUniqueException() : base() { }
public ObjectNotUniqueException(string message) : base(message) { }
public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotUniqueException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -66,9 +68,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(978, 24); groupBoxTools.Location = new Point(980, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(236, 621); groupBoxTools.Size = new Size(236, 656);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -85,6 +87,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddFighter); panelCompanyTools.Controls.Add(buttonAddFighter);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@ -94,7 +98,7 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 336); panelCompanyTools.Location = new Point(3, 336);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(230, 282); panelCompanyTools.Size = new Size(230, 317);
panelCompanyTools.TabIndex = 11; panelCompanyTools.TabIndex = 11;
// //
// buttonAddFighter // buttonAddFighter
@ -110,7 +114,7 @@
// //
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Location = new Point(2, 107); maskedTextBox.Location = new Point(2, 58);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(224, 23); maskedTextBox.Size = new Size(224, 23);
@ -120,7 +124,7 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(2, 232); buttonRefresh.Location = new Point(2, 183);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(224, 42); buttonRefresh.Size = new Size(224, 42);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -131,7 +135,7 @@
// buttonRemoveFighter // buttonRemoveFighter
// //
buttonRemoveFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveFighter.Location = new Point(2, 136); buttonRemoveFighter.Location = new Point(2, 87);
buttonRemoveFighter.Name = "buttonRemoveFighter"; buttonRemoveFighter.Name = "buttonRemoveFighter";
buttonRemoveFighter.Size = new Size(224, 42); buttonRemoveFighter.Size = new Size(224, 42);
buttonRemoveFighter.TabIndex = 4; buttonRemoveFighter.TabIndex = 4;
@ -142,7 +146,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(2, 184); buttonGoToCheck.Location = new Point(2, 135);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(224, 42); buttonGoToCheck.Size = new Size(224, 42);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(978, 621); pictureBox.Size = new Size(980, 656);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -258,7 +262,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1214, 24); menuStrip.Size = new Size(1216, 24);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@ -293,11 +297,33 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 275);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(224, 42);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 227);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(224, 42);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormWarPlaneCollection // FormWarPlaneCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1214, 645); ClientSize = new Size(1216, 680);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -342,5 +368,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -2,7 +2,6 @@
using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings; using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System.Windows.Forms;
namespace ProjectAirFighter; namespace ProjectAirFighter;
@ -74,6 +73,11 @@ public partial class FormWarPlaneCollection : Form
MessageBox.Show("Ошибка переполнения коллекции"); MessageBox.Show("Ошибка переполнения коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
catch (ObjectNotUniqueException ex)
{
MessageBox.Show("Такой объект уже присутствует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -236,7 +240,7 @@ public partial class FormWarPlaneCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -323,4 +327,39 @@ public partial class FormWarPlaneCollection : Form
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
ComparePlanes(new DrawningPlaneCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
ComparePlanes(new DrawningPlaneCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void ComparePlanes(IComparer<DrawningWarPlane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }