Лабораторная работа №8

This commit is contained in:
artur-kalimullin 2024-05-25 00:01:15 +04:00
parent b30af7c287
commit 58dc4abc49
13 changed files with 427 additions and 78 deletions

View File

@ -60,7 +60,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAirCraft aircraft) public static int operator +(AbstractCompany company, DrawningAirCraft aircraft)
{ {
return company._collection.Insert(aircraft); return company._collection.Insert(aircraft, new DrawningAirCraftEqutables());
} }
/// <summary> /// <summary>
@ -110,6 +110,12 @@ public abstract class AbstractCompany
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAirCraft?> 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

@ -25,16 +25,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>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -60,5 +62,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

@ -48,16 +48,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
if (_collection[position] == null) throw new ObjectNotFoundException(); if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException();
}
}
_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 = null)
{ {
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException(position);
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
@ -76,4 +90,8 @@ 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

@ -57,12 +57,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new ObjectAlreadyExistsException(i);
}
}
}
return Insert(obj, 0); return Insert(obj, 0);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
@ -70,6 +80,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new PositionOutOfCollectionException(); throw new PositionOutOfCollectionException();
} }
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new ObjectAlreadyExistsException(i);
}
}
}
if (_collection[position] != null) if (_collection[position] != null)
{ {
bool pushed = false; bool pushed = false;
@ -122,4 +143,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> lst = [.. _collection];
lst.Sort(comparer.Compare);
for (int i = 0; i < _collection.Length; ++i)
{
_collection[i] = lst[i];
}
}
} }

View File

@ -15,12 +15,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 +42,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,13 +52,13 @@ 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)
{ {
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (_storages.ContainsKey(name)) return; if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return; if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>(); _storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>(); _storages[collectionInfo] = new ListGenericObjects<T>();
} }
/// <summary> /// <summary>
@ -67,8 +67,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
_storages.Remove(name); if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
} }
/// <summary> /// <summary>
@ -80,8 +81,9 @@ public class StorageCollection<T>
{ {
get get
{ {
if (_storages.ContainsKey(name)) CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
return _storages[name]; if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null; return null;
} }
} }
@ -105,7 +107,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
@ -118,10 +120,9 @@ public class StorageCollection<T>
sb.Append(value.Key); sb.Append(value.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -134,6 +135,7 @@ public class StorageCollection<T>
} }
writer.Write(sb); writer.Write(sb);
} }
} }
} }
@ -145,7 +147,7 @@ public class StorageCollection<T>
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException($"{filename} не существует"); throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
@ -153,29 +155,31 @@ public class StorageCollection<T>
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
throw new FileFormatException("Файл не подходит"); throw new ArgumentException("В файле нет данных");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
throw new IOException("В файле неверные данные"); throw new InvalidDataException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции" + record[0]);
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null) if (collection == null)
{ {
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); throw new InvalidOperationException("Не удалось создать коллекцию");
} }
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?.CreateDrawningAirCraft() is T aircraft) if (elem?.CreateDrawningAirCraft() is T aircraft)
@ -184,7 +188,7 @@ public class StorageCollection<T>
{ {
if (collection.Insert(aircraft) == -1) if (collection.Insert(aircraft) == -1)
{ {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
} }
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
@ -193,7 +197,7 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }
@ -212,5 +216,4 @@ public class StorageCollection<T>
_ => null, _ => null,
}; };
} }
} }

View File

@ -0,0 +1,27 @@
namespace ProjectAirFighter.Drawnings;
public class DrawningAirCraftCompareByColor : IComparer<DrawningAirCraft?>
{
public int Compare(DrawningAirCraft? x, DrawningAirCraft? y)
{
if (x == null || x.EntityAirCraft == null)
{
return 1;
}
if (y == null || y.EntityAirCraft == null)
{
return -1;
}
var bodycolorCompare = x.EntityAirCraft.BodyColor.Name.CompareTo(y.EntityAirCraft.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityAirCraft.Speed.CompareTo(y.EntityAirCraft.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAirCraft.Weight.CompareTo(y.EntityAirCraft.Weight);
}
}

View File

@ -0,0 +1,31 @@
using ProjectAirFighter.Drawnings;
public class DrawingAirCraftCompareByType : IComparer<DrawningAirCraft?>
{
public int Compare(DrawningAirCraft? x, DrawningAirCraft? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityAirCraft == null)
{
return 1;
}
if (y == null || y.EntityAirCraft == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityAirCraft.Speed.CompareTo(y.EntityAirCraft.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAirCraft.Weight.CompareTo(y.EntityAirCraft.Weight);
}
}

View File

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

View File

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

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
@ -68,7 +70,7 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(828, 28); groupBoxTools.Location = new Point(828, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(215, 594); groupBoxTools.Size = new Size(215, 657);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -76,7 +78,7 @@
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateCompany.Location = new Point(17, 316); buttonCreateCompany.Location = new Point(17, 311);
buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(186, 35); buttonCreateCompany.Size = new Size(186, 35);
buttonCreateCompany.TabIndex = 8; buttonCreateCompany.TabIndex = 8;
@ -180,6 +182,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddAirCraft); panelCompanyTools.Controls.Add(buttonAddAirCraft);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@ -188,13 +192,13 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 352); panelCompanyTools.Location = new Point(6, 352);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(203, 270); panelCompanyTools.Size = new Size(203, 299);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonAddAirCraft // buttonAddAirCraft
// //
buttonAddAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirCraft.Location = new Point(11, 21); buttonAddAirCraft.Location = new Point(11, 5);
buttonAddAirCraft.Name = "buttonAddAirCraft"; buttonAddAirCraft.Name = "buttonAddAirCraft";
buttonAddAirCraft.Size = new Size(186, 49); buttonAddAirCraft.Size = new Size(186, 49);
buttonAddAirCraft.TabIndex = 1; buttonAddAirCraft.TabIndex = 1;
@ -204,7 +208,7 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(11, 85); maskedTextBoxPosition.Location = new Point(11, 60);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(186, 27); maskedTextBoxPosition.Size = new Size(186, 27);
@ -214,7 +218,7 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(11, 203); buttonRefresh.Location = new Point(11, 178);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(186, 31); buttonRefresh.Size = new Size(186, 31);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -225,7 +229,7 @@
// buttonRemoveAirCraft // buttonRemoveAirCraft
// //
buttonRemoveAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveAirCraft.Location = new Point(11, 118); buttonRemoveAirCraft.Location = new Point(11, 93);
buttonRemoveAirCraft.Name = "buttonRemoveAirCraft"; buttonRemoveAirCraft.Name = "buttonRemoveAirCraft";
buttonRemoveAirCraft.Size = new Size(186, 38); buttonRemoveAirCraft.Size = new Size(186, 38);
buttonRemoveAirCraft.TabIndex = 4; buttonRemoveAirCraft.TabIndex = 4;
@ -236,7 +240,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(11, 162); buttonGoToCheck.Location = new Point(11, 137);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(186, 35); buttonGoToCheck.Size = new Size(186, 35);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(828, 594); pictureBox.Size = new Size(828, 657);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -294,11 +298,33 @@
// //
openFileDialog.Filter = "txt file|*.txt"; openFileDialog.Filter = "txt file|*.txt";
// //
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(11, 215);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(186, 35);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(11, 256);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(186, 35);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// FormAirCraftCollection // FormAirCraftCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1043, 622); ClientSize = new Size(1043, 685);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -343,5 +369,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,6 +2,7 @@
using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings; using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System.Xml.Linq;
namespace ProjectAirFighter; namespace ProjectAirFighter;
@ -77,7 +78,12 @@ public partial class FormAirCraftCollection : Form
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError($"Не удалось добавить объект: {ex.Message}"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ObjectAlreadyExistsException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка: такой объект уже существует {0}", aircraft);
} }
} }
@ -90,7 +96,7 @@ public partial class FormAirCraftCollection : Form
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
_logger.LogError("Удаление объекта из несуществующей коллекции"); _logger.LogWarning("Удаление объекта из несуществующей коллекции");
return; return;
} }
@ -104,18 +110,18 @@ public partial class FormAirCraftCollection : Form
{ {
object decrementObject = _company - pos; object decrementObject = _company - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}"); _logger.LogInformation($"Удален по позиции {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
catch (ObjectNotFoundException) catch (ObjectNotFoundException ex)
{ {
MessageBox.Show("Объект не найден"); MessageBox.Show("Объект не найден");
_logger.LogError($"Удаление не найденного объекта в позиции {pos} "); _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} ");
} }
catch (PositionOutOfCollectionException) catch (PositionOutOfCollectionException ex)
{ {
MessageBox.Show("Удаление вне рамках коллекции"); MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogError($"Удаление объекта за пределами коллекции {pos} "); _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
} }
} }
@ -130,33 +136,29 @@ public partial class FormAirCraftCollection : Form
{ {
return; return;
} }
try
DrawningAirCraft? aircraft = null;
int counter = 100;
while (aircraft == null)
{ {
DrawningAirCraft? aircraft = null; aircraft = _company.GetRandomObject();
int counter = 100; counter--;
while (aircraft == null) if (counter <= 0)
{ {
aircraft = _company.GetRandomObject(); break;
counter--;
if (counter <= 0)
{
break;
}
} }
if (aircraft == null)
{
return;
}
FormAirFighter form = new()
{
SetAirCraft = aircraft
};
form.ShowDialog();
} }
catch (ObjectNotFoundException)
if (aircraft == null)
{ {
_logger.LogError("Ошибка при передаче объекта на FormAirFighter"); return;
} }
FormAirFighter form = new()
{
SetAirCraft = aircraft
};
form.ShowDialog();
} }
/// <summary> /// <summary>
@ -184,7 +186,7 @@ public partial class FormAirCraftCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Не заполненная коллекция"); _logger.LogWarning("Не заполненная коллекция");
return; return;
} }
@ -213,7 +215,7 @@ public partial class FormAirCraftCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogError("Удаление невыбранной коллекции"); _logger.LogWarning("Удаление невыбранной коллекции");
return; return;
} }
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
@ -234,7 +236,7 @@ public partial class FormAirCraftCollection : 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);
@ -251,7 +253,7 @@ public partial class FormAirCraftCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogError("Создание компании невыбранной коллекции"); _logger.LogWarning("Создание компании невыбранной коллекции");
return; return;
} }
@ -259,7 +261,7 @@ public partial class FormAirCraftCollection : Form
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
_logger.LogError("Не удалось инициализировать коллекцию"); _logger.LogWarning("Не удалось инициализировать коллекцию");
return; return;
} }
@ -320,4 +322,39 @@ public partial class FormAirCraftCollection : Form
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareAirCraft(new DrawingAirCraftCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareAirCraft(new DrawningAirCraftCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareAirCraft(IComparer<DrawningAirCraft?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }

View File

@ -1,5 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion Condition="'$(MSBuildProjectExtension)'=='.csproj'">preview</LangVersion>
</PropertyGroup>
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework> <TargetFramework>net7.0-windows</TargetFramework>