PIbd-12_Kuznetsov_D.V. LabWork08 Simple #9

Closed
ZakenChannel wants to merge 3 commits from Lab_8 into Lab_7
12 changed files with 398 additions and 47 deletions

View File

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

@ -1,4 +1,6 @@
namespace ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -21,16 +23,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 +60,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
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 System.Linq;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -54,22 +56,31 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); }
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException(position);
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
@ -88,4 +99,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
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;
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)
{
@ -84,6 +85,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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(position);
}
}
for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
@ -129,4 +139,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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 System.Text;
using System.Xml.Linq;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -14,12 +16,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 +44,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -52,17 +54,18 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
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)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { });
_storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { });
_storages.Add(collectionInfo, new ListGenericObjects<T> { });
return;
}
@ -74,8 +77,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name)) { return; }
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (name == null || !_storages.ContainsKey(collectionInfo)) { return; }
_storages.Remove(collectionInfo);
}
/// <summary>
@ -87,8 +91,9 @@ public class StorageCollection<T>
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
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))
{
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)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -159,20 +163,25 @@ public class StorageCollection<T>
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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("Не удалось определить тип коллекции:" + record[1]);
if (collection == null)
{
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)
{
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,69 @@
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();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -66,9 +68,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(978, 24);
groupBoxTools.Location = new Point(980, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(236, 621);
groupBoxTools.Size = new Size(236, 656);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -85,6 +87,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddFighter);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -94,7 +98,7 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 336);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(230, 282);
panelCompanyTools.Size = new Size(230, 317);
panelCompanyTools.TabIndex = 11;
//
// buttonAddFighter
@ -110,7 +114,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(2, 107);
maskedTextBox.Location = new Point(2, 58);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(224, 23);
@ -120,7 +124,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(2, 232);
buttonRefresh.Location = new Point(2, 183);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(224, 42);
buttonRefresh.TabIndex = 6;
@ -131,7 +135,7 @@
// buttonRemoveFighter
//
buttonRemoveFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveFighter.Location = new Point(2, 136);
buttonRemoveFighter.Location = new Point(2, 87);
buttonRemoveFighter.Name = "buttonRemoveFighter";
buttonRemoveFighter.Size = new Size(224, 42);
buttonRemoveFighter.TabIndex = 4;
@ -142,7 +146,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(2, 184);
buttonGoToCheck.Location = new Point(2, 135);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(224, 42);
buttonGoToCheck.TabIndex = 5;
@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(978, 621);
pictureBox.Size = new Size(980, 656);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -258,7 +262,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1214, 24);
menuStrip.Size = new Size(1216, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
@ -293,11 +297,33 @@
//
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
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1214, 645);
ClientSize = new Size(1216, 680);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -342,5 +368,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -2,7 +2,6 @@
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
using System.Windows.Forms;
namespace ProjectAirFighter;
@ -74,6 +73,11 @@ public partial class FormWarPlaneCollection : Form
MessageBox.Show("Ошибка переполнения коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotUniqueException ex)
{
MessageBox.Show("Такой объект уже присутствует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -115,16 +119,16 @@ public partial class FormWarPlaneCollection : Form
_logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -236,7 +240,7 @@ public partial class FormWarPlaneCollection : 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);
@ -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();
}
}