370 lines
12 KiB
C#
370 lines
12 KiB
C#
using Battleship.CollectionGenericObjects;
|
||
using Microsoft.Extensions.Logging;
|
||
using ProjectBattleship.CollectionGenericObjects;
|
||
using ProjectBattleship.DrawingObject;
|
||
using System.Windows.Forms;
|
||
|
||
namespace ProjectBattleship;
|
||
/// <summary>
|
||
/// Форма работы с компанией и ее коллекцией
|
||
/// </summary>
|
||
public partial class FormWarshipCollection : Form
|
||
{
|
||
/// <summary>
|
||
/// Хранилише коллекций
|
||
/// </summary>
|
||
private readonly StorageCollection<DrawingWarship> _storageCollection;
|
||
/// <summary>
|
||
/// Компания
|
||
/// </summary>
|
||
private AbstractCompany? _company = null;
|
||
/// <summary>
|
||
/// Логер
|
||
/// </summary>
|
||
private readonly ILogger _logger;
|
||
/// <summary>
|
||
/// Конструктор
|
||
/// </summary>
|
||
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
|
||
{
|
||
InitializeComponent();
|
||
_storageCollection = new();
|
||
_logger = logger;
|
||
}
|
||
/// <summary>
|
||
/// Выбор компании
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender,
|
||
EventArgs e)
|
||
{
|
||
panelCompanyTools.Enabled = false;
|
||
}
|
||
/// <summary>
|
||
/// Добавление военного корабля
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ButtonAddWarship_Click(object sender, EventArgs e)
|
||
{
|
||
FormWarshipConfig form = new();
|
||
form.Show();
|
||
form.AddEvent(SetWarship);
|
||
}
|
||
/// <summary>
|
||
/// Добавление военного корабля в коллекцию
|
||
/// </summary>
|
||
/// <param name="Warship"></param>
|
||
private void SetWarship(DrawingWarship warship)
|
||
{
|
||
if (_company == null || warship == null)
|
||
{
|
||
return;
|
||
}
|
||
try
|
||
{
|
||
var res = _company + warship;
|
||
MessageBox.Show("Объект добавлен");
|
||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||
pictureBox.Image = _company.Show();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||
MessageBoxIcon.Error);
|
||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// Добавление линкора
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ButtonAddBattleship_Click(object sender, EventArgs e) =>
|
||
CreateObject(nameof(DrawingBattleship));
|
||
/// <summary>
|
||
/// Создание объекта класса-перемещения
|
||
/// </summary>
|
||
/// <param name="type">Тип создаваемого объекта</param>
|
||
private void CreateObject(string type)
|
||
{
|
||
if (_company == null)
|
||
{
|
||
return;
|
||
}
|
||
Random random = new();
|
||
DrawingWarship drawingWarship;
|
||
switch (type)
|
||
{
|
||
case nameof(DrawingWarship):
|
||
drawingWarship = new DrawingWarship(random.Next(100, 300),
|
||
random.Next(1000, 3000), GetColor(random));
|
||
break;
|
||
case nameof(DrawingBattleship):
|
||
drawingWarship = new DrawingBattleship(random.Next(100, 300),
|
||
random.Next(1000, 3000),
|
||
GetColor(random), GetColor(random),
|
||
Convert.ToBoolean(random.Next(0, 2)),
|
||
Convert.ToBoolean(random.Next(0, 2)));
|
||
break;
|
||
default:
|
||
return;
|
||
}
|
||
if (_company + drawingWarship != -1)
|
||
{
|
||
MessageBox.Show("Объект добавлен");
|
||
pictureBox.Image = _company.Show();
|
||
}
|
||
else
|
||
{
|
||
MessageBox.Show("Не удалось добавить объект");
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// Получение цвета
|
||
/// </summary>
|
||
/// <param name="random">Генератор случайных чисел</param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
/// <summary>
|
||
/// Удаление объекта
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ButtonRemoveWarship_Click(object sender, EventArgs e)
|
||
{
|
||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|
||
|| _company == null)
|
||
{
|
||
return;
|
||
}
|
||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||
{
|
||
return;
|
||
}
|
||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||
try
|
||
{
|
||
var res = _company - pos;
|
||
MessageBox.Show("Объект удален");
|
||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||
pictureBox.Image = _company.Show();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// Передача объекта в другую форму
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||
{
|
||
if (_company == null)
|
||
{
|
||
return;
|
||
}
|
||
DrawingWarship? warship = null;
|
||
int counter = 100;
|
||
while (warship == null)
|
||
{
|
||
warship = _company.GetRandomObject();
|
||
counter--;
|
||
if (counter <= 0)
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
if (warship == null)
|
||
{
|
||
return;
|
||
}
|
||
FormBattleship form = new()
|
||
{
|
||
SetWarship = warship
|
||
};
|
||
form.ShowDialog();
|
||
}
|
||
/// <summary>
|
||
/// Перерисовка коллекции
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||
{
|
||
if (_company == null)
|
||
{
|
||
return;
|
||
}
|
||
pictureBox.Image = _company.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;
|
||
}
|
||
|
||
try
|
||
{
|
||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||
_logger.LogInformation("Добавление коллекции");
|
||
RerfreshListBoxItems();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||
}
|
||
|
||
}
|
||
/// <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("Коллекция удалена");
|
||
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)
|
||
{
|
||
MessageBox.Show("Коллекция не выбрана");
|
||
return;
|
||
}
|
||
ICollectionGenericObjects<DrawingWarship>? collection =
|
||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||
if (collection == null)
|
||
{
|
||
MessageBox.Show("Коллекция не проинициализирована");
|
||
return;
|
||
}
|
||
switch (comboBoxSelectorCompany.Text)
|
||
{
|
||
case "Хранилище":
|
||
_company = new Docks(pictureBox.Width,
|
||
pictureBox.Height, collection);
|
||
break;
|
||
}
|
||
panelCompanyTools.Enabled = true;
|
||
RerfreshListBoxItems();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Обработка нажатия "Сохранение"
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
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("Не сохранилось", "Результат", 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)
|
||
{
|
||
try
|
||
{
|
||
_storageCollection.LoadData(openFileDialog.FileName);
|
||
RerfreshListBoxItems();
|
||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||
}
|
||
}
|
||
}
|
||
}
|