12 Commits

18 changed files with 696 additions and 46 deletions

View File

@@ -1,6 +1,6 @@
namespace Locomotives
{
internal abstract class AbstractMap
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
/// <summary>
/// Поле от интерфейса прорисовки
@@ -239,5 +239,35 @@
/// <param name="i"></param>
/// <param name="j"></param>
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
/// <summary>
/// Реализация сравнения
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(AbstractMap? other)
{
if (other == null)
{
return false;
}
if (_map.GetLength(0) == other._map.GetLength(0) && _map.GetLength(1) == other._map.GetLength(1))
{
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;
}
}
}
}
else
{
return false;
}
return true;
}
}
}

View File

@@ -8,7 +8,7 @@
/// <summary>
/// Объект от класса отрисовки локомотива
/// </summary>
private DrawningLocomotive _locomotive = null;
public DrawningLocomotive _locomotive { get; set; }
public DrawningObjectLocomotive(DrawningLocomotive locomotive)
{
_locomotive = locomotive;
@@ -30,6 +30,66 @@
{
_locomotive.DrawTransport(g);
}
public string GetInfo() => _locomotive?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectLocomotive(data.CreateDrawningLocomotive());
/// <summary>
/// Реализация проверки на равенство с другим объектом
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IDrawningObject? other)
{
//проверка на существование второго объекта
if (other == null)
{
return false;
}
var otherLocomotive = other as DrawningObjectLocomotive;
if (otherLocomotive == null)
{
return false;
}
var locomotive = _locomotive.Locomotive;
var otherLocomotiveLocomotive = otherLocomotive._locomotive.Locomotive;
//проверка характеристик базовой сущности
if (locomotive.Speed != otherLocomotiveLocomotive.Speed)
{
return false;
}
if (locomotive.Weight != otherLocomotiveLocomotive.Weight)
{
return false;
}
if (locomotive.BodyColor != otherLocomotiveLocomotive.BodyColor)
{
return false;
}
//проверка на одинаковость типов первого и второго объекта (не является ли один из них наследником, а другой базовым классом)
if (locomotive is EntityWarmlyLocomotive && otherLocomotiveLocomotive is not EntityWarmlyLocomotive)
{
return false;
}
if (locomotive is not EntityWarmlyLocomotive && otherLocomotiveLocomotive is EntityWarmlyLocomotive)
{
return false;
}
//если оба объекта являются продвинутыми, сравниваем дополнительные характеристики
if (locomotive is EntityWarmlyLocomotive warmlyLocomotive && otherLocomotiveLocomotive is EntityWarmlyLocomotive otherWarmlyLocomotive)
{
if (warmlyLocomotive.AdditionalColor != otherWarmlyLocomotive.AdditionalColor)
{
return false;
}
if (warmlyLocomotive.HasPipe != otherWarmlyLocomotive.HasPipe)
{
return false;
}
if (warmlyLocomotive.HasFuelTank != otherWarmlyLocomotive.HasFuelTank)
{
return false;
}
}
return true;
}
}
}

View File

@@ -0,0 +1,50 @@
namespace Locomotives
{
/// <summary>
/// Расширение для класса DrawningLocomotive
/// </summary>
internal static class ExtentionLocomotive
{
/// <summary>
/// Разделитель для записи информации
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Получаем данные для сохранения в файл
/// </summary>
/// <param name="drawningLocomotive"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningLocomotive drawningLocomotive)
{
var locomotive = drawningLocomotive.Locomotive;
var str = $"{locomotive.Speed}{_separatorForObject}{locomotive.Weight}{_separatorForObject}{locomotive.BodyColor.Name}";
if (locomotive is not EntityWarmlyLocomotive warmlyLocomotive)
{
return str;
}
return $"{str}{_separatorForObject}{warmlyLocomotive.AdditionalColor.Name}{_separatorForObject}{warmlyLocomotive.HasPipe}{_separatorForObject}{warmlyLocomotive.HasFuelTank}";
}
/// <summary>
/// Восстанавливаем объект по полученной из файла информации
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningLocomotive CreateDrawningLocomotive(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningLocomotive(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningWarmlyLocomotive
(
Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), 160, 85,
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5])
);
}
return null;
}
}
}

View File

@@ -29,6 +29,8 @@
private void InitializeComponent()
{
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
@@ -45,13 +47,22 @@
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddCar = new System.Windows.Forms.Button();
this.pictureBoxLocomotives = new System.Windows.Forms.PictureBox();
this.menuStrip1 = 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.pictureBoxLocomotives)).BeginInit();
this.menuStrip1.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.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonDown);
@@ -63,13 +74,33 @@
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddCar);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(950, 0);
this.groupBoxTools.Location = new System.Drawing.Point(462, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(223, 676);
this.groupBoxTools.Size = new System.Drawing.Size(223, 652);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(31, 341);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(164, 23);
this.buttonSortByColor.TabIndex = 3;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(31, 312);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(164, 23);
this.buttonSortByType.TabIndex = 3;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBoxMaps
//
this.groupBoxMaps.Anchor = System.Windows.Forms.AnchorStyles.Right;
@@ -140,7 +171,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Locomotives.Properties.Resources.ArrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(107, 604);
this.buttonUp.Location = new System.Drawing.Point(107, 580);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 10;
@@ -152,7 +183,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Locomotives.Properties.Resources.ArrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(107, 640);
this.buttonDown.Location = new System.Drawing.Point(107, 616);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 9;
@@ -164,7 +195,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Locomotives.Properties.Resources.ArrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(71, 640);
this.buttonLeft.Location = new System.Drawing.Point(71, 616);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
@@ -176,7 +207,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Locomotives.Properties.Resources.ArrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(143, 640);
this.buttonRight.Location = new System.Drawing.Point(143, 616);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 7;
@@ -185,7 +216,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(31, 426);
this.buttonShowOnMap.Location = new System.Drawing.Point(31, 526);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(164, 26);
this.buttonShowOnMap.TabIndex = 5;
@@ -195,7 +226,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(31, 394);
this.buttonShowStorage.Location = new System.Drawing.Point(31, 494);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(164, 26);
this.buttonShowStorage.TabIndex = 4;
@@ -205,7 +236,7 @@
//
// buttonRemoveLocomotive
//
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(31, 362);
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(31, 462);
this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
this.buttonRemoveLocomotive.Size = new System.Drawing.Size(164, 26);
this.buttonRemoveLocomotive.TabIndex = 3;
@@ -215,7 +246,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(31, 333);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(31, 433);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(164, 23);
@@ -223,7 +254,7 @@
//
// buttonAddCar
//
this.buttonAddCar.Location = new System.Drawing.Point(31, 291);
this.buttonAddCar.Location = new System.Drawing.Point(31, 391);
this.buttonAddCar.Name = "buttonAddCar";
this.buttonAddCar.Size = new System.Drawing.Size(164, 26);
this.buttonAddCar.TabIndex = 1;
@@ -234,19 +265,62 @@
// pictureBoxLocomotives
//
this.pictureBoxLocomotives.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxLocomotives.Location = new System.Drawing.Point(0, 0);
this.pictureBoxLocomotives.Location = new System.Drawing.Point(0, 24);
this.pictureBoxLocomotives.Name = "pictureBoxLocomotives";
this.pictureBoxLocomotives.Size = new System.Drawing.Size(950, 676);
this.pictureBoxLocomotives.Size = new System.Drawing.Size(462, 652);
this.pictureBoxLocomotives.TabIndex = 1;
this.pictureBoxLocomotives.TabStop = false;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(685, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip";
//
// 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(48, 20);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file|*.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file|*.txt";
//
// FormMapWithSetLocomotives
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1173, 676);
this.ClientSize = new System.Drawing.Size(685, 676);
this.Controls.Add(this.pictureBoxLocomotives);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMapWithSetLocomotives";
this.Text = "Карта с набором объектов";
this.groupBoxTools.ResumeLayout(false);
@@ -254,7 +328,10 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocomotives)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -277,5 +354,13 @@
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip1;
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 @@
namespace Locomotives
using Serilog;
namespace Locomotives
{
/// <summary>
/// Форма для работы с набором объектов
@@ -18,12 +19,14 @@
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetLocomotives()
public FormMapWithSetLocomotives(ILogger logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBoxLocomotives.Width, pictureBoxLocomotives.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -72,8 +75,9 @@
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
textBoxNewMapName.Text = "";
ReloadMaps();
_logger.Information($"Создана карта типа {comboBoxSelectorMap.Text} с названием {textBoxNewMapName.Text}");
textBoxNewMapName.Text = "";
}
/// <summary>
/// Выбор карты
@@ -83,6 +87,7 @@
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.Information($"Выбрана карта с названием {listBoxMaps.SelectedItem}");
}
/// <summary>
/// Удаление карты
@@ -99,6 +104,7 @@
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.Information($"Удалена карта с названием {listBoxMaps.SelectedItem}");
}
MessageBox.Show("Карта удалена");
}
@@ -111,19 +117,38 @@
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
FormLocomotiveConfig formLocomotiveConfig = new();
formLocomotiveConfig.AddEvent(new (AddLocomotive));
formLocomotiveConfig.AddEvent(new(AddLocomotive));
formLocomotiveConfig.Show();
}
private void AddLocomotive(DrawningLocomotive locomotive)
{
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive)) > -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive)) > -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.Information($"Добавлен новый объект на карту {listBoxMaps.SelectedItem}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (NotUniqueObjectException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Ошибка добавления: {ex.Message}");
_logger.Warning($"Не удалось добавить объект: {ex.Message}");
}
catch (StorageOverflowException ex)
{
MessageBox.Show($"Ошибка добавления: {ex.Message}");
_logger.Warning($"Не удалось добавить объект: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.Warning($"Не удалось добавить объект: {ex.Message}");
}
}
/// <summary>
@@ -146,16 +171,29 @@
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) > -1)
try
{
MessageBox.Show("Объект удален");
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) > -1)
{
MessageBox.Show("Объект удален");
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.Information($"Удалён объект с карты {listBoxMaps.SelectedItem}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (LocomotiveNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.Warning($"Не удалось удалить объект: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.Warning($"Не удалось удалить объект: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
@@ -214,5 +252,82 @@
}
pictureBoxLocomotives.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.Information($"Коллекция карт сохранена в файл по адресу {saveFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Warning($"Ошибка сохранения файла по адресу {saveFileDialog.FileName}: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
_logger.Information($"Коллекция карт загружена из файла по адресу {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось загрузить файл: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Warning($"Ошибка загрузки файла по адресу {openFileDialog.FileName}: {ex.Message}");
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new LocomotiveCompareByType());
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new LocomotiveCompareByColor());
pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@@ -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="menuStrip1.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>132, 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>

View File

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

View File

@@ -0,0 +1,43 @@
namespace Locomotives
{
/// <summary>
/// Реализация класса-компаратора для сравнения по цвету
/// </summary>
internal class LocomotiveCompareByColor : 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 xLocomotive = x as DrawningObjectLocomotive;
var yLocomotive = y as DrawningObjectLocomotive;
if (xLocomotive == null && yLocomotive == null)
{
return 0;
}
if (xLocomotive == null && yLocomotive != null)
{
return 1;
}
if (xLocomotive != null && yLocomotive == null)
{
return -1;
}
//сравниваем цвета по названию
var xColorName = xLocomotive._locomotive.Locomotive.BodyColor.Name;
var yColorName = yLocomotive._locomotive.Locomotive.BodyColor.Name;
return xColorName.CompareTo(yColorName);
}
}
}

View File

@@ -0,0 +1,52 @@
namespace Locomotives
{
/// <summary>
/// Реализация класса-компаратора для сортировки, сравнение по типу.
/// </summary>
internal class LocomotiveCompareByType : 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 xLocomotive = x as DrawningObjectLocomotive;
var yLocomotive = y as DrawningObjectLocomotive;
if (xLocomotive == null && yLocomotive == null)
{
return 0;
}
if (xLocomotive == null && yLocomotive != null)
{
return 1;
}
if (xLocomotive != null && yLocomotive == null)
{
return -1;
}
if (xLocomotive?._locomotive.GetType().Name != yLocomotive?._locomotive.GetType().Name)
{
if (xLocomotive?._locomotive.GetType().Name == "DrawningLocomotive")
{
return -1;
}
return 1;
}
var speedCompare = xLocomotive._locomotive.Locomotive.Speed.CompareTo(yLocomotive._locomotive.Locomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xLocomotive._locomotive.Locomotive.Weight.CompareTo(yLocomotive?._locomotive.Locomotive.Weight);
}
}
}

View File

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

View File

@@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appconfig.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appconfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -27,4 +37,20 @@
<Folder Include="Resources\" />
</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.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.DependencyModel" Version="7.0.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<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>
</Project>

View File

@@ -1,7 +1,7 @@
namespace Locomotives
{
internal class MapWithSetLocomotivesGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
@@ -174,5 +174,36 @@
CurrentLocomotiveNumber++;
}
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="separatorType"></param>
/// <param name="separatorData"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
//Получаем название карты
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var locomotive in _setLocomotives.GetLocomotives())
{
data += $"{locomotive.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var record in records)
{
_setLocomotives.Insert(DrawningObjectLocomotive.Create(record) as T);
}
}
public void Sort(IComparer<T> comparer)
{
_setLocomotives.SortSet(comparer);
}
}
}

View File

@@ -1,4 +1,6 @@
namespace Locomotives
using System.Text;
using System.IO;
namespace Locomotives
{
/// <summary>
/// Класс для хранения коллекции карт
@@ -8,7 +10,7 @@
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@@ -22,13 +24,21 @@
/// </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, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -39,7 +49,7 @@
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
_mapStorages.Add(name, new MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
@@ -54,13 +64,65 @@
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> this[string ind]
public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
return _mapStorages[ind];
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write("MapsCollection\n");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}\n");
}
sw.Close();
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найдён");
}
using (StreamReader sr = new(filename))
{
string firstStr = sr.ReadLine();
if (firstStr == null || !firstStr.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("Формат данных в файле неправильный");
}
string? currentString;
while ((currentString = sr.ReadLine()) != null)
{
var elem = currentString.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "CrossMap":
map = new CrossMap();
break;
case "RoadsMap":
map = new RoadsMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
sr.Close();
}
}
}
}

View File

@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace Locomotives
{
[Serializable]
internal class NotUniqueObjectException : ApplicationException
{
public NotUniqueObjectException() : base("Такой объект уже есть в коллекции") { }
public NotUniqueObjectException(string message) : base(message) { }
public NotUniqueObjectException(string message, Exception Exception) : base(message, Exception) { }
protected NotUniqueObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -1,3 +1,6 @@
using Microsoft.Extensions.Configuration;
using Serilog;
namespace Locomotives
{
internal static class Program
@@ -8,8 +11,17 @@ namespace Locomotives
[STAThread]
static void Main()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appconfig.json")
.AddJsonFile($"appconfig.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
var Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.ReadFrom.Configuration(configuration)
.CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetLocomotives());
Application.Run(new FormMapWithSetLocomotives(Logger));
}
}
}

View File

@@ -1,7 +1,7 @@
namespace Locomotives
{
internal class SetLocomotivesGeneric<T>
where T : class
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
@@ -28,6 +28,10 @@
/// <returns></returns>
public int Insert(T locomotive)
{
if (_places.Contains(locomotive))
{
throw new NotUniqueObjectException();
}
if (_places.Count == 0)
{
_places.Add(locomotive);
@@ -43,7 +47,7 @@
_places.Insert(0, locomotive);
return 0;
}
return -1;
throw new StorageOverflowException(_places.Count);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@@ -62,7 +66,7 @@
_places.Insert(position, locomotive);
return position;
}
return -1;
throw new StorageOverflowException(_places.Count);
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@@ -71,9 +75,9 @@
/// <returns></returns>
public int Remove(int position)
{
if (position > Count || _places[position] == null)
if (position >= Count || _places[position] == null)
{
return -1;
throw new LocomotiveNotFoundException(position);
}
_places.RemoveAt(position);
return position;
@@ -119,5 +123,13 @@
}
}
}
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace Locomotives
{
[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 context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,17 @@
{
"Serilog":
{
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args":
{
"path": "Logs/log.log",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}] {Level}: {Message};{NewLine}"
}
}
]
}
}