diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs index 5dd6c68..7ffb05a 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs @@ -55,7 +55,8 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawingWarship warship) { - return company._collection?.Insert(warship, new DrawiningWarshipEqutables()) ?? 0; + return company._collection?.Insert(warship, new DrawingWarshipEqutables()) ?? + throw new DrawningEquitablesException(); } /// /// Перегрузка оператора удаления для класса @@ -81,7 +82,7 @@ public abstract class AbstractCompany /// Сортировка /// /// Сравнитель объектов - public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод всей коллекции /// diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/CollectionInfo.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..754df0d --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,82 @@ +namespace ProjectBattleship.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 bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs index 821add1..5534751 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -22,25 +22,23 @@ where T : class /// Добавление объекта в коллекцию /// /// Добавляемый объект - /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, IEqualityComparer? comparer = null); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция - /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position, IEqualityComparer? comparer = null); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось - T? Remove(int position); + T Remove(int position); /// /// Получение объекта по позиции diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs index 69193fd..5af053c 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs @@ -3,7 +3,7 @@ using ProjectBattleship.DrawingObject; using ProjectBattleship.Exceptions; -namespace Battleship.CollectionGenericObjects; +namespace ProjectBattleship.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -53,10 +53,9 @@ where T : class return _collection[position]; } - public int Insert(T obj, IEqualityComparer? comparer = null) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOverflowException(Count); - if (comparer != null) { for (int i = 0; i < Count; i++) @@ -71,8 +70,7 @@ where T : class _collection.Add(obj); return Count; } - - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); @@ -88,7 +86,6 @@ where T : class } } - _collection.Insert(position, obj); return position; } @@ -108,7 +105,6 @@ where T : class yield return _collection[i]; } } - public void CollectionSort(IComparer comparer) { _collection.Sort(comparer); diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs index 0b7b054..025c4f3 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -2,7 +2,7 @@ using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.DrawingObject; -namespace Battleship.CollectionGenericObjects; +namespace ProjectBattleship.CollectionGenericObjects; /// /// Параметризованный набор объектов /// @@ -61,7 +61,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj, IEqualityComparer? comparer = null) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (comparer != null) { @@ -74,6 +74,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + // вставка в свободное место набора for (int i = 0; i < Count; i++) { @@ -87,7 +88,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); @@ -135,14 +136,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - // вставка _collection[position] = obj; return position; } + public T? Remove(int position) { - // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); @@ -151,6 +151,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; ++i) @@ -158,7 +159,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } - public void CollectionSort(IComparer comparer) { List value = new List(_collection); diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs index 911b109..f799f5a 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs @@ -1,23 +1,20 @@ -using ProjectBattleship.CollectionGenericObjects; +using ProjectBattleship.Exceptions; using ProjectBattleship.DrawingObject; -using ProjectBattleship.Exceptions; +using System.Text; -namespace Battleship.CollectionGenericObjects; +namespace ProjectBattleship.CollectionGenericObjects; -/// -/// Класс-хранилище коллекций -/// -/// -public class StorageCollection where T : DrawingWarship +public class StorageCollection + where T : DrawingWarship { /// /// Словарь (хранилище) с коллекциями /// - private Dictionary> _storages; + private Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -39,166 +36,170 @@ public class StorageCollection where T : DrawingWarship /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } + /// /// Добавление коллекции в хранилище /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + /// тип коллекции + public void AddCollection(CollectionInfo collectionInfo) { - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) - return; - switch (collectionType) - { - case CollectionType.List: - _storages.Add(name, new ListGenericObjects()); - break; - case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects()); - break; - default: - break; - } + if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo); + if (collectionInfo.CollectionType == CollectionType.None) + throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionInfo.CollectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionInfo.CollectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); } /// /// Удаление коллекции /// - /// Название коллекции - public void DelCollection(string name) + /// тип коллекции + public void DelCollection(CollectionInfo collectionInfo) { - if (_storages.ContainsKey(name)) { _storages.Remove(name); } + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } + /// /// Доступ к коллекции /// - /// Название коллекции + /// /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { - if (_storages.TryGetValue(name, out ICollectionGenericObjects? value)) - return value; + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } + /// - /// Сохранение информации по самолетам в хранилище в файл + /// Сохранение информации по самолетам в файл /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных + /// + /// public void SaveData(string filename) { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new EmptyFileException(); } - if (File.Exists(filename)) { File.Delete(filename); } - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter streamWriter = new StreamWriter(fs); - streamWriter.Write(_collectionKey); - - foreach (KeyValuePair> value in _storages) + using (StreamWriter writer = new StreamWriter(filename)) { - streamWriter.Write(Environment.NewLine); - - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - - streamWriter.Write(value.Key); - streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.MaxCount); - streamWriter.Write(_separatorForKeyValue); - - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + StringBuilder sb = new(); + sb.Append(Environment.NewLine); + if (value.Value.Count == 0) { continue; } + sb.Append(value.Key); + 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)) + { + continue; + } - streamWriter.Write(data); - streamWriter.Write(_separatorItems); + sb.Append(data); + sb.Append(_separatorItems); + } + writer.Write(sb); } } } /// - /// Загрузка информации по кораблям в хранилище из файла + /// Загрузка информации по автомобилям в хранилище из файла /// - /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { if (!File.Exists(filename)) { - throw new System.IO.FileNotFoundException("Файл не существует"); + throw new Exceptions.FileNotFoundException(filename); } - using (StreamReader sr = new StreamReader(filename)) + using (StreamReader fs = File.OpenText(filename)) { - string? str; - str = sr.ReadLine(); - if (str != _collectionKey.ToString()) - throw new FormatException("В файле неверные данные"); - _storages.Clear(); - while ((str = sr.ReadLine()) != null) + string str = fs.ReadLine(); + if (string.IsNullOrEmpty(str)) { - string[] record = str.Split(_separatorForKeyValue); - if (record.Length != 4) + throw new EmptyFileException(filename); + } + + if (!str.StartsWith(_collectionKey)) + { + throw new Exceptions.FileFormatException(filename); + } + + _storages.Clear(); + string strs = ""; + while ((strs = fs.ReadLine()) != null) + { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawingWarship() is T Warship) + if (elem?.CreateDrawingWarship() is T ship) { try { - if (collection.Insert(Warship) == -1) - { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(ship); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new CollectionOverflowException("Коллекция переполнена", ex); + throw new Exceptions.FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } } } - private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) => collectionType switch + private static ICollectionGenericObjects? + CreateCollection(CollectionType collectionType) { - CollectionType.Massive => new MassiveGenericObjects(), - CollectionType.List => new ListGenericObjects(), - _ => null, - }; + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByColor.cs b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByColor.cs index e480ffd..59d788f 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByColor.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByColor.cs @@ -1,5 +1,5 @@ using ProjectBattleship.DrawingObject; -namespace Battleship; +namespace ProjectBattleship; public class DrawingWarshipCompareByColor : IComparer { diff --git a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByType.cs b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByType.cs index 763b300..9942b7a 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByType.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipCompareByType.cs @@ -1,5 +1,5 @@ using ProjectBattleship.DrawingObject; -namespace Battleship; +namespace ProjectBattleship; public class DrawingWarshipCompareByType : IComparer { diff --git a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipEquitables.cs b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipEquitables.cs index 366b193..6d4465a 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipEquitables.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarshipEquitables.cs @@ -4,7 +4,7 @@ namespace ProjectBattleship.DrawingObject; /// /// Реализация сравнения двух объектов класса-прорисовки /// -public class DrawiningWarshipEqutables : IEqualityComparer +public class DrawingWarshipEqutables : IEqualityComparer { public bool Equals(DrawingWarship? x, DrawingWarship? y) { diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/CollectionAlreadyExistsException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/CollectionAlreadyExistsException.cs index f9fa8a4..b260f09 100644 --- a/ProjectBattleship/ProjectBattleship/Exceptions/CollectionAlreadyExistsException.cs +++ b/ProjectBattleship/ProjectBattleship/Exceptions/CollectionAlreadyExistsException.cs @@ -1,9 +1,10 @@ using System.Runtime.Serialization; +using ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.Exceptions; public class CollectionAlreadyExistsException : Exception { public CollectionAlreadyExistsException() : base() { } - public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } + public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { } public CollectionAlreadyExistsException(string name, Exception exception) : base($"Коллекция {name} уже существует!", exception) { } diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/EmptyFileException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/EmptyFileException.cs new file mode 100644 index 0000000..1f11729 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/Exceptions/EmptyFileException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; +namespace ProjectBattleship.Exceptions; + +public class EmptyFileException : Exception +{ + public EmptyFileException(string name) : base($"Файл {name} пустой ") { } + public EmptyFileException() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileException(string name, string message) : base(message) { } + public EmptyFileException(string name, string message, Exception exception) : + base(message, exception) + { } + protected EmptyFileException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/EmptyFileExeption.cs b/ProjectBattleship/ProjectBattleship/Exceptions/EmptyFileExeption.cs deleted file mode 100644 index 87539db..0000000 --- a/ProjectBattleship/ProjectBattleship/Exceptions/EmptyFileExeption.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Runtime.Serialization; -namespace ProjectBattleship.Exceptions; - -public class EmptyFileExeption : Exception -{ - public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { } - public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { } - public EmptyFileExeption(string name, string message) : base(message) { } - public EmptyFileExeption(string name, string message, Exception exception) : - base(message, exception) - { } - protected EmptyFileExeption(SerializationInfo info, StreamingContext - contex) : base(info, contex) { } -} diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs index 243f0ef..d7b93b1 100644 --- a/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs @@ -9,8 +9,8 @@ internal class PositionOutOfCollectionException : ApplicationException public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } public PositionOutOfCollectionException() : base() { } public PositionOutOfCollectionException(string message) : base(message) { } - public PositionOutOfCollectionException(string message, Exception - exception) : base(message, exception) { } + public PositionOutOfCollectionException(string message, Exception + exception) : base(message, exception) { } protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs index c1efc3d..873fdc8 100644 --- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs +++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs @@ -32,6 +32,8 @@ namespace ProjectBattleship { groupBoxCollectionTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonRefresh = new Button(); maskedTextBoxPosition = new MaskedTextBox(); buttonAddWarship = new Button(); @@ -70,13 +72,15 @@ namespace ProjectBattleship groupBoxCollectionTools.Controls.Add(panelCollection); groupBoxCollectionTools.Location = new Point(699, 27); groupBoxCollectionTools.Name = "groupBoxCollectionTools"; - groupBoxCollectionTools.Size = new Size(279, 653); + groupBoxCollectionTools.Size = new Size(279, 639); groupBoxCollectionTools.TabIndex = 1; groupBoxCollectionTools.TabStop = false; groupBoxCollectionTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonAddWarship); @@ -85,9 +89,29 @@ namespace ProjectBattleship panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(6, 354); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(267, 208); + panelCompanyTools.Size = new Size(267, 279); panelCompanyTools.TabIndex = 11; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(8, 243); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(251, 34); + buttonSortByColor.TabIndex = 13; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(8, 203); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(251, 34); + buttonSortByType.TabIndex = 12; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // buttonRefresh // buttonRefresh.Location = new Point(8, 163); @@ -244,7 +268,7 @@ namespace ProjectBattleship pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; pictureBox.Location = new Point(0, 51); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(688, 602); + pictureBox.Size = new Size(688, 615); pictureBox.TabIndex = 2; pictureBox.TabStop = false; // @@ -293,7 +317,7 @@ namespace ProjectBattleship // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(978, 653); + ClientSize = new Size(978, 666); Controls.Add(groupBoxCollectionTools); Controls.Add(pictureBox); Controls.Add(menuStrip); @@ -337,5 +361,7 @@ namespace ProjectBattleship private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByType; + private Button buttonSortByColor; } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs index b8a763b..f9a4b4e 100644 --- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs +++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs @@ -1,6 +1,5 @@ -using Battleship.CollectionGenericObjects; +using ProjectBattleship.CollectionGenericObjects; using Microsoft.Extensions.Logging; -using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.DrawingObject; using System.Windows.Forms; @@ -39,7 +38,13 @@ public partial class FormWarshipCollection : Form private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { - panelCompanyTools.Enabled = false; + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new Docks(pictureBox.Width, pictureBox.Height, + new MassiveGenericObjects()); + break; + } } /// /// Добавление военного корабля @@ -240,7 +245,7 @@ public partial class FormWarshipCollection : Form try { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } @@ -270,7 +275,8 @@ public partial class FormWarshipCollection : Form return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -283,10 +289,10 @@ public partial class FormWarshipCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? col = _storageCollection.Keys?[i]; + if (!col!.IsEmpty()) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(col); } } } @@ -303,9 +309,9 @@ public partial class FormWarshipCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) + ICollectionGenericObjects? collection = _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; @@ -366,4 +372,38 @@ public partial class FormWarshipCollection : Form } } } + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareWarships(new DrawingWarshipCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareWarships(new DrawingWarshipCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareWarships(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } diff --git a/ProjectBattleship/ProjectBattleship/FormWarshipConfig.cs b/ProjectBattleship/ProjectBattleship/FormWarshipConfig.cs index 184341c..630365f 100644 --- a/ProjectBattleship/ProjectBattleship/FormWarshipConfig.cs +++ b/ProjectBattleship/ProjectBattleship/FormWarshipConfig.cs @@ -38,14 +38,7 @@ namespace ProjectBattleship /// public void AddEvent(Action warshipDelegate) { - if (WarshipDelegate != null) - { - WarshipDelegate = warshipDelegate; - } - else - { - WarshipDelegate += warshipDelegate; - } + WarshipDelegate += warshipDelegate; } /// /// Прорисовка объекта