diff --git a/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs b/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs
index e17901a..4c8e110 100644
--- a/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs
+++ b/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs
@@ -62,7 +62,7 @@ public abstract class AbstractCompany
///
public static int operator +(AbstractCompany company, DrawingShip ship)
{
- return company._collection.Insert(ship);
+ return company._collection.Insert(ship, new DrawingShipEqutables());
}
///
@@ -111,4 +111,5 @@ public abstract class AbstractCompany
protected abstract void SetObjectsPosition();
protected abstract void DrawBackground(Graphics g);
+ public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer);
}
diff --git a/Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs b/Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs
new file mode 100644
index 0000000..e837095
--- /dev/null
+++ b/Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs
@@ -0,0 +1,75 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Cruiser.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/Cruiser/Cruiser/CollectionGenericObjects/CollectionType.cs b/Cruiser/Cruiser/CollectionGenericObjects/CollectionType.cs
index ab2f253..43fd4c1 100644
--- a/Cruiser/Cruiser/CollectionGenericObjects/CollectionType.cs
+++ b/Cruiser/Cruiser/CollectionGenericObjects/CollectionType.cs
@@ -8,7 +8,7 @@ namespace Cruiser.CollectionGenericObjects;
public enum CollectionType
{
- None = 1,
+ None = 0,
Massive = 1,
List = 2
}
diff --git a/Cruiser/Cruiser/CollectionGenericObjects/ICollectionGenericObjects.cs b/Cruiser/Cruiser/CollectionGenericObjects/ICollectionGenericObjects.cs
index c1197b9..9a38f2a 100644
--- a/Cruiser/Cruiser/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/Cruiser/Cruiser/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using Cruiser.Drawings;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -24,7 +25,7 @@ public interface ICollectionGenericObjects
///
///
///
- int Insert(T obj);
+ int Insert(T obj, IEqualityComparer? comarer = null);
///
/// Добавление в коллекцию по индексу
@@ -32,7 +33,7 @@ public interface ICollectionGenericObjects
///
///
///
- int Insert(T obj, int position);
+ int Insert(T obj, int position, IEqualityComparer? comarer = null);
///
/// Удаление из коллекции по индесу
@@ -58,4 +59,6 @@ public interface ICollectionGenericObjects
///
/// Поэлементый вывод элементов коллекции
IEnumerable GetItems();
+
+ void CollectionSort(IComparer comparer);
}
diff --git a/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs b/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs
index 5689d25..8f8db20 100644
--- a/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs
+++ b/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,8 +1,10 @@
using System;
+using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using Cruiser.Drawings;
using Cruiser.Exceptions;
namespace Cruiser.CollectionGenericObjects;
@@ -53,17 +55,31 @@ public class ListGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException();
+ if (comparer != null)
+ {
+ if (_collection.Contains(obj, comparer))
+ {
+ throw new ObjectAlreadyExistsException(obj);
+ }
+ }
_collection.Add(obj);
return Count;
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException();
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
+ if (comparer != null)
+ {
+ if (_collection.Contains(obj, comparer))
+ {
+ throw new ObjectAlreadyExistsException(obj);
+ }
+ }
_collection.Insert(position, obj);
return position;
}
@@ -83,4 +99,9 @@ public class ListGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+ public void CollectionSort(IComparer comparer)
+ {
+ _collection.Sort(comparer);
+ }
}
diff --git a/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs b/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs
index b818bd9..018def7 100644
--- a/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -51,9 +51,19 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
- for (int i = 0; i < _collection.Length; i++)
+ if (comparer != null)
+ {
+ foreach (T? i in _collection)
+ {
+ if (comparer.Equals(i, obj))
+ {
+ throw new ObjectAlreadyExistsException(i);
+ }
+ }
+ }
+ for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
@@ -64,9 +74,21 @@ public class MassiveGenericObjects : ICollectionGenericObjects
throw new CollectionOverflowException();
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
+
+ if (comparer != null)
+ {
+ foreach (T? i in _collection)
+ {
+ if (comparer.Equals(i, obj))
+ {
+ throw new ObjectAlreadyExistsException(i);
+ }
+ }
+ }
+
if (_collection[position] == null)
{
_collection[position] = obj;
@@ -111,6 +133,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+ public void CollectionSort(IComparer comparer)
+ {
+ Array.Sort(_collection, comparer);
+ }
}
diff --git a/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs b/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs
index 935a800..9539790 100644
--- a/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs
+++ b/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs
@@ -14,12 +14,12 @@ public class StorageCollection where T : DrawingShip
///
/// Словарь (хранилище) с коллекциями
///
- readonly Dictionary> _storages;
+ readonly Dictionary> _storages;
///
/// Возвращение списка названий коллекций
///
- public List Keys => _storages.Keys.ToList();
+ public List Keys => _storages.Keys.ToList();
///
/// Ключевое слово, с которого должен начинаться файл
@@ -29,7 +29,7 @@ public class StorageCollection where T : DrawingShip
///
/// Разделитель для записи ключа и значения элемента словаря
///
- private readonly string _separatorForKeyValue = "|";
+ private readonly string _separatorKeyValue = "|";
///
/// Разделитель для записей коллекции данных в файл
@@ -41,7 +41,7 @@ public class StorageCollection where T : DrawingShip
///
public StorageCollection()
{
- _storages = new Dictionary>();
+ _storages = new Dictionary>();
}
@@ -54,43 +54,47 @@ public class StorageCollection where T : DrawingShip
{
if (_storages.Count == 0)
{
- throw new Exception("В хранилище отсутствуют коллекции для сохранения");
+ throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
- StringBuilder sb = new();
- sb.Append(_collectionKey);
- foreach (KeyValuePair> value in
- _storages)
+
+
+ using (StreamWriter writer = new(filename))
{
- sb.Append(Environment.NewLine);
- // не сохраняем пустые коллекции
- if (value.Value.Count == 0)
+ writer.Write(_collectionKey);
+ foreach (KeyValuePair> value in _storages)
{
- continue;
- }
- sb.Append(value.Key);
- sb.Append(_separatorForKeyValue);
- sb.Append(value.Value.GetCollectionType);
- sb.Append(_separatorForKeyValue);
- sb.Append(value.Value.MaxCount);
- sb.Append(_separatorForKeyValue);
- foreach (T? item in value.Value.GetItems())
- {
- string data = item?.GetDataForSave() ?? string.Empty;
- if (string.IsNullOrEmpty(data))
+ writer.Write(Environment.NewLine);
+ if (value.Value.Count == 0)
{
continue;
}
- sb.Append(data);
- sb.Append(_separatorItems);
+
+ writer.Write(value.Key);
+ writer.Write(_separatorKeyValue);
+
+ writer.Write(value.Value.MaxCount);
+ writer.Write(_separatorKeyValue);
+
+ foreach (T? item in value.Value.GetItems())
+ {
+ string data = item?.GetDataForSave() ?? string.Empty;
+ if (string.IsNullOrEmpty(data))
+ {
+ continue;
+ }
+
+ writer.Write(data);
+ writer.Write(_separatorItems);
+ }
}
+ writer.Close();
+
}
- using FileStream fs = new(filename, FileMode.Create);
- byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
- fs.Write(info, 0, info.Length);
+
}
///
@@ -102,68 +106,66 @@ public class StorageCollection where T : DrawingShip
{
if (!File.Exists(filename))
{
- throw new FileNotFoundException("Файл не существует");
- }
- string bufferTextFromFile = "";
- using (FileStream fs = new(filename, FileMode.Open))
- {
- byte[] b = new byte[fs.Length];
- UTF8Encoding temp = new(true);
- while (fs.Read(b, 0, b.Length) > 0)
- {
- bufferTextFromFile += temp.GetString(b);
- }
- }
- string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
- StringSplitOptions.RemoveEmptyEntries);
- if (strs == null || strs.Length == 0)
- {
- throw new Exception("В файле нет данных");
- }
- if (!strs[0].Equals(_collectionKey))
- {
- throw new Exception("В файле неверные данные");
- }
- _storages.Clear();
- foreach (string data in strs)
- {
- string[] record = data.Split(_separatorForKeyValue,
- StringSplitOptions.RemoveEmptyEntries);
- if (record.Length != 4)
- {
- continue;
- }
- CollectionType collectionType =
- (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
- ICollectionGenericObjects? collection =
- StorageCollection.CreateCollection(collectionType);
- if (collection == null)
- {
- throw new Exception("Не удалось создать коллекцию");
- }
- collection.MaxCount = Convert.ToInt32(record[2]);
- string[] set = record[3].Split(_separatorItems,
- StringSplitOptions.RemoveEmptyEntries);
- foreach (string elem in set)
- {
- if (elem?.CreateDrawingShip() is T ship)
- {
- try
- {
- if (collection.Insert(ship) == -1)
- {
- throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
- }
- }
- catch (CollectionOverflowException ex)
- {
- throw new DataException("Коллекция переполнена", ex);
- }
- }
- }
- _storages.Add(record[0], collection);
+ throw new FileNotFoundException("Файл не существует!");
}
+ using (StreamReader reader = new(filename))
+ {
+ string line = reader.ReadLine();
+ if (line == null || line.Length == 0)
+ {
+ throw new ArgumentException("В файле нет данных");
+ }
+ if (!line.Equals(_collectionKey))
+ {
+ throw new InvalidDataException("В файле неверные данные");
+ }
+
+ _storages.Clear();
+ while ((line = reader.ReadLine()) != null)
+ {
+ string[] record = line.Split(_separatorKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ if (record.Length != 3)
+ {
+ continue;
+ }
+
+ //CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
+ 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 InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
+
+ }
+
+ collection.MaxCount = Convert.ToInt32(record[1]);
+
+ string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
+ {
+ if (elem?.CreateDrawingShip() is T ship)
+ {
+ try
+ {
+ if (collection.Insert(ship) < 0)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new CollectionOverflowException("Коллекция переполнена", ex);
+ }
+
+ }
+ }
+ _storages.Add(collectionInfo, collection);
+
+ }
+ }
}
///
@@ -188,19 +190,23 @@ public class StorageCollection where T : DrawingShip
/// Тип коллекции
public void AddCollection(string name, CollectionType collectionType)
{
- if (_storages.ContainsKey(name))// || collectionType == CollectionType.None)
+ CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
+
+ if (name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
switch (collectionType)
{
+ case CollectionType.None:
+ return;
case CollectionType.Massive:
- _storages[name] = new MassiveGenericObjects();
- break;
+ _storages[collectionInfo] = new MassiveGenericObjects();
+ return;
case CollectionType.List:
- _storages[name] = new ListGenericObjects();
- break;
+ _storages[collectionInfo] = new ListGenericObjects();
+ return;
}
}
@@ -210,9 +216,10 @@ public class StorageCollection where T : DrawingShip
/// Название коллекции
public void DelCollection(string name)
{
- if (_storages.ContainsKey(name) && name != null)
+ CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
+ if (_storages.ContainsKey(collectionInfo))
{
- _storages.Remove(name);
+ _storages.Remove(collectionInfo);
}
}
@@ -225,11 +232,12 @@ public class StorageCollection where T : DrawingShip
{
get
{
- if (_storages.ContainsKey(name))
+ CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
+ if (!_storages.ContainsKey(collectionInfo))
{
- return _storages[name];
+ return null;
}
- return null;
+ return _storages[collectionInfo];
}
}
}
\ No newline at end of file
diff --git a/Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs b/Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs
new file mode 100644
index 0000000..e9f24f1
--- /dev/null
+++ b/Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Cruiser.Drawings;
+
+public class DrawingShipCompareByColor : IComparer
+{
+ public int Compare(DrawingShip? x, DrawingShip? y)
+ {
+ if (x == null || x.EntityShip == null)
+ {
+ return 1;
+ }
+
+ if (y == null || y.EntityShip == null)
+ {
+ return -1;
+ }
+ var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
+ if (bodycolorCompare != 0)
+ {
+ return bodycolorCompare;
+ }
+ 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/Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs b/Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs
new file mode 100644
index 0000000..c66747d
--- /dev/null
+++ b/Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Cruiser.Drawings;
+
+namespace Cruiser.CollectionGenericObjects;
+
+public class DrawingShipCompareByType : IComparer
+{
+ public int Compare(DrawingShip? x, DrawingShip? y)
+ {
+ 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/Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs b/Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs
new file mode 100644
index 0000000..9dba285
--- /dev/null
+++ b/Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs
@@ -0,0 +1,56 @@
+using Cruiser.Entities;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Security.Cryptography.Xml;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Cruiser.Drawings;
+
+public class DrawingShipEqutables : IEqualityComparer
+{
+ public bool Equals(DrawingShip? x, DrawingShip? 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 DrawingCruiser && y is DrawingCruiser)
+ {
+ EntityCruiser crx = (EntityCruiser)x.EntityShip;
+ EntityCruiser cry = (EntityCruiser)y.EntityShip;
+ if (crx.Helicopter != cry.Helicopter) return false;
+ if (crx.BodyKit != cry.BodyKit) return false;
+ if (crx.Arms != cry.Arms) return false;
+ if (crx.AdditionalColor != cry.AdditionalColor) return false;
+ }
+ return true;
+ }
+
+ public int GetHashCode([DisallowNull] DrawingShip obj)
+ {
+ return obj.GetHashCode();
+ }
+}
diff --git a/Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs b/Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs
new file mode 100644
index 0000000..84b1c6b
--- /dev/null
+++ b/Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs
@@ -0,0 +1,19 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Cruiser.Exceptions;
+
+[Serializable]
+public class ObjectAlreadyExistsException : ApplicationException
+{
+ public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { }
+ public ObjectAlreadyExistsException() : base() { }
+ public ObjectAlreadyExistsException(string message) : base(message) { }
+ public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception)
+ { }
+ protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+}
diff --git a/Cruiser/Cruiser/FormShipCollection.Designer.cs b/Cruiser/Cruiser/FormShipCollection.Designer.cs
index 548682e..53e0b67 100644
--- a/Cruiser/Cruiser/FormShipCollection.Designer.cs
+++ b/Cruiser/Cruiser/FormShipCollection.Designer.cs
@@ -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();
@@ -68,7 +70,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(852, 28);
groupBoxTools.Name = "groupBoxTools";
- groupBoxTools.Size = new Size(324, 742);
+ groupBoxTools.Size = new Size(324, 841);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -97,15 +99,17 @@
//
// panelCompanyTools
//
+ panelCompanyTools.Controls.Add(buttonSortByColor);
+ panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRemoveShip);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Enabled = false;
- panelCompanyTools.Location = new Point(12, 446);
+ panelCompanyTools.Location = new Point(12, 415);
panelCompanyTools.Name = "panelCompanyTools";
- panelCompanyTools.Size = new Size(300, 300);
+ panelCompanyTools.Size = new Size(300, 414);
panelCompanyTools.TabIndex = 2;
//
// buttonRefresh
@@ -248,7 +252,7 @@
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 28);
pictureBoxCollection.Name = "pictureBoxCollection";
- pictureBoxCollection.Size = new Size(852, 742);
+ pictureBoxCollection.Size = new Size(852, 841);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
@@ -288,17 +292,38 @@
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
-
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
+ // buttonSortByColor
+ //
+ buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
+ buttonSortByColor.Location = new Point(19, 335);
+ buttonSortByColor.Name = "buttonSortByColor";
+ buttonSortByColor.Size = new Size(240, 52);
+ buttonSortByColor.TabIndex = 8;
+ buttonSortByColor.Text = "Сортировка по цвету";
+ buttonSortByColor.UseVisualStyleBackColor = true;
+ buttonSortByColor.Click += ButtonSortByColor_Click;
+ //
+ // buttonSortByType
+ //
+ buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
+ buttonSortByType.Location = new Point(19, 277);
+ buttonSortByType.Name = "buttonSortByType";
+ buttonSortByType.Size = new Size(240, 52);
+ buttonSortByType.TabIndex = 7;
+ buttonSortByType.Text = "Сортировка по типу";
+ buttonSortByType.UseVisualStyleBackColor = true;
+ buttonSortByType.Click += ButtonSortByType_Click;
+ //
// FormShipCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(1176, 770);
+ ClientSize = new Size(1176, 869);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@@ -343,5 +368,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
+ private Button buttonSortByColor;
+ private Button buttonSortByType;
}
}
\ No newline at end of file
diff --git a/Cruiser/Cruiser/FormShipCollection.cs b/Cruiser/Cruiser/FormShipCollection.cs
index 3717582..f230dbf 100644
--- a/Cruiser/Cruiser/FormShipCollection.cs
+++ b/Cruiser/Cruiser/FormShipCollection.cs
@@ -39,6 +39,11 @@ public partial class FormShipCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: В коллекции превышено допустимое количество");
}
+ catch (ObjectAlreadyExistsException)
+ {
+ MessageBox.Show("Такой объект уже существует");
+ _logger.LogError("Ошибка: такой объект уже существует {0}", ship);
+ }
}
@@ -105,7 +110,7 @@ public partial class FormShipCollection : Form
{
DrawingShip? ship = null;
int counter = 100;
- while(ship == null)
+ while (ship == null)
{
ship = _company.GetRandomObject();
counter--;
@@ -136,27 +141,27 @@ public partial class FormShipCollection : Form
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
- if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
- {
- MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
+ if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonMassive.Checked && !radioButtonList.Checked))
+ {
+ MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Неверно введены данные для создания коллекции");
+ return;
+ }
- CollectionType collectionType = CollectionType.None;
- if (radioButtonList.Checked)
- {
- collectionType = CollectionType.List;
- }
- else if (radioButtonMassive.Checked)
- {
- collectionType = CollectionType.Massive;
- }
+ CollectionType collectionType = CollectionType.None;
+ if (radioButtonMassive.Checked)
+ {
+ collectionType = CollectionType.Massive;
+ }
+ else if (radioButtonList.Checked)
+ {
+ collectionType = CollectionType.List;
+ }
-
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
- RefreshListBoxItems();
- _logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
- }
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ _logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}");
+ RefreshListBoxItems();
+ }
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
@@ -180,7 +185,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);
@@ -225,9 +230,9 @@ public partial class FormShipCollection : Form
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- _logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
+ _logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
}
- catch(Exception ex)
+ catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
@@ -259,4 +264,18 @@ public partial class FormShipCollection : Form
}
}
}
+
+ private void ButtonSortByType_Click(object sender, EventArgs e) => CompareShips(new DrawingShipCompareByType());
+
+ private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new DrawingShipCompareByColor());
+
+ private void CompareShips(IComparer comparer)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+ _company.Sort(comparer);
+ pictureBoxCollection.Image = _company.Show();
+ }
}