diff --git a/Battleship/Battleship/Battleship.csproj b/Battleship/Battleship/Battleship.csproj index e1a0735..54659fd 100644 --- a/Battleship/Battleship/Battleship.csproj +++ b/Battleship/Battleship/Battleship.csproj @@ -8,4 +8,14 @@ enable + + + + + + + + + + \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs index 8225125..1fd9715 100644 --- a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs +++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs @@ -9,7 +9,7 @@ public abstract class AbstractCompany /// /// Размер места (ширина) /// - protected readonly int _placeSizeWidth = 210; + protected readonly int _placeSizeWidth = 260; /// /// Размер места (высота) diff --git a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs index 05cd404..a86229f 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace Battleship.CollectionGenericObjects; +using Battleship.Exceptions; + +namespace Battleship.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -40,7 +42,7 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { if (position < 0 || position >= _collection.Count) - return null; + throw new PositionOutOfCollectionException(position); return _collection[position]; } @@ -51,13 +53,15 @@ public class ListGenericObjects : ICollectionGenericObjects _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; } @@ -65,7 +69,7 @@ public class ListGenericObjects : ICollectionGenericObjects 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; diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs index 6f35a82..bf51643 100644 --- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace Battleship.CollectionGenericObjects; +using Battleship.Exceptions; + +namespace Battleship.CollectionGenericObjects; /// /// Параметризованный набор объектов /// @@ -53,10 +55,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { if (position < 0 || position >= _collection.Length) - return null; + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); return _collection[position]; } - public int Insert(T obj) //??? Уточнить реализацию + public int Insert(T obj) { for (int i = 0; i < _collection.Length; i++) { @@ -66,12 +70,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects 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; @@ -93,16 +97,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects 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; - return temp; } diff --git a/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs b/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs index ed35c78..ab9fcbc 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs @@ -31,10 +31,10 @@ public class ShipDocks : AbstractCompany { while (x + _placeSizeWidth < _pictureWidth) { - g.DrawLine(pen, x, y, x + _placeSizeWidth, y); + g.DrawLine(pen, x, y, x + _placeSizeWidth - 50, 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, x, y + _placeSizeHeight, x + _placeSizeWidth - 50, y + _placeSizeHeight); + x += _placeSizeWidth; } y += _placeSizeHeight; x = 0; @@ -46,10 +46,13 @@ public class ShipDocks : AbstractCompany int count = 0; for (int iy = _placeSizeHeight * 11 + 5; iy >= 0; iy -= _placeSizeHeight) { - for(int ix = 5; ix + _placeSizeWidth+50 < _pictureWidth; ix += _placeSizeWidth + 50) + for(int ix = 5; ix + _placeSizeWidth <= _pictureWidth; ix += _placeSizeWidth) { - _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(count)?.SetPosition(ix, iy); + if (count < _collection.Count) + { + _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(count)?.SetPosition(ix, iy); + } count++; } } diff --git a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs index 7d722bc..f649f2d 100644 --- a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs +++ b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using Battleship.Drawnings; +using Battleship.Exceptions; using System.Text; namespace Battleship.CollectionGenericObjects; @@ -97,7 +98,7 @@ public class StorageCollection { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -143,7 +144,7 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) @@ -151,7 +152,7 @@ public class StorageCollection string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - throw new Exception("В файле неверные данные"); + throw new FormatException("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -164,7 +165,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - throw new Exception("Не удалось определить тип коллекции:" + record[1]); + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -174,8 +175,17 @@ public class StorageCollection { if (elem?.CreateDrawningShip() is T ship) { - if (collection.Insert(ship) == -1) - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + try + { + if (collection.Insert(ship) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); diff --git a/Battleship/Battleship/FormShipCollection.Designer.cs b/Battleship/Battleship/FormShipCollection.Designer.cs index af1d2dd..2e3ea2c 100644 --- a/Battleship/Battleship/FormShipCollection.Designer.cs +++ b/Battleship/Battleship/FormShipCollection.Designer.cs @@ -66,9 +66,9 @@ Tools.Controls.Add(panelStorage); Tools.Controls.Add(comboBoxSelectorCompany); Tools.Dock = DockStyle.Right; - Tools.Location = new Point(1605, 40); + Tools.Location = new Point(1566, 40); Tools.Name = "Tools"; - Tools.Size = new Size(488, 1224); + Tools.Size = new Size(488, 1209); Tools.TabIndex = 0; Tools.TabStop = false; Tools.Text = "Инструменты"; @@ -249,7 +249,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1605, 1224); + pictureBox.Size = new Size(1566, 1209); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -259,7 +259,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(2093, 40); + menuStrip.Size = new Size(2054, 40); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip"; // @@ -298,7 +298,7 @@ // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(2093, 1264); + ClientSize = new Size(2054, 1249); Controls.Add(pictureBox); Controls.Add(Tools); Controls.Add(menuStrip); diff --git a/Battleship/Battleship/FormShipCollection.cs b/Battleship/Battleship/FormShipCollection.cs index bd2fa9a..d411f8a 100644 --- a/Battleship/Battleship/FormShipCollection.cs +++ b/Battleship/Battleship/FormShipCollection.cs @@ -1,6 +1,7 @@ using Battleship.CollectionGenericObjects; using Battleship.Drawnings; - +using Battleship.Exceptions; +using Microsoft.Extensions.Logging; namespace Battleship; @@ -11,14 +12,19 @@ public partial class FormShipCollection : Form /// Компания /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; /// /// Конструктор /// - public FormShipCollection() - { - InitializeComponent(); - _storageCollection = new(); - } + public FormShipCollection(ILogger logger) + { + InitializeComponent(); + _storageCollection = new(); + _logger = logger; + } #region Работа с компанией /// /// Выбор компании @@ -30,6 +36,33 @@ public partial class FormShipCollection : Form panelCompanyTools.Enabled = false; } /// + /// Метод установки корабля в компанию + /// + private void SetShip(DrawningShip? ship) + { + if (_company == null) + return; + try + { + if (_company + ship != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавление корабля {ship} в коллекцию", ship); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", ship); + } + } + catch(CollectionOverflowException ex) + { + MessageBox.Show("Ошибка переполнения коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + /// /// Кнопка удаления корабля /// /// @@ -45,17 +78,32 @@ public partial class FormShipCollection : Form { return; } + try + { + int pos = Convert.ToInt32(maskedTextBox.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); + } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } } /// /// Кнопка отправки на тест @@ -118,23 +166,7 @@ public partial class FormShipCollection : Form form.AddEvent(SetShip); form.Show(); } - /// - /// Метод установки корабля в компанию - /// - private void SetShip(DrawningShip? ship) - { - if (_company == null) - return; - if (_company + ship != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } + #endregion #region Работа с коллекцией /// @@ -147,6 +179,7 @@ public partial class FormShipCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } @@ -160,6 +193,7 @@ public partial class FormShipCollection : Form collectionType = CollectionType.List; } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); RerfreshListBoxItems(); } /// @@ -177,6 +211,7 @@ public partial class FormShipCollection : Form if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } /// @@ -220,8 +255,9 @@ public partial class FormShipCollection : Form case "Доки": _company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection); break; + default: + return; } - panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } @@ -236,13 +272,16 @@ public partial class FormShipCollection : Form { 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); } } } @@ -255,14 +294,17 @@ public partial class FormShipCollection : Form { 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}", saveFileDialog.FileName); } - else + catch (Exception ex) { MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/Battleship/Battleship/Program.cs b/Battleship/Battleship/Program.cs index 65edaed..0175bd8 100644 --- a/Battleship/Battleship/Program.cs +++ b/Battleship/Battleship/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace Battleship { internal static class Program @@ -11,7 +16,30 @@ namespace Battleship // 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()); + } + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "C:\\Users\\grishazagidulin\\source\\repos\\Pi-12_Zagidulin_GA_Simple\\Battleship\\Battleship\\appSetting.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } } \ No newline at end of file diff --git a/Battleship/Battleship/appSetting.json b/Battleship/Battleship/appSetting.json new file mode 100644 index 0000000..165ec4f --- /dev/null +++ b/Battleship/Battleship/appSetting.json @@ -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" + } + } +}