16 Commits

24 changed files with 1370 additions and 71 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

@@ -23,6 +23,10 @@ namespace AircraftCarrier
{
Warship = new EntityAircraftCarrier(speed, weight, bodyColor, dopColor, bodyKit, сabin, superEngine);
}
public void SetDopColor(Color color)
{
((EntityAircraftCarrier)Warship).DopColor = color;
}
public override void DrawTransport(Graphics g)
{
@@ -33,8 +37,6 @@ namespace AircraftCarrier
Pen pen = new(Color.Black);
Brush dopBrush = new SolidBrush(aircraftCarrier.DopColor);
Brush brGray = new SolidBrush(Color.Gray);
Brush brRed = new SolidBrush(Color.Red);
Brush br = new SolidBrush(Warship?.BodyColor ?? Color.White);
if (aircraftCarrier.BodyKit)
@@ -62,22 +64,22 @@ namespace AircraftCarrier
{
pontStartLine1, pontStartLine2, pontStartLine3, pontStartLine4
};
g.FillPolygon(brGray, PointsStartLine);
g.FillPolygon(dopBrush, PointsStartLine);
g.DrawPolygon(pen, PointsStartLine);
}
if (aircraftCarrier.SuperEngine)
{
g.FillEllipse(brRed, _startPosX, _startPosY, 10, 10);
g.FillEllipse(dopBrush, _startPosX, _startPosY, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY, 10, 10);
g.FillEllipse(brRed, _startPosX, _startPosY + 10, 10, 10);
g.FillEllipse(dopBrush, _startPosX, _startPosY + 10, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY + 10, 10, 10);
g.FillEllipse(brRed, _startPosX, _startPosY + 18, 10, 10);
g.FillEllipse(dopBrush, _startPosX, _startPosY + 18, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY + 18, 10, 10);
g.FillEllipse(brRed, _startPosX, _startPosY + 30, 10, 10);
g.FillEllipse(dopBrush, _startPosX, _startPosY + 30, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY + 30, 10, 10);
}
@@ -85,13 +87,13 @@ namespace AircraftCarrier
if (aircraftCarrier.Сabin)
{
g.FillEllipse(brGray, _startPosX + 10, _startPosY + 15, 10, 10);
g.FillEllipse(dopBrush, _startPosX + 10, _startPosY + 15, 10, 10);
g.DrawEllipse(pen, _startPosX + 10, _startPosY + 15, 10, 10);
g.FillEllipse(brGray, _startPosX + 20, _startPosY + 15, 10, 10);
g.FillEllipse(dopBrush, _startPosX + 20, _startPosY + 15, 10, 10);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 15, 10, 10);
g.FillRectangle(brGray, _startPosX + 15, _startPosY + 15, 10, 10);
g.FillRectangle(dopBrush, _startPosX + 15, _startPosY + 15, 10, 10);
g.DrawRectangle(pen, _startPosX + 15, _startPosY + 15, 10, 10);
}
}

View File

@@ -16,11 +16,18 @@ 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;
}
public string GetInfo()
{
return _warship?.GetDataForSave();
}
public void MoveObject(Direction direction)
{
_warship?.MoveTransport(direction);
@@ -31,9 +38,36 @@ namespace AircraftCarrier
_warship.SetPosition(x, y, width, height);
}
void IDrawingObject.DrawningObject(Graphics g)
void IDrawingObject.DrawningObject(Graphics g) => _warship.DrawTransport(g);
public static IDrawingObject Create(string data) => new DrawingObjectWarship(data.CreateDrawningWarship());
public bool Equals(IDrawingObject? other)
{
_warship.DrawTransport(g);
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

@@ -64,6 +64,8 @@ namespace AircraftCarrier
_warshipWidth = warshipWidth;
_warshipHeight = warshipHeight;
}
public void SetColor(Color color) => Warship.BodyColor = color;
/// <summary>
/// Установка позиции военного корабля
/// </summary>

View File

@@ -6,12 +6,12 @@ using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class EntityAircraftCarrier : EntityWarship
public class EntityAircraftCarrier : EntityWarship
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
public Color DopColor { get; set; }
/// <summary>
/// Признак наличия боковой площадки
/// </summary>

View File

@@ -22,7 +22,7 @@ namespace AircraftCarrier
/// <summary>
/// Цвет
/// </summary>
public Color BodyColor { get; private set; }
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения
/// </summary>

View File

@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
/// <summary>
/// Расширение для класса DrawingWarship
/// </summary>
internal static class ExtentionWarship
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawingWarship CreateDrawningWarship(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingWarship(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawingAircraftCarrier(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingWarship"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawingWarship drawingWarship)
{
var warship = drawingWarship.Warship;
var str = $"{warship.Speed}{_separatorForObject}{warship.Weight}{_separatorForObject}{warship.BodyColor.Name}";
if (warship is not EntityAircraftCarrier aircraftCarrier)
{
return str;
}
return $"{str}{_separatorForObject}{aircraftCarrier.DopColor.Name}{_separatorForObject}{aircraftCarrier.BodyKit}{_separatorForObject}{aircraftCarrier.Сabin}{_separatorForObject}{aircraftCarrier.SuperEngine}";
}
}
}

View File

@@ -45,13 +45,24 @@
this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
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.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();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// 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);
@@ -63,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, 0);
this.groupBoxTools.Location = new System.Drawing.Point(580, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(217, 649);
this.groupBoxTools.Size = new System.Drawing.Size(217, 652);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Tools";
@@ -135,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;
@@ -145,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;
@@ -155,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;
@@ -165,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);
@@ -174,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;
@@ -187,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, 609);
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;
@@ -200,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, 609);
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;
@@ -213,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, 573);
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;
@@ -226,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, 609);
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;
@@ -237,19 +248,81 @@
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(754, 649);
this.pictureBox.Size = new System.Drawing.Size(580, 652);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
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(797, 24);
this.menuStrip.TabIndex = 2;
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(100, 22);
this.SaveToolStripMenuItem.Text = "Save";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(100, 22);
this.LoadToolStripMenuItem.Text = "Load";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
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);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetWarships";
this.Text = "FormMapWithSetWarships";
this.groupBoxTools.ResumeLayout(false);
@@ -257,7 +330,10 @@
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();
}
@@ -280,5 +356,13 @@
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
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();
}
}
@@ -114,24 +125,42 @@ namespace AircraftCarrier
/// <param name="e"></param>
private void ButtonAddWarship_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
var formWarshipConfig = new FormWarshipConfig();
formWarshipConfig.AddEvent(AddWarshipOnForm);
formWarshipConfig.Show();
}
/// <summary>
/// добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddWarshipOnForm(DrawingWarship drawningWarship)
{
try
{
return;
}
FormWarship form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawingObjectWarship warship = new(form.SelectedWarship);
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("Не удалось добавить объект");
}
}
catch(StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
@@ -140,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>
@@ -220,5 +253,64 @@ namespace AircraftCarrier
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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)
{
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <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);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
catch (Exception ex)
{
_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

@@ -57,4 +57,16 @@
<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>125, 17</value>
</metadata>
<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

@@ -0,0 +1,394 @@
namespace AircraftCarrier
{
partial class FormWarshipConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxSportLine = new System.Windows.Forms.CheckBox();
this.checkBoxWing = new System.Windows.Forms.CheckBox();
this.checkBoxBodyKit = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelSpeed = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxSportLine);
this.groupBoxConfig.Controls.Add(this.checkBoxWing);
this.groupBoxConfig.Controls.Add(this.checkBoxBodyKit);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 12);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(520, 220);
this.groupBoxConfig.TabIndex = 1;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Parameters";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(394, 162);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(97, 38);
this.labelModifiedObject.TabIndex = 16;
this.labelModifiedObject.Text = "Advanced";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(282, 162);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(97, 38);
this.labelSimpleObject.TabIndex = 15;
this.labelSimpleObject.Text = "Simple";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(267, 22);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(241, 127);
this.groupBoxColors.TabIndex = 14;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Colors";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(184, 73);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
this.panelPurple.TabIndex = 3;
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(184, 22);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 1;
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(127, 73);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 4;
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(127, 22);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 1;
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(72, 73);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 5;
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(72, 22);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 1;
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(15, 73);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 2;
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(15, 22);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 0;
//
// checkBoxSportLine
//
this.checkBoxSportLine.AutoSize = true;
this.checkBoxSportLine.Location = new System.Drawing.Point(22, 185);
this.checkBoxSportLine.Name = "checkBoxSportLine";
this.checkBoxSportLine.Size = new System.Drawing.Size(134, 19);
this.checkBoxSportLine.TabIndex = 13;
this.checkBoxSportLine.Text = "Sign of super engine";
this.checkBoxSportLine.UseVisualStyleBackColor = true;
//
// checkBoxWing
//
this.checkBoxWing.AutoSize = true;
this.checkBoxWing.Location = new System.Drawing.Point(22, 149);
this.checkBoxWing.Name = "checkBoxWing";
this.checkBoxWing.Size = new System.Drawing.Size(95, 19);
this.checkBoxWing.TabIndex = 12;
this.checkBoxWing.Text = "Sign of cabin";
this.checkBoxWing.UseVisualStyleBackColor = true;
//
// checkBoxBodyKit
//
this.checkBoxBodyKit.AutoSize = true;
this.checkBoxBodyKit.Location = new System.Drawing.Point(22, 115);
this.checkBoxBodyKit.Name = "checkBoxBodyKit";
this.checkBoxBodyKit.Size = new System.Drawing.Size(145, 19);
this.checkBoxBodyKit.TabIndex = 11;
this.checkBoxBodyKit.Text = "Sign of a side platform";
this.checkBoxBodyKit.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(90, 72);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(79, 23);
this.numericUpDownWeight.TabIndex = 10;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(22, 74);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(48, 15);
this.labelWeight.TabIndex = 9;
this.labelWeight.Text = "Weight:";
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(90, 30);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(79, 23);
this.numericUpDownSpeed.TabIndex = 8;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(22, 32);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(42, 15);
this.labelSpeed.TabIndex = 7;
this.labelSpeed.Text = "Speed:";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(679, 202);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(104, 30);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(558, 202);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(104, 30);
this.buttonOk.TabIndex = 7;
this.buttonOk.Text = "Add";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(538, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(262, 184);
this.panelObject.TabIndex = 6;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(141, 9);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(104, 32);
this.labelDopColor.TabIndex = 2;
this.labelDopColor.Text = "DopColor";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(20, 9);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(104, 32);
this.labelBaseColor.TabIndex = 1;
this.labelBaseColor.Text = "Color";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(20, 44);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(225, 125);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// FormWarshipConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(815, 244);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormWarshipConfig";
this.Text = "Creating object";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private CheckBox checkBoxSportLine;
private CheckBox checkBoxWing;
private CheckBox checkBoxBodyKit;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private Button buttonCancel;
private Button buttonOk;
private Panel panelObject;
private Label labelDopColor;
private Label labelBaseColor;
private PictureBox pictureBoxObject;
}
}

View File

@@ -0,0 +1,171 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AircraftCarrier
{
public partial class FormWarshipConfig : Form
{
/// <summary>
/// Переменная-выбранный корабль
/// </summary>
DrawingWarship _warship = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingWarship> EventAddWarshp;
/// <summary>
/// Конструктор
/// </summary>
public FormWarshipConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Отрисовать корабль
/// </summary>
private void DrawingWarship()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_warship?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_warship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(Action<DrawingWarship> ev)
{
if (EventAddWarshp == null)
{
EventAddWarshp = ev;
}
else
{
EventAddWarshp += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_warship = new DrawingWarship((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_warship = new DrawingAircraftCarrier((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxBodyKit.Checked, checkBoxWing.Checked, checkBoxSportLine.Checked);
break;
}
DrawingWarship();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
Color color = (Color)e.Data.GetData(typeof(Color));
_warship.SetColor(color);
DrawingWarship();
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
Color dopColor = (Color)e.Data.GetData(typeof(Color));
if (_warship is DrawingAircraftCarrier aircraftCarrier)
{
aircraftCarrier.SetDopColor(dopColor);
DrawingWarship();
}
}
/// <summary>
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddWarshp?.Invoke(_warship);
Close();
}
}
}

View File

@@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -9,7 +9,7 @@ namespace AircraftCarrier
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawingObject
internal interface IDrawingObject : IEquatable<IDrawingObject>
{
/// <summary>
/// Шаг перемещения объекта
@@ -39,5 +39,10 @@ namespace AircraftCarrier
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

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>
@@ -113,6 +113,39 @@ namespace AircraftCarrier
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 warship in _setWarships.GetWarships())
{
data += $"{warship.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setWarships.Insert(DrawingObjectWarship.Create(rec) as T);
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setWarships.SortSet(comparer);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
@@ -124,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;
}
@@ -164,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

@@ -11,7 +11,7 @@ namespace AircraftCarrier
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@@ -25,13 +25,21 @@ namespace AircraftCarrier
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -57,7 +65,7 @@ namespace AircraftCarrier
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap> this[string ind]
public MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap> this[string ind]
{
get
{
@@ -65,5 +73,63 @@ namespace AircraftCarrier
return MapWithSetWarshipsGeneric;
}
}
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void 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}");
}
}
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "Преграды-линии":
map = new LineMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

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"
}
}
}