This commit is contained in:
Ilya Ryabov 2024-05-22 20:45:45 +04:00
parent 79d55471b8
commit bf928927e9
12 changed files with 327 additions and 44 deletions

View File

@ -62,7 +62,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBaseStormtrooper stormtrooper)
{
return company._collection.Insert(stormtrooper);
return company._collection.Insert(stormtrooper, new DrawingBaseStormtrooperEqutables());
}
/// <summary>
@ -118,4 +118,9 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningBaseStormtrooper?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,45 @@

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

View File

@ -47,17 +47,31 @@ where T : class
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 выброс ошибки если переполнение
// TODO выброс ошибки если за границу
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
@ -80,6 +94,11 @@ where T : class
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -57,9 +57,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 выброс ошибки если переполнение
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningBaseStormtrooper>).Equals(obj as DrawningBaseStormtrooper, item as DrawningBaseStormtrooper))
throw new ObjectIsEqualException();
}
}
int index = 0;
while (index < _collection.Length)
{
@ -73,10 +81,18 @@ 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)
{
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если выход за границу
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningBaseStormtrooper>).Equals(obj as DrawningBaseStormtrooper, item as DrawningBaseStormtrooper))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -124,4 +140,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -14,17 +14,17 @@ where T : DrawningBaseStormtrooper
/// <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>
/// Добавление коллекции в хранилище
@ -35,14 +35,16 @@ where T : DrawningBaseStormtrooper
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) {
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(collectionInfo)) {
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(collectionInfo, new ListGenericObjects<T>());
}
else if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(collectionInfo, new MassiveGenericObjects<T>());
}
}
}
@ -53,7 +55,8 @@ where T : DrawningBaseStormtrooper
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>
/// Доступ к коллекции
@ -65,10 +68,8 @@ where T : DrawningBaseStormtrooper
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;
}
}
@ -104,7 +105,7 @@ where T : DrawningBaseStormtrooper
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);
if (value.Value.Count == 0)
@ -113,8 +114,6 @@ where T : DrawningBaseStormtrooper
}
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())
@ -157,18 +156,18 @@ where T : DrawningBaseStormtrooper
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?.CreateDrawningStormtrooper() is T stormtrooper)
@ -186,7 +185,7 @@ where T : DrawningBaseStormtrooper
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,57 @@
using ProjectStormtrooper.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectStormtrooper.Drawnings;
public class DrawingBaseStormtrooperEqutables : IEqualityComparer<DrawningBaseStormtrooper?>
{
public bool Equals(DrawningBaseStormtrooper? x, DrawningBaseStormtrooper? y)
{
if (x == null || x.EntityBaseStormtrooper == null)
{
return false;
}
if (y == null || y.EntityBaseStormtrooper == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBaseStormtrooper.Speed != y.EntityBaseStormtrooper.Speed)
{
return false;
}
if (x.EntityBaseStormtrooper.Weight != y.EntityBaseStormtrooper.Weight)
{
return false;
}
if (x.EntityBaseStormtrooper.BodyColor != y.EntityBaseStormtrooper.BodyColor)
{
return false;
}
if (x is DrawingStormtrooper && y is DrawingStormtrooper)
{
EntityStormtrooper _x = (EntityStormtrooper)x.EntityBaseStormtrooper;
EntityStormtrooper _y = (EntityStormtrooper)x.EntityBaseStormtrooper;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Rockets != _y.Rockets)
{
return false;
}
if (_x.Bombs != _y.Bombs)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBaseStormtrooper obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,14 @@

using System.Runtime.Serialization;
namespace ProjectStormtrooper.Exceptions;
public 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();
@ -74,6 +76,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonCreateCompany);
panelCompanyTools.Controls.Add(buttonAddStormtrooper);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -82,9 +86,9 @@
panelCompanyTools.Controls.Add(buttonRemoveStormtrooper);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 294);
panelCompanyTools.Location = new Point(3, 269);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(219, 357);
panelCompanyTools.Size = new Size(219, 382);
panelCompanyTools.TabIndex = 8;
//
// buttonCreateCompany
@ -109,7 +113,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(3, 293);
buttonRefresh.Location = new Point(6, 235);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(213, 52);
buttonRefresh.TabIndex = 6;
@ -119,7 +123,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 148);
maskedTextBoxPosition.Location = new Point(3, 90);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(213, 23);
@ -128,7 +132,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(3, 235);
buttonGoToCheck.Location = new Point(3, 177);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(213, 52);
buttonGoToCheck.TabIndex = 5;
@ -138,7 +142,7 @@
//
// buttonRemoveStormtrooper
//
buttonRemoveStormtrooper.Location = new Point(3, 177);
buttonRemoveStormtrooper.Location = new Point(3, 119);
buttonRemoveStormtrooper.Name = "buttonRemoveStormtrooper";
buttonRemoveStormtrooper.Size = new Size(213, 52);
buttonRemoveStormtrooper.TabIndex = 4;
@ -158,12 +162,12 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(219, 242);
panelStorage.Size = new Size(219, 215);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 211);
buttonCollectionDel.Location = new Point(3, 181);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(213, 23);
buttonCollectionDel.TabIndex = 6;
@ -177,7 +181,7 @@
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 111);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(213, 94);
listBoxCollection.Size = new Size(213, 64);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
@ -234,7 +238,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 267);
comboBoxSelectorCompany.Location = new Point(6, 240);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(213, 23);
comboBoxSelectorCompany.TabIndex = 0;
@ -290,6 +294,26 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(6, 344);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(213, 29);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(6, 309);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(213, 29);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormStormtrooperCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -339,5 +363,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -64,9 +64,14 @@ public partial class FormStormtrooperCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Добавление бомбардировщика
/// </summary>
@ -98,7 +103,7 @@ public partial class FormStormtrooperCollection : Form
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
int tempSize = StormtrooperSharingService.getAmountOfObjects();
try
try
{
if (_company - pos != null)
{
@ -107,12 +112,12 @@ public partial class FormStormtrooperCollection : Form
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -194,7 +199,7 @@ public partial class FormStormtrooperCollection : Form
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch(Exception ex)
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
@ -268,7 +273,7 @@ public partial class FormStormtrooperCollection : 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);
@ -316,7 +321,7 @@ public partial class FormStormtrooperCollection : Form
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Загрузка не удалась", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -325,6 +330,28 @@ public partial class FormStormtrooperCollection : Form
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareStormtrooper(new DrawingBaseStormtrooperCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareStormtrooper(new DrawingBaseStormtrooperCompareByColor());
}
private void CompareStormtrooper(IComparer<DrawningBaseStormtrooper?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}