3 Commits

Author SHA1 Message Date
Катя Ихонкина
99871550b4 Коммит 2022-12-16 20:46:30 +04:00
Катя Ихонкина
41ccf1460c лабораторная 7 2022-12-16 20:29:27 +04:00
Катя Ихонкина
585ce78621 Коммит 1 2022-12-10 12:11:05 +04:00
15 changed files with 463 additions and 79 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace MotorBoat
{
internal abstract class AbstractMap
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
protected int[,] _map = null;
@@ -170,6 +170,47 @@ namespace MotorBoat
return true;
}
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;
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat
{
internal class BoatCompareByColor : 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 xShip = x as DrawningObjectBoat;
var yShip = y as DrawningObjectBoat;
if (xShip == null && yShip == null)
{
return 0;
}
if (xShip == null && yShip != null)
{
return 1;
}
if (xShip != null && yShip == null)
{
return -1;
}
var xEntityShip = xShip.GetShip.Boat;
var yEntityShip = yShip.GetShip.Boat;
var baseColorCompare = xEntityShip.BodyColor.ToArgb().CompareTo(yEntityShip.BodyColor.ToArgb());
if (baseColorCompare != 0)
{
return baseColorCompare;
}
if (xEntityShip is EntityMotorBoat xWarmlyShip && yEntityShip is EntityMotorBoat yWarmlyShip)
{
var dopColorCompare = xWarmlyShip.DopColor.ToArgb().CompareTo(yWarmlyShip.DopColor.ToArgb());
if (dopColorCompare != 0)
{
return dopColorCompare;
}
}
var speedCompare = xShip.GetShip.Boat.Speed.CompareTo(yShip.GetShip.Boat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xShip.GetShip.Boat.Weight.CompareTo(yShip.GetShip.Boat.Weight);
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat
{
internal class BoatCompareByType : 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 DrawningObjectBoat;
var yCar = y as DrawningObjectBoat;
if (xCar == null && yCar == null)
{
return 0;
}
if (xCar == null && yCar != null)
{
return 1;
}
if (xCar != null && yCar == null)
{
return -1;
}
if (xCar.GetShip.GetType().Name != yCar.GetShip.GetType().Name)
{
if (xCar.GetShip.GetType().Name == "DrawningBoat")
{
return -1;
}
return 1;
}
var speedCompare =
xCar.GetShip.Boat.Speed.CompareTo(yCar.GetShip.Boat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xCar.GetShip.Boat.Weight.CompareTo(yCar.GetShip.Boat.Weight);
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat
{
internal class BoatNotFoundException : ApplicationException
{
public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BoatNotFoundException() : base() { }
public BoatNotFoundException(string message) : base(message) { }
public BoatNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BoatNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -18,13 +19,17 @@ namespace MotorBoat
{
return _boat?.GetCurrentPosition() ?? default;
}
public DrawningBoat GetShip => _boat;
public void MoveObject(Direction direction)
{
_boat?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_boat.SetPosition(x, y, width, height);
_boat.SetPosition(x, y, width, height);
}
void IDrawningObject.DrawningObject(Graphics g)
{
@@ -32,5 +37,52 @@ namespace MotorBoat
}
public string GetInfo() => _boat?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectBoat(data.CreateDrawningBoat());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherShip = other as DrawningObjectBoat;
if (otherShip == null)
{
return false;
}
var ship = _boat.Boat;
var otherShipShip = otherShip._boat.Boat;
if (ship.GetType().Name != otherShipShip.GetType().Name)
{
return false;
}
if (ship.Speed != otherShipShip.Speed)
{
return false;
}
if (ship.Weight != otherShipShip.Weight)
{
return false;
}
if (ship.BodyColor != otherShipShip.BodyColor)
{
return false;
}
if (ship is EntityMotorBoat liner && otherShipShip is EntityMotorBoat otherLiner)
{
if (liner.DopColor != otherLiner.DopColor)
{
return false;
}
if (liner.SportLine != otherLiner.SportLine)
{
return false;
}
if (liner.Wing != otherLiner.Wing)
{
return false;
}
}
return true;
}
}
}

View File

@@ -29,6 +29,8 @@
private void InitializeComponent()
{
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.ButtonSortColor = new System.Windows.Forms.Button();
this.ButtonSortType = new System.Windows.Forms.Button();
this.ButtonDeleteMap = new System.Windows.Forms.Button();
this.ListBoxMaps = new System.Windows.Forms.ListBox();
this.ButtonAddMap = new System.Windows.Forms.Button();
@@ -57,6 +59,8 @@
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.ButtonSortColor);
this.groupBoxTools.Controls.Add(this.ButtonSortType);
this.groupBoxTools.Controls.Add(this.ButtonDeleteMap);
this.groupBoxTools.Controls.Add(this.ListBoxMaps);
this.groupBoxTools.Controls.Add(this.ButtonAddMap);
@@ -79,6 +83,26 @@
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "v";
//
// ButtonSortColor
//
this.ButtonSortColor.Location = new System.Drawing.Point(130, 268);
this.ButtonSortColor.Name = "ButtonSortColor";
this.ButtonSortColor.Size = new System.Drawing.Size(83, 23);
this.ButtonSortColor.TabIndex = 36;
this.ButtonSortColor.Text = "По цвету";
this.ButtonSortColor.UseVisualStyleBackColor = true;
this.ButtonSortColor.Click += new System.EventHandler(this.ButtonSortColor_Click);
//
// ButtonSortType
//
this.ButtonSortType.Location = new System.Drawing.Point(38, 268);
this.ButtonSortType.Name = "ButtonSortType";
this.ButtonSortType.Size = new System.Drawing.Size(86, 23);
this.ButtonSortType.TabIndex = 35;
this.ButtonSortType.Text = "По типу";
this.ButtonSortType.UseVisualStyleBackColor = true;
this.ButtonSortType.Click += new System.EventHandler(this.ButtonSortType_Click);
//
// ButtonDeleteMap
//
this.ButtonDeleteMap.Location = new System.Drawing.Point(38, 209);
@@ -118,7 +142,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(38, 328);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(38, 359);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(175, 23);
@@ -127,7 +151,7 @@
//
// buttonRemoveBoat
//
this.buttonRemoveBoat.Location = new System.Drawing.Point(38, 357);
this.buttonRemoveBoat.Location = new System.Drawing.Point(38, 388);
this.buttonRemoveBoat.Name = "buttonRemoveBoat";
this.buttonRemoveBoat.Size = new System.Drawing.Size(175, 35);
this.buttonRemoveBoat.TabIndex = 14;
@@ -137,7 +161,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(38, 412);
this.buttonShowStorage.Location = new System.Drawing.Point(38, 443);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(175, 35);
this.buttonShowStorage.TabIndex = 15;
@@ -150,7 +174,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::MotorBoat.Properties.Resources.d;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(112, 529);
this.buttonDown.Location = new System.Drawing.Point(112, 560);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 20;
@@ -162,7 +186,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::MotorBoat.Properties.Resources.up;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(148, 529);
this.buttonRight.Location = new System.Drawing.Point(148, 560);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 19;
@@ -174,7 +198,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::MotorBoat.Properties.Resources.left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(76, 529);
this.buttonLeft.Location = new System.Drawing.Point(76, 560);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 18;
@@ -186,7 +210,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::MotorBoat.Properties.Resources.r;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(112, 493);
this.buttonUp.Location = new System.Drawing.Point(112, 524);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 17;
@@ -195,7 +219,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(38, 453);
this.buttonShowOnMap.Location = new System.Drawing.Point(38, 484);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(175, 35);
this.buttonShowOnMap.TabIndex = 16;
@@ -205,7 +229,7 @@
//
// buttonAddBoat
//
this.buttonAddBoat.Location = new System.Drawing.Point(38, 287);
this.buttonAddBoat.Location = new System.Drawing.Point(38, 318);
this.buttonAddBoat.Name = "buttonAddBoat";
this.buttonAddBoat.Size = new System.Drawing.Size(175, 35);
this.buttonAddBoat.TabIndex = 12;
@@ -225,7 +249,6 @@
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(175, 23);
this.comboBoxSelectorMap.TabIndex = 11;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
//
// pictureBox
//
@@ -258,14 +281,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
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(180, 22);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@@ -322,5 +345,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortColor;
private Button ButtonSortType;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -15,7 +16,6 @@ namespace MotorBoat
/// <summary>
/// Объект от класса карты с набором объектов
/// </summary>
private MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap> _mapShipCollectionGeneric;
private readonly Dictionary<string, AbstractMap> _mapDict = new()
{
{"Простая карта", new SimpleMap() },
@@ -23,12 +23,14 @@ namespace MotorBoat
{"Морская карта",new SeaMap() }
};
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetBoats()
public FormMapWithSetBoats(ILogger<FormMapWithSetBoats> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapDict)
@@ -57,32 +59,6 @@ namespace MotorBoat
}
}
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender,
EventArgs e)
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
{
case "Простая карта":
map = new SimpleMap();
break;
case "Розовая карта":
map = new PinkMap();
break;
case "Морская карта":
map = new SeaMap();
break;
}
if (map != null)
{
_mapShipCollectionGeneric = new MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>(
pictureBox.Width, pictureBox.Height, map);
}
else
{
_mapShipCollectionGeneric = null;
}
}
/// <summary>
/// Выбор карты
/// </summary>
@@ -104,21 +80,32 @@ namespace MotorBoat
public void AddBoat(DrawningBoat boat)
{
if (ListBoxMaps.SelectedIndex == -1)
try
{
return;
}
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectBoat(boat) != -1)
{
MessageBox.Show("Object is added");
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectBoat(boat) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Boat}", boat);
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Unable to add object");
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
@@ -140,14 +127,30 @@ namespace MotorBoat
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 boatForDel = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (boatForDel != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Boat}", boatForDel);
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (BoatNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
@@ -213,19 +216,23 @@ namespace MotorBoat
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
}
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);
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
@@ -236,6 +243,7 @@ namespace MotorBoat
}
if (MessageBox.Show($"Удалить карту {ListBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_logger.LogInformation("Удалена карта {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_mapsCollection.DelMap(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
@@ -245,13 +253,16 @@ namespace MotorBoat
{
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)
{
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
@@ -262,17 +273,41 @@ namespace MotorBoat
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortType_Click(object sender, EventArgs e)
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new BoatCompareByType());
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonSortColor_Click(object sender, EventArgs e)
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new BoatCompareByColor());
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

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

View File

@@ -2,7 +2,7 @@
{
/// Карта с набром объектов под нее
internal class MapWithSetBoatsGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// Ширина окна отрисовки
@@ -22,7 +22,7 @@
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setBoats = new SetBoatsGeneric<T>(width * height);
_setBoats = new SetBoatsGeneric<T>(21);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
@@ -30,6 +30,7 @@
/// Перегрузка оператора сложения
public static int operator +(MapWithSetBoatsGeneric<T, U> map, T boat)
{
return map._setBoats.Insert(boat);
}
/// Перегрузка оператора вычитания
@@ -66,6 +67,13 @@
return new(_pictureWidth, _pictureHeight);
}
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
///
public void Sort(IComparer<T> comparer)
{
_setBoats.SortSet(comparer);
}
private void Shaking()
{
int j = _setBoats.Count - 1;

View File

@@ -44,7 +44,7 @@ namespace MotorBoat
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -59,13 +59,12 @@ namespace MotorBoat
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
string str = "";
using (StreamReader fs = new StreamReader(filename))
@@ -73,8 +72,7 @@ namespace MotorBoat
str = fs.ReadLine();
if (!str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = fs.ReadLine()) != null)
@@ -97,7 +95,6 @@ namespace MotorBoat
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData,StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.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.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.InfluxDBv2" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace MotorBoat
{
internal static class Program
@@ -11,7 +16,27 @@ namespace MotorBoat
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetBoats());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetBoats>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetBoats>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration)
.WriteTo.RollingFile("Logs\\log.txt")
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MotorBoat
{
internal class SetBoatsGeneric<T>
where T : class
where T : class, IEquatable<T>
{
private readonly List<T> _places;
public int Count => _places.Count;
@@ -19,7 +19,12 @@ namespace MotorBoat
}
public int Insert(T boat)
{
if (_places.Count > _maxCount)
if (_places.Contains(boat))
{
return -1;
}
if (_places.Count > _maxCount)
{
return -1;
}
@@ -27,14 +32,15 @@ namespace MotorBoat
}
public int Insert(T boat, int position)
{
if (position >= _maxCount || position < 0) return -1;
if (Count == _maxCount) { throw new StorageOverflowException(_maxCount); }
if (position > _maxCount || position < 0) return -1;
_places.Insert(position, boat);
return position;
}
public T Remove(int position)
{
// TODO проверка позиции
if (position >= _maxCount || position < 0) return null;
if (position >= Count || position < 0) throw new BoatNotFoundException(position);
// TODO удаление объекта из массива, присовив элементу массива значение null
T temp = _places[position];
_places.RemoveAt(position);
@@ -74,5 +80,14 @@ namespace MotorBoat
}
}
}
}
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 MotorBoat
{
[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,19 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "MotorBoat"
}
}
}