8 лабораторная

This commit is contained in:
zolotovart 2024-05-18 15:30:48 +03:00
parent 85cf4068b2
commit b2fbbab01a
12 changed files with 387 additions and 50 deletions

View File

@ -55,7 +55,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingShip ship)
{
return company._collection.Insert(ship);
return company._collection.Insert(ship, new DrawingShipEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -93,6 +93,8 @@ public abstract class AbstractCompany
}
return bitmap;
}
public void Sort(IComparer<DrawingShip?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.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,5 @@
using System;
using ProjectLinkor.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -25,15 +26,17 @@ where T : class
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объеков</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">Сравнение двух объеков</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@ -56,4 +59,6 @@ where T : class
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,4 +1,5 @@
using ProjectLinkor.Exceptions;
using ProjectLinkor.Drawnings;
using ProjectLinkor.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -48,16 +49,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 == _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 == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException(position);
}
}
_collection.Insert(position, obj);
return position;
@ -77,4 +92,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 ProjectLinkor.Exceptions;
using ProjectLinkor.Drawnings;
using ProjectLinkor.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -52,8 +53,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
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);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -64,12 +75,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
throw new CollectionOverflowException();
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException();
}
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new ObjectAlreadyExistsException(i);
}
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
@ -96,13 +117,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
--temp;
}
return -1;
throw new CollectionOverflowException();
}
public T Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null) throw new ObjectNotFoundException();
T myObject = _collection[position];
T? myObject = _collection[position];
_collection[position] = null;
return myObject;
}
@ -114,4 +135,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -2,6 +2,7 @@
using ProjectLinkor.Exceptions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -17,11 +18,11 @@ 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>
/// Ключевое слово, с которого должен начинаться файл
@ -41,7 +42,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -50,20 +51,20 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (name == null || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(collectionInfo))
return;
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
default: break;
}
}
@ -73,9 +74,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
@ -86,17 +87,18 @@ public class StorageCollection<T>
{
get
{
// TODO Продумать логику получения объекта
if (name == null || !_storages.ContainsKey(name))
return null;
return _storages[name];
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -105,7 +107,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -115,8 +117,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);
@ -159,17 +159,20 @@ public class StorageCollection<T>
{
string[] record = line.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) ??
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ;
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingShip() is T ship)
@ -178,16 +181,16 @@ public class StorageCollection<T>
{
if (collection.Insert(ship) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
throw new DataException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.Drawnings;
public class DrawingShipCompareByColor : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? y)
{
if (x == null || x.EntityShip == null)
{
return 1;
}
if (y == null || y.EntityShip == null)
{
return -1;
}
var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.Drawnings;
public class DrawingShipCompareByType : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? y)
{
if (x == null || x.EntityShip == null)
{
return -1;
}
if (y == null || y.EntityShip == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,64 @@
using ProjectLinkor.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.Drawnings;
public class DrawingShipEqutables : IEqualityComparer<DrawingShip?>
{
public bool Equals(DrawingShip? x, DrawingShip? y)
{
if (x == null || x.EntityShip == null)
{
return false;
}
if (y == null || y.EntityShip == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is DrawingLinkor && y is DrawingLinkor)
{
// TODO доделать логику сравнения дополнительных параметров
EntityLinkor entityX = (EntityLinkor)x.EntityShip;
EntityLinkor entityY = (EntityLinkor)y.EntityShip;
if (entityX.Rocket != entityY.Rocket)
{
return false;
}
if (entityX.Gun != entityY.Gun)
{
return false;
}
if (entityX.AdditionalColor != entityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingShip? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.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();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(752, 33);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(300, 854);
groupBoxTools.Size = new Size(300, 957);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,7 +87,7 @@
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 479);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(294, 372);
panelCompanyTools.Size = new Size(294, 475);
panelCompanyTools.TabIndex = 8;
//
// buttonAddShip
@ -98,7 +102,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(17, 125);
maskedTextBoxPosition.Location = new Point(13, 79);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(264, 31);
@ -108,7 +112,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(17, 303);
buttonRefresh.Location = new Point(13, 257);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(264, 60);
buttonRefresh.TabIndex = 6;
@ -119,7 +123,7 @@
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(17, 171);
buttonRemoveShip.Location = new Point(13, 125);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(264, 60);
buttonRemoveShip.TabIndex = 4;
@ -130,7 +134,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(17, 237);
buttonGoToCheck.Location = new Point(13, 191);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(264, 60);
buttonGoToCheck.TabIndex = 5;
@ -247,7 +251,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 33);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(752, 854);
pictureBox.Size = new Size(752, 957);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -292,11 +296,33 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(13, 389);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(264, 60);
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(13, 323);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(264, 60);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1052, 887);
ClientSize = new Size(1052, 990);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -341,5 +367,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 FormShipCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ObjectAlreadyExistsException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка: такой объект уже существует {0}", ship);
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
@ -223,7 +228,7 @@ public partial class FormShipCollection : 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);
@ -308,4 +313,23 @@ public partial class FormShipCollection : Form
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareShips(new DrawingShipCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawingShipCompareByColor());
}
private void CompareShips(IComparer<DrawingShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}