diff --git a/Battleship/Battleship/Battleship.csproj b/Battleship/Battleship/Battleship.csproj
index ce5a288..835bda0 100644
--- a/Battleship/Battleship/Battleship.csproj
+++ b/Battleship/Battleship/Battleship.csproj
@@ -9,16 +9,16 @@
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs
index b503062..891a2c9 100644
--- a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs
@@ -56,7 +56,7 @@ public abstract class AbstractCompany
///
public static int operator +(AbstractCompany company, DrawingWarship warship)
{
- return company._collection.Insert(warship);
+ return company._collection.Insert(warship, new DrawingWarshipEqutables());
}
///
/// Перезагрузка оператора удаления для класса
@@ -98,6 +98,12 @@ public abstract class AbstractCompany
return bitmap;
}
+ ///
+ /// Сортировка
+ ///
+ ///
+ public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer);
+
///
/// Вывод заднего фона
///
diff --git a/Battleship/Battleship/CollectionGenericObjects/CollectionInfo.cs b/Battleship/Battleship/CollectionGenericObjects/CollectionInfo.cs
new file mode 100644
index 0000000..501d3d9
--- /dev/null
+++ b/Battleship/Battleship/CollectionGenericObjects/CollectionInfo.cs
@@ -0,0 +1,71 @@
+namespace Battleship.CollectionGenericObjects;
+
+///
+/// Класс, хранящий информацию по коллекции
+///
+public class CollectionInfo : IEquatable
+{
+ ///
+ /// Название
+ ///
+ 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();
+ }
+}
diff --git a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs
index 5400905..c438ebd 100644
--- a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -1,4 +1,6 @@
-namespace Battleship.CollectionGenericObjects;
+using Battleship.Drawings;
+
+namespace Battleship.CollectionGenericObjects;
///
/// Интерфейс описания действий для набора хранимых объектов
@@ -22,16 +24,18 @@ public interface ICollectionGenericObjects
/// Добавление объекта в коллекцию
///
/// Добавляемый объект
+ /// Сравнение двух объектов
/// true - вставка прошла удачно, false - вставка не удалась
- int Insert(T obj);
+ int Insert(T obj, IEqualityComparer comparer = null);
///
/// Добавление объекта в коллекцию на конкретную позицию
///
/// Добавляемый объект
/// Позиция
+ /// Сравнение двух объектов
/// true - вставка прошла удачно, false - вставка не удалась
- int Insert(T obj, int position);
+ int Insert(T obj, int position, IEqualityComparer comparer = null);
///
/// Удаление объекта из коллекции с конкретной позиции
@@ -57,4 +61,10 @@ public interface ICollectionGenericObjects
///
///
IEnumerable GetItems();
+
+ ///
+ /// Сортировка коллекции
+ ///
+ ///
+ void CollectionSort(IComparer comparer);
}
\ No newline at end of file
diff --git a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
index 05502a6..71e5678 100644
--- a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
@@ -38,8 +38,13 @@ public class ListGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
+ // TODO выброс ошибки, если такой объект есть в коллекции
+ if (comparer != null && _collection.Contains(obj, comparer))
+ {
+ throw new CollectionAlreadyExistsException();
+ }
// проверка, что не превышено максимальное количество элементов
if (_collection.Count >= _maxCount)
{
@@ -50,8 +55,13 @@ public class ListGenericObjects : ICollectionGenericObjects
return _maxCount;
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
+ // TODO выброс ошибки, если такой объект есть в коллекции
+ if (comparer != null && _collection.Contains(obj, comparer))
+ {
+ throw new CollectionAlreadyExistsException();
+ }
// проверка, что не превышено максимальное количество элементов
if (Count >= _maxCount)
throw new CollectionOverflowException(_maxCount);
@@ -82,4 +92,9 @@ public class ListGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+ public void CollectionSort(IComparer comparer)
+ {
+ _collection.Sort(comparer);
+ }
}
\ No newline at end of file
diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
index f258dfa..5d9be79 100644
--- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,5 @@
using Battleship.CollectionGenericObjects;
+using Battleship.Drawings;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
@@ -60,8 +61,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
+ // TODO выброс ошибки, если такой объект есть в коллекции
+ if (comparer != null && _collection.Contains(obj, comparer))
+ {
+ throw new CollectionAlreadyExistsException();
+ }
// вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
@@ -76,8 +82,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects
throw new CollectionOverflowException(Count);
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
+
+ // TODO выброс ошибки, если такой объект есть в коллекции
+ if (comparer != null && _collection.Contains(obj, comparer))
+ {
+ throw new CollectionAlreadyExistsException();
+ }
+
// проверка позиции
if (position >= _collection.Length || position < 0)
throw new PositionOutOfCollectionException(position);
@@ -138,4 +151,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+ public void CollectionSort(IComparer comparer)
+ {
+ List lst = [.. _collection];
+ lst.Sort(comparer.Compare);
+ for (int i = 0; i < _collection.Length; ++i)
+ {
+ _collection[i] = lst[i];
+ }
+ }
}
\ No newline at end of file
diff --git a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
index d702a86..f3e3e56 100644
--- a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
@@ -14,12 +14,12 @@ public class StorageCollection
///
/// Словарь (хранилище) с коллекциями
///
- readonly Dictionary> _storages;
+ readonly Dictionary> _storages;
///
/// Возвращение списка названий коллекций
///
- public List Keys => _storages.Keys.ToList();
+ public List Keys => _storages.Keys.ToList();
///
/// Ключевое слово, с которого должен начинаться файл
@@ -41,7 +41,7 @@ public class StorageCollection
///
public StorageCollection()
{
- _storages = new Dictionary>();
+ _storages = new Dictionary>();
}
private readonly string _collectionKey = "CollectionsStorage";
@@ -58,18 +58,19 @@ public class StorageCollection
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());
+ _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects());
}
if (collectionType == CollectionType.Massive)
{
- _storages.Add(name, new MassiveGenericObjects());
+ _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects());
}
}
@@ -80,8 +81,8 @@ public class StorageCollection
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));
}
///
@@ -94,9 +95,9 @@ public class StorageCollection
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;
}
@@ -121,7 +122,7 @@ public class StorageCollection
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
- foreach (KeyValuePair> value in _storages)
+ foreach (KeyValuePair> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@@ -132,8 +133,6 @@ public class StorageCollection
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
- writer.Write(value.Value.GetCollectionType);
- writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
@@ -183,21 +182,23 @@ public class StorageCollection
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? collection = StorageCollection.CreateCollection(collectionType);
+ CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
+ throw new Exception("Не удалось определить информацию коллекции" + record[0]);
+ ICollectionGenericObjects? collection = StorageCollection.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)
@@ -216,7 +217,7 @@ public class StorageCollection
}
}
- _storages.Add(record[0], collection);
+ _storages.Add(collectionInfo, collection);
}
}
}
diff --git a/Battleship/Battleship/Drawings/DrawingWarshipCompareByType.cs b/Battleship/Battleship/Drawings/DrawingWarshipCompareByType.cs
new file mode 100644
index 0000000..57c7b78
--- /dev/null
+++ b/Battleship/Battleship/Drawings/DrawingWarshipCompareByType.cs
@@ -0,0 +1,34 @@
+namespace Battleship.Drawings;
+
+///
+/// Сравнение по типу, скорости, весу
+///
+internal class DrawingWarshipCompareByType : IComparer
+{
+ 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);
+ }
+}
diff --git a/Battleship/Battleship/Drawings/DrawingWarshipComparerByColor.cs b/Battleship/Battleship/Drawings/DrawingWarshipComparerByColor.cs
new file mode 100644
index 0000000..414eb89
--- /dev/null
+++ b/Battleship/Battleship/Drawings/DrawingWarshipComparerByColor.cs
@@ -0,0 +1,35 @@
+namespace Battleship.Drawings;
+
+///
+/// Сравнение по цвету, скорости, весу
+///
+public class DrawingWarshipComparerByColor : IComparer
+{
+ 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);
+ }
+}
diff --git a/Battleship/Battleship/Drawings/DrawingWarshipEqutables.cs b/Battleship/Battleship/Drawings/DrawingWarshipEqutables.cs
new file mode 100644
index 0000000..512ce10
--- /dev/null
+++ b/Battleship/Battleship/Drawings/DrawingWarshipEqutables.cs
@@ -0,0 +1,71 @@
+namespace Battleship.Drawings;
+
+using Battleship.Entities;
+using System.Diagnostics.CodeAnalysis;
+
+///
+/// Реализация сравнения двух объектов класса-прорисовки
+///
+public class DrawingWarshipEqutables : IEqualityComparer
+{
+ 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.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
+ {
+ 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();
+ }
+}
diff --git a/Battleship/Battleship/Exception/CollectionAlreadyExistsException.cs b/Battleship/Battleship/Exception/CollectionAlreadyExistsException.cs
new file mode 100644
index 0000000..10e1840
--- /dev/null
+++ b/Battleship/Battleship/Exception/CollectionAlreadyExistsException.cs
@@ -0,0 +1,17 @@
+using Battleship.CollectionGenericObjects;
+using System.Runtime.Serialization;
+
+namespace Battleship.Exceptions;
+
+///
+/// Класс, описывающий ошибку повторяющегося элемента в коллекции
+///
+[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) { }
+}
diff --git a/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs b/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs
index 37ed4b9..509d389 100644
--- a/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs
+++ b/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs
@@ -2,6 +2,9 @@
namespace Battleship.Exceptions;
+///
+/// Класс, описывающий ошибку, что позиция вышла за границы коллекции
+///
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
@@ -10,4 +13,4 @@ internal class PositionOutOfCollectionException : ApplicationException
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
-}
+}
\ No newline at end of file
diff --git a/Battleship/Battleship/FormWarshipCollection.Designer.cs b/Battleship/Battleship/FormWarshipCollection.Designer.cs
index a2f2871..dc367ab 100644
--- a/Battleship/Battleship/FormWarshipCollection.Designer.cs
+++ b/Battleship/Battleship/FormWarshipCollection.Designer.cs
@@ -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;
}
}
\ No newline at end of file
diff --git a/Battleship/Battleship/FormWarshipCollection.cs b/Battleship/Battleship/FormWarshipCollection.cs
index 62fcb05..0139428 100644
--- a/Battleship/Battleship/FormWarshipCollection.cs
+++ b/Battleship/Battleship/FormWarshipCollection.cs
@@ -80,7 +80,11 @@ public partial class FormWarshipCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
-
+ catch (CollectionAlreadyExistsException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
///
@@ -94,8 +98,7 @@ public partial class FormWarshipCollection : Form
{
return;
}
-
- if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
+ if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
@@ -182,7 +185,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);
@@ -231,8 +234,7 @@ public partial class FormWarshipCollection : Form
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
- MessageBox.Show("Коллекция не выбрана");
- return;
+ MessageBox.Show("Коллекция не выбрана"); return;
}
try
{
@@ -263,9 +265,7 @@ public partial class FormWarshipCollection : Form
return;
}
- ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
-
- if (collection == null)
+ ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
@@ -329,4 +329,50 @@ public partial class FormWarshipCollection : Form
}
}
}
+
+ ///
+ /// Сортировка по типу
+ ///
+ ///
+ ///
+ private void buttonSortByType_Click(object sender, EventArgs e)
+ {
+ CompareWarship(new DrawingWarshipCompareByType());
+ }
+
+ ///
+ /// Сортировка по цвету
+ ///
+ ///
+ ///
+ private void ButtonSortByColor_Click(object sender, EventArgs e)
+ {
+ CompareExcavators(new DrawingWarshipComparerByColor());
+ }
+
+ private void CompareExcavators(IComparer comparer)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+
+ _company.Sort(comparer);
+ pictureBox.Image = _company.Show();
+ }
+
+ ///
+ /// Сортировка по сравнителю
+ ///
+ /// Сравнитель объектов
+ private void CompareWarship(IComparer comparer)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+
+ _company.Sort(comparer);
+ pictureBox.Image = _company.Show();
+ }
}