6 Commits

14 changed files with 451 additions and 43 deletions

View File

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

View File

@@ -10,6 +10,7 @@ namespace WarmlyLocomotive
{
private DrawningLocomotive _locomotive = null;
public float Step => _locomotive?.Locomotive?.Step ?? 0;
public DrawningLocomotive GetLocomotive => _locomotive;
public DrawningObjectLocomotive(DrawningLocomotive locomotive)
{
_locomotive = locomotive;
@@ -32,5 +33,55 @@ namespace WarmlyLocomotive
}
public string GetInfo() => _locomotive?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectLocomotive(data.CreateDrawningLocomotive());
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 warmlyLocomotive && otherLocomotiveLocomotive is EntityWarmlyLocomotive otherWarmlyLocomotive)
{
if(warmlyLocomotive.Pipe != otherWarmlyLocomotive.Pipe)
{
return false;
}
if (warmlyLocomotive.FuelCompartment != otherWarmlyLocomotive.FuelCompartment)
{
return false;
}
if (warmlyLocomotive.WarmlyLines != otherWarmlyLocomotive.WarmlyLines)
{
return false;
}
if (warmlyLocomotive.DopColor != otherWarmlyLocomotive.DopColor)
{
return false;
}
}
else if(locomotive is EntityWarmlyLocomotive || otherLocomotiveLocomotive is EntityWarmlyLocomotive)
{
return false;
}
return true;
}
}
}

View File

@@ -29,6 +29,8 @@
private void InitializeComponent()
{
this.groupBox = 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();
@@ -59,6 +61,8 @@
//
// groupBox
//
this.groupBox.Controls.Add(this.buttonSortByColor);
this.groupBox.Controls.Add(this.buttonSortByType);
this.groupBox.Controls.Add(this.groupBoxMaps);
this.groupBox.Controls.Add(this.buttonDown);
this.groupBox.Controls.Add(this.buttonRight);
@@ -72,11 +76,31 @@
this.groupBox.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox.Location = new System.Drawing.Point(668, 24);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(200, 638);
this.groupBox.Size = new System.Drawing.Size(200, 693);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(19, 340);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(169, 30);
this.buttonSortByColor.TabIndex = 12;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(19, 304);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(169, 30);
this.buttonSortByType.TabIndex = 11;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
@@ -147,7 +171,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(87, 591);
this.buttonDown.Location = new System.Drawing.Point(87, 646);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 9;
@@ -159,7 +183,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(123, 591);
this.buttonRight.Location = new System.Drawing.Point(123, 646);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 8;
@@ -171,7 +195,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(51, 591);
this.buttonLeft.Location = new System.Drawing.Point(51, 646);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 7;
@@ -183,7 +207,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(87, 555);
this.buttonUp.Location = new System.Drawing.Point(87, 610);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 6;
@@ -193,7 +217,7 @@
// buttonShowOnMap
//
this.buttonShowOnMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowOnMap.Location = new System.Drawing.Point(19, 500);
this.buttonShowOnMap.Location = new System.Drawing.Point(19, 554);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(169, 30);
this.buttonShowOnMap.TabIndex = 5;
@@ -204,7 +228,7 @@
// buttonShowStorage
//
this.buttonShowStorage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowStorage.Location = new System.Drawing.Point(19, 452);
this.buttonShowStorage.Location = new System.Drawing.Point(19, 506);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(169, 30);
this.buttonShowStorage.TabIndex = 4;
@@ -215,7 +239,7 @@
// buttonRemoveLocomotive
//
this.buttonRemoveLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(19, 406);
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(19, 460);
this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
this.buttonRemoveLocomotive.Size = new System.Drawing.Size(169, 30);
this.buttonRemoveLocomotive.TabIndex = 3;
@@ -226,7 +250,7 @@
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 377);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 431);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23);
@@ -235,7 +259,7 @@
// buttonAddLocomotive
//
this.buttonAddLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAddLocomotive.Location = new System.Drawing.Point(19, 341);
this.buttonAddLocomotive.Location = new System.Drawing.Point(19, 395);
this.buttonAddLocomotive.Name = "buttonAddLocomotive";
this.buttonAddLocomotive.Size = new System.Drawing.Size(169, 30);
this.buttonAddLocomotive.TabIndex = 1;
@@ -248,7 +272,7 @@
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(668, 638);
this.pictureBox.Size = new System.Drawing.Size(668, 693);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
@@ -297,7 +321,7 @@
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(868, 662);
this.ClientSize = new System.Drawing.Size(868, 717);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.menuStrip);
@@ -341,5 +365,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -27,11 +28,16 @@ namespace WarmlyLocomotive
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetLocomotives()
public FormMapWithSetLocomotives(ILogger<FormMapWithSetLocomotives> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -77,14 +83,34 @@ namespace WarmlyLocomotive
return;
}
DrawningObjectLocomotive locomotive = new(drawningLocomotive);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1)
{
_logger.LogInformation($"Добавление объекта {locomotive}");
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось добавить объект");
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(ArgumentException ex)
{
_logger.LogWarning($"Ошибка при добавлении: {ex.Message}");
MessageBox.Show($"Ошибка при добавлении: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
@@ -107,14 +133,30 @@ namespace WarmlyLocomotive
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 deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedLocomotive != null)
{
_logger.LogInformation($"Объект {deletedLocomotive} удалён");
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation($"Не удалось удалить объект по позиции {pos}");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (LocomotiveNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Ошибка удаления: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
@@ -183,21 +225,25 @@ namespace WarmlyLocomotive
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
_logger.LogInformation("Не все данные заполнены при попытке создании карты");
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
_logger.LogInformation($"Нет карты с названием {comboBoxSelectorMap.Text}");
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
{
_logger.LogInformation("Присутствуют символы, недопустимые для имени карты");
MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
@@ -207,6 +253,7 @@ namespace WarmlyLocomotive
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Текущая карта сменена на {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Удаление карты
@@ -224,6 +271,7 @@ namespace WarmlyLocomotive
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
}
/// <summary>
@@ -235,13 +283,16 @@ namespace WarmlyLocomotive
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Успешное сохранение по пути {saveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить данные. Ошибка - {ex.Message}");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -254,16 +305,47 @@ namespace WarmlyLocomotive
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
_logger.LogInformation($"Успешная загрузка по пути {openFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить данные. Ошибка - {ex.Message}");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <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());
pictureBox.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());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace WarmlyLocomotive
{
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace WarmlyLocomotive
{
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 xEntityLocomotive = xLocomotive.GetLocomotive.Locomotive;
var yEntityLocomotive = yLocomotive.GetLocomotive.Locomotive;
var baseColorCompare = xEntityLocomotive.BodyColor.ToArgb().CompareTo(yEntityLocomotive.BodyColor.ToArgb());
if(baseColorCompare != 0)
{
return baseColorCompare;
}
if(xEntityLocomotive is EntityWarmlyLocomotive xWarmlyLocomotive && yEntityLocomotive is EntityWarmlyLocomotive yWarmlyLocomotive)
{
var dopColorCompare = xWarmlyLocomotive.DopColor.ToArgb().CompareTo(yWarmlyLocomotive.DopColor.ToArgb());
if (dopColorCompare != 0)
{
return dopColorCompare;
}
}
var speedCompare = xLocomotive.GetLocomotive.Locomotive.Speed.CompareTo(yLocomotive.GetLocomotive.Locomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xLocomotive.GetLocomotive.Locomotive.Weight.CompareTo(yLocomotive.GetLocomotive.Locomotive.Weight);
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyLocomotive
{
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.GetLocomotive.GetType().Name != yLocomotive.GetLocomotive.GetType().Name)
{
if (xLocomotive.GetLocomotive.GetType().Name == "DrawningLocomotive")
{
return -1;
}
return 1;
}
var speedCompare = xLocomotive.GetLocomotive.Locomotive.Speed.CompareTo(yLocomotive.GetLocomotive.Locomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xLocomotive.GetLocomotive.Locomotive.Weight.CompareTo(yLocomotive.GetLocomotive.Locomotive.Weight);
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyLocomotive
{
[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 contex) : base(info, contex) { }
}
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace WarmlyLocomotive
{
internal class MapWithSetLocomotivesGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
@@ -133,6 +133,14 @@ namespace WarmlyLocomotive
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setLocomotives.SortSet(comparer);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()

View File

@@ -94,7 +94,7 @@ namespace WarmlyLocomotive
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -108,18 +108,17 @@ namespace WarmlyLocomotive
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка информации по локомотивам в депо из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@@ -127,7 +126,7 @@ namespace WarmlyLocomotive
if (!str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
@@ -150,7 +149,6 @@ namespace WarmlyLocomotive
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace WarmlyLocomotive
{
internal static class Program
@@ -11,7 +16,25 @@ namespace WarmlyLocomotive
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetLocomotives());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetLocomotives>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetLocomotives>()
.AddLogging(option =>
{
var serilogLogger = new LoggerConfiguration()
.WriteTo.File("LogOfProgram.txt")
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(serilogLogger, true);
});
}
}
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace WarmlyLocomotive
{
internal class SetLocomotivesGeneric<T>
where T : class
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
@@ -44,9 +44,13 @@ namespace WarmlyLocomotive
/// <returns></returns>
public int Insert(T locomotive, int position)
{
if (_places.Contains(locomotive))
{
throw new ArgumentException($"Объект {locomotive} уже присутствует в наборе");
}
if (position < 0 || position > Count || _maxCount == Count)
{
return -1;
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, locomotive);
return position;
@@ -60,7 +64,7 @@ namespace WarmlyLocomotive
{
if (position < 0 || position >= Count)
{
return null;
throw new LocomotiveNotFoundException(position);
}
T memoryObj = _places[position];
_places.RemoveAt(position);
@@ -107,5 +111,17 @@ namespace WarmlyLocomotive
}
}
}
/// <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 WarmlyLocomotive
{
[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

@@ -8,6 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<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="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>