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

This commit is contained in:
victinass 2024-05-13 08:58:31 +04:00
parent 26fd2f83d9
commit a810260e69
13 changed files with 399 additions and 43 deletions

View File

@ -56,7 +56,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingWarship warship)
{
return company._collection.Insert(warship);
return company._collection.Insert(warship, new DrawingWarshipEqutables());
}
/// <summary>
/// Перезагрузка оператора удаления для класса
@ -98,6 +98,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<DrawingWarship?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,71 @@
namespace Battleship.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;
}
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 Battleship.CollectionGenericObjects;
using Battleship.Drawings;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -22,16 +24,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<DrawingWarship?> 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<DrawingWarship?> comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -57,4 +61,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,4 +1,5 @@
using Battleship.Exceptions;
using Battleship.Drawings;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
@ -38,8 +39,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj))
{
throw new CollectionAlreadyExistsException();
}
// проверка, что не превышено максимальное количество элементов
if (_collection.Count >= _maxCount)
{
@ -50,8 +56,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _maxCount;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj))
{
throw new CollectionAlreadyExistsException();
}
// проверка, что не превышено максимальное количество элементов
if (Count >= _maxCount)
throw new CollectionOverflowException(_maxCount);
@ -82,4 +93,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 Battleship.CollectionGenericObjects;
using Battleship.Drawings;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
@ -60,8 +61,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj))
{
throw new CollectionAlreadyExistsException();
}
// вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
@ -76,8 +82,15 @@ 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<DrawingWarship?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj))
{
throw new CollectionAlreadyExistsException();
}
// проверка позиции
if (position >= _collection.Length || position < 0)
throw new PositionOutOfCollectionException(position);
@ -138,4 +151,14 @@ 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

@ -14,12 +14,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>
/// Ключевое слово, с которого должен начинаться файл
@ -41,7 +41,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -52,18 +52,19 @@ public class StorageCollection<T>
public void AddCollection(string name, CollectionType collectionType)
{
// проверка, что name не пустой и нет в словаре записи с таким ключом
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty)))
{
MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// прописать логику для добавления
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects<T>());
}
if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects<T>());
}
}
@ -74,8 +75,8 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
// прописать логику для удаления коллекции
if (!_storages.ContainsKey(name)) return;
_storages.Remove(name);
if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return;
_storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty));
}
/// <summary>
@ -88,9 +89,9 @@ public class StorageCollection<T>
get
{
// продумать логику получения объекта
if (_storages.ContainsKey((string)name))
if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty)))
{
return _storages[name];
return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)];
}
return null;
}
@ -115,7 +116,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);
// не сохраняем пустые коллекции
@ -126,8 +127,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);
@ -177,21 +176,23 @@ public class StorageCollection<T>
while ((strs = reader.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]);
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?.CreateDrawingWarship() is T bulldozer)
@ -210,7 +211,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,34 @@
namespace Battleship.Drawings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
internal class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
{
return 1;
}
if (y == null || y.EntityWarship == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
}
}

View File

@ -0,0 +1,35 @@
namespace Battleship.Drawings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawingWarshipComparerByColor : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
// TODO прописать логику сравнения по цветам, скорости, весу
if (x == null || x.EntityWarship == null)
{
return 1;
}
if (y == null || y.EntityWarship == null)
{
return -1;
}
if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
{
return x.EntityWarship.BodyColor.Name.CompareTo(y.EntityWarship.BodyColor.Name);
}
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
}
}

View File

@ -0,0 +1,67 @@
namespace Battleship.Drawings;
using Battleship.Entities;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawingWarshipEqutables : IEqualityComparer<DrawingWarship?>
{
public bool Equals(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
{
return false;
}
if (y == null || y.EntityWarship == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarship.Speed != y.EntityWarship.Speed)
{
return false;
}
if (x.EntityWarship.Weight != y.EntityWarship.Weight)
{
return false;
}
if (x is DrawingBattleship && y is DrawingBattleship)
{
// TODO доделать логику сравнения дополнительных параметров
EntityBattleship xBattleship = (EntityBattleship)x.EntityWarship;
EntityBattleship yBattleship = (EntityBattleship)y.EntityWarship;
if (xBattleship.AdditionalColor != yBattleship.AdditionalColor)
{
return false;
}
if (xBattleship.Compartment != yBattleship.Compartment)
{
return false;
}
if (xBattleship.Tower != yBattleship.Tower)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarship obj)
{
return obj.GetHashCode();
}
}

View File

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

View File

@ -2,6 +2,9 @@
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что позиция вышла за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{

View File

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonRefresh = new Button();
maskedTextBox1 = new MaskedTextBox();
buttonGoToCheck = new Button();
@ -66,7 +68,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(876, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(292, 628);
groupBoxTools.Size = new Size(292, 744);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -74,20 +76,44 @@
// panelCompanyTools
//
panelCompanyTools.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox1);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddWarship);
panelCompanyTools.Controls.Add(buttonRemoveWarship);
panelCompanyTools.Location = new Point(6, 367);
panelCompanyTools.Location = new Point(6, 395);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(283, 255);
panelCompanyTools.Size = new Size(283, 337);
panelCompanyTools.TabIndex = 10;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(0, 283);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(280, 42);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(0, 235);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(283, 42);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 214);
buttonRefresh.Location = new Point(0, 187);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(280, 42);
buttonRefresh.TabIndex = 6;
@ -98,7 +124,7 @@
// maskedTextBox1
//
maskedTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox1.Location = new Point(3, 85);
maskedTextBox1.Location = new Point(3, 55);
maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(277, 27);
@ -107,7 +133,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(0, 166);
buttonGoToCheck.Location = new Point(0, 139);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(283, 42);
buttonGoToCheck.TabIndex = 5;
@ -129,7 +155,7 @@
// buttonRemoveWarship
//
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(0, 118);
buttonRemoveWarship.Location = new Point(0, 91);
buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(283, 42);
buttonRemoveWarship.TabIndex = 4;
@ -253,7 +279,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(876, 628);
pictureBox.Size = new Size(876, 744);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -303,7 +329,7 @@
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1168, 656);
ClientSize = new Size(1168, 772);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
@ -347,5 +373,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog1;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -182,7 +182,7 @@ public partial class FormWarshipCollection : 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);
@ -263,9 +263,7 @@ public partial class FormWarshipCollection : Form
return;
}
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
@ -329,4 +327,50 @@ public partial class FormWarshipCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareWarship(new DrawingWarshipCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareExcavators(new DrawingWarshipComparerByColor());
}
private void CompareExcavators(IComparer<DrawingWarship?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareWarship(IComparer<DrawingWarship?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}