PIbd-21_Eliseev_E.E._Airbus.../Airbus/Airbus/FormMapWithSetPlanes.cs

296 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Airbus
{
public partial class FormMapWithSetPlanes : Form
{
//словарь для выпадающего списка
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{"Простая карта", new SimpleMap() },
{"Буря в пустыне", new DesertStormMap() },
{"Звёздные войны", new StarWarsMap() }
};
//объект от коллекции карт
private readonly MapsCollection _mapsCollection;
//логер
private readonly ILogger _logger;
//конструктор
public FormMapWithSetPlanes(ILogger<FormMapWithSetPlanes> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var element in _mapsDict)
{
comboBoxSelectorMap.Items.Add(element.Key);
}
}
//заполнение ListBoxMaps
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
}
}
//добавление карты
private void ButtonAddMap_Click_1(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Отсутствует карта с названием {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
//Выбор карты
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
// Удаление карты
private void buttonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
}
//отрисовка добавленного объекта в хранилище
private void AddPlane(DrawningAirbus plane)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Airbus}", plane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch(StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка, хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Airbus}", ex.Message, plane);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//добавление объекта
private void ButtonAddPlane_Click(object sender, EventArgs e)
{
var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlane);
formPlaneConfig.Show();
}
//удаление объекта
private void ButtonRemovePlane_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1 || string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
var deletedPlane = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedPlane != null)
{
MessageBox.Show("Объект удалён");
_logger.LogInformation("Из текущей карты удалён объект {@Airbus}", deletedPlane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (PlaneNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
//вывод набора
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty] == null)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
}
//вывод карты
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty] == null)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowOnMap();
}
//перемещение
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty] == null)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].MoveObject(dir);
}
//обработка нажатия сохранения
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
//обработка нажатия загрузки
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
MessageBox.Show("Загрузка данных прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
}
}