From 6ead7f2b6908088689406fa14e32922fb459dc28 Mon Sep 17 00:00:00 2001 From: Alkin Ivan Date: Tue, 21 May 2024 03:28:00 +0400 Subject: [PATCH] finish --- .../AbstractCompany.cs | 17 +- .../ListGenericObjects.cs | 3 +- .../MassiveGenericObjects.cs | 2 +- .../StorageCollection.cs | 3 +- AirBomber/FormAirPlaneCollection.cs | 603 +++++++++--------- 5 files changed, 317 insertions(+), 311 deletions(-) diff --git a/AirBomber/CollectionGenericObjects/AbstractCompany.cs b/AirBomber/CollectionGenericObjects/AbstractCompany.cs index ab94fa9..e05c894 100644 --- a/AirBomber/CollectionGenericObjects/AbstractCompany.cs +++ b/AirBomber/CollectionGenericObjects/AbstractCompany.cs @@ -40,7 +40,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -62,9 +62,9 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningAirPlane boat) + public static int operator +(AbstractCompany company, DrawningAirPlane airPlane) { - return company._collection?.Insert(boat) ?? -1; + return company._collection?.Insert(airPlane) ?? -1; } /// @@ -101,8 +101,13 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningAirPlane? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningAirPlane? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } + } return bitmap; @@ -118,4 +123,4 @@ public abstract class AbstractCompany /// Расстановка объектов /// protected abstract void SetObjectsPosition(); -} +} \ No newline at end of file diff --git a/AirBomber/CollectionGenericObjects/ListGenericObjects.cs b/AirBomber/CollectionGenericObjects/ListGenericObjects.cs index 4c9bc9f..798ce16 100644 --- a/AirBomber/CollectionGenericObjects/ListGenericObjects.cs +++ b/AirBomber/CollectionGenericObjects/ListGenericObjects.cs @@ -61,6 +61,7 @@ public class ListGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); _collection.Insert(position, obj); return position; + } public T Remove(int position) @@ -78,4 +79,4 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } -} \ No newline at end of file +} diff --git a/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs index 57f097b..fd698b6 100644 --- a/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AirBomber/CollectionGenericObjects/MassiveGenericObjects.cs @@ -119,4 +119,4 @@ where T : class yield return _collection[i]; } } -} \ No newline at end of file +} diff --git a/AirBomber/CollectionGenericObjects/StorageCollection.cs b/AirBomber/CollectionGenericObjects/StorageCollection.cs index 4d7db31..1a67094 100644 --- a/AirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/AirBomber/CollectionGenericObjects/StorageCollection.cs @@ -70,7 +70,7 @@ public class StorageCollection return; } } - + /// /// Удаление коллекции /// @@ -201,7 +201,6 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); } } diff --git a/AirBomber/FormAirPlaneCollection.cs b/AirBomber/FormAirPlaneCollection.cs index 13603c2..c1a133d 100644 --- a/AirBomber/FormAirPlaneCollection.cs +++ b/AirBomber/FormAirPlaneCollection.cs @@ -12,337 +12,338 @@ using System.Windows.Forms; using Microsoft.Extensions.Logging; using AirBomber.Exceptions; -namespace AirBomber +namespace AirBomber; + +public partial class FormAirPlaneCollection : Form { - public partial class FormAirPlaneCollection : Form + /// + /// Хранилище коллекций + /// + private readonly StorageCollection _storageCollection; + + /// + /// Компания + /// + private AbstractCompany? _company = null; + + private readonly ILogger _logger; + + /// + /// Конструктор + /// + public FormAirPlaneCollection(ILogger logger) { - /// - /// Хранилище коллекций - /// - private readonly StorageCollection _storageCollection; + InitializeComponent(); + _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); + } - /// - /// Компания - /// - private AbstractCompany? _company; + /// + /// Выбор компании + /// + /// + /// + private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + panelCompanyTools.Enabled = false; + } - private readonly ILogger _logger; + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта - /// - /// Конструктор - /// - public FormAirPlaneCollection(ILogger logger) + + /// + /// Добавление самолета + /// + /// + /// + private void buttonAddAirPlane_Click(object sender, EventArgs e) + { + FormAirPlaneConfig form = new(); + //TODO передать метод + form.Show(); + form.AddEvent(SetAirPlane); + } + + /// + /// Добавление самолета в коллекцию + /// + /// + private void SetAirPlane(DrawningAirPlane airplane) + { + try { - InitializeComponent(); - _storageCollection = new(); - } - - /// - /// Выбор компании - /// - /// - /// - private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) - { - panelCompanyTools.Enabled = false; - } - - /// - /// Создание объекта класса-перемещения - /// - /// Тип создаваемого объекта - - - /// - /// Добавление самолета - /// - /// - /// - private void buttonAddAirPlane_Click(object sender, EventArgs e) - { - FormAirPlaneConfig form = new(); - //TODO передать метод - form.Show(); - form.AddEvent(SetAirPlane); - } - - /// - /// Добавление самолета в коллекцию - /// - /// - private void SetAirPlane(DrawningAirPlane airplane) - { - try - { - if (_company == null || airplane == null) - { - return; - } - - if (_company + airplane != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave()); - } - } - catch (ObjectNotFoundException) { } - catch (CollectionOverflowException ex) - { - MessageBox.Show("В коллекции превышено допустимое количество элементов"); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - - } - - /// - /// Получение цвета - /// - /// Генератор случайных чисел - /// - private static Color GetColor(Random random) - { - Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); - ColorDialog dialog = new(); - if (dialog.ShowDialog() == DialogResult.OK) - { - color = dialog.Color; - } - - return color; - } - - /// - /// Удаление объекта - /// - /// - /// - private void ButtonRemoveAirPlane_Click(object sender, EventArgs e) - { - int pos = Convert.ToInt32(maskedTextBox.Text); - try - { - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) - { - throw new Exception("Входные данные отсутствуют"); - } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - - - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Объект удален"); - } - } - catch (Exception ex) - { - MessageBox.Show("Не найден объект по позиции " + pos); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - } - - /// - /// Передача объекта в другую форму - /// - /// - /// - private void ButtonGoToCheck_Click(object sender, EventArgs e) - { - if (_company == null) + if (_company == null || airplane == null) { return; } - DrawningAirPlane? airPlane = null; - int counter = 100; + if (_company + airplane != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave()); + } + } + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) + { + MessageBox.Show("В коллекции превышено допустимое количество элементов"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + + } + + /// + /// Получение цвета + /// + /// Генератор случайных чисел + /// + private static Color GetColor(Random random) + { + Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + color = dialog.Color; + } + + return color; + } + + /// + /// Удаление объекта + /// + /// + /// + private void ButtonRemoveAirPlane_Click(object sender, EventArgs e) + { + int pos = Convert.ToInt32(maskedTextBox.Text); + try + { + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) + { + throw new Exception("Входные данные отсутствуют"); + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект удален"); + } + } + catch (Exception ex) + { + MessageBox.Show("Не найден объект по позиции " + pos); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + + /// + /// Передача объекта в другую форму + /// + /// + /// + private void ButtonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawningAirPlane? airPlane = null; + int counter = 100; + try + { + while (airPlane == null) + { + airPlane = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (airPlane == null) + { + return; + } + + FormAirBomber form = new FormAirBomber(); + form.SetAirPlane = airPlane; + form.ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } + + private void FormAirPlaneCollection_Load(object sender, EventArgs e) + { + + } + + private void buttonCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + { + MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RefreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + + private void RefreshListBoxItems() + { + 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 buttonCollectionDel_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RefreshListBoxItems(); + } + /// + /// Создание компании + /// + /// + /// + private void buttonCreateCompany_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + if (collection == null) + { + MessageBox.Show("Коллекция не проинициализирована"); + return; + } + + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection); + break; + } + + panelCompanyTools.Enabled = true; + RefreshListBoxItems(); + } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { try { - while (airPlane == null) - { - airPlane = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } - } - - if (airPlane == null) - { - return; - } - - FormAirBomber form = new FormAirBomber(); - form.SetAirPlane = airPlane; - form.ShowDialog(); + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - /// - /// Перерисовка коллекции - /// - /// - /// - private void ButtonRefresh_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; + _logger.LogError("Ошибка: {Message}", ex.Message); } - pictureBox.Image = _company.Show(); - } - - private void FormAirPlaneCollection_Load(object sender, EventArgs e) - { } + } - private void buttonCollectionAdd_Click(object sender, EventArgs e) + /// + /// Обработка кнопки загрузки + /// + /// + /// + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) - { - MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - try { - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RefreshListBoxItems(); - _logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } catch (Exception ex) { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } - - private void RefreshListBoxItems() - { - 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 buttonCollectionDel_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RefreshListBoxItems(); - } - /// - /// Создание компании - /// - /// - /// - private void buttonCreateCompany_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) - { - MessageBox.Show("Коллекция не проинициализирована"); - return; - } - - switch (comboBoxSelectorCompany.Text) - { - case "Хранилище": - _company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection); - break; - } - - panelCompanyTools.Enabled = true; - RefreshListBoxItems(); - } - - /// - /// Обработка нажатия "Сохранение" - /// - /// - /// - private void saveToolStripMenuItem_Click(object sender, EventArgs e) - { - if (saveFileDialog.ShowDialog() == DialogResult.OK) - { - try - { - _storageCollection.SaveData(saveFileDialog.FileName); - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - - - } - } - - /// - /// Обработка кнопки загрузки - /// - /// - /// - private void loadToolStripMenuItem_Click(object sender, EventArgs e) - { - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - try - { - _storageCollection.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RefreshListBoxItems(); - _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); - } - catch (Exception ex) - { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - } - } } }