PIbd-14_Calimullin_A.R._Lab08_Simple #10

Closed
Bloody_Arthur wants to merge 3 commits from Lab08 into Lab07
13 changed files with 395 additions and 43 deletions

View File

@ -60,7 +60,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAirCraft aircraft)
{
return company._collection.Insert(aircraft);
return company._collection.Insert(aircraft, new DrawningAirCraftEqutables());
}
/// <summary>
@ -110,6 +110,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAirCraft?> comparer) => _collection?.CollectionSort(comparer);
/// <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>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -60,5 +62,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
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();
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 (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException();
}
}
_collection.Add(obj);
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 (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException(position);
}
}
_collection.Insert(position, obj);
return position;
}
@ -76,4 +90,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
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];
}
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);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count)
@ -70,6 +80,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new PositionOutOfCollectionException();
}
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new ObjectAlreadyExistsException(i);
}
}
}
if (_collection[position] != null)
{
bool pushed = false;
@ -122,4 +143,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -42,7 +42,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -52,13 +52,13 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name)) return;
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
@ -67,8 +67,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
@ -80,8 +81,9 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
return _storages[name];
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -105,7 +107,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
@ -118,10 +120,9 @@ public class StorageCollection<T>
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -134,6 +135,7 @@ public class StorageCollection<T>
}
writer.Write(sb);
}
}
}
@ -164,18 +166,20 @@ public class StorageCollection<T>
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции" + record[0]);
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)
{
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningAirCraft() is T aircraft)
@ -184,7 +188,7 @@ public class StorageCollection<T>
{
if (collection.Insert(aircraft) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
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,
};
}
}
}

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();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout();
@ -68,7 +70,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(828, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(215, 594);
groupBoxTools.Size = new Size(215, 657);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -76,7 +78,7 @@
// buttonCreateCompany
//
buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateCompany.Location = new Point(17, 316);
buttonCreateCompany.Location = new Point(17, 311);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(186, 35);
buttonCreateCompany.TabIndex = 8;
@ -180,6 +182,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddAirCraft);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -188,13 +192,13 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 352);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(203, 270);
panelCompanyTools.Size = new Size(203, 299);
panelCompanyTools.TabIndex = 9;
//
// buttonAddAirCraft
//
buttonAddAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirCraft.Location = new Point(11, 21);
buttonAddAirCraft.Location = new Point(11, 5);
buttonAddAirCraft.Name = "buttonAddAirCraft";
buttonAddAirCraft.Size = new Size(186, 49);
buttonAddAirCraft.TabIndex = 1;
@ -204,7 +208,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(11, 85);
maskedTextBoxPosition.Location = new Point(11, 60);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(186, 27);
@ -214,7 +218,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(11, 203);
buttonRefresh.Location = new Point(11, 178);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(186, 31);
buttonRefresh.TabIndex = 6;
@ -225,7 +229,7 @@
// buttonRemoveAirCraft
//
buttonRemoveAirCraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveAirCraft.Location = new Point(11, 118);
buttonRemoveAirCraft.Location = new Point(11, 93);
buttonRemoveAirCraft.Name = "buttonRemoveAirCraft";
buttonRemoveAirCraft.Size = new Size(186, 38);
buttonRemoveAirCraft.TabIndex = 4;
@ -236,7 +240,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(11, 162);
buttonGoToCheck.Location = new Point(11, 137);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(186, 35);
buttonGoToCheck.TabIndex = 5;
@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(828, 594);
pictureBox.Size = new Size(828, 657);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -294,11 +298,33 @@
//
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
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1043, 622);
ClientSize = new Size(1043, 685);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -343,5 +369,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -79,6 +79,11 @@ public partial class FormAirCraftCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError($"Не удалось добавить объект: {ex.Message}");
}
catch (ObjectAlreadyExistsException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка: такой объект уже существует {0}", aircraft);
}
}
/// <summary>
@ -234,7 +239,7 @@ public partial class FormAirCraftCollection : Form
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -320,4 +325,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">
<PropertyGroup>
<LangVersion Condition="'$(MSBuildProjectExtension)'=='.csproj'">preview</LangVersion>
</PropertyGroup>
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>