Compare commits

..

2 Commits

13 changed files with 392 additions and 54 deletions

View File

@ -56,7 +56,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningStormtrooperBase stormtrooper)
{
return company._collection.Insert(stormtrooper);
return company._collection.Insert(stormtrooper, new DrawinigStormtrooperBaseEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -108,4 +108,9 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningStormtrooperBase?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper.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></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 ProjectStormtrooper.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -24,15 +25,17 @@ 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>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@ -55,5 +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

@ -1,4 +1,5 @@
using ProjectStormtrooper.Exceptions;
using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -53,21 +54,35 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// 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 проверка позиции
// 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);
@ -91,4 +106,8 @@ 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 ProjectStormtrooper.Exceptions;
using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -58,8 +59,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach(T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningStormtrooperBase>).Equals(obj as DrawningStormtrooperBase, item as DrawningStormtrooperBase))
throw new ObjectIsEqualException();
}
}
// TODO вставка в свободное место набора
int index = 0;
while ( index < _collection.Length)
@ -74,13 +83,21 @@ 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 проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningStormtrooperBase>).Equals(obj as DrawningStormtrooperBase, item as DrawningStormtrooperBase))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -128,4 +145,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -17,17 +17,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>
/// Добавление коллекции в хранилище
@ -38,17 +38,13 @@ public class StorageCollection<T>
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
{
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
}
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
@ -57,9 +53,10 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
@ -73,8 +70,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;
}
@ -110,7 +108,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);
if (value.Value.Count == 0)
@ -164,18 +162,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?.CreateDrawningStormtrooper() is T stormtrooper)
@ -195,7 +195,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}

View File

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

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;
/// <summary>
/// Сравнению по цвету, скорости, весу
/// </summary>
public class DrawningStormtrooperBaseByColor:IComparer<DrawningStormtrooperBase?>
{
public int Compare(DrawningStormtrooperBase? x, DrawningStormtrooperBase? y)
{
if (x == null || x.EntityStormtrooperBase == null)
{
return 1;
}
if (y == null || y.EntityStormtrooperBase == null)
{
return -1;
}
var bodycolorCompare = x.EntityStormtrooperBase.BodyColor.Name.CompareTo(y.EntityStormtrooperBase.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityStormtrooperBase.Speed.CompareTo(y.EntityStormtrooperBase.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityStormtrooperBase.Weight.CompareTo(y.EntityStormtrooperBase.Weight);
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper.Drawnings;
/// <summary>
/// Сравнению по типу, скорости, весу
/// </summary>
public class DrawningStormtrooperBaseByType: IComparer<DrawningStormtrooperBase?>
{
public int Compare(DrawningStormtrooperBase? x, DrawningStormtrooperBase? y)
{
if (x == null || x.EntityStormtrooperBase == null)
{
return 1;
}
if (y == null || y.EntityStormtrooperBase == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityStormtrooperBase.Speed.CompareTo(y.EntityStormtrooperBase.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityStormtrooperBase.Weight.CompareTo(y.EntityStormtrooperBase.Weight);
}
}

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace ProjectStormtrooper.Drawnings
{
public static class ExtentionDrawningStormtrooper
public static class ExtentionDrawningStormtrooperBase
{
/// <summary>
/// Разделитель для записи информации по объекту в файл

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 ProjectStormtrooper.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
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

@ -29,6 +29,8 @@
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
buttonSortByColor = new Button();
buttonSortByType = new Button();
panelCompanyTools = new Panel();
buttonAddStormtrooperBase = new Button();
maskedTextBox = new MaskedTextBox();
@ -68,14 +70,38 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(911, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(173, 646);
groupBoxTools.Size = new Size(173, 687);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(5, 238);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(153, 32);
buttonSortByColor.TabIndex = 10;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 196);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(155, 36);
buttonSortByType.TabIndex = 9;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddStormtrooperBase);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveStormtrooper);
@ -83,7 +109,7 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 361);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(161, 261);
panelCompanyTools.Size = new Size(161, 276);
panelCompanyTools.TabIndex = 7;
//
// buttonAddStormtrooperBase
@ -99,7 +125,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(8, 99);
maskedTextBox.Location = new Point(7, 48);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(153, 23);
@ -109,7 +135,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(7, 209);
buttonRefresh.Location = new Point(5, 158);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(155, 32);
buttonRefresh.TabIndex = 6;
@ -120,9 +146,9 @@
// buttonRemoveStormtrooper
//
buttonRemoveStormtrooper.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveStormtrooper.Location = new Point(6, 128);
buttonRemoveStormtrooper.Location = new Point(5, 77);
buttonRemoveStormtrooper.Name = "buttonRemoveStormtrooper";
buttonRemoveStormtrooper.Size = new Size(166, 33);
buttonRemoveStormtrooper.Size = new Size(153, 33);
buttonRemoveStormtrooper.TabIndex = 4;
buttonRemoveStormtrooper.Text = "Удалить Штурмовик";
buttonRemoveStormtrooper.UseVisualStyleBackColor = true;
@ -131,9 +157,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(7, 167);
buttonGoToCheck.Location = new Point(3, 116);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(166, 36);
buttonGoToCheck.Size = new Size(158, 36);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -248,7 +274,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(911, 646);
pictureBox.Size = new Size(911, 687);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
@ -296,7 +322,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1084, 670);
ClientSize = new Size(1084, 711);
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

@ -91,6 +91,11 @@ public partial class FormStormtrooperCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch(ObjectIsEqualException ex)
{
MessageBox.Show("Такой объект уже существует ");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -247,7 +252,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);
@ -334,11 +339,35 @@ public partial class FormStormtrooperCollection : Form
}
}
/// <summary>
/// сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareStorntrooper(new DrawningStormtrooperBaseByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareStorntrooper(new DrawningStormtrooperBaseByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareStorntrooper(IComparer<DrawningStormtrooperBase?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}