1 Commits

14 changed files with 92 additions and 524 deletions

View File

@@ -8,27 +8,6 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serilogConfig.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class AirFighterNotFoundException : ApplicationException
{
public AirFighterNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public AirFighterNotFoundException() : base() { }
public AirFighterNotFoundException(string message) : base(message) { }
public AirFighterNotFoundException(string message, Exception exception) :
base(message, exception)
{ }
protected AirFighterNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -34,9 +34,5 @@ namespace AirFighter
{
_airFighter?.SetPosition(x, y, width, height);
}
public string GetInfo() => _airFighter?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectAirFighter(data.CreateDrawningCar());
}
}

View File

@@ -1,60 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
/// <summary>
/// Расширение для класса DrawningAirFighter
/// </summary>
internal static class ExtentionAirFighter
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningAirFighter CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirFighter(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningUpgradeAirFighter(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningAirFighter drawningAirFighter)
{
var airFighter = drawningAirFighter.AirFighter;
var str =
$"{airFighter.Speed}{_separatorForObject}{airFighter.Weight}{_separatorForObject}{airFighter.BodyColor.Name}";
if (airFighter is not EntityUpgradeAirFighter upgradeAirFighter)
{
return str;
}
return
$"{str}{_separatorForObject}{upgradeAirFighter.DopColor.Name}{_separatorForObject}{upgradeAirFighter.DopWing}{_separatorForObject}{upgradeAirFighter.Rocket}";
}
}
}

View File

@@ -29,12 +29,6 @@
private void InitializeComponent()
{
this.groupBox = new System.Windows.Forms.GroupBox();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
@@ -44,17 +38,16 @@
this.buttonRemoveAirFighter = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddAirFighter = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.groupBox.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
this.SuspendLayout();
//
// groupBox
@@ -70,82 +63,19 @@
this.groupBox.Controls.Add(this.maskedTextBoxPosition);
this.groupBox.Controls.Add(this.buttonAddAirFighter);
this.groupBox.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox.Location = new System.Drawing.Point(732, 28);
this.groupBox.Location = new System.Drawing.Point(732, 0);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(250, 561);
this.groupBox.Size = new System.Drawing.Size(250, 555);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(0, 12);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(250, 278);
this.groupBoxMaps.TabIndex = 6;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(17, 244);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(210, 29);
this.buttonDeleteMap.TabIndex = 4;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(17, 154);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(210, 84);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(17, 119);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(210, 29);
this.buttonAddMap.TabIndex = 2;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(17, 36);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(210, 27);
this.textBoxNewMapName.TabIndex = 1;
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Карта шторма"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(17, 75);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(210, 28);
this.comboBoxSelectorMap.TabIndex = 0;
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AirFighter.Properties.Resources.Up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(135, 481);
this.buttonUp.Location = new System.Drawing.Point(135, 475);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 2;
@@ -157,7 +87,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirFighter.Properties.Resources.Down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(135, 519);
this.buttonDown.Location = new System.Drawing.Point(135, 513);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 3;
@@ -169,7 +99,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirFighter.Properties.Resources.Left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(99, 519);
this.buttonLeft.Location = new System.Drawing.Point(99, 513);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 4;
@@ -181,7 +111,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AirFighter.Properties.Resources.Right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(171, 519);
this.buttonRight.Location = new System.Drawing.Point(171, 513);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 5;
@@ -236,76 +166,93 @@
this.buttonAddAirFighter.UseVisualStyleBackColor = true;
this.buttonAddAirFighter.Click += new System.EventHandler(this.ButtonAddAirFighter_Click);
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Карта шторма"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(17, 75);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(210, 28);
this.comboBoxSelectorMap.TabIndex = 0;
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 28);
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(732, 561);
this.pictureBox.Size = new System.Drawing.Size(732, 555);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
// groupBoxMaps
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(982, 28);
this.menuStrip.TabIndex = 2;
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(0, 12);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(250, 278);
this.groupBoxMaps.TabIndex = 6;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// FileToolStripMenuItem
// buttonDeleteMap
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.FileToolStripMenuItem.Text = "Файл";
this.buttonDeleteMap.Location = new System.Drawing.Point(17, 244);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(210, 29);
this.buttonDeleteMap.TabIndex = 4;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// SaveToolStripMenuItem
// listBoxMaps
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(17, 154);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(210, 84);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// LoadToolStripMenuItem
// buttonAddMap
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
this.buttonAddMap.Location = new System.Drawing.Point(17, 119);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(210, 29);
this.buttonAddMap.TabIndex = 2;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// openFileDialog
// textBoxNewMapName
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
this.textBoxNewMapName.Location = new System.Drawing.Point(17, 36);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(210, 27);
this.textBoxNewMapName.TabIndex = 1;
//
// FormMapWithSetAirFighters
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(982, 589);
this.ClientSize = new System.Drawing.Size(982, 555);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirFighters";
this.Text = "FormMapWithSetAirFighters";
this.groupBox.ResumeLayout(false);
this.groupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -328,11 +275,5 @@
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -1,5 +1,4 @@
using Microsoft.Extensions.Logging;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -27,15 +26,10 @@ namespace AirFighter
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
public FormMapWithSetAirFighters(ILogger<FormMapWithSetAirFighters> logger)
public FormMapWithSetAirFighters()
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -74,29 +68,14 @@ namespace AirFighter
if (_airFighter != null)
{
DrawningObjectAirFighter airFighter = new(_airFighter);
try
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airFighter) == 0)
{
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airFighter) == 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавлен объект {airFighter}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Не удалось добавить объект {airFighter}");
}
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
catch (StorageOverflowException ex)
else
{
MessageBox.Show($"Ошибка добавления: {ex.Message}");
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show("Не удалось добавить объект");
}
}
}
@@ -134,29 +113,14 @@ namespace AirFighter
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) != null)
{
var deletedObject = (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos);
if (deletedObject != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удаление объекта {deletedObject}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Не удалось удалить объект {deletedObject}");
}
}catch(AirFighterNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка, объект не найден: {ex.Message}");
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
catch(Exception ex)
else
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
@@ -237,7 +201,6 @@ namespace AirFighter
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
ReloadMaps();
}
/// <summary>
@@ -248,7 +211,6 @@ namespace AirFighter
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Осуществлен переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Удаление карты
@@ -265,55 +227,6 @@ namespace AirFighter
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem}");
}
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></par
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение в файл {saveFileDialog.FileName} прошло успешно");
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить в файл. Ошибка: {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
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName} прошла успешна");
ReloadMaps();
}
catch(Exception ex)
{
MessageBox.Show($"Загрузка не удалась: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить из файла. Ошибка: {ex.Message}");
}
}
}
}

View File

@@ -57,13 +57,4 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<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="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>311, 17</value>
</metadata>
</root>

View File

@@ -37,12 +37,8 @@ namespace AirFighter
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom)GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
(float Left, float Right, float Top, float Bottom)
GetCurrentPosition();
}
}

View File

@@ -114,31 +114,6 @@ namespace AirFighter
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var airFighter in _setAirFighters.GetAirFighters())
{
data += $"{airFighter.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setAirFighters.Insert(DrawningObjectAirFighter.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()

View File

@@ -14,7 +14,7 @@ namespace AirFighter
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@@ -24,14 +24,6 @@ namespace AirFighter
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
@@ -42,7 +34,7 @@ namespace AirFighter
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -55,7 +47,7 @@ namespace AirFighter
{
if (!string.IsNullOrEmpty(name) && map != null && !Keys.Contains(name))
{
_mapStorages.Add(name, new MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
}
/// <summary>
@@ -74,11 +66,11 @@ namespace AirFighter
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap> this[string ind]
public MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap> this[string ind]
{
get
{
MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap> _map;
MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap> _map;
if (_mapStorages.TryGetValue(ind, out _map))
{
return _map;
@@ -87,68 +79,5 @@ namespace AirFighter
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка нформации по самолетам на парковках из файла
/// </summary>
/// <param name = "filename" ></ param >
/// < returns ></ returns >
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
string bufferTextFromFile = "";
using (StreamReader sr = new(filename))
{
string checkMap = sr.ReadLine();
if (!checkMap.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
bufferTextFromFile = sr.ReadLine();
_mapStorages.Clear();
while (bufferTextFromFile != null)
{
var strs = bufferTextFromFile.Split(separatorDict);
AbstractMap map = null;
switch (strs[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "StormMap":
map = new StormMap();
break;
}
_mapStorages.Add(strs[0], new MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[strs[0]].LoadData(strs[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
bufferTextFromFile = sr.ReadLine();
}
}
}
}
}

View File

@@ -1,8 +1,3 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirFighter
{
internal static class Program
@@ -16,31 +11,7 @@ namespace AirFighter
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirFighters>());
}
Application.Run(new FormMapWithSetAirFighters());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetAirFighters>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -52,10 +52,6 @@ namespace AirFighter
/// <returns></returns>
public int Insert(T airFighter, int position)
{
if (Count >= _maxCount)
{
throw new StorageOverflowException();
}
if (position < 0 && position > _maxCount)
{
return -1;
@@ -73,16 +69,14 @@ namespace AirFighter
/// <returns></returns>
public T Remove(int position)
{
if (position >= 0 && position < Count)
if (position >= 0 && position < _maxCount && _places[position] != null)
{
T temp = _places[position];
_places.RemoveAt(position);
return temp;
}
else
{
throw new AirFighterNotFoundException(position);
}
return null;
}
/// <summary>
/// Получение объекта из набора по позиции

View File

@@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) :
base(message, exception)
{ }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -1,16 +0,0 @@
{
"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}"
}
}
]
}
}