9 Commits

Author SHA1 Message Date
7b5981095f Изменения в AbstractMap 2022-11-29 20:24:26 +04:00
19a089dce3 Сортировка 2022-11-29 20:19:41 +04:00
4e684f963f Сравнение объектов 2022-11-29 19:50:58 +04:00
4dbe6d880b изменения логирования 2022-11-28 12:13:37 +04:00
47b268ae21 доработки 2022-11-28 11:26:09 +04:00
d53e5be32e изменения 2022-11-27 15:57:24 +04:00
cf6e8d4416 Serilog 2022-11-27 15:47:42 +04:00
b89a088a10 Логирование 2022-11-27 15:01:26 +04:00
b599cbae15 Генерация ошибок 2022-11-27 14:34:19 +04:00
17 changed files with 467 additions and 81 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace AircraftCarrier
{
internal abstract class AbstractMap
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawingObject _drawingObject = null;
protected int[,] _map = null;
@@ -156,5 +156,27 @@ namespace AircraftCarrier
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
public bool Equals(AbstractMap? other)
{
if (other == null || _map != other._map || _width != other._width ||
_size_x != other._size_x || _size_y != other._size_y || _height != other._height ||
GetType() != other.GetType() || _map.GetLength(0) != other._map.GetLength(0) ||
_map.GetLength(1) != other._map.GetLength(1))
{
return false;
}
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] != other._map[i, j])
{
return false;
}
}
}
return true;
}
}
}

View File

@@ -8,6 +8,32 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="jsconfig.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="jsconfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.DependencyInjection.Abstractions" 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="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -16,6 +16,8 @@ namespace AircraftCarrier
}
public float Step => _warship?.Warship?.Step ?? 0;
public DrawingWarship GetWarship => _warship;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _warship?.GetCurrentPosition() ?? default;
@@ -39,5 +41,33 @@ namespace AircraftCarrier
void IDrawingObject.DrawningObject(Graphics g) => _warship.DrawTransport(g);
public static IDrawingObject Create(string data) => new DrawingObjectWarship(data.CreateDrawningWarship());
public bool Equals(IDrawingObject? other)
{
if (other is not DrawingObjectWarship otherWarship)
{
return false;
}
var warship = _warship.Warship;
var otherEntity = otherWarship._warship.Warship;
if (warship.GetType() != otherEntity.GetType() ||
warship.Speed != otherEntity.Speed ||
warship.Weight != otherEntity.Weight ||
warship.BodyColor != otherEntity.BodyColor)
{
return false;
}
if (warship is EntityAircraftCarrier entityAircraftCarrier &&
otherEntity is EntityAircraftCarrier otherEntityAircraftCarrier && (
entityAircraftCarrier.BodyKit != otherEntityAircraftCarrier.BodyKit ||
entityAircraftCarrier.Сabin != otherEntityAircraftCarrier.Сabin ||
entityAircraftCarrier.SuperEngine != otherEntityAircraftCarrier.SuperEngine ||
entityAircraftCarrier.DopColor != otherEntityAircraftCarrier.DopColor))
{
return false;
}
return true;
}
}
}

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class EntityAircraftCarrier : EntityWarship
public class EntityAircraftCarrier : EntityWarship
{
/// <summary>
/// Дополнительный цвет

View File

@@ -51,6 +51,8 @@
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
@@ -59,6 +61,8 @@
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.buttonSortByColor);
this.groupBoxTools.Controls.Add(this.buttonSortByType);
this.groupBoxTools.Controls.Add(this.groupBoxMaps);
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonShowStorage);
@@ -70,9 +74,9 @@
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(754, 24);
this.groupBoxTools.Location = new System.Drawing.Point(580, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(217, 625);
this.groupBoxTools.Size = new System.Drawing.Size(217, 652);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Tools";
@@ -142,7 +146,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 516);
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 545);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(180, 35);
this.buttonShowOnMap.TabIndex = 18;
@@ -152,7 +156,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(20, 475);
this.buttonShowStorage.Location = new System.Drawing.Point(20, 504);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(180, 35);
this.buttonShowStorage.TabIndex = 17;
@@ -162,7 +166,7 @@
//
// buttonRemoveWarship
//
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 434);
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 463);
this.buttonRemoveWarship.Name = "buttonRemoveWarship";
this.buttonRemoveWarship.Size = new System.Drawing.Size(180, 35);
this.buttonRemoveWarship.TabIndex = 16;
@@ -172,7 +176,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 405);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 434);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(180, 23);
@@ -181,7 +185,7 @@
//
// buttonAddWarship
//
this.buttonAddWarship.Location = new System.Drawing.Point(20, 364);
this.buttonAddWarship.Location = new System.Drawing.Point(20, 393);
this.buttonAddWarship.Name = "buttonAddWarship";
this.buttonAddWarship.Size = new System.Drawing.Size(180, 35);
this.buttonAddWarship.TabIndex = 14;
@@ -194,7 +198,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(126, 594);
this.buttonRight.Location = new System.Drawing.Point(126, 621);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 13;
@@ -207,7 +211,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(54, 594);
this.buttonLeft.Location = new System.Drawing.Point(54, 621);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 12;
@@ -220,7 +224,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(90, 558);
this.buttonUp.Location = new System.Drawing.Point(90, 585);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 11;
@@ -233,7 +237,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(90, 594);
this.buttonDown.Location = new System.Drawing.Point(90, 621);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 10;
@@ -246,7 +250,7 @@
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(754, 625);
this.pictureBox.Size = new System.Drawing.Size(580, 652);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
@@ -256,7 +260,7 @@
this.fileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(971, 24);
this.menuStrip.Size = new System.Drawing.Size(797, 24);
this.menuStrip.TabIndex = 2;
//
// fileToolStripMenuItem
@@ -290,11 +294,31 @@
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(18, 296);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(180, 35);
this.buttonSortByType.TabIndex = 20;
this.buttonSortByType.Text = "Sort by type";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(18, 337);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(180, 35);
this.buttonSortByColor.TabIndex = 21;
this.buttonSortByColor.Text = "Sort by color";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// FormMapWithSetWarships
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(971, 649);
this.ClientSize = new System.Drawing.Size(797, 676);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
@@ -338,5 +362,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -26,11 +27,16 @@ namespace AircraftCarrier
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetWarships()
public FormMapWithSetWarships(ILogger<FormMapWithSetWarships> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -70,15 +76,18 @@ namespace AircraftCarrier
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.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
/// <summary>
/// Выбор карты
@@ -88,6 +97,7 @@ namespace AircraftCarrier
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);
}
/// <summary>
/// Удаление карты
@@ -104,6 +114,7 @@ namespace AircraftCarrier
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
@@ -125,22 +136,31 @@ namespace AircraftCarrier
/// <param name="e"></param>
private void AddWarshipOnForm(DrawingWarship drawningWarship)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
DrawingObjectWarship warship = new(drawningWarship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship >= 0)
{
_logger.LogInformation($"Добавлен объект {warship}");
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
DrawingObjectWarship warship = new(drawningWarship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
catch(StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
@@ -149,27 +169,31 @@ namespace AircraftCarrier
/// <param name="e"></param>
private void ButtonRemoveWarship_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (listBoxMaps.SelectedIndex == -1 || string.IsNullOrEmpty(maskedTextBoxPosition.Text) ||
MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
var deletedWarship = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedWarship != null)
{
_logger.LogInformation($"Объект {deletedWarship} удалён");
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
}
}
else
catch (WarshipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
}
}
/// <summary>
@@ -238,13 +262,16 @@ namespace AircraftCarrier
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -257,16 +284,33 @@ namespace AircraftCarrier
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void Sorting(IComparer<IDrawingObject> comparer)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(comparer);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void buttonSortByType_Click(object sender, EventArgs e) => Sorting(new WarshipCompareByType());
private void buttonSortByColor_Click(object sender, EventArgs e) => Sorting(new WarshipCompareByColor());
}
}

View File

@@ -66,4 +66,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>50</value>
</metadata>
</root>

View File

@@ -9,7 +9,7 @@ namespace AircraftCarrier
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawingObject
internal interface IDrawingObject : IEquatable<IDrawingObject>
{
/// <summary>
/// Шаг перемещения объекта

View File

@@ -12,7 +12,7 @@ namespace AircraftCarrier
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetWarshipsGeneric <T, U>
where T : class, IDrawingObject
where T : class, IDrawingObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
@@ -138,6 +138,14 @@ namespace AircraftCarrier
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setWarships.SortSet(comparer);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
@@ -149,10 +157,10 @@ namespace AircraftCarrier
{
for (; j > i; j--)
{
var car = _setWarships[j];
if (car != null)
var warship = _setWarships[j];
if (warship != null)
{
_setWarships.Insert(car, i);
_setWarships.Insert(warship, i);
_setWarships.Remove(j);
break;
}
@@ -189,14 +197,33 @@ namespace AircraftCarrier
/// <param name="g"></param>
private void DrawWarships(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int countInLine = _pictureWidth / _placeSizeWidth;
int countInColumn = _pictureHeight / _placeSizeHeight;
int maxLeft = (countInLine - 1) * _placeSizeWidth;
int maxDown = (countInColumn - 1) * _placeSizeHeight;
for (int i = 0; i < _setWarships.Count; i++)
{
var warship = _setWarships[i];
warship?.SetObject(i % countInLine * _placeSizeWidth, maxDown - i / countInLine * _placeSizeHeight + 7, _pictureWidth, _pictureHeight);
//warship?.SetObject(i % countInLine * _placeSizeWidth - 3, i / countInLine * _placeSizeHeight, _pictureWidth, _pictureHeight);
//warship?.SetObject(i % countInLine * _placeSizeWidth - 3, maxDown - i * countInColumn * _placeSizeHeight, _pictureWidth, _pictureHeight);
//warship?.SetObject(i % _pictureWidth * _placeSizeWidth, (countInColumn - 1 - i / countInLine) * _placeSizeHeight + 5, _pictureWidth, _pictureHeight);
warship?.DrawningObject(g);
}
/*int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _setWarships.Count; i++)
{
var warship = _setWarships[i];
warship?.SetObject(i % _pictureWidth * _placeSizeWidth, (height - 1 - i / width) * _placeSizeHeight + 4, _pictureWidth, _pictureHeight);
warship?.DrawningObject(g);
}
}*/
}
}
}

View File

@@ -74,21 +74,11 @@ namespace AircraftCarrier
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -102,7 +92,6 @@ namespace AircraftCarrier
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
@@ -110,18 +99,18 @@ namespace AircraftCarrier
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
return false;
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
@@ -141,7 +130,6 @@ namespace AircraftCarrier
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

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

View File

@@ -11,7 +11,7 @@ namespace AircraftCarrier
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetWarshipsGeneric<T>
where T : class
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
@@ -49,10 +49,21 @@ namespace AircraftCarrier
/// <returns></returns>
public int Insert(T warship, int position)
{
if (position >= _maxCount || position < 0) return -1;
if (_places.Contains(warship))
throw new ArgumentException($"Объект {warship} уже есть в наборе");
if (Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!isCorrectPosition(position)) return -1;
_places.Insert(position, warship);
return 1;
}
private bool isCorrectPosition(int position)
{
return 0 <= position && position < _maxCount;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
@@ -60,10 +71,11 @@ namespace AircraftCarrier
/// <returns></returns>
public T Remove(int position)
{
if (position >= _maxCount || position < 0)
if (!isCorrectPosition(position))
return null;
var result = _places[position];
var result = this[position];
if (result == null)
throw new WarshipNotFoundException(position);
_places.RemoveAt(position);
return result;
}
@@ -76,8 +88,7 @@ namespace AircraftCarrier
{
get
{
if (position >= _maxCount || position < 0) return null;
return _places[position];
return isCorrectPosition(position) && position < Count ? _places[position] : null;
}
set
{
@@ -102,5 +113,17 @@ namespace AircraftCarrier
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
[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

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class WarshipCompareByColor : IComparer<IDrawingObject>
{
public int Compare(IDrawingObject? x, IDrawingObject? y)
{
var xWarship = x as DrawingObjectWarship;
var yWarship = y as DrawingObjectWarship;
if (xWarship == yWarship)
{
return 0;
}
if (xWarship == null)
{
return 1;
}
if (yWarship == null)
{
return -1;
}
var xEntity = xWarship.GetWarship.Warship;
var yEntity = yWarship.GetWarship.Warship;
var colorWeight = xEntity.BodyColor.ToArgb().CompareTo(yEntity.BodyColor.ToArgb());
if (colorWeight != 0 || xEntity is not EntityAircraftCarrier xEntityAircraftCarrier ||
yEntity is not EntityAircraftCarrier yEntityWarmlyShip)
{
return colorWeight;
}
return xEntityAircraftCarrier.DopColor.ToArgb().CompareTo(yEntityWarmlyShip.DopColor.ToArgb());
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class WarshipCompareByType : IComparer<IDrawingObject>
{
public int Compare(IDrawingObject? x, IDrawingObject? y)
{
var xWarship = x as DrawingObjectWarship;
var yWarship = y as DrawingObjectWarship;
if (xWarship == yWarship)
{
return 0;
}
if (xWarship == null)
{
return 1;
}
if (yWarship == null)
{
return -1;
}
if (xWarship.GetWarship.GetType().Name != yWarship.GetWarship.GetType().Name)
{
if (xWarship.GetWarship.GetType() == typeof(DrawingWarship))
{
return -1;
}
return 1;
}
var speedCompare = xWarship.GetWarship.Warship.Speed.CompareTo(yWarship.GetWarship.Warship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xWarship.GetWarship.Warship.Weight.CompareTo(yWarship.GetWarship.Warship.Weight);
}
}
}

View File

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

View File

@@ -0,0 +1,48 @@
{
"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" ],
"Destructure": [
{
"Name": "ByTransforming",
"Args": {
"returnType": "AircraftCarrier.EntityWarship",
"transformation": "r => new { BodyColor = r.BodyColor.Name, r.Speed, r.Weight }"
}
},
{
"Name": "ByTransforming",
"Args": {
"returnType": "AircraftCarrier.EntityAircraftCarrier",
"transformation": "r => new { BodyColor = r.BodyColor.Name, DopColor = r.DopColor, r.BodyKit, r.Сabin, r.SuperEngine, r.Speed, r.Weight }"
}
},
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 4 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 100 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 10 }
}
],
"Properties": {
"Application": "AircraftCarrier"
}
}
}