diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs
index 7495e55..01d554d 100644
--- a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs
@@ -58,9 +58,13 @@ public abstract class AbstractCompany
///
public static int operator +(AbstractCompany company, DrawningShip ship)
{
- return company._collection.Insert(ship);
+ return company._collection.Insert(ship, new DrawningShipEqutables());
}
-
+ ///
+ /// Сортировка
+ ///
+ /// Сравнитель объектов
+ 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..ad3d1ee
--- /dev/null
+++ b/Battleship/Battleship/CollectionGenericObjects/CollectionInfo.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+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;
+ }
+
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка
+ /// Объект или null
+ 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 73a6aef..1fd1989 100644
--- a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -22,14 +22,14 @@ public interface ICollectionGenericObjects
///
/// Добавляемый объект
/// true - удачно, false - вставка не удалась
- int Insert(T obj);
+ int Insert(T obj, IEqualityComparer? comparer = null);
///
/// Добавление объекта в коллекцию на конкретную позицию
///
/// Добавляемый объект
/// Позиция
/// true - удачно, false - вставка не удалась
- bool Insert(T obj, int position);
+ bool Insert(T obj, int position, IEqualityComparer? comparer = null);
///
/// Удаление объекта из коллекции с конкретной позиции
@@ -54,4 +54,9 @@ public interface ICollectionGenericObjects
///
/// Поэлементый вывод элементов коллекции
IEnumerable GetItems();
+ ///
+ /// Сортировка коллекции
+ ///
+ /// Сравнитель объектов
+ void CollectionSort(IComparer comparer);
}
diff --git a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
index a86229f..8873a5c 100644
--- a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
@@ -46,22 +46,27 @@ public class ListGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
- if (_collection.Count + 1 <= _maxCount)
+ if (Count + 1 <= _maxCount)
{
+ if (_collection.Contains(obj, comparer))
+ throw new ObjectExistsException();
_collection.Add(obj);
- return _collection.Count - 1;
+ return Count - 1;
}
throw new CollectionOverflowException(MaxCount);
}
- public bool Insert(T obj, int position)
+ public bool Insert(T obj, int position, IEqualityComparer? comparer = null)
{
if (_collection.Count + 1 > MaxCount)
throw new CollectionOverflowException(MaxCount);
if (position < 0 || position >= MaxCount)
throw new PositionOutOfCollectionException(position);
+ if (_collection.Contains(obj, comparer))
+ throw new ObjectExistsException();
+
_collection.Insert(position, obj);
return true;
}
@@ -82,4 +87,8 @@ public class ListGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+ public void CollectionSort(IComparer comparer)
+ {
+ _collection.Sort(comparer);
+ }
}
diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
index bf51643..d987ee5 100644
--- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,5 @@
using Battleship.Exceptions;
+using System;
namespace Battleship.CollectionGenericObjects;
///
@@ -60,22 +61,27 @@ public class MassiveGenericObjects : ICollectionGenericObjects
throw new ObjectNotFoundException(position);
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
- for (int i = 0; i < _collection.Length; i++)
+ int index = Array.IndexOf(_collection, null);
+ if (_collection.Contains(obj, comparer))
+ throw new ObjectExistsException(index);
+
+ if (index >= 0)
{
- if (_collection[i] == null)
- {
- _collection[i] = obj;
- return i;
- }
+ _collection[index] = obj;
+ return index;
}
throw new CollectionOverflowException(_collection.Length);
}
- public bool Insert(T obj, int position)
+ public bool Insert(T obj, int position, IEqualityComparer? comparer = null)
{
if (position < 0 || position >= _collection.Length) // проверка позиции
throw new PositionOutOfCollectionException(position);
+
+ if (_collection.Contains(obj, comparer))
+ throw new ObjectExistsException(position);
+
if (_collection[position] == null) // Попытка вставить на указанную позицию
{
_collection[position] = obj;
@@ -118,4 +124,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+ public void CollectionSort(IComparer comparer)
+ {
+ if (_collection?.Length > 0)
+ {
+ Array.Sort(_collection, comparer);
+ Array.Reverse(_collection);
+ }
+
+ }
}
diff --git a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
index f649f2d..0f11ee9 100644
--- a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
@@ -1,5 +1,6 @@
using Battleship.Drawnings;
using Battleship.Exceptions;
+using Microsoft.AspNetCore.Http;
using System.Text;
namespace Battleship.CollectionGenericObjects;
@@ -14,12 +15,12 @@ public class StorageCollection
///
/// Словарь (хранилище) с коллекциями
///
- readonly Dictionary> _storages;
+ readonly Dictionary> _storages;
///
/// Возвращение списка названий коллекций
///
- public List Keys => _storages.Keys.ToList();
+ public List Keys => _storages.Keys.ToList();
///
/// Ключевое слово, с которого должен начинаться файл
@@ -41,7 +42,7 @@ public class StorageCollection
///
public StorageCollection()
{
- _storages = new Dictionary>();
+ _storages = new Dictionary>();
}
///
@@ -51,15 +52,16 @@ public class StorageCollection
/// тип коллекции
public void AddCollection(string name, CollectionType collectionType)
{
- if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
+ CollectionInfo tempInfo = new(name, collectionType, string.Empty);
+ if (string.IsNullOrEmpty(name) || _storages.ContainsKey(tempInfo))
return;
switch (collectionType)
{
case CollectionType.List:
- _storages.Add(name, new ListGenericObjects());
+ _storages.Add(tempInfo, new ListGenericObjects());
break;
case CollectionType.Massive:
- _storages.Add(name, new MassiveGenericObjects());
+ _storages.Add(tempInfo, new MassiveGenericObjects());
break;
default:
break;
@@ -72,8 +74,9 @@ public class StorageCollection
/// Название коллекции
public void DelCollection(string name)
{
- if (_storages.ContainsKey(name)) //??? спрросить, зачем проверка
- _storages.Remove(name);
+ CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
+ if (tempInfo.Name != null && _storages.ContainsKey(tempInfo))
+ _storages.Remove(tempInfo);
}
///
@@ -85,10 +88,10 @@ public class StorageCollection
{
get
{
- if (_storages.TryGetValue(name, out ICollectionGenericObjects? value))
- return value;
- return null;
- }
+ CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
+ if (tempInfo == null || !_storages.ContainsKey(tempInfo)) { return null; }
+ return _storages[tempInfo];
+ }
}
///
/// Сохранение информации по кораблям в хранилище в файл
@@ -97,31 +100,27 @@ public class StorageCollection
public void SaveData(string filename)
{
if (_storages.Count == 0)
- {
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
- }
if (File.Exists(filename))
- {
File.Delete(filename);
- }
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
- foreach (KeyValuePair> kvpair in _storages)
+ foreach (KeyValuePair> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
+
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
- sb.Append(kvpair.Value.GetCollectionType);
- sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
+
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@@ -143,9 +142,7 @@ public class StorageCollection
public void LoadData(string filename)
{
if (!File.Exists(filename))
- {
throw new FileNotFoundException("Файл не существует");
- }
using (StreamReader sr = new StreamReader(filename))
{
@@ -157,20 +154,19 @@ public class StorageCollection
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
- 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);
if (collection == null)
- {
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
- }
collection.MaxCount = Convert.ToInt32(record[2]);
- string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
+ string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
@@ -188,7 +184,7 @@ public class StorageCollection
}
}
}
- _storages.Add(record[0], collection);
+ _storages.Add(collectionInfo, collection);
}
}
}
diff --git a/Battleship/Battleship/Drawnings/DrawningCompareByColor.cs b/Battleship/Battleship/Drawnings/DrawningCompareByColor.cs
new file mode 100644
index 0000000..d55483b
--- /dev/null
+++ b/Battleship/Battleship/Drawnings/DrawningCompareByColor.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.Drawnings;
+public class DrawningCompareByColor : IComparer
+{
+ public int Compare(DrawningShip? x, DrawningShip? y)
+ {
+ if (x == null && y == null)
+ {
+ return 0;
+ }
+ if (x == null || x.EntityShip == null)
+ {
+ return -1;
+ }
+
+ if (y == null || y.EntityShip == null)
+ {
+ return 1;
+ }
+
+ if (x.EntityShip.BodyColor.Name != y.EntityShip.BodyColor.Name)
+ {
+ return x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
+ }
+
+ var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
+ if (speedCompare != 0)
+ {
+ return speedCompare;
+ }
+
+ return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
+ }
+}
diff --git a/Battleship/Battleship/Drawnings/DrawningCompareByType.cs b/Battleship/Battleship/Drawnings/DrawningCompareByType.cs
new file mode 100644
index 0000000..3874658
--- /dev/null
+++ b/Battleship/Battleship/Drawnings/DrawningCompareByType.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.Drawnings;
+
+public class DrawningCompareByType : IComparer
+{
+ public int Compare(DrawningShip? x, DrawningShip? y)
+ {
+ if (x == null && y == null)
+ {
+ return 0;
+ }
+ 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);
+ }
+}
diff --git a/Battleship/Battleship/Drawnings/DrawningShipEqutables.cs b/Battleship/Battleship/Drawnings/DrawningShipEqutables.cs
new file mode 100644
index 0000000..ddb63d7
--- /dev/null
+++ b/Battleship/Battleship/Drawnings/DrawningShipEqutables.cs
@@ -0,0 +1,68 @@
+using Battleship.Entities;
+using System.Diagnostics.CodeAnalysis;
+
+namespace Battleship.Drawnings;
+
+///
+/// Реализация сравнения двух объектов класса-прорисовки
+///
+public class DrawningShipEqutables : IEqualityComparer
+{
+ public bool Equals(DrawningShip? x, DrawningShip? 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 DrawningBattleship && y is DrawningBattleship)
+ {
+ EntityBattleship EntityX = (EntityBattleship)x.EntityShip;
+ EntityBattleship EntityY = (EntityBattleship)y.EntityShip;
+ if (EntityX.Rockets != EntityY.Rockets)
+ {
+ return false;
+ }
+ if (EntityX.Weapon != EntityY.Weapon)
+ {
+ return false;
+ }
+ if (EntityX.AdditionalColor != EntityY.AdditionalColor)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public int GetHashCode([DisallowNull] DrawningShip obj)
+ {
+ return obj.GetHashCode();
+ }
+}
\ No newline at end of file
diff --git a/Battleship/Battleship/Exceptions/ObjectExistsException.cs b/Battleship/Battleship/Exceptions/ObjectExistsException.cs
new file mode 100644
index 0000000..c654cd9
--- /dev/null
+++ b/Battleship/Battleship/Exceptions/ObjectExistsException.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.Exceptions;
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+internal class ObjectExistsException : ApplicationException
+{
+ public ObjectExistsException(int count) : base("Вставка существующего объекта") { }
+
+ public ObjectExistsException() : base() { }
+
+ public ObjectExistsException(string message) : base(message) { }
+
+ public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
+
+ protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
diff --git a/Battleship/Battleship/FormShipCollection.Designer.cs b/Battleship/Battleship/FormShipCollection.Designer.cs
index 2e3ea2c..3c37c34 100644
--- a/Battleship/Battleship/FormShipCollection.Designer.cs
+++ b/Battleship/Battleship/FormShipCollection.Designer.cs
@@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
+ buttonSortByType = new Button();
+ buttonSortByColor = new Button();
Tools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@@ -75,15 +77,17 @@
//
// panelCompanyTools
//
+ panelCompanyTools.Controls.Add(buttonSortByColor);
+ panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonGoToTest);
panelCompanyTools.Controls.Add(buttonDelShip);
panelCompanyTools.Enabled = false;
- panelCompanyTools.Location = new Point(0, 686);
+ panelCompanyTools.Location = new Point(0, 639);
panelCompanyTools.Name = "panelCompanyTools";
- panelCompanyTools.Size = new Size(488, 569);
+ panelCompanyTools.Size = new Size(488, 577);
panelCompanyTools.TabIndex = 8;
//
// buttonAddShip
@@ -91,7 +95,7 @@
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(9, 3);
buttonAddShip.Name = "buttonAddShip";
- buttonAddShip.Size = new Size(473, 90);
+ buttonAddShip.Size = new Size(473, 70);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавить корабль";
buttonAddShip.UseVisualStyleBackColor = true;
@@ -100,9 +104,9 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRefresh.Location = new Point(16, 432);
+ buttonRefresh.Location = new Point(12, 294);
buttonRefresh.Name = "buttonRefresh";
- buttonRefresh.Size = new Size(466, 90);
+ buttonRefresh.Size = new Size(473, 70);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -111,7 +115,7 @@
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- maskedTextBox.Location = new Point(12, 195);
+ maskedTextBox.Location = new Point(12, 97);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(470, 39);
@@ -121,9 +125,9 @@
// buttonGoToTest
//
buttonGoToTest.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonGoToTest.Location = new Point(16, 336);
+ buttonGoToTest.Location = new Point(12, 218);
buttonGoToTest.Name = "buttonGoToTest";
- buttonGoToTest.Size = new Size(466, 90);
+ buttonGoToTest.Size = new Size(473, 70);
buttonGoToTest.TabIndex = 5;
buttonGoToTest.Text = "Передать на тест";
buttonGoToTest.UseVisualStyleBackColor = true;
@@ -132,9 +136,9 @@
// buttonDelShip
//
buttonDelShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonDelShip.Location = new Point(12, 240);
+ buttonDelShip.Location = new Point(12, 142);
buttonDelShip.Name = "buttonDelShip";
- buttonDelShip.Size = new Size(473, 90);
+ buttonDelShip.Size = new Size(473, 70);
buttonDelShip.TabIndex = 4;
buttonDelShip.Text = "Удалить корабль";
buttonDelShip.UseVisualStyleBackColor = true;
@@ -142,9 +146,9 @@
//
// buttonCreateCompany
//
- buttonCreateCompany.Location = new Point(9, 612);
+ buttonCreateCompany.Location = new Point(6, 584);
buttonCreateCompany.Name = "buttonCreateCompany";
- buttonCreateCompany.Size = new Size(473, 68);
+ buttonCreateCompany.Size = new Size(473, 49);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@@ -162,7 +166,7 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 35);
panelStorage.Name = "panelStorage";
- panelStorage.Size = new Size(482, 512);
+ panelStorage.Size = new Size(482, 497);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
@@ -238,7 +242,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Доки" });
- comboBoxSelectorCompany.Location = new Point(9, 566);
+ comboBoxSelectorCompany.Location = new Point(6, 538);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(476, 40);
comboBoxSelectorCompany.TabIndex = 0;
@@ -294,6 +298,26 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
+ // buttonSortByType
+ //
+ buttonSortByType.Location = new Point(12, 389);
+ buttonSortByType.Name = "buttonSortByType";
+ buttonSortByType.Size = new Size(473, 70);
+ buttonSortByType.TabIndex = 7;
+ buttonSortByType.Text = "Сортировка по типу";
+ buttonSortByType.UseVisualStyleBackColor = true;
+ buttonSortByType.Click += buttonSortByType_Click;
+ //
+ // buttonSortByColor
+ //
+ buttonSortByColor.Location = new Point(3, 465);
+ buttonSortByColor.Name = "buttonSortByColor";
+ buttonSortByColor.Size = new Size(473, 70);
+ buttonSortByColor.TabIndex = 8;
+ buttonSortByColor.Text = "Сортировка по цвету";
+ buttonSortByColor.UseVisualStyleBackColor = true;
+ buttonSortByColor.Click += buttonSortByColor_Click;
+ //
// FormShipCollection
//
AutoScaleDimensions = new SizeF(13F, 32F);
@@ -343,5 +367,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
+ private Button buttonSortByType;
+ private Button buttonSortByColor;
}
}
\ No newline at end of file
diff --git a/Battleship/Battleship/FormShipCollection.cs b/Battleship/Battleship/FormShipCollection.cs
index 55c7cd7..2dd7628 100644
--- a/Battleship/Battleship/FormShipCollection.cs
+++ b/Battleship/Battleship/FormShipCollection.cs
@@ -20,11 +20,11 @@ public partial class FormShipCollection : Form
/// Конструктор
///
public FormShipCollection(ILogger logger)
- {
- InitializeComponent();
- _storageCollection = new();
- _logger = logger;
- }
+ {
+ InitializeComponent();
+ _storageCollection = new();
+ _logger = logger;
+ }
#region Работа с компанией
///
/// Выбор компании
@@ -56,11 +56,16 @@ public partial class FormShipCollection : Form
_logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", ship);
}
}
- catch(CollectionOverflowException ex)
+ catch (CollectionOverflowException ex)
{
MessageBox.Show("Ошибка переполнения коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
+ catch (ObjectExistsException ex)
+ {
+ MessageBox.Show("Такой объект есть в коллекции");
+ _logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
+ }
}
///
/// Кнопка удаления корабля
@@ -93,7 +98,7 @@ public partial class FormShipCollection : Form
_logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos);
}
}
- catch(ObjectNotFoundException ex)
+ catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
@@ -166,7 +171,7 @@ public partial class FormShipCollection : Form
form.AddEvent(SetShip);
form.Show();
}
-
+
#endregion
#region Работа с коллекцией
///
@@ -222,7 +227,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);
@@ -273,12 +278,13 @@ public partial class FormShipCollection : Form
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- try {
+ try
+ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
- catch(Exception ex)
+ catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
@@ -308,4 +314,33 @@ public partial class FormShipCollection : Form
}
}
}
+ ///
+ /// Сортировка по типу
+ ///
+ ///
+ ///
+ private void buttonSortByType_Click(object sender, EventArgs e)
+ {
+ CompareShips(new DrawningCompareByType());
+ }
+
+ private void buttonSortByColor_Click(object sender, EventArgs e)
+ {
+ CompareShips(new DrawningCompareByColor());
+
+ }
+ ///
+ /// Сортировка по сравнителю
+ ///
+ /// Сравнитель объектов
+ private void CompareShips(IComparer comparer)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+
+ _company.Sort(comparer);
+ pictureBox.Image = _company.Show();
+ }
}