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

View File

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

View File

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

View File

@ -7,6 +7,7 @@ using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
@ -27,32 +28,45 @@ namespace ProjectBattleship.CollectionGenericObjects;
protected override void DrawBackground(Graphics g)
{
Pen pen = new Pen(Color.Brown, 4);
int x = 0, y = 0;
while (y + _placeSizeHeight < _pictureHeight)
Pen pen = new(Color.Black);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
while (x + _placeSizeWidth < _pictureWidth)
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, x, y, x + _placeSizeWidth, y);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight);
g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth, y + _placeSizeHeight);
x += _placeSizeWidth + 50;
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
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()
{
int count = 0;
for (int iy = _placeSizeHeight * 11 + 5; iy >= 0; iy -= _placeSizeHeight)
int n = 0;
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);
_collection?.Get(count)?.SetPosition(ix, iy);
count++;
try
{
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.Drawnings;
using System.Text;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
@ -73,11 +74,11 @@ public class StorageCollection<T>
return null;
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -110,20 +111,19 @@ public class StorageCollection<T>
sb.Clear();
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
throw new FormatException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
@ -136,22 +136,30 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
{
try
{
if (collection.Insert(ship) == -1)
return false;
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <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
{
@ -28,15 +28,8 @@
/// </summary>
private void InitializeComponent()
{
Tools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddShip = new Button();
buttonRefresh = new Button();
maskedTextBox = new MaskedTextBox();
buttonGoToTest = new Button();
buttonDelShip = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
pictureBox = new PictureBox();
groupBoxTools = new GroupBox();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
@ -45,162 +38,89 @@
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
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();
файлToolStripMenuItem = new ToolStripMenuItem();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
Tools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
saveFileDialog = new SaveFileDialog();
panelCompanyTools = new Panel();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
groupBoxTools.SuspendLayout();
menuStrip.SuspendLayout();
panelCompanyTools.SuspendLayout();
SuspendLayout();
//
// Tools
// pictureBox
//
Tools.Controls.Add(panelCompanyTools);
Tools.Controls.Add(buttonCreateCompany);
Tools.Controls.Add(panelStorage);
Tools.Controls.Add(comboBoxSelectorCompany);
Tools.Dock = DockStyle.Right;
Tools.Location = new Point(1605, 40);
Tools.Name = "Tools";
Tools.Size = new Size(488, 1224);
Tools.TabIndex = 0;
Tools.TabStop = false;
Tools.Text = "Инструменты";
pictureBox.Dock = DockStyle.Left;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(783, 592);
pictureBox.TabIndex = 0;
pictureBox.TabStop = false;
//
// panelCompanyTools
// groupBoxTools
//
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonGoToTest);
panelCompanyTools.Controls.Add(buttonDelShip);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 686);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(488, 569);
panelCompanyTools.TabIndex = 8;
//
// buttonAddShip
//
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(9, 3);
buttonAddShip.Name = "buttonAddShip";
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;
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(buttonCollectionDel);
groupBoxTools.Controls.Add(listBoxCollection);
groupBoxTools.Controls.Add(buttonCollectionAdd);
groupBoxTools.Controls.Add(radioButtonList);
groupBoxTools.Controls.Add(radioButtonMassive);
groupBoxTools.Controls.Add(textBoxCollectionName);
groupBoxTools.Controls.Add(labelCollectionName);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(784, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(178, 592);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(6, 443);
buttonCollectionDel.Location = new Point(7, 232);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(473, 46);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Size = new Size(167, 23);
buttonCollectionDel.TabIndex = 13;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
buttonCollectionDel.Click += buttonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 32;
listBoxCollection.Location = new Point(9, 209);
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(7, 118);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(473, 228);
listBoxCollection.TabIndex = 5;
listBoxCollection.Size = new Size(167, 109);
listBoxCollection.TabIndex = 12;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(6, 157);
buttonCollectionAdd.Location = new Point(7, 90);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(473, 46);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Size = new Size(167, 23);
buttonCollectionAdd.TabIndex = 11;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(306, 102);
radioButtonList.Location = new Point(102, 64);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(125, 36);
radioButtonList.TabIndex = 3;
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 10;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
@ -208,28 +128,28 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(43, 102);
radioButtonMassive.Location = new Point(20, 64);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(128, 36);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 9;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(6, 48);
textBoxCollectionName.Location = new Point(7, 36);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(476, 39);
textBoxCollectionName.TabIndex = 1;
textBoxCollectionName.Size = new Size(167, 23);
textBoxCollectionName.TabIndex = 8;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(128, 13);
labelCollectionName.Location = new Point(31, 18);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(251, 32);
labelCollectionName.TabIndex = 0;
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 7;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
@ -237,111 +157,173 @@
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Доки" });
comboBoxSelectorCompany.Location = new Point(9, 566);
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(7, 274);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(476, 40);
comboBoxSelectorCompany.Size = new Size(166, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
// buttonCreateCompany
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 40);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1605, 1224);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
buttonCreateCompany.Location = new Point(9, 313);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(165, 23);
buttonCreateCompany.TabIndex = 14;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// buttonRefresh
//
buttonRefresh.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.ImageScalingSize = new Size(32, 32);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(2093, 40);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(962, 24);
menuStrip.TabIndex = 1;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
// fileToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(90, 36);
файлToolStripMenuItem.Text = "Файл";
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(48, 20);
fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(343, 44);
saveToolStripMenuItem.Size = new Size(133, 22);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(343, 44);
loadToolStripMenuItem.Size = new Size(133, 22);
loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// 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
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(2093, 1264);
ClientSize = new Size(962, 616);
Controls.Add(panelCompanyTools);
Controls.Add(groupBoxTools);
Controls.Add(pictureBox);
Controls.Add(Tools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "Коллекция кораблей";
Tools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox Tools;
private Button buttonAddShip;
private ComboBox comboBoxSelectorCompany;
private Button buttonDelShip;
private MaskedTextBox maskedTextBox;
private PictureBox pictureBox;
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddShip;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRefresh;
private Button buttonGoToTest;
private Panel panelStorage;
private Label labelCollectionName;
private Button buttonGoToCheck;
private Button buttonRemoveShip;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Panel panelCompanyTools;
}
}

View File

@ -1,24 +1,29 @@
using ProjectBattleship;
using Battleship;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings;
using System.Windows.Forms;
using Battleship.Exceptions;
using Microsoft.Extensions.Logging;
namespace Battleship;
public partial class FormShipCollection : Form
namespace ProjectBattleship
{
public partial class FormShipCollection : Form
{
private readonly StorageCollection<DrawingShip> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
@ -27,16 +32,46 @@ public partial class FormShipCollection : Form
/// <param name="e"></param>
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;
}
/// <summary>
/// Кнопка удаления корабля
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></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;
}
@ -46,34 +81,49 @@ public partial class FormShipCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление корабля по индексу {pos}", pos);
}
else
{
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>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToTest_Click(object sender, EventArgs e)
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawingShip? ship = null;
DrawingShip? car = null;
int counter = 100;
while (ship == null)
while (car == null)
{
ship = _company.GetRandomObject();
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
@ -81,20 +131,19 @@ public partial class FormShipCollection : Form
}
}
if (ship == null)
if (car == null)
{
return;
}
FormBattleship form = new()
{
SetShip = ship
SetShip = car
};
form.ShowDialog();
}
/// <summary>
/// Кнопка обновить
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@ -107,98 +156,8 @@ public partial class FormShipCollection : Form
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;
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)
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
@ -215,50 +174,97 @@ public partial class FormShipCollection : Form
switch (comboBoxSelectorCompany.Text)
{
case "Доки":
case "Хранилище":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
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());
_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)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
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)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
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">
<value>17, 17</value>
</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">
<value>447, 17</value>
<value>145, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>307, 17</value>
</metadata>
</root>

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using Battleship;
namespace ProjectBattleship
@ -13,7 +17,35 @@ namespace ProjectBattleship
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<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"
}
}
}