Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bb8d33a297 | |||
| 4719ebf161 | |||
| 4dbe6d880b | |||
| 47b268ae21 | |||
| d53e5be32e | |||
| cf6e8d4416 | |||
| b89a088a10 | |||
| b599cbae15 | |||
| c881f02fa8 | |||
| a01ca36876 | |||
| 92e7f24c62 |
@@ -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>
|
||||
|
||||
@@ -21,6 +21,11 @@ namespace AircraftCarrier
|
||||
return _warship?.GetCurrentPosition() ?? default;
|
||||
}
|
||||
|
||||
public string GetInfo()
|
||||
{
|
||||
return _warship?.GetDataForSave();
|
||||
}
|
||||
|
||||
public void MoveObject(Direction direction)
|
||||
{
|
||||
_warship?.MoveTransport(direction);
|
||||
@@ -31,9 +36,8 @@ namespace AircraftCarrier
|
||||
_warship.SetPosition(x, y, width, height);
|
||||
}
|
||||
|
||||
void IDrawingObject.DrawningObject(Graphics g)
|
||||
{
|
||||
_warship.DrawTransport(g);
|
||||
}
|
||||
void IDrawingObject.DrawningObject(Graphics g) => _warship.DrawTransport(g);
|
||||
|
||||
public static IDrawingObject Create(string data) => new DrawingObjectWarship(data.CreateDrawningWarship());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace AircraftCarrier
|
||||
{
|
||||
internal class EntityAircraftCarrier : EntityWarship
|
||||
public class EntityAircraftCarrier : EntityWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Дополнительный цвет
|
||||
|
||||
57
AircraftCarrier/AircraftCarrier/ExtentionWarship.cs
Normal file
57
AircraftCarrier/AircraftCarrier/ExtentionWarship.cs
Normal 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}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,9 +45,16 @@
|
||||
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.groupBoxTools.SuspendLayout();
|
||||
this.groupBoxMaps.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
|
||||
this.menuStrip.SuspendLayout();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// groupBoxTools
|
||||
@@ -63,9 +70,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, 547);
|
||||
this.groupBoxTools.TabIndex = 0;
|
||||
this.groupBoxTools.TabStop = false;
|
||||
this.groupBoxTools.Text = "Tools";
|
||||
@@ -135,7 +142,7 @@
|
||||
//
|
||||
// buttonShowOnMap
|
||||
//
|
||||
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 516);
|
||||
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 437);
|
||||
this.buttonShowOnMap.Name = "buttonShowOnMap";
|
||||
this.buttonShowOnMap.Size = new System.Drawing.Size(180, 35);
|
||||
this.buttonShowOnMap.TabIndex = 18;
|
||||
@@ -145,7 +152,7 @@
|
||||
//
|
||||
// buttonShowStorage
|
||||
//
|
||||
this.buttonShowStorage.Location = new System.Drawing.Point(20, 475);
|
||||
this.buttonShowStorage.Location = new System.Drawing.Point(20, 396);
|
||||
this.buttonShowStorage.Name = "buttonShowStorage";
|
||||
this.buttonShowStorage.Size = new System.Drawing.Size(180, 35);
|
||||
this.buttonShowStorage.TabIndex = 17;
|
||||
@@ -155,7 +162,7 @@
|
||||
//
|
||||
// buttonRemoveWarship
|
||||
//
|
||||
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 434);
|
||||
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 355);
|
||||
this.buttonRemoveWarship.Name = "buttonRemoveWarship";
|
||||
this.buttonRemoveWarship.Size = new System.Drawing.Size(180, 35);
|
||||
this.buttonRemoveWarship.TabIndex = 16;
|
||||
@@ -165,7 +172,7 @@
|
||||
//
|
||||
// maskedTextBoxPosition
|
||||
//
|
||||
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 405);
|
||||
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 326);
|
||||
this.maskedTextBoxPosition.Mask = "00";
|
||||
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
|
||||
this.maskedTextBoxPosition.Size = new System.Drawing.Size(180, 23);
|
||||
@@ -174,7 +181,7 @@
|
||||
//
|
||||
// buttonAddWarship
|
||||
//
|
||||
this.buttonAddWarship.Location = new System.Drawing.Point(20, 364);
|
||||
this.buttonAddWarship.Location = new System.Drawing.Point(20, 285);
|
||||
this.buttonAddWarship.Name = "buttonAddWarship";
|
||||
this.buttonAddWarship.Size = new System.Drawing.Size(180, 35);
|
||||
this.buttonAddWarship.TabIndex = 14;
|
||||
@@ -187,7 +194,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, 516);
|
||||
this.buttonRight.Name = "buttonRight";
|
||||
this.buttonRight.Size = new System.Drawing.Size(30, 30);
|
||||
this.buttonRight.TabIndex = 13;
|
||||
@@ -200,7 +207,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, 516);
|
||||
this.buttonLeft.Name = "buttonLeft";
|
||||
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
|
||||
this.buttonLeft.TabIndex = 12;
|
||||
@@ -213,7 +220,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, 480);
|
||||
this.buttonUp.Name = "buttonUp";
|
||||
this.buttonUp.Size = new System.Drawing.Size(30, 30);
|
||||
this.buttonUp.TabIndex = 11;
|
||||
@@ -226,7 +233,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, 516);
|
||||
this.buttonDown.Name = "buttonDown";
|
||||
this.buttonDown.Size = new System.Drawing.Size(30, 30);
|
||||
this.buttonDown.TabIndex = 10;
|
||||
@@ -237,19 +244,61 @@
|
||||
// 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, 547);
|
||||
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";
|
||||
//
|
||||
// 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, 571);
|
||||
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 +306,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 +332,11 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -229,5 +253,50 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,4 +57,13 @@
|
||||
<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>
|
||||
</root>
|
||||
@@ -39,5 +39,10 @@ namespace AircraftCarrier
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
|
||||
/// <summary>
|
||||
/// Получение информации по объекту
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
string GetInfo();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +113,31 @@ 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>
|
||||
private void Shaking()
|
||||
@@ -124,10 +149,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,12 +189,14 @@ namespace AircraftCarrier
|
||||
/// <param name="g"></param>
|
||||
private void DrawWarships(Graphics g)
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
int countInLine = _pictureWidth / _placeSizeWidth;
|
||||
int countInColumn = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int maxDown = (countInColumn - 1) * _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?.SetObject(i % countInLine * _placeSizeWidth, maxDown - i / countInLine * _placeSizeHeight + 7, _pictureWidth, _pictureHeight);
|
||||
warship?.DrawningObject(g);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,19 @@ namespace AircraftCarrier
|
||||
/// <returns></returns>
|
||||
public int Insert(T warship, int position)
|
||||
{
|
||||
if (position >= _maxCount || position < 0) return -1;
|
||||
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 +69,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 +86,7 @@ namespace AircraftCarrier
|
||||
{
|
||||
get
|
||||
{
|
||||
if (position >= _maxCount || position < 0) return null;
|
||||
return _places[position];
|
||||
return isCorrectPosition(position) && position < Count ? _places[position] : null;
|
||||
}
|
||||
set
|
||||
{
|
||||
|
||||
19
AircraftCarrier/AircraftCarrier/StorageOverflowException.cs
Normal file
19
AircraftCarrier/AircraftCarrier/StorageOverflowException.cs
Normal 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) { }
|
||||
}
|
||||
}
|
||||
19
AircraftCarrier/AircraftCarrier/WarshipNotFoundException.cs
Normal file
19
AircraftCarrier/AircraftCarrier/WarshipNotFoundException.cs
Normal 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) { }
|
||||
}
|
||||
}
|
||||
48
AircraftCarrier/AircraftCarrier/jsconfig.json
Normal file
48
AircraftCarrier/AircraftCarrier/jsconfig.json
Normal 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"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user