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

This commit is contained in:
Иван Захаров 2024-05-21 16:48:21 +04:00
parent bd3d6be678
commit 1604ddb14b
13 changed files with 337 additions and 43 deletions

View File

@ -57,7 +57,7 @@ public abstract class AbstractCompany
public static int operator +(AbstractCompany company, DrawningWarPlane warPlane)
{
if (company._collection == null) return -1;
return company._collection.Insert(warPlane);
return company._collection.Insert(warPlane, new DrawiningPlaneEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -106,4 +106,10 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningWarPlane?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,43 @@
namespace ProjectAirFighter.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
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

@ -21,16 +21,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>
/// Удаление объекта из коллекции с конкретной позиции
@ -56,4 +58,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -45,18 +45,29 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов и вставка в конец набора
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки если переполнение
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
// TODO выброс ошибки если за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
@ -78,4 +89,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@

using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -53,10 +54,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO вставка в свободное место набора
for(int i = 0; i < Count; i++)
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningWarPlane>).Equals(obj as DrawningWarPlane, item as DrawningWarPlane))
throw new ObjectIsEqualException();
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
@ -67,8 +75,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningWarPlane>).Equals(obj as DrawningWarPlane, item as DrawningWarPlane))
throw new ObjectIsEqualException();
}
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -119,4 +135,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -9,17 +9,17 @@ 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>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -28,14 +28,14 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
if (_storages.ContainsKey(name)) return;
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
// TODO Прописать логику для добавления
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>
/// Удаление коллекции
@ -44,9 +44,9 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
@ -57,9 +57,9 @@ public class StorageCollection<T>
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -97,7 +97,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)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -107,8 +107,6 @@ public class StorageCollection<T>
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
@ -153,18 +151,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;
}
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("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
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?.CreateDrawningWarPlane() is T plane)
@ -182,7 +182,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
return true;
}

View File

@ -0,0 +1,61 @@
using ProjectAirFighter.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectAirFighter.Drawnings;
public class DrawiningPlaneEqutables : IEqualityComparer<DrawningWarPlane?>
{
public bool Equals(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityWarPlane == null)
{
return false;
}
if (y == null || y.EntityWarPlane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarPlane.Speed != y.EntityWarPlane.Speed)
{
return false;
}
if (x.EntityWarPlane.Weight != y.EntityWarPlane.Weight)
{
return false;
}
if (x.EntityWarPlane.BodyColor != y.EntityWarPlane.BodyColor)
{
return false;
}
if (x is DrawningAirFighter && y is DrawningAirFighter)
{
EntityAirFighter _x = (EntityAirFighter)x.EntityWarPlane;
EntityAirFighter _y = (EntityAirFighter)x.EntityWarPlane;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Engines != _y.Engines)
{
return false;
}
if (_x.ExtraWings != _y.ExtraWings)
{
return false;
}
if (_x.Rockets != _y.Rockets)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningWarPlane obj)
{
return obj.GetHashCode();
}
}

View File

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

View File

@ -0,0 +1,29 @@
namespace ProjectAirFighter.Drawnings;
public class DrawningPlaneCompareByType : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityWarPlane == null)
{
return 1;
}
if (y == null || y.EntityWarPlane == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight);
}
}

View File

@ -0,0 +1,12 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
internal class ObjectIsEqualException : ApplicationException
{
public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectIsEqualException() : base() { }
public ObjectIsEqualException(string message) : base(message) { }
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -70,13 +72,15 @@
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 4, 3, 4);
groupBoxTools.Size = new Size(238, 800);
groupBoxTools.Size = new Size(238, 912);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddWarPlane);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
@ -85,7 +89,7 @@
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 446);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(232, 350);
panelCompanyTools.Size = new Size(232, 462);
panelCompanyTools.TabIndex = 8;
//
// buttonAddWarPlane
@ -103,7 +107,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(14, 279);
buttonRefresh.Location = new Point(14, 246);
buttonRefresh.Margin = new Padding(3, 4, 3, 4);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(206, 61);
@ -114,7 +118,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(14, 106);
maskedTextBoxPosition.Location = new Point(14, 73);
maskedTextBoxPosition.Margin = new Padding(3, 4, 3, 4);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
@ -125,7 +129,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(14, 210);
buttonGoToCheck.Location = new Point(14, 177);
buttonGoToCheck.Margin = new Padding(3, 4, 3, 4);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(206, 61);
@ -137,7 +141,7 @@
// buttonRemovePlane
//
buttonRemovePlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemovePlane.Location = new Point(14, 141);
buttonRemovePlane.Location = new Point(14, 108);
buttonRemovePlane.Margin = new Padding(3, 4, 3, 4);
buttonRemovePlane.Name = "buttonRemovePlane";
buttonRemovePlane.Size = new Size(206, 61);
@ -257,7 +261,7 @@
pictureBox.Location = new Point(0, 28);
pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(991, 800);
pictureBox.Size = new Size(991, 912);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -302,11 +306,35 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(14, 384);
buttonSortByColor.Margin = new Padding(3, 4, 3, 4);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(206, 61);
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(14, 315);
buttonSortByType.Margin = new Padding(3, 4, 3, 4);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(206, 61);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1229, 828);
ClientSize = new Size(1229, 940);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -352,5 +380,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -74,6 +74,11 @@ public partial class FormPlaneCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonRemovePlane_Click(object sender, EventArgs e)
{
@ -168,7 +173,7 @@ public partial class FormPlaneCollection : 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);
@ -279,4 +284,24 @@ public partial class FormPlaneCollection : Form
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
ComparePlane(new DrawningPlaneCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
ComparePlane(new DrawningPlaneCompareByColor());
}
private void ComparePlane(IComparer<DrawningWarPlane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -8,3 +8,18 @@
[ERROR] [2024-05-20 14:39:08.8637] Ошибка: "В коллекции превышено допустимое количество: 15"
[INFORMATION] [2024-05-20 14:39:16.4465] Удален объект по позиции 2
[ERROR] [2024-05-20 14:39:20.0041] Ошибка: "Не найден объект по позиции 2"
[INFORMATION] [2024-05-21 16:44:55.7300] Форма загрузилась
[INFORMATION] [2024-05-21 16:45:04.9837] Коллекция добавлена 123
[INFORMATION] [2024-05-21 16:45:17.3743] Добавлен объект: EntityWarPlane:300:1000:Blue
[ERROR] [2024-05-21 16:45:24.6381] Ошибка: "Error in the application."
[ERROR] [2024-05-21 16:45:35.4419] Ошибка: "Error in the application."
[INFORMATION] [2024-05-21 16:45:42.6411] Добавлен объект: EntityAirFighter:300:1000:Blue:Black:False:False:False
[INFORMATION] [2024-05-21 16:45:53.9937] Удален объект по позиции 1
[INFORMATION] [2024-05-21 16:46:10.3753] Добавлен объект: EntityAirFighter:300:1000:Blue:Red:True:True:True
[ERROR] [2024-05-21 16:46:27.3728] Ошибка: "Error in the application."
[INFORMATION] [2024-05-21 16:46:49.3891] Добавлен объект: EntityAirFighter:300:1000:Gray:Red:True:True:True
[INFORMATION] [2024-05-21 16:47:11.4253] Коллекция добавлена 1232
[INFORMATION] [2024-05-21 16:47:22.6725] Добавлен объект: EntityWarPlane:300:1000:White
[ERROR] [2024-05-21 16:47:28.3987] Ошибка: "Error in the application."
[INFORMATION] [2024-05-21 16:47:41.9521] Загрузка из файла: "C:\\Users\\VirBiuM\\Documents\\123.txt"
[INFORMATION] [2024-05-21 16:47:51.2609] Загрузка из файла: "C:\\Users\\VirBiuM\\Documents\\12.txt"