This commit is contained in:
leonteva.v 2024-06-15 03:12:12 +04:00
parent f177ed3b2c
commit f22b50acad
14 changed files with 620 additions and 482 deletions

View File

@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.CollectionGenericObjects;
/// <summary> /// <summary>
@ -38,7 +39,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -98,14 +99,16 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawingShip? obj = _collection?.Get(i); DrawingShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (ObjectNotFoundException) { };
}
return bitmap; return bitmap;
} }
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.CollectionGenericObjects;
@ -41,7 +42,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= _collection.Count) if (position < 0 || position >= _collection.Count)
return null; throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
@ -51,19 +52,21 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.Add(obj); _collection.Add(obj);
return _collection.Count - 1; return _collection.Count - 1;
} }
return -1; throw new CollectionOverflowException(MaxCount);
} }
public bool Insert(T obj, int position) public bool Insert(T obj, int position)
{ {
if (_collection.Count + 1 > _maxCount || position < 0 || position >= _collection.Count) if (_collection.Count + 1 > MaxCount)
return false; throw new CollectionOverflowException(MaxCount);
if (position < 0 || position >= MaxCount)
throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return true; return true;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _collection.Count) if (position < 0 || position >= _collection.Count)
return null; throw new PositionOutOfCollectionException(position);
T temp = _collection[position]; T temp = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;

View File

@ -6,6 +6,8 @@ using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -58,8 +60,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// <returns></returns> /// <returns></returns>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= _collection.Length) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return null;
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
@ -72,12 +73,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException(_collection.Length);
} }
public bool Insert(T obj, int position) public bool Insert(T obj, int position)
{ {
if (position < 0 || position >= _collection.Length) // проверка позиции if (position < 0 || position >= _collection.Length) // проверка позиции
return false; throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) // Попытка вставить на указанную позицию if (_collection[position] == null) // Попытка вставить на указанную позицию
{ {
_collection[position] = obj; _collection[position] = obj;
@ -99,12 +100,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return true; return true;
} }
} }
return false; throw new CollectionOverflowException(_collection.Length);
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _collection.Length || _collection[position] == null) // проверка позиции и наличия объекта if (position < 0 || position >= _collection.Length) // проверка позиции
return null; throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
throw new ObjectNotFoundException(position);
T temp = _collection[position]; T temp = _collection[position];
_collection[position] = null; _collection[position] = null;

View File

@ -7,6 +7,7 @@ using System.Linq;
using System.Security.AccessControl; using System.Security.AccessControl;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.CollectionGenericObjects;
@ -27,32 +28,45 @@ namespace ProjectBattleship.CollectionGenericObjects;
protected override void DrawBackground(Graphics g) protected override void DrawBackground(Graphics g)
{ {
Pen pen = new Pen(Color.Brown, 4); Pen pen = new(Color.Black);
int x = 0, y = 0; for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
while (y + _placeSizeHeight < _pictureHeight)
{ {
while (x + _placeSizeWidth < _pictureWidth) for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{ {
g.DrawLine(pen, x, y, x + _placeSizeWidth, y); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
g.DrawLine(pen, x, y, x, y + _placeSizeHeight); new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth, y + _placeSizeHeight); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
x += _placeSizeWidth + 50; new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
} }
y += _placeSizeHeight;
x = 0; g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
} }
} }
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
{ {
int count = 0; int n = 0;
for (int iy = _placeSizeHeight * 11 + 5; iy >= 0; iy -= _placeSizeHeight) for (int j = _pictureHeight / _placeSizeHeight - 1; j >= 0; j--)
{ {
for (int ix = 5; ix + _placeSizeWidth + 50 < _pictureWidth; ix += _placeSizeWidth + 50) for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{ {
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); try
_collection?.Get(count)?.SetPosition(ix, iy); {
count++; DrawingShip? drawingTrans = _collection?.Get(n);
if (drawingTrans != null)
{
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException e)
{
}
catch (PositionOutOfCollectionException e)
{
}
n++;
} }
} }
} }

View File

@ -1,6 +1,7 @@
using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings; using ProjectBattleship.Drawnings;
using System.Text; using System.Text;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects; namespace ProjectBattleship.CollectionGenericObjects;
@ -73,11 +74,11 @@ public class StorageCollection<T>
return null; return null;
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -110,20 +111,19 @@ public class StorageCollection<T>
sb.Clear(); sb.Clear();
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader sr = new StreamReader(filename)) using (StreamReader sr = new StreamReader(filename))
{ {
string? str; string? str;
str = sr.ReadLine(); str = sr.ReadLine();
if (str != _collectionKey.ToString()) if (str != _collectionKey.ToString())
return false; throw new FormatException("В файле неверные данные");
_storages.Clear(); _storages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
@ -136,22 +136,30 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; 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[3].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)
{
try
{ {
if (collection.Insert(ship) == -1) if (collection.Insert(ship) == -1)
return false; {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Создание коллекции по типу /// Создание коллекции по типу

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
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) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,4 +1,4 @@
namespace Battleship namespace ProjectBattleship
{ {
partial class FormShipCollection partial class FormShipCollection
{ {
@ -28,15 +28,8 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
Tools = new GroupBox(); pictureBox = new PictureBox();
panelCompanyTools = new Panel(); groupBoxTools = new GroupBox();
buttonAddShip = new Button();
buttonRefresh = new Button();
maskedTextBox = new MaskedTextBox();
buttonGoToTest = new Button();
buttonDelShip = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button(); buttonCollectionDel = new Button();
listBoxCollection = new ListBox(); listBoxCollection = new ListBox();
buttonCollectionAdd = new Button(); buttonCollectionAdd = new Button();
@ -45,162 +38,89 @@
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); buttonCreateCompany = new Button();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveShip = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddShip = new Button();
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem(); fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem(); saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
Tools.SuspendLayout(); saveFileDialog = new SaveFileDialog();
panelCompanyTools.SuspendLayout(); panelCompanyTools = new Panel();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
groupBoxTools.SuspendLayout();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
panelCompanyTools.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// Tools // pictureBox
// //
Tools.Controls.Add(panelCompanyTools); pictureBox.Dock = DockStyle.Left;
Tools.Controls.Add(buttonCreateCompany); pictureBox.Location = new Point(0, 24);
Tools.Controls.Add(panelStorage); pictureBox.Name = "pictureBox";
Tools.Controls.Add(comboBoxSelectorCompany); pictureBox.Size = new Size(783, 592);
Tools.Dock = DockStyle.Right; pictureBox.TabIndex = 0;
Tools.Location = new Point(1605, 40); pictureBox.TabStop = false;
Tools.Name = "Tools";
Tools.Size = new Size(488, 1224);
Tools.TabIndex = 0;
Tools.TabStop = false;
Tools.Text = "Инструменты";
// //
// panelCompanyTools // groupBoxTools
// //
panelCompanyTools.Controls.Add(buttonAddShip); groupBoxTools.Controls.Add(buttonCreateCompany);
panelCompanyTools.Controls.Add(buttonRefresh); groupBoxTools.Controls.Add(buttonCollectionDel);
panelCompanyTools.Controls.Add(maskedTextBox); groupBoxTools.Controls.Add(listBoxCollection);
panelCompanyTools.Controls.Add(buttonGoToTest); groupBoxTools.Controls.Add(buttonCollectionAdd);
panelCompanyTools.Controls.Add(buttonDelShip); groupBoxTools.Controls.Add(radioButtonList);
panelCompanyTools.Enabled = false; groupBoxTools.Controls.Add(radioButtonMassive);
panelCompanyTools.Location = new Point(0, 686); groupBoxTools.Controls.Add(textBoxCollectionName);
panelCompanyTools.Name = "panelCompanyTools"; groupBoxTools.Controls.Add(labelCollectionName);
panelCompanyTools.Size = new Size(488, 569); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
panelCompanyTools.TabIndex = 8; groupBoxTools.Dock = DockStyle.Right;
// groupBoxTools.Location = new Point(784, 24);
// buttonAddShip groupBoxTools.Name = "groupBoxTools";
// groupBoxTools.Size = new Size(178, 592);
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; groupBoxTools.TabIndex = 0;
buttonAddShip.Location = new Point(9, 3); groupBoxTools.TabStop = false;
buttonAddShip.Name = "buttonAddShip"; groupBoxTools.Text = "Инструменты";
buttonAddShip.Size = new Size(473, 90);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавить корабль";
buttonAddShip.UseVisualStyleBackColor = true;
buttonAddShip.Click += ButtonAddShip_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(16, 432);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(466, 90);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(12, 195);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(470, 39);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonGoToTest
//
buttonGoToTest.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToTest.Location = new Point(16, 336);
buttonGoToTest.Name = "buttonGoToTest";
buttonGoToTest.Size = new Size(466, 90);
buttonGoToTest.TabIndex = 5;
buttonGoToTest.Text = "Передать на тест";
buttonGoToTest.UseVisualStyleBackColor = true;
buttonGoToTest.Click += ButtonGoToTest_Click;
//
// buttonDelShip
//
buttonDelShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelShip.Location = new Point(12, 240);
buttonDelShip.Name = "buttonDelShip";
buttonDelShip.Size = new Size(473, 90);
buttonDelShip.TabIndex = 4;
buttonDelShip.Text = "Удалить корабль";
buttonDelShip.UseVisualStyleBackColor = true;
buttonDelShip.Click += ButtonDelShip_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(9, 612);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(473, 68);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 35);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(482, 512);
panelStorage.TabIndex = 7;
// //
// buttonCollectionDel // buttonCollectionDel
// //
buttonCollectionDel.Location = new Point(6, 443); buttonCollectionDel.Location = new Point(7, 232);
buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(473, 46); buttonCollectionDel.Size = new Size(167, 23);
buttonCollectionDel.TabIndex = 6; buttonCollectionDel.TabIndex = 13;
buttonCollectionDel.Text = "Удалить коллекцию"; buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true; buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click; buttonCollectionDel.Click += buttonCollectionDel_Click;
// //
// listBoxCollection // listBoxCollection
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 32; listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(9, 209); listBoxCollection.Location = new Point(7, 118);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(473, 228); listBoxCollection.Size = new Size(167, 109);
listBoxCollection.TabIndex = 5; listBoxCollection.TabIndex = 12;
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(6, 157); buttonCollectionAdd.Location = new Point(7, 90);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(473, 46); buttonCollectionAdd.Size = new Size(167, 23);
buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.TabIndex = 11;
buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true; buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click; buttonCollectionAdd.Click += buttonCollectionAdd_Click;
// //
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(306, 102); radioButtonList.Location = new Point(102, 64);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(125, 36); radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3; radioButtonList.TabIndex = 10;
radioButtonList.TabStop = true; radioButtonList.TabStop = true;
radioButtonList.Text = "Список"; radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true; radioButtonList.UseVisualStyleBackColor = true;
@ -208,28 +128,28 @@
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(43, 102); radioButtonMassive.Location = new Point(20, 64);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(128, 36); radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2; radioButtonMassive.TabIndex = 9;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true; radioButtonMassive.UseVisualStyleBackColor = true;
// //
// textBoxCollectionName // textBoxCollectionName
// //
textBoxCollectionName.Location = new Point(6, 48); textBoxCollectionName.Location = new Point(7, 36);
textBoxCollectionName.Name = "textBoxCollectionName"; textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(476, 39); textBoxCollectionName.Size = new Size(167, 23);
textBoxCollectionName.TabIndex = 1; textBoxCollectionName.TabIndex = 8;
// //
// labelCollectionName // labelCollectionName
// //
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(128, 13); labelCollectionName.Location = new Point(31, 18);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(251, 32); labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 7;
labelCollectionName.Text = "Название коллекции:"; labelCollectionName.Text = "Название коллекции:";
// //
// comboBoxSelectorCompany // comboBoxSelectorCompany
@ -237,111 +157,173 @@
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
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(9, 566); comboBoxSelectorCompany.Location = new Point(7, 274);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(476, 40); comboBoxSelectorCompany.Size = new Size(166, 23);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
// //
// pictureBox // buttonCreateCompany
// //
pictureBox.Dock = DockStyle.Fill; buttonCreateCompany.Location = new Point(9, 313);
pictureBox.Location = new Point(0, 40); buttonCreateCompany.Name = "buttonCreateCompany";
pictureBox.Name = "pictureBox"; buttonCreateCompany.Size = new Size(165, 23);
pictureBox.Size = new Size(1605, 1224); buttonCreateCompany.TabIndex = 14;
pictureBox.TabIndex = 1; buttonCreateCompany.Text = "Создать компанию";
pictureBox.TabStop = false; buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(8, 208);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(164, 40);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(8, 162);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(164, 40);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(8, 116);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(164, 40);
buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удалить корабль";
buttonRemoveShip.UseVisualStyleBackColor = true;
buttonRemoveShip.Click += ButtonRemoveShip_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(8, 87);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(164, 23);
maskedTextBoxPosition.TabIndex = 3;
//
// buttonAddShip
//
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(8, 41);
buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(164, 40);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавление корабля";
buttonAddShip.UseVisualStyleBackColor = true;
buttonAddShip.Click += ButtonAddShip_Click;
// //
// menuStrip // menuStrip
// //
menuStrip.ImageScalingSize = new Size(32, 32); menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); 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.Size = new Size(2093, 40); menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.TabIndex = 2; menuStrip.Size = new Size(962, 24);
menuStrip.Text = "menuStrip"; menuStrip.TabIndex = 1;
menuStrip.Text = "menuStrip1";
// //
// файлToolStripMenuItem // fileToolStripMenuItem
// //
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem"; fileToolStripMenuItem.Name = "fileToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(90, 36); fileToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл"; fileToolStripMenuItem.Text = "Файл";
// //
// saveToolStripMenuItem // saveToolStripMenuItem
// //
saveToolStripMenuItem.Name = "saveToolStripMenuItem"; saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; saveToolStripMenuItem.Size = new Size(133, 22);
saveToolStripMenuItem.Size = new Size(343, 44);
saveToolStripMenuItem.Text = "Сохранить"; saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
// //
// loadToolStripMenuItem // loadToolStripMenuItem
// //
loadToolStripMenuItem.Name = "loadToolStripMenuItem"; loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; loadToolStripMenuItem.Size = new Size(133, 22);
loadToolStripMenuItem.Size = new Size(343, 44);
loadToolStripMenuItem.Text = "Загрузить"; loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
// //
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog // openFileDialog
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.FileName = "Ships";
//
// saveFileDialog
//
saveFileDialog.FileName = "Ships";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRemoveShip);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(784, 366);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(178, 250);
panelCompanyTools.TabIndex = 15;
// //
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(2093, 1264); ClientSize = new Size(962, 616);
Controls.Add(panelCompanyTools);
Controls.Add(groupBoxTools);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(Tools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Name = "FormShipCollection"; Name = "FormShipCollection";
Text = "Коллекция кораблей"; Text = "Коллекция кораблей";
Tools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
menuStrip.ResumeLayout(false); menuStrip.ResumeLayout(false);
menuStrip.PerformLayout(); menuStrip.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
#endregion #endregion
private GroupBox Tools;
private Button buttonAddShip;
private ComboBox comboBoxSelectorCompany;
private Button buttonDelShip;
private MaskedTextBox maskedTextBox;
private PictureBox pictureBox; private PictureBox pictureBox;
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddShip;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRefresh; private Button buttonRefresh;
private Button buttonGoToTest; private Button buttonGoToCheck;
private Panel panelStorage; private Button buttonRemoveShip;
private Label labelCollectionName; private ListBox listBoxCollection;
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 Button buttonCollectionDel; private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip; private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem; private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Panel panelCompanyTools;
} }
} }

View File

@ -1,24 +1,29 @@
using ProjectBattleship; using Battleship;
using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings; using ProjectBattleship.Drawnings;
using System.Windows.Forms;
using Battleship.Exceptions;
using Microsoft.Extensions.Logging;
namespace ProjectBattleship
namespace Battleship;
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;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormShipCollection() public FormShipCollection(ILogger<FormShipCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@ -27,16 +32,46 @@ public partial class FormShipCollection : Form
/// <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)
{
case "Хранилище":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawingShip>());
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 ButtonDelShip_Click(object sender, EventArgs e) private void ButtonAddShip_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) FormShipConfig form = new();
form.Show();
form.AddEvent(SetShip);
}
private void SetShip(DrawingShip? ship)
{
if (_company == null || ship == null)
return;
try
{
var res = _company + ship;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (CollectionOverflowException ex)
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
return; return;
} }
@ -46,34 +81,49 @@ public partial class FormShipCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление корабля по индексу {pos}", pos);
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
_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 ButtonGoToTest_Click(object sender, EventArgs e) private void ButtonGoToCheck_Click(object sender, EventArgs e)
{ {
if (_company == null) if (_company == null)
{ {
return; return;
} }
DrawingShip? ship = null; DrawingShip? car = null;
int counter = 100; int counter = 100;
while (ship == null) while (car == null)
{ {
ship = _company.GetRandomObject(); car = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
@ -81,20 +131,19 @@ public partial class FormShipCollection : Form
} }
} }
if (ship == null) if (car == null)
{ {
return; return;
} }
FormBattleship form = new() FormBattleship form = new()
{ {
SetShip = ship 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>
@ -107,98 +156,8 @@ public partial class FormShipCollection : Form
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
/// <summary>
/// Кнопка добавления корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
FormShipConfig form = new();
form.AddEvent(SetShip);
form.Show();
}
/// <summary>
/// Метод установки корабля в компанию
/// </summary>
private void SetShip(DrawingShip? ship)
{
if (_company == null)
return;
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None; private void buttonCreateCompany_Click(object sender, EventArgs e)
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
return;
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
@ -215,50 +174,97 @@ public partial class FormShipCollection : Form
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();
} }
/// <summary>
/// Обработка кнопки сохранения private void buttonCollectionDel_Click(object sender, EventArgs e)
/// </summary> {
/// <param name="sender"></param> if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
/// <param name="e"></param> {
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
return;
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
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)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems(); RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
} }
} }

View File

@ -120,13 +120,10 @@
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value> <value>17, 17</value>
</metadata> </metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>204, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>447, 17</value> <value>145, 17</value>
</metadata> </metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>25</value> <value>307, 17</value>
</metadata> </metadata>
</root> </root>

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using Battleship; using Battleship;
namespace ProjectBattleship namespace ProjectBattleship
@ -13,7 +17,35 @@ namespace ProjectBattleship
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Battleship"
}
}
}