5 Commits
Lab6 ... Lab8

Author SHA1 Message Date
c626ef8818 лаб 8 2022-11-19 23:45:19 +04:00
d2e92a906a цвет 2022-11-19 22:54:33 +04:00
6f7fc52f5d фиксы 2022-11-10 14:50:20 +04:00
41d3c491a8 лаб 7 комменты 2022-11-10 13:44:29 +04:00
da8bae0858 лабораторная работа 7 2022-11-05 22:49:39 +04:00
17 changed files with 432 additions and 63 deletions

View File

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

View File

@@ -8,36 +8,62 @@ namespace WarmlyShip
{
internal class DrawningObjectShip : IDrawningObject
{
private DrawningShip _ship = null;
public DrawningObjectShip(DrawningShip ship)
{
_ship = ship;
Ship = ship;
}
public float Step => _ship?.Ship?.Step ?? 0;
public float Step => Ship?.Ship?.Step ?? 0;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _ship?.GetCurrentPosition() ?? default;
return Ship?.GetCurrentPosition() ?? default;
}
public DrawningShip Ship { get; private set; }
public void MoveObject(Direction direction)
{
_ship?.MoveTransport(direction);
Ship?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_ship.SetPosition(x, y, width, height);
Ship.SetPosition(x, y, width, height);
}
void IDrawningObject.DrawningObject(Graphics g)
{
_ship.DrawTransport(g);
Ship.DrawTransport(g);
}
public string GetInfo() => _ship?.GetDataForSave();
public string GetInfo() => Ship?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectShip(data.CreateDrawningShip());
public bool Equals(IDrawningObject? other)
{
if (other is not DrawningObjectShip otherShip)
{
return false;
}
var entity = Ship.Ship;
var otherEntity = otherShip.Ship.Ship;
if (entity.GetType() != otherEntity.GetType() ||
entity.Speed != otherEntity.Speed ||
entity.Weight != otherEntity.Weight ||
entity.BodyColor != otherEntity.BodyColor)
{
return false;
}
if (entity is EntityWarmlyShip entityWarmlyShip &&
otherEntity is EntityWarmlyShip otherEntityWarmlyShip && (
entityWarmlyShip.Pipes != otherEntityWarmlyShip.Pipes ||
entityWarmlyShip.DopColor != otherEntityWarmlyShip.DopColor ||
entityWarmlyShip.FuelCompartment != otherEntityWarmlyShip.FuelCompartment))
{
return false;
}
return true;
}
}
}

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace WarmlyShip
{
internal class EntityWarmlyShip : EntityShip
public class EntityWarmlyShip : EntityShip
{
/// <summary>
/// Дополнительный цвет

View File

@@ -51,6 +51,8 @@
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
@@ -59,6 +61,8 @@
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.buttonSortByColor);
this.groupBoxTools.Controls.Add(this.buttonSortByType);
this.groupBoxTools.Controls.Add(this.groupBoxMaps);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonRight);
@@ -72,7 +76,7 @@
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(616, 28);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(250, 566);
this.groupBoxTools.Size = new System.Drawing.Size(250, 666);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@@ -144,7 +148,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(73, 516);
this.buttonLeft.Location = new System.Drawing.Point(73, 616);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 10;
@@ -157,7 +161,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(145, 515);
this.buttonRight.Location = new System.Drawing.Point(145, 615);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 9;
@@ -170,7 +174,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(109, 479);
this.buttonUp.Location = new System.Drawing.Point(109, 579);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 8;
@@ -183,7 +187,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(109, 515);
this.buttonDown.Location = new System.Drawing.Point(109, 615);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 7;
@@ -193,7 +197,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(6, 478);
this.buttonShowOnMap.Location = new System.Drawing.Point(9, 532);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(238, 29);
this.buttonShowOnMap.TabIndex = 5;
@@ -203,7 +207,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(6, 443);
this.buttonShowStorage.Location = new System.Drawing.Point(9, 497);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(238, 29);
this.buttonShowStorage.TabIndex = 4;
@@ -213,7 +217,7 @@
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(6, 399);
this.buttonRemoveShip.Location = new System.Drawing.Point(9, 453);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(238, 29);
this.buttonRemoveShip.TabIndex = 3;
@@ -223,7 +227,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 366);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(9, 420);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(238, 27);
@@ -231,7 +235,7 @@
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(6, 331);
this.buttonAddShip.Location = new System.Drawing.Point(9, 385);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(238, 29);
this.buttonAddShip.TabIndex = 1;
@@ -244,7 +248,7 @@
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(616, 566);
this.pictureBox.Size = new System.Drawing.Size(616, 666);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
@@ -270,14 +274,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@@ -289,11 +293,31 @@
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(9, 315);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(238, 29);
this.buttonSortByType.TabIndex = 13;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(9, 350);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(238, 29);
this.buttonSortByColor.TabIndex = 14;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// FormMapWithSetShips
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(866, 594);
this.ClientSize = new System.Drawing.Size(866, 694);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
@@ -337,5 +361,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
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;
@@ -24,10 +25,14 @@ namespace WarmlyShip
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
public FormMapWithSetShips()
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormMapWithSetShips(ILogger<FormMapWithSetShips> logger)
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
_logger = logger;
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
@@ -66,15 +71,18 @@ namespace WarmlyShip
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
/// <summary>
/// Выбор карты
@@ -84,6 +92,7 @@ namespace WarmlyShip
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
/// <summary>
/// Удаление карты
@@ -100,6 +109,7 @@ namespace WarmlyShip
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
@@ -116,18 +126,35 @@ namespace WarmlyShip
}
private void AddShip(DrawningShip ship)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(ship) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Airplane}", ship);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(ship) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, ship);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
@@ -143,14 +170,25 @@ namespace WarmlyShip
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 deletedShip = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedShip != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удален объект {@ship}", deletedShip);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (ShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
}
/// <summary>
@@ -223,13 +261,16 @@ namespace WarmlyShip
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
@@ -238,16 +279,32 @@ namespace WarmlyShip
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
ReloadMaps();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось открыть", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
private void SortBy(IComparer<IDrawningObject> comparer)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(comparer);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonSortByType_Click(object sender, EventArgs e) => SortBy(new ShipCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => SortBy(new ShipCompareByColor());
}
}

View File

@@ -119,7 +119,7 @@
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64)))));
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(230, 96);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 50);
@@ -164,7 +164,7 @@
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(89, 26);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(50, 50);

View File

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

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace WarmlyShip
{
internal class MapWithSetShipsGeneric<T, U>
where T : class, IDrawningObject
where T : class, IEquatable<T>, IDrawningObject
where U : AbstractMap
{
/// <summary>
@@ -198,5 +198,13 @@ namespace WarmlyShip
_setShips.Insert(DrawningObjectShip.Create(rec) as T);
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setShips.SortSet(comparer);
}
}
}

View File

@@ -73,11 +73,11 @@ namespace WarmlyShip
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -91,25 +91,24 @@ namespace WarmlyShip
fs.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 fs = new(filename))
{
if (!fs.ReadLine().Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new FileFormatException("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
@@ -132,7 +131,6 @@ namespace WarmlyShip
StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

@@ -1,3 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using System;
namespace WarmlyShip
{
internal static class Program
@@ -11,7 +18,30 @@ namespace WarmlyShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetShips());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetShips>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetShips>()
.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

@@ -7,8 +7,8 @@ using System.Threading.Tasks;
namespace WarmlyShip
{
internal class SetShipsGeneric<T>
where T : class
{
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
@@ -48,13 +48,17 @@ namespace WarmlyShip
/// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T airplane, int position)
public int Insert(T ship, int position)
{
if (_places.Contains(ship))
throw new ArgumentException($"Объект {ship} уже есть в наборе");
if (Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!isCorrectPosition(position))
{
return -1;
}
_places.Insert(position, airplane);
_places.Insert(position, ship);
return position;
}
/// <summary>
@@ -66,7 +70,9 @@ namespace WarmlyShip
{
if (!isCorrectPosition(position))
return null;
var result = _places[position];
var result = this[position];
if (result == null)
throw new ShipNotFoundException(position);
_places.RemoveAt(position);
return result;
}
@@ -104,5 +110,17 @@ namespace WarmlyShip
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
internal class ShipCompareByColor : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
var xShip = x as DrawningObjectShip;
var yShip = y as DrawningObjectShip;
if (xShip == yShip)
{
return 0;
}
if (xShip == null)
{
return 1;
}
if (yShip == null)
{
return -1;
}
var xEntity = xShip.Ship.Ship;
var yEntity = yShip.Ship.Ship;
var colorWeight = xEntity.BodyColor.ToArgb().CompareTo(yEntity.BodyColor.ToArgb());
if (colorWeight != 0 ||
xEntity is not EntityWarmlyShip xEntityWarmlyShip ||
yEntity is not EntityWarmlyShip yEntityWarmlyShip)
{
return colorWeight;
}
return xEntityWarmlyShip.DopColor.ToArgb().CompareTo(yEntityWarmlyShip.DopColor.ToArgb());
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
internal class ShipCompareByType : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
var xShip = x as DrawningObjectShip;
var yShip = y as DrawningObjectShip;
if (xShip == yShip)
{
return 0;
}
if (xShip == null)
{
return 1;
}
if (yShip == null)
{
return -1;
}
if (xShip.Ship.GetType().Name != yShip.Ship.GetType().Name)
{
if (xShip.Ship.GetType() == typeof(DrawningShip))
{
return -1;
}
return 1;
}
var speedCompare = xShip.Ship.Ship.Speed.CompareTo(yShip.Ship.Ship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xShip.Ship.Ship.Weight.CompareTo(yShip.Ship.Ship.Weight);
}
}
}

View File

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

View File

@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace WarmlyShip
{
[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,27 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,48 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Destructure": [
{
"Name": "ByTransforming",
"Args": {
"returnType": "WarmlyShip.EntityShip",
"transformation": "r => new { BodyColor = r.BodyColor.Name, r.Speed, r.Weight }"
}
},
{
"Name": "ByTransforming",
"Args": {
"returnType": "WarmlyShip.EntityWarmlyShip",
"transformation": "r => new { BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.Pipes, r.FuelCompartment, r.Speed, r.Weight }"
}
},
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 4 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 100 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 10 }
}
],
"Properties": {
"Application": "WarmlyShip"
}
}
}