This commit is contained in:
leonteva.v 2024-06-15 07:47:15 +04:00
parent f22b50acad
commit 794d1d800c
13 changed files with 794 additions and 472 deletions

View File

@ -1,5 +1,6 @@
using ProjectBattleship.Drawnings; using ProjectBattleship.Drawnings;
using System; using System;
using Battleship.Drawnings;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -63,9 +64,9 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawingShip ship) public static int operator +(AbstractCompany company, DrawingShip ship)
{ {
return company._collection.Insert(ship); return company._collection.Insert(ship, new DrawningShipEqutables());
} }
public void Sort(IComparer<DrawingShip?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Перегрузка оператора удаления для класса /// Перегрузка оператора удаления для класса
/// </summary> /// </summary>

View File

@ -0,0 +1,73 @@
using ProjectBattleship.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -24,14 +24,14 @@ namespace ProjectBattleship.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - удачно, false - вставка не удалась</returns> /// <returns>true - удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - удачно, false - вставка не удалась</returns> /// <returns>true - удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position); bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -56,5 +56,6 @@ namespace ProjectBattleship.CollectionGenericObjects
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
} }
} }

View File

@ -45,21 +45,25 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (_collection.Count + 1 <= _maxCount) if (Count + 1 <= _maxCount)
{ {
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException();
_collection.Add(obj); _collection.Add(obj);
return _collection.Count - 1; return Count - 1;
} }
throw new CollectionOverflowException(MaxCount); throw new CollectionOverflowException(MaxCount);
} }
public bool Insert(T obj, int position) public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (_collection.Count + 1 > MaxCount) if (_collection.Count + 1 > MaxCount)
throw new CollectionOverflowException(MaxCount); throw new CollectionOverflowException(MaxCount);
if (position < 0 || position >= MaxCount) if (position < 0 || position >= MaxCount)
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException();
_collection.Insert(position, obj); _collection.Insert(position, obj);
return true; return true;
} }
@ -78,4 +82,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -63,22 +63,24 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? 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[index] = obj;
{ return index;
_collection[i] = obj;
return i;
}
} }
throw new CollectionOverflowException(_collection.Length); throw new CollectionOverflowException(_collection.Length);
} }
public bool Insert(T obj, int position) public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (position < 0 || position >= _collection.Length) // проверка позиции if (position < 0 || position >= _collection.Length) // проверка позиции
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException(position);
if (_collection[position] == null) // Попытка вставить на указанную позицию if (_collection[position] == null) // Попытка вставить на указанную позицию
{ {
_collection[position] = obj; _collection[position] = obj;
@ -120,4 +122,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
} }

View File

@ -2,6 +2,8 @@
using ProjectBattleship.Drawnings; using ProjectBattleship.Drawnings;
using System.Text; using System.Text;
using Battleship.Exceptions; using Battleship.Exceptions;
using Microsoft.AspNetCore.Http;
using Battleship.CollectionGenericObjects;
namespace ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.CollectionGenericObjects;
@ -15,11 +17,11 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -28,7 +30,7 @@ public class StorageCollection<T>
private readonly string _separatorItems = ";"; private readonly string _separatorItems = ";";
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -37,15 +39,16 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) 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; return;
switch (collectionType) switch (collectionType)
{ {
case CollectionType.List: case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>()); _storages.Add(tempInfo, new ListGenericObjects<T>());
break; break;
case CollectionType.Massive: case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>()); _storages.Add(tempInfo, new MassiveGenericObjects<T>());
break; break;
default: default:
break; break;
@ -57,8 +60,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
_storages.Remove(name); if (tempInfo.Name != null && _storages.ContainsKey(tempInfo))
_storages.Remove(tempInfo);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@ -69,9 +73,9 @@ public class StorageCollection<T>
{ {
get get
{ {
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value)) CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
return value; if (tempInfo == null || !_storages.ContainsKey(tempInfo)) { return null; }
return null; return _storages[tempInfo];
} }
} }
public void SaveData(string filename) public void SaveData(string filename)
@ -88,15 +92,13 @@ public class StorageCollection<T>
using (StreamWriter sw = new StreamWriter(filename)) using (StreamWriter sw = new StreamWriter(filename))
{ {
sw.WriteLine(_collectionKey.ToString()); sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{ {
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (kvpair.Value.Count == 0) if (kvpair.Value.Count == 0)
continue; continue;
sb.Append(kvpair.Key); sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount); sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems()) foreach (T? item in kvpair.Value.GetItems())
@ -128,18 +130,19 @@ public class StorageCollection<T>
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
string[] record = str.Split(_separatorForKeyValue); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null) if (collection == null)
{ {
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); 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) foreach (string elem in set)
{ {
if (elem?.CreateDrawningShip() is T ship) if (elem?.CreateDrawningShip() is T ship)
@ -157,7 +160,7 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }

View File

@ -0,0 +1,36 @@
using ProjectBattleship.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningCompareByColor : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? 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);
}
}

View File

@ -0,0 +1,36 @@
using ProjectBattleship.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningCompareByType : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? 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);
}
}

View File

@ -0,0 +1,62 @@
using ProjectBattleship.Entities;
using ProjectBattleship.Drawnings;
using ProjectBattleship.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Battleship.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningShipEqutables : IEqualityComparer<DrawingShip?>
{
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 DrawingBattleship && y is DrawingBattleship)
{
EntityBattleship EntityX = (EntityBattleship)x.EntityShip;
EntityBattleship EntityY = (EntityBattleship)y.EntityShip;
if (EntityX.RocketLauncher != EntityY.RocketLauncher)
{
return false;
}
if (EntityX.Turret != EntityY.Turret)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingShip obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[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) { }
}

View File

@ -30,6 +30,7 @@
{ {
pictureBox = new PictureBox(); pictureBox = new PictureBox();
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonCreateCompany = new Button();
buttonCollectionDel = new Button(); buttonCollectionDel = new Button();
listBoxCollection = new ListBox(); listBoxCollection = new ListBox();
buttonCollectionAdd = new Button(); buttonCollectionAdd = new Button();
@ -38,7 +39,6 @@
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
buttonCreateCompany = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
buttonGoToCheck = new Button(); buttonGoToCheck = new Button();
buttonRemoveShip = new Button(); buttonRemoveShip = new Button();
@ -51,6 +51,8 @@
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByType = new Button();
buttonSortByColor = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
@ -60,14 +62,18 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Left; pictureBox.Dock = DockStyle.Left;
pictureBox.Location = new Point(0, 24); pictureBox.Location = new Point(0, 30);
pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(783, 592); pictureBox.Size = new Size(895, 836);
pictureBox.TabIndex = 0; pictureBox.TabIndex = 0;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// groupBoxTools // groupBoxTools
// //
groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(buttonCreateCompany); groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(buttonCollectionDel); groupBoxTools.Controls.Add(buttonCollectionDel);
groupBoxTools.Controls.Add(listBoxCollection); groupBoxTools.Controls.Add(listBoxCollection);
@ -78,18 +84,32 @@
groupBoxTools.Controls.Add(labelCollectionName); groupBoxTools.Controls.Add(labelCollectionName);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(784, 24); groupBoxTools.Location = new Point(897, 30);
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(178, 592); groupBoxTools.Padding = new Padding(3, 4, 3, 4);
groupBoxTools.Size = new Size(203, 836);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(9, 384);
buttonCreateCompany.Margin = new Padding(3, 4, 3, 4);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(189, 31);
buttonCreateCompany.TabIndex = 14;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// buttonCollectionDel // buttonCollectionDel
// //
buttonCollectionDel.Location = new Point(7, 232); buttonCollectionDel.Location = new Point(8, 309);
buttonCollectionDel.Margin = new Padding(3, 4, 3, 4);
buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(167, 23); buttonCollectionDel.Size = new Size(191, 31);
buttonCollectionDel.TabIndex = 13; buttonCollectionDel.TabIndex = 13;
buttonCollectionDel.Text = "Удалить коллекцию"; buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true; buttonCollectionDel.UseVisualStyleBackColor = true;
@ -98,17 +118,19 @@
// listBoxCollection // listBoxCollection
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15; listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(7, 118); listBoxCollection.Location = new Point(8, 157);
listBoxCollection.Margin = new Padding(3, 4, 3, 4);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(167, 109); listBoxCollection.Size = new Size(190, 144);
listBoxCollection.TabIndex = 12; listBoxCollection.TabIndex = 12;
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(7, 90); buttonCollectionAdd.Location = new Point(8, 120);
buttonCollectionAdd.Margin = new Padding(3, 4, 3, 4);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(167, 23); buttonCollectionAdd.Size = new Size(191, 31);
buttonCollectionAdd.TabIndex = 11; buttonCollectionAdd.TabIndex = 11;
buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true; buttonCollectionAdd.UseVisualStyleBackColor = true;
@ -117,9 +139,10 @@
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(102, 64); radioButtonList.Location = new Point(117, 85);
radioButtonList.Margin = new Padding(3, 4, 3, 4);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19); radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 10; radioButtonList.TabIndex = 10;
radioButtonList.TabStop = true; radioButtonList.TabStop = true;
radioButtonList.Text = "Список"; radioButtonList.Text = "Список";
@ -128,9 +151,10 @@
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(20, 64); radioButtonMassive.Location = new Point(23, 85);
radioButtonMassive.Margin = new Padding(3, 4, 3, 4);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19); radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 9; radioButtonMassive.TabIndex = 9;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
@ -138,17 +162,18 @@
// //
// textBoxCollectionName // textBoxCollectionName
// //
textBoxCollectionName.Location = new Point(7, 36); textBoxCollectionName.Location = new Point(8, 48);
textBoxCollectionName.Margin = new Padding(3, 4, 3, 4);
textBoxCollectionName.Name = "textBoxCollectionName"; textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(167, 23); textBoxCollectionName.Size = new Size(190, 27);
textBoxCollectionName.TabIndex = 8; textBoxCollectionName.TabIndex = 8;
// //
// labelCollectionName // labelCollectionName
// //
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(31, 18); labelCollectionName.Location = new Point(35, 24);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15); labelCollectionName.Size = new Size(158, 20);
labelCollectionName.TabIndex = 7; labelCollectionName.TabIndex = 7;
labelCollectionName.Text = "Название коллекции:"; labelCollectionName.Text = "Название коллекции:";
// //
@ -158,27 +183,19 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(7, 274); comboBoxSelectorCompany.Location = new Point(10, 348);
comboBoxSelectorCompany.Margin = new Padding(3, 4, 3, 4);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(166, 23); comboBoxSelectorCompany.Size = new Size(189, 28);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
// //
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(9, 313);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(165, 23);
buttonCreateCompany.TabIndex = 14;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Location = new Point(8, 208); buttonRefresh.Location = new Point(9, 277);
buttonRefresh.Margin = new Padding(3, 4, 3, 4);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(164, 40); buttonRefresh.Size = new Size(187, 53);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -186,9 +203,10 @@
// //
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Location = new Point(8, 162); buttonGoToCheck.Location = new Point(9, 216);
buttonGoToCheck.Margin = new Padding(3, 4, 3, 4);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(164, 40); buttonGoToCheck.Size = new Size(187, 53);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@ -197,9 +215,10 @@
// buttonRemoveShip // buttonRemoveShip
// //
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(8, 116); buttonRemoveShip.Location = new Point(9, 155);
buttonRemoveShip.Margin = new Padding(3, 4, 3, 4);
buttonRemoveShip.Name = "buttonRemoveShip"; buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(164, 40); buttonRemoveShip.Size = new Size(187, 53);
buttonRemoveShip.TabIndex = 4; buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удалить корабль"; buttonRemoveShip.Text = "Удалить корабль";
buttonRemoveShip.UseVisualStyleBackColor = true; buttonRemoveShip.UseVisualStyleBackColor = true;
@ -207,18 +226,20 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(8, 87); maskedTextBoxPosition.Location = new Point(9, 116);
maskedTextBoxPosition.Margin = new Padding(3, 4, 3, 4);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(164, 23); maskedTextBoxPosition.Size = new Size(187, 27);
maskedTextBoxPosition.TabIndex = 3; maskedTextBoxPosition.TabIndex = 3;
// //
// buttonAddShip // buttonAddShip
// //
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(8, 41); buttonAddShip.Location = new Point(9, 55);
buttonAddShip.Margin = new Padding(3, 4, 3, 4);
buttonAddShip.Name = "buttonAddShip"; buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(164, 40); buttonAddShip.Size = new Size(187, 53);
buttonAddShip.TabIndex = 1; buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавление корабля"; buttonAddShip.Text = "Добавление корабля";
buttonAddShip.UseVisualStyleBackColor = true; buttonAddShip.UseVisualStyleBackColor = true;
@ -230,8 +251,8 @@
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2); menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(962, 24); menuStrip.Size = new Size(1100, 30);
menuStrip.TabIndex = 1; menuStrip.TabIndex = 1;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@ -239,20 +260,20 @@
// //
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem"; fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(48, 20); fileToolStripMenuItem.Size = new Size(59, 24);
fileToolStripMenuItem.Text = "Файл"; fileToolStripMenuItem.Text = "Файл";
// //
// saveToolStripMenuItem // saveToolStripMenuItem
// //
saveToolStripMenuItem.Name = "saveToolStripMenuItem"; saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(133, 22); saveToolStripMenuItem.Size = new Size(166, 26);
saveToolStripMenuItem.Text = "Сохранить"; saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
// //
// loadToolStripMenuItem // loadToolStripMenuItem
// //
loadToolStripMenuItem.Name = "loadToolStripMenuItem"; loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new Size(133, 22); loadToolStripMenuItem.Size = new Size(166, 26);
loadToolStripMenuItem.Text = "Загрузить"; loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
// //
@ -272,21 +293,44 @@
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(784, 366); panelCompanyTools.Location = new Point(0, 507);
panelCompanyTools.Margin = new Padding(3, 4, 3, 4);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(178, 250); panelCompanyTools.Size = new Size(203, 329);
panelCompanyTools.TabIndex = 15; panelCompanyTools.TabIndex = 15;
// //
// buttonSortByType
//
buttonSortByType.Location = new Point(9, 423);
buttonSortByType.Margin = new Padding(3, 4, 3, 4);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(189, 31);
buttonSortByType.TabIndex = 15;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(10, 462);
buttonSortByColor.Margin = new Padding(3, 4, 3, 4);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(189, 31);
buttonSortByColor.TabIndex = 16;
buttonSortByColor.Text = "Сортировать по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(962, 616); ClientSize = new Size(1100, 866);
Controls.Add(panelCompanyTools);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Margin = new Padding(3, 4, 3, 4);
Name = "FormShipCollection"; Name = "FormShipCollection";
Text = "Коллекция кораблей"; Text = "Коллекция кораблей";
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
@ -325,5 +369,7 @@
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -4,11 +4,11 @@ using ProjectBattleship.Drawnings;
using System.Windows.Forms; using System.Windows.Forms;
using Battleship.Exceptions; using Battleship.Exceptions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Battleship.Drawnings;
namespace ProjectBattleship namespace ProjectBattleship
{ {
public partial class FormShipCollection : Form public partial class FormShipCollection : Form
{ {
private readonly StorageCollection<DrawingShip> _storageCollection; private readonly StorageCollection<DrawingShip> _storageCollection;
/// <summary> /// <summary>
@ -68,6 +68,11 @@ namespace ProjectBattleship
MessageBoxIcon.Error); MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message); _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
catch (ObjectExistsException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
} }
private void ButtonRemoveShip_Click(object sender, EventArgs e) private void ButtonRemoveShip_Click(object sender, EventArgs e)
{ {
@ -200,7 +205,7 @@ namespace ProjectBattleship
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -267,5 +272,23 @@ namespace ProjectBattleship
} }
} }
} }
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<DrawingShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }
} }

View File

@ -126,4 +126,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>307, 17</value> <value>307, 17</value>
</metadata> </metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>