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

@ -1,329 +1,375 @@
namespace ProjectBattleship namespace ProjectBattleship
{ {
partial class FormShipCollection partial class FormShipCollection
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBox = new PictureBox(); pictureBox = new PictureBox();
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonCollectionDel = new Button(); buttonCreateCompany = new Button();
listBoxCollection = new ListBox(); buttonCollectionDel = new Button();
buttonCollectionAdd = new Button(); listBoxCollection = new ListBox();
radioButtonList = new RadioButton(); buttonCollectionAdd = new Button();
radioButtonMassive = new RadioButton(); radioButtonList = new RadioButton();
textBoxCollectionName = new TextBox(); radioButtonMassive = new RadioButton();
labelCollectionName = new Label(); textBoxCollectionName = new TextBox();
comboBoxSelectorCompany = new ComboBox(); labelCollectionName = new Label();
buttonCreateCompany = new Button(); comboBoxSelectorCompany = new ComboBox();
buttonRefresh = new Button(); buttonRefresh = new Button();
buttonGoToCheck = new Button(); buttonGoToCheck = new Button();
buttonRemoveShip = new Button(); buttonRemoveShip = new Button();
maskedTextBoxPosition = new MaskedTextBox(); maskedTextBoxPosition = new MaskedTextBox();
buttonAddShip = new Button(); buttonAddShip = new Button();
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem(); fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem(); saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); buttonSortByType = new Button();
groupBoxTools.SuspendLayout(); buttonSortByColor = new Button();
menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTools.SuspendLayout(); groupBoxTools.SuspendLayout();
SuspendLayout(); menuStrip.SuspendLayout();
// panelCompanyTools.SuspendLayout();
// pictureBox SuspendLayout();
// //
pictureBox.Dock = DockStyle.Left; // pictureBox
pictureBox.Location = new Point(0, 24); //
pictureBox.Name = "pictureBox"; pictureBox.Dock = DockStyle.Left;
pictureBox.Size = new Size(783, 592); pictureBox.Location = new Point(0, 30);
pictureBox.TabIndex = 0; pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.TabStop = false; pictureBox.Name = "pictureBox";
// pictureBox.Size = new Size(895, 836);
// groupBoxTools pictureBox.TabIndex = 0;
// pictureBox.TabStop = false;
groupBoxTools.Controls.Add(buttonCreateCompany); //
groupBoxTools.Controls.Add(buttonCollectionDel); // groupBoxTools
groupBoxTools.Controls.Add(listBoxCollection); //
groupBoxTools.Controls.Add(buttonCollectionAdd); groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(radioButtonList); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(radioButtonMassive); groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(textBoxCollectionName); groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(labelCollectionName); groupBoxTools.Controls.Add(buttonCollectionDel);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(listBoxCollection);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Controls.Add(buttonCollectionAdd);
groupBoxTools.Location = new Point(784, 24); groupBoxTools.Controls.Add(radioButtonList);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Controls.Add(radioButtonMassive);
groupBoxTools.Size = new Size(178, 592); groupBoxTools.Controls.Add(textBoxCollectionName);
groupBoxTools.TabIndex = 0; groupBoxTools.Controls.Add(labelCollectionName);
groupBoxTools.TabStop = false; groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Text = "Инструменты"; groupBoxTools.Dock = DockStyle.Right;
// groupBoxTools.Location = new Point(897, 30);
// buttonCollectionDel groupBoxTools.Margin = new Padding(3, 4, 3, 4);
// groupBoxTools.Name = "groupBoxTools";
buttonCollectionDel.Location = new Point(7, 232); groupBoxTools.Padding = new Padding(3, 4, 3, 4);
buttonCollectionDel.Name = "buttonCollectionDel"; groupBoxTools.Size = new Size(203, 836);
buttonCollectionDel.Size = new Size(167, 23); groupBoxTools.TabIndex = 0;
buttonCollectionDel.TabIndex = 13; groupBoxTools.TabStop = false;
buttonCollectionDel.Text = "Удалить коллекцию"; groupBoxTools.Text = "Инструменты";
buttonCollectionDel.UseVisualStyleBackColor = true; //
buttonCollectionDel.Click += buttonCollectionDel_Click; // buttonCreateCompany
// //
// listBoxCollection buttonCreateCompany.Location = new Point(9, 384);
// buttonCreateCompany.Margin = new Padding(3, 4, 3, 4);
listBoxCollection.FormattingEnabled = true; buttonCreateCompany.Name = "buttonCreateCompany";
listBoxCollection.ItemHeight = 15; buttonCreateCompany.Size = new Size(189, 31);
listBoxCollection.Location = new Point(7, 118); buttonCreateCompany.TabIndex = 14;
listBoxCollection.Name = "listBoxCollection"; buttonCreateCompany.Text = "Создать компанию";
listBoxCollection.Size = new Size(167, 109); buttonCreateCompany.UseVisualStyleBackColor = true;
listBoxCollection.TabIndex = 12; buttonCreateCompany.Click += buttonCreateCompany_Click;
// //
// buttonCollectionAdd // buttonCollectionDel
// //
buttonCollectionAdd.Location = new Point(7, 90); buttonCollectionDel.Location = new Point(8, 309);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionDel.Margin = new Padding(3, 4, 3, 4);
buttonCollectionAdd.Size = new Size(167, 23); buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionAdd.TabIndex = 11; buttonCollectionDel.Size = new Size(191, 31);
buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionDel.TabIndex = 13;
buttonCollectionAdd.UseVisualStyleBackColor = true; buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionAdd.Click += buttonCollectionAdd_Click; buttonCollectionDel.UseVisualStyleBackColor = true;
// buttonCollectionDel.Click += buttonCollectionDel_Click;
// radioButtonList //
// // listBoxCollection
radioButtonList.AutoSize = true; //
radioButtonList.Location = new Point(102, 64); listBoxCollection.FormattingEnabled = true;
radioButtonList.Name = "radioButtonList"; listBoxCollection.ItemHeight = 20;
radioButtonList.Size = new Size(66, 19); listBoxCollection.Location = new Point(8, 157);
radioButtonList.TabIndex = 10; listBoxCollection.Margin = new Padding(3, 4, 3, 4);
radioButtonList.TabStop = true; listBoxCollection.Name = "listBoxCollection";
radioButtonList.Text = "Список"; listBoxCollection.Size = new Size(190, 144);
radioButtonList.UseVisualStyleBackColor = true; listBoxCollection.TabIndex = 12;
// //
// radioButtonMassive // buttonCollectionAdd
// //
radioButtonMassive.AutoSize = true; buttonCollectionAdd.Location = new Point(8, 120);
radioButtonMassive.Location = new Point(20, 64); buttonCollectionAdd.Margin = new Padding(3, 4, 3, 4);
radioButtonMassive.Name = "radioButtonMassive"; buttonCollectionAdd.Name = "buttonCollectionAdd";
radioButtonMassive.Size = new Size(67, 19); buttonCollectionAdd.Size = new Size(191, 31);
radioButtonMassive.TabIndex = 9; buttonCollectionAdd.TabIndex = 11;
radioButtonMassive.TabStop = true; buttonCollectionAdd.Text = "Добавить коллекцию";
radioButtonMassive.Text = "Массив"; buttonCollectionAdd.UseVisualStyleBackColor = true;
radioButtonMassive.UseVisualStyleBackColor = true; buttonCollectionAdd.Click += buttonCollectionAdd_Click;
// //
// textBoxCollectionName // radioButtonList
// //
textBoxCollectionName.Location = new Point(7, 36); radioButtonList.AutoSize = true;
textBoxCollectionName.Name = "textBoxCollectionName"; radioButtonList.Location = new Point(117, 85);
textBoxCollectionName.Size = new Size(167, 23); radioButtonList.Margin = new Padding(3, 4, 3, 4);
textBoxCollectionName.TabIndex = 8; radioButtonList.Name = "radioButtonList";
// radioButtonList.Size = new Size(80, 24);
// labelCollectionName radioButtonList.TabIndex = 10;
// radioButtonList.TabStop = true;
labelCollectionName.AutoSize = true; radioButtonList.Text = "Список";
labelCollectionName.Location = new Point(31, 18); radioButtonList.UseVisualStyleBackColor = true;
labelCollectionName.Name = "labelCollectionName"; //
labelCollectionName.Size = new Size(125, 15); // radioButtonMassive
labelCollectionName.TabIndex = 7; //
labelCollectionName.Text = "Название коллекции:"; radioButtonMassive.AutoSize = true;
// radioButtonMassive.Location = new Point(23, 85);
// comboBoxSelectorCompany radioButtonMassive.Margin = new Padding(3, 4, 3, 4);
// radioButtonMassive.Name = "radioButtonMassive";
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; radioButtonMassive.Size = new Size(82, 24);
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; radioButtonMassive.TabIndex = 9;
comboBoxSelectorCompany.FormattingEnabled = true; radioButtonMassive.TabStop = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); radioButtonMassive.Text = "Массив";
comboBoxSelectorCompany.Location = new Point(7, 274); radioButtonMassive.UseVisualStyleBackColor = true;
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; //
comboBoxSelectorCompany.Size = new Size(166, 23); // textBoxCollectionName
comboBoxSelectorCompany.TabIndex = 0; //
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; textBoxCollectionName.Location = new Point(8, 48);
// textBoxCollectionName.Margin = new Padding(3, 4, 3, 4);
// buttonCreateCompany textBoxCollectionName.Name = "textBoxCollectionName";
// textBoxCollectionName.Size = new Size(190, 27);
buttonCreateCompany.Location = new Point(9, 313); textBoxCollectionName.TabIndex = 8;
buttonCreateCompany.Name = "buttonCreateCompany"; //
buttonCreateCompany.Size = new Size(165, 23); // labelCollectionName
buttonCreateCompany.TabIndex = 14; //
buttonCreateCompany.Text = "Создать компанию"; labelCollectionName.AutoSize = true;
buttonCreateCompany.UseVisualStyleBackColor = true; labelCollectionName.Location = new Point(35, 24);
buttonCreateCompany.Click += buttonCreateCompany_Click; labelCollectionName.Name = "labelCollectionName";
// labelCollectionName.Size = new Size(158, 20);
// buttonRefresh labelCollectionName.TabIndex = 7;
// labelCollectionName.Text = "Название коллекции:";
buttonRefresh.Location = new Point(8, 208); //
buttonRefresh.Name = "buttonRefresh"; // comboBoxSelectorCompany
buttonRefresh.Size = new Size(164, 40); //
buttonRefresh.TabIndex = 6; comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Text = "Обновить"; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
buttonRefresh.UseVisualStyleBackColor = true; comboBoxSelectorCompany.FormattingEnabled = true;
buttonRefresh.Click += ButtonRefresh_Click; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
// comboBoxSelectorCompany.Location = new Point(10, 348);
// buttonGoToCheck comboBoxSelectorCompany.Margin = new Padding(3, 4, 3, 4);
// comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
buttonGoToCheck.Location = new Point(8, 162); comboBoxSelectorCompany.Size = new Size(189, 28);
buttonGoToCheck.Name = "buttonGoToCheck"; comboBoxSelectorCompany.TabIndex = 0;
buttonGoToCheck.Size = new Size(164, 40); comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
buttonGoToCheck.TabIndex = 5; //
buttonGoToCheck.Text = "Передать на тесты"; // buttonRefresh
buttonGoToCheck.UseVisualStyleBackColor = true; //
buttonGoToCheck.Click += ButtonGoToCheck_Click; buttonRefresh.Location = new Point(9, 277);
// buttonRefresh.Margin = new Padding(3, 4, 3, 4);
// buttonRemoveShip buttonRefresh.Name = "buttonRefresh";
// buttonRefresh.Size = new Size(187, 53);
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.TabIndex = 6;
buttonRemoveShip.Location = new Point(8, 116); buttonRefresh.Text = "Обновить";
buttonRemoveShip.Name = "buttonRemoveShip"; buttonRefresh.UseVisualStyleBackColor = true;
buttonRemoveShip.Size = new Size(164, 40); buttonRefresh.Click += ButtonRefresh_Click;
buttonRemoveShip.TabIndex = 4; //
buttonRemoveShip.Text = "Удалить корабль"; // buttonGoToCheck
buttonRemoveShip.UseVisualStyleBackColor = true; //
buttonRemoveShip.Click += ButtonRemoveShip_Click; buttonGoToCheck.Location = new Point(9, 216);
// buttonGoToCheck.Margin = new Padding(3, 4, 3, 4);
// maskedTextBoxPosition buttonGoToCheck.Name = "buttonGoToCheck";
// buttonGoToCheck.Size = new Size(187, 53);
maskedTextBoxPosition.Location = new Point(8, 87); buttonGoToCheck.TabIndex = 5;
maskedTextBoxPosition.Mask = "00"; buttonGoToCheck.Text = "Передать на тесты";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; buttonGoToCheck.UseVisualStyleBackColor = true;
maskedTextBoxPosition.Size = new Size(164, 23); buttonGoToCheck.Click += ButtonGoToCheck_Click;
maskedTextBoxPosition.TabIndex = 3; //
// // buttonRemoveShip
// buttonAddShip //
// buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveShip.Location = new Point(9, 155);
buttonAddShip.Location = new Point(8, 41); buttonRemoveShip.Margin = new Padding(3, 4, 3, 4);
buttonAddShip.Name = "buttonAddShip"; buttonRemoveShip.Name = "buttonRemoveShip";
buttonAddShip.Size = new Size(164, 40); buttonRemoveShip.Size = new Size(187, 53);
buttonAddShip.TabIndex = 1; buttonRemoveShip.TabIndex = 4;
buttonAddShip.Text = "Добавление корабля"; buttonRemoveShip.Text = "Удалить корабль";
buttonAddShip.UseVisualStyleBackColor = true; buttonRemoveShip.UseVisualStyleBackColor = true;
buttonAddShip.Click += ButtonAddShip_Click; buttonRemoveShip.Click += ButtonRemoveShip_Click;
// //
// menuStrip // maskedTextBoxPosition
// //
menuStrip.ImageScalingSize = new Size(20, 20); maskedTextBoxPosition.Location = new Point(9, 116);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); maskedTextBoxPosition.Margin = new Padding(3, 4, 3, 4);
menuStrip.Location = new Point(0, 0); maskedTextBoxPosition.Mask = "00";
menuStrip.Name = "menuStrip"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
menuStrip.Padding = new Padding(5, 2, 0, 2); maskedTextBoxPosition.Size = new Size(187, 27);
menuStrip.Size = new Size(962, 24); maskedTextBoxPosition.TabIndex = 3;
menuStrip.TabIndex = 1; //
menuStrip.Text = "menuStrip1"; // buttonAddShip
// //
// fileToolStripMenuItem buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
// buttonAddShip.Location = new Point(9, 55);
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); buttonAddShip.Margin = new Padding(3, 4, 3, 4);
fileToolStripMenuItem.Name = "fileToolStripMenuItem"; buttonAddShip.Name = "buttonAddShip";
fileToolStripMenuItem.Size = new Size(48, 20); buttonAddShip.Size = new Size(187, 53);
fileToolStripMenuItem.Text = "Файл"; buttonAddShip.TabIndex = 1;
// buttonAddShip.Text = "Добавление корабля";
// saveToolStripMenuItem buttonAddShip.UseVisualStyleBackColor = true;
// buttonAddShip.Click += ButtonAddShip_Click;
saveToolStripMenuItem.Name = "saveToolStripMenuItem"; //
saveToolStripMenuItem.Size = new Size(133, 22); // menuStrip
saveToolStripMenuItem.Text = "Сохранить"; //
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; menuStrip.ImageScalingSize = new Size(20, 20);
// menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
// loadToolStripMenuItem menuStrip.Location = new Point(0, 0);
// menuStrip.Name = "menuStrip";
loadToolStripMenuItem.Name = "loadToolStripMenuItem"; menuStrip.Padding = new Padding(6, 3, 0, 3);
loadToolStripMenuItem.Size = new Size(133, 22); menuStrip.Size = new Size(1100, 30);
loadToolStripMenuItem.Text = "Загрузить"; menuStrip.TabIndex = 1;
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; menuStrip.Text = "menuStrip1";
// //
// openFileDialog // fileToolStripMenuItem
// //
openFileDialog.FileName = "Ships"; fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
// fileToolStripMenuItem.Name = "fileToolStripMenuItem";
// saveFileDialog fileToolStripMenuItem.Size = new Size(59, 24);
// fileToolStripMenuItem.Text = "Файл";
saveFileDialog.FileName = "Ships"; //
// // saveToolStripMenuItem
// panelCompanyTools //
// saveToolStripMenuItem.Name = "saveToolStripMenuItem";
panelCompanyTools.Controls.Add(buttonAddShip); saveToolStripMenuItem.Size = new Size(166, 26);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); saveToolStripMenuItem.Text = "Сохранить";
panelCompanyTools.Controls.Add(buttonRemoveShip); saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
panelCompanyTools.Controls.Add(buttonGoToCheck); //
panelCompanyTools.Controls.Add(buttonRefresh); // loadToolStripMenuItem
panelCompanyTools.Enabled = false; //
panelCompanyTools.Location = new Point(784, 366); loadToolStripMenuItem.Name = "loadToolStripMenuItem";
panelCompanyTools.Name = "panelCompanyTools"; loadToolStripMenuItem.Size = new Size(166, 26);
panelCompanyTools.Size = new Size(178, 250); loadToolStripMenuItem.Text = "Загрузить";
panelCompanyTools.TabIndex = 15; loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
// //
// FormShipCollection // openFileDialog
// //
AutoScaleDimensions = new SizeF(7F, 15F); openFileDialog.FileName = "Ships";
AutoScaleMode = AutoScaleMode.Font; //
ClientSize = new Size(962, 616); // saveFileDialog
Controls.Add(panelCompanyTools); //
Controls.Add(groupBoxTools); saveFileDialog.FileName = "Ships";
Controls.Add(pictureBox); //
Controls.Add(menuStrip); // panelCompanyTools
MainMenuStrip = menuStrip; //
Name = "FormShipCollection"; panelCompanyTools.Controls.Add(buttonAddShip);
Text = "Коллекция кораблей"; panelCompanyTools.Controls.Add(maskedTextBoxPosition);
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); panelCompanyTools.Controls.Add(buttonRemoveShip);
groupBoxTools.ResumeLayout(false); panelCompanyTools.Controls.Add(buttonGoToCheck);
groupBoxTools.PerformLayout(); panelCompanyTools.Controls.Add(buttonRefresh);
menuStrip.ResumeLayout(false); panelCompanyTools.Enabled = false;
menuStrip.PerformLayout(); panelCompanyTools.Location = new Point(0, 507);
panelCompanyTools.ResumeLayout(false); panelCompanyTools.Margin = new Padding(3, 4, 3, 4);
panelCompanyTools.PerformLayout(); panelCompanyTools.Name = "panelCompanyTools";
ResumeLayout(false); panelCompanyTools.Size = new Size(203, 329);
PerformLayout(); 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
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1100, 866);
Controls.Add(groupBoxTools);
Controls.Add(pictureBox);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 4, 3, 4);
Name = "FormShipCollection";
Text = "Коллекция кораблей";
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private PictureBox pictureBox; private PictureBox pictureBox;
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonAddShip; private Button buttonAddShip;
private MaskedTextBox maskedTextBoxPosition; private MaskedTextBox maskedTextBoxPosition;
private Button buttonRefresh; private Button buttonRefresh;
private Button buttonGoToCheck; private Button buttonGoToCheck;
private Button buttonRemoveShip; private Button buttonRemoveShip;
private ListBox listBoxCollection; private ListBox listBoxCollection;
private Button buttonCollectionAdd; private Button buttonCollectionAdd;
private RadioButton radioButtonList; private RadioButton radioButtonList;
private RadioButton radioButtonMassive; private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName; private TextBox textBoxCollectionName;
private Label labelCollectionName; private Label labelCollectionName;
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private MenuStrip menuStrip; private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem; private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
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,17 +4,17 @@ 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> /// Компания
/// Компания /// </summary>
/// </summary> private AbstractCompany? _company = null;
private AbstractCompany? _company = null;
private readonly ILogger _logger; private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -31,26 +31,26 @@ namespace ProjectBattleship
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawingShip>()); _company = new ShipDocks(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawingShip>());
break; break;
} }
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
} }
/// <summary> /// <summary>
/// Добавление обычного автомобиля /// Добавление обычного автомобиля
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e) private void ButtonAddShip_Click(object sender, EventArgs e)
{ {
FormShipConfig form = new(); FormShipConfig form = new();
form.Show(); form.Show();
form.AddEvent(SetShip); form.AddEvent(SetShip);
} }
private void SetShip(DrawingShip? ship) private void SetShip(DrawingShip? ship)
{ {
if (_company == null || ship == null) if (_company == null || ship == null)
@ -68,18 +68,23 @@ 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)
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{ {
return; return;
} }
try try
{ {
@ -106,84 +111,84 @@ namespace ProjectBattleship
MessageBox.Show("Ошибка: неправильная позиция"); MessageBox.Show("Ошибка: неправильная позиция");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
/// Передача объекта в другую форму /// Передача объекта в другую форму
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e) private void ButtonGoToCheck_Click(object sender, EventArgs e)
{ {
if (_company == null) if (_company == null)
{ {
return; return;
} }
DrawingShip? car = null; DrawingShip? car = null;
int counter = 100; int counter = 100;
while (car == null) while (car == null)
{ {
car = _company.GetRandomObject(); car = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
break; break;
} }
} }
if (car == null) if (car == null)
{ {
return; return;
} }
FormBattleship form = new() FormBattleship form = new()
{ {
SetShip = car SetShip = car
}; };
form.ShowDialog(); form.ShowDialog();
} }
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e) private void ButtonRefresh_Click(object sender, EventArgs e)
{ {
if (_company == null) if (_company == null)
{ {
return; return;
} }
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawingShip>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawingShip>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection); _company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection);
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void buttonCollectionDel_Click(object sender, EventArgs e) private void buttonCollectionDel_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
@ -195,20 +200,20 @@ namespace ProjectBattleship
_logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {
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);
} }
} }
} }
private void buttonCollectionAdd_Click(object sender, EventArgs e) private void buttonCollectionAdd_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -230,8 +235,8 @@ namespace ProjectBattleship
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
@ -249,8 +254,8 @@ namespace ProjectBattleship
} }
} }
private void loadToolStripMenuItem_Click(object sender, EventArgs e) private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try try
@ -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>