11 Commits

Author SHA1 Message Date
DozorovaA.A
ed2545c5d6 fix 2022-12-01 23:44:18 +04:00
DozorovaA.A
6f2ab026a9 add sort 2022-11-20 13:50:21 +04:00
DozorovaA.A
fdba620e54 comparison of object 2022-11-19 18:32:34 +04:00
DozorovaA.A
2b2b5f3e5e fix conflict 2022-11-16 15:51:02 +04:00
DozorovaA.A
6852b6bfb3 try fix conflict 2022-11-16 11:08:57 +04:00
DozorovaA.A
2fe71b1d22 little fix 2022-11-16 10:40:23 +04:00
DozorovaA.A
e6075c78d4 fix comment 2022-11-16 09:16:52 +04:00
DozorovaA.A
6be3584202 logging 2022-11-13 15:50:05 +04:00
DozorovaA.A
470476d1a8 add exceptions 2022-11-13 14:02:54 +04:00
DozorovaA.A
aa61b946f9 delete saved map 2022-11-13 13:45:08 +04:00
DozorovaA.A
0a889412fc fuull lab 2022-11-13 13:41:25 +04:00
20 changed files with 741 additions and 63 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal abstract class AbstractMap
internal abstract class AbstractMap:IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
protected int[,] _map = null;
@@ -225,5 +225,11 @@ namespace ArmoredVehicle
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)
{
return this == other && this._width == other._width &&
this._height == other._height && this._map == other._map && this._drawningObject == other._drawningObject;
}
}
}

View File

@@ -8,6 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" 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.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -8,6 +8,7 @@
{
_machine = machine;
}
public DrawingArmoredVehicle GetMachine => _machine;
public float Step => _machine?.ArmoredVehicle?.Step ?? 0;
@@ -31,5 +32,50 @@
_machine.DrawTransport(g);
}
public string GetInfo() => _machine?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningCar());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otheMachine = other as DrawningObject;
if (otheMachine == null)
{
return false;
}
var machine = _machine.ArmoredVehicle;
var otherMachineMachine = otheMachine._machine.ArmoredVehicle;
if (machine.Speed != otherMachineMachine.Speed)
{
return false;
}
if (machine.Weight != otherMachineMachine.Weight)
{
return false;
}
if (machine.BodyColor != otherMachineMachine.BodyColor)
{
return false;
}
if (machine is TankEnity && otherMachineMachine is TankEnity)
{
var tank = machine as TankEnity;
var otherMachineTank = otherMachineMachine as TankEnity;
if (tank.DopColor != otherMachineTank.DopColor || tank.Tower != otherMachineTank.Tower ||
tank.MachineGun != otherMachineTank.MachineGun)
{
return false;
}
}else if (machine is TankEnity || otherMachineMachine is TankEnity)
{
return false;
}
return true;
}
}
}

View File

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

View File

@@ -46,13 +46,24 @@
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.pictureBoxImage = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = 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.SortBuTypeButton = new System.Windows.Forms.Button();
this.SortByColorButton = new System.Windows.Forms.Button();
this.groupBoxInstruments.SuspendLayout();
this.groupBoxMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxImage)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxInstruments
//
this.groupBoxInstruments.Controls.Add(this.SortByColorButton);
this.groupBoxInstruments.Controls.Add(this.SortBuTypeButton);
this.groupBoxInstruments.Controls.Add(this.groupBoxMap);
this.groupBoxInstruments.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxInstruments.Controls.Add(this.ButtonDown);
@@ -64,9 +75,9 @@
this.groupBoxInstruments.Controls.Add(this.buttonDelete);
this.groupBoxInstruments.Controls.Add(this.buttonAdd);
this.groupBoxInstruments.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxInstruments.Location = new System.Drawing.Point(964, 0);
this.groupBoxInstruments.Location = new System.Drawing.Point(964, 33);
this.groupBoxInstruments.Name = "groupBoxInstruments";
this.groupBoxInstruments.Size = new System.Drawing.Size(300, 910);
this.groupBoxInstruments.Size = new System.Drawing.Size(300, 1003);
this.groupBoxInstruments.TabIndex = 0;
this.groupBoxInstruments.TabStop = false;
this.groupBoxInstruments.Text = "Инструменты";
@@ -140,7 +151,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(10, 506);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(10, 613);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(270, 31);
@@ -151,7 +162,7 @@
this.ButtonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonDown.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonDown.BackgroundImage")));
this.ButtonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonDown.Location = new System.Drawing.Point(129, 823);
this.ButtonDown.Location = new System.Drawing.Point(129, 947);
this.ButtonDown.Name = "ButtonDown";
this.ButtonDown.Size = new System.Drawing.Size(40, 36);
this.ButtonDown.TabIndex = 17;
@@ -163,7 +174,7 @@
this.ButtonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonRight.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonRight.BackgroundImage")));
this.ButtonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonRight.Location = new System.Drawing.Point(172, 776);
this.ButtonRight.Location = new System.Drawing.Point(172, 900);
this.ButtonRight.Name = "ButtonRight";
this.ButtonRight.Size = new System.Drawing.Size(40, 36);
this.ButtonRight.TabIndex = 16;
@@ -175,7 +186,7 @@
this.ButtonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonLeft.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonLeft.BackgroundImage")));
this.ButtonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonLeft.Location = new System.Drawing.Point(89, 778);
this.ButtonLeft.Location = new System.Drawing.Point(89, 902);
this.ButtonLeft.Name = "ButtonLeft";
this.ButtonLeft.Size = new System.Drawing.Size(40, 36);
this.ButtonLeft.TabIndex = 15;
@@ -187,7 +198,7 @@
this.ButtonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonUp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonUp.BackgroundImage")));
this.ButtonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonUp.Location = new System.Drawing.Point(129, 728);
this.ButtonUp.Location = new System.Drawing.Point(129, 852);
this.ButtonUp.Name = "ButtonUp";
this.ButtonUp.Size = new System.Drawing.Size(40, 36);
this.ButtonUp.TabIndex = 14;
@@ -196,7 +207,7 @@
//
// buttonMap
//
this.buttonMap.Location = new System.Drawing.Point(18, 680);
this.buttonMap.Location = new System.Drawing.Point(18, 787);
this.buttonMap.Name = "buttonMap";
this.buttonMap.Size = new System.Drawing.Size(262, 34);
this.buttonMap.TabIndex = 5;
@@ -206,7 +217,7 @@
//
// buttonStore
//
this.buttonStore.Location = new System.Drawing.Point(16, 614);
this.buttonStore.Location = new System.Drawing.Point(16, 721);
this.buttonStore.Name = "buttonStore";
this.buttonStore.Size = new System.Drawing.Size(264, 34);
this.buttonStore.TabIndex = 4;
@@ -216,7 +227,7 @@
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(12, 561);
this.buttonDelete.Location = new System.Drawing.Point(12, 668);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(268, 34);
this.buttonDelete.TabIndex = 3;
@@ -226,7 +237,7 @@
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(5, 444);
this.buttonAdd.Location = new System.Drawing.Point(5, 551);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(275, 34);
this.buttonAdd.TabIndex = 1;
@@ -237,19 +248,83 @@
// pictureBoxImage
//
this.pictureBoxImage.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxImage.Location = new System.Drawing.Point(0, 0);
this.pictureBoxImage.Location = new System.Drawing.Point(0, 33);
this.pictureBoxImage.Name = "pictureBoxImage";
this.pictureBoxImage.Size = new System.Drawing.Size(964, 910);
this.pictureBoxImage.Size = new System.Drawing.Size(964, 1003);
this.pictureBoxImage.TabIndex = 1;
this.pictureBoxImage.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1264, 33);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(69, 29);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(217, 34);
this.SaveToolStripMenuItem.Text = "Сохранение ";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(217, 34);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "text file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "text file | *.txt";
//
// SortBuTypeButton
//
this.SortBuTypeButton.Location = new System.Drawing.Point(20, 454);
this.SortBuTypeButton.Name = "SortBuTypeButton";
this.SortBuTypeButton.Size = new System.Drawing.Size(246, 34);
this.SortBuTypeButton.TabIndex = 20;
this.SortBuTypeButton.Text = "Сортировать по типу";
this.SortBuTypeButton.UseVisualStyleBackColor = true;
this.SortBuTypeButton.Click += new System.EventHandler(this.SortBuTypeButton_Click);
//
// SortByColorButton
//
this.SortByColorButton.Location = new System.Drawing.Point(25, 503);
this.SortByColorButton.Name = "SortByColorButton";
this.SortByColorButton.Size = new System.Drawing.Size(243, 34);
this.SortByColorButton.TabIndex = 21;
this.SortByColorButton.Text = "Сортировать по цвету";
this.SortByColorButton.UseVisualStyleBackColor = true;
this.SortByColorButton.Click += new System.EventHandler(this.SortByColorButton_Click);
//
// FormMapWithSetMachine
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1264, 910);
this.ClientSize = new System.Drawing.Size(1264, 1036);
this.Controls.Add(this.pictureBoxImage);
this.Controls.Add(this.groupBoxInstruments);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetMachine";
this.Text = "Карта с набором объектов";
this.groupBoxInstruments.ResumeLayout(false);
@@ -257,7 +332,10 @@
this.groupBoxMap.ResumeLayout(false);
this.groupBoxMap.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxImage)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -280,5 +358,13 @@
private Button buttonAddMap;
private ComboBox comboBoxSelectorMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button SortByColorButton;
private Button SortBuTypeButton;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -25,12 +26,18 @@ namespace ArmoredVehicle
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetMachine()
public FormMapWithSetMachine(ILogger<FormMapWithSetMachine> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBoxImage.Width, pictureBoxImage.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -72,15 +79,18 @@ namespace ArmoredVehicle
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation($"Попытка добавить несуществующую карту: {textBoxNewMapName.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
}
/// <summary>
@@ -91,6 +101,7 @@ namespace ArmoredVehicle
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Переход на карту: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
/// <summary>
@@ -102,6 +113,7 @@ namespace ArmoredVehicle
{
if (listBoxMaps.SelectedIndex == -1)
{
_logger.LogInformation($"Попытка удалить несуществующую карту: {textBoxNewMapName.Text}");
return;
}
@@ -109,6 +121,7 @@ namespace ArmoredVehicle
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта: {listBoxMaps.SelectedItem?.ToString()}");
}
}
@@ -122,7 +135,6 @@ namespace ArmoredVehicle
FormMachineConfig formMachine = new();
formMachine.AddEvent(new(AddMachine));
formMachine.Show();
}
/// <summary>
/// Добавление объекта
@@ -130,24 +142,37 @@ namespace ArmoredVehicle
/// <param name="machine"></param>
private void AddMachine(DrawingArmoredVehicle machine)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
_logger.LogInformation($"Попытка добавления объекта на невыбранную карту");
return;
}
if (machine == null)
{
MessageBox.Show("Необходимо выбрать объект перед добавлением!");
_logger.LogInformation($"Не выбран объект для добавления на карту ");
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(machine) != -1)
{
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {machine} на карту ");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Не удалось добавить объект {machine} на карту ");
}
}
if(machine == null)
catch (StorageOverflowException ex)
{
MessageBox.Show("Необходимо выбрать объект перед добавлением!");
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(machine) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
///<summary>
/// Удаление объекта
@@ -165,14 +190,29 @@ namespace ArmoredVehicle
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("С карты удален объект {0}", pos);
}
else
{
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (MachineNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Произошла неизвестная ошибка: {0}", ex.Message);
MessageBox.Show($"Неизестная ошибка: {ex.Message}");
}
}
@@ -235,5 +275,75 @@ namespace ArmoredVehicle
}
pictureBoxImage.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);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning("Успешное сохранение карты в файл: {0}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка сохранения карты в файл: {0}", saveFileDialog.FileName);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
_logger.LogWarning("Успешная загрузка карты из файла: {0}", saveFileDialog.FileName);
}
catch (LoadFileException ex)
{
MessageBox.Show($"Загрузка не удалась {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка загрузки карты из файла: {0}", saveFileDialog.FileName);
}
}
}
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SortBuTypeButton_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new MachineCompareByType());
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void SortByColorButton_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new MachineCompareByColor());
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@@ -3379,4 +3379,13 @@
KgIWwAgCFgD9CVgAVBGwAEYQsADoT8ACoIqABTCCgAVAd9/85v8DkZmkbaZCAjsAAAAASUVORK5CYII=
</value>
</data>
<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>163, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>347, 17</value>
</metadata>
</root>

View File

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

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class LoadFileException : ApplicationException
{
public LoadFileException() : base() { }
public LoadFileException(string message) : base(message) { }
public LoadFileException(string message, Exception exception) : base(message, exception) { }
protected LoadFileException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,49 @@
namespace ArmoredVehicle
{
internal class MachineCompareByColor : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xCar = x as DrawningObject;
var yCar = y as DrawningObject;
if (xCar == null && yCar == null)
{
return 0;
}
if (xCar == null && yCar != null)
{
return 1;
}
if (xCar != null && yCar == null)
{
return -1;
}
if (xCar.GetMachine.ArmoredVehicle.BodyColor == yCar.GetMachine.ArmoredVehicle.BodyColor)
{
return 0;
}
if (xCar.GetMachine.ArmoredVehicle.BodyColor.R.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.R) == 0)
{
if (xCar.GetMachine.ArmoredVehicle.BodyColor.R.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.R) == 0)
{
return xCar.GetMachine.ArmoredVehicle.BodyColor.B.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.B);
}
else return xCar.GetMachine.ArmoredVehicle.BodyColor.G.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.G);
}
else return xCar.GetMachine.ArmoredVehicle.BodyColor.R.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.R);
}
}
}

View File

@@ -0,0 +1,49 @@
namespace ArmoredVehicle
{
internal class MachineCompareByType : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xMachine= x as DrawningObject;
var yMachine = y as DrawningObject;
if (xMachine == null && yMachine == null)
{
return 0;
}
if (xMachine == null && yMachine != null)
{
return 1;
}
if (xMachine != null && yMachine == null)
{
return -1;
}
if (xMachine.GetMachine.GetType().Name != yMachine.GetMachine.GetType().Name)
{
if (xMachine.GetMachine.GetType().Name == "DrawingArmoredVehicle")
{
return -1;
}
return 1;
}
var speedCompare = xMachine.GetMachine.ArmoredVehicle.Speed.CompareTo(yMachine.GetMachine.ArmoredVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xMachine.GetMachine.ArmoredVehicle.Weight.CompareTo(yMachine.GetMachine.ArmoredVehicle.Weight);
}
}
}

View File

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

View File

@@ -6,7 +6,7 @@
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetMachineGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
@@ -57,7 +57,7 @@
/// <returns></returns>
public static int operator +(MapWithSetMachineGeneric<T, U> map, T machine)
{
return map._setMachines.Insert(machine);
return map._setMachines.Insert(machine);
}
/// <summary>
/// Перегрузка оператора вычитания
@@ -107,6 +107,36 @@
}
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 machine in _setMachines.GetMachine())
{
data += $"{machine.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setMachines.Insert(DrawningObject.Create(rec) as T);
}
}
public void Sort(IComparer<T> comparer)
{
_setMachines.SortSet(comparer);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>

View File

@@ -14,7 +14,7 @@ namespace ArmoredVehicle
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetMachineGeneric<DrawningObject,
readonly Dictionary<string, MapWithSetMachineGeneric<IDrawningObject,
AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
@@ -29,6 +29,14 @@ namespace ArmoredVehicle
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
@@ -36,7 +44,7 @@ namespace ArmoredVehicle
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string,
MapWithSetMachineGeneric<DrawningObject, AbstractMap>>();
MapWithSetMachineGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -54,7 +62,7 @@ namespace ArmoredVehicle
}
else
{
var NewElem = new MapWithSetMachineGeneric<DrawningObject, AbstractMap>(
var NewElem = new MapWithSetMachineGeneric<IDrawningObject, AbstractMap>(
_pictureWidth, _pictureHeight, map);
_mapStorages.Add(name, NewElem);
}
@@ -80,7 +88,7 @@ namespace ArmoredVehicle
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetMachineGeneric<DrawningObject, AbstractMap> this[string ind]
public MapWithSetMachineGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@@ -92,6 +100,71 @@ namespace ArmoredVehicle
return null;
}
}
/// <summary>
/// Сохранение информации по машинам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.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 LoadFileException($"Файл {filename} не найден");
}
string bufferTextFromFile = "";
using (StreamReader sr = new(filename))
{
string checkMap = sr.ReadLine();
if (!checkMap.Contains("MapsCollection"))
{
throw new LoadFileException($"Неверный формат данных в файле {filename}");
}
bufferTextFromFile = sr.ReadLine();
_mapStorages.Clear();
while (bufferTextFromFile != null)
{
var strs = bufferTextFromFile.Split(separatorDict);
AbstractMap map = null;
switch (strs[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "VertivalMap":
map = new VerticalMap();
break;
case "HorizontalMap":
map = new HorizontalMap();
break;
}
_mapStorages.Add(strs[0], new MapWithSetMachineGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[strs[0]].LoadData(strs[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
bufferTextFromFile = sr.ReadLine();
}
}
}
}
}

View File

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

View File

@@ -5,7 +5,7 @@
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetMachineGeneric<T>
where T : class
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
@@ -16,7 +16,6 @@
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
private int BusyPlaces = 0;
/// <summary>
/// Конструктор
/// </summary>
@@ -35,7 +34,7 @@
public int Insert(T machine)
{
if (Count + 1 <= _maxCount) return Insert(machine, 0);
else return -1;
else throw new StorageOverflowException(_maxCount);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@@ -45,14 +44,14 @@
/// <returns></returns>
public int Insert(T machine, int position)
{
if (position >= _maxCount && position < 0)
{
return -1;
if(_places.All(p => p.Equals(machine) == false))
{
if (position >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, machine);
return position;
}
_places.Insert(position, machine);
return position;
return -1;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@@ -71,9 +70,9 @@
return result;
}
return null;
else throw new MachineNotFoundException(position);
}
return null;
else throw new MachineNotFoundException(position);
}
/// <summary>
/// Получение объекта из набора по позиции
@@ -118,6 +117,17 @@
}
}
}
/// <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 ArmoredVehicle
{
[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

@@ -12,8 +12,8 @@ namespace ArmoredVehicle
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="weight">Вес танка</param>
/// <param name="bodyColor">Цвет башни</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="MachineGun">Признак наличия пулемета</param>
/// <param name="Tower">Признак наличия башни</param>

View File

@@ -0,0 +1,36 @@
namespace ArmoredVehicle
{
partial class appsettings
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>