4 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
Катя Ихонкина
5f939eb88b Шестая лабораторная работа 2022-11-19 11:47:18 +04:00
17 changed files with 699 additions and 75 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,6 +19,9 @@ namespace MotorBoat
{
return _boat?.GetCurrentPosition() ?? default;
}
public DrawningBoat GetShip => _boat;
public void MoveObject(Direction direction)
{
_boat?.MoveTransport(direction);
@@ -25,10 +29,60 @@ namespace MotorBoat
public void SetObject(int x, int y, int width, int height)
{
_boat.SetPosition(x, y, width, height);
}
void IDrawningObject.DrawningObject(Graphics g)
{
_boat.DrawTransport(g);
}
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

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat
{
internal static class ExtentionCar
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningBoat CreateDrawningBoat(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningMotorBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningBoat drawningBoat)
{
var boat = drawningBoat.Boat;
var str =
$"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntityMotorBoat motorBoat)
{
return str;
}
return
$"{str}{_separatorForObject}{motorBoat.DopColor.Name}{_separatorForObject}{motorBoat.BodyKit}{_separatorForObject}{motorBoat.Wing}{_separatorForObject}{motorBoat.SportLine}";
}
}
}

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();
@@ -44,12 +46,21 @@
this.buttonAddBoat = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// 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);
@@ -65,13 +76,33 @@
this.groupBoxTools.Controls.Add(this.buttonAddBoat);
this.groupBoxTools.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(809, 0);
this.groupBoxTools.Location = new System.Drawing.Point(809, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(251, 645);
this.groupBoxTools.Size = new System.Drawing.Size(251, 621);
this.groupBoxTools.TabIndex = 0;
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);
@@ -111,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);
@@ -120,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;
@@ -130,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;
@@ -143,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, 553);
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;
@@ -155,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, 553);
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;
@@ -167,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, 553);
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;
@@ -179,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, 517);
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;
@@ -188,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;
@@ -198,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;
@@ -218,17 +249,58 @@
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
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(809, 645);
this.pictureBox.Size = new System.Drawing.Size(809, 621);
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1060, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.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.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetBoats
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@@ -236,12 +308,16 @@
this.ClientSize = new System.Drawing.Size(1060, 645);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip1);
this.Name = "FormMapWithSetBoats";
this.Text = "Лодка";
this.Text = "FormMapWithSetBoats";
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -263,5 +339,13 @@
private ListBox ListBoxMaps;
private Button ButtonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
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>
@@ -103,6 +79,8 @@ namespace MotorBoat
}
public void AddBoat(DrawningBoat boat)
{
try
{
if (ListBoxMaps.SelectedIndex == -1)
{
@@ -111,14 +89,23 @@ namespace MotorBoat
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("Не удалось добавить");
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
@@ -140,16 +127,32 @@ namespace MotorBoat
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
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("Не удалось удалить объект");
}
}
catch (BoatNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
/// </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,10 +243,71 @@ 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();
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
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

@@ -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>14, 13</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>129, 13</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>269, 13</value>
</metadata>
</root>

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace MotorBoat
{
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта
@@ -36,5 +36,9 @@ namespace MotorBoat
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

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;
@@ -163,5 +171,22 @@
}
}
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var boat in _setBoats.GetBoat())
{
data += $"{boat.GetInfo()}{separatorData}";
}
return data;
}
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setBoats.Insert(DrawningObjectBoat.Create(rec) as T);
}
}
}
}

View File

@@ -8,13 +8,16 @@ namespace MotorBoat
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -22,14 +25,14 @@ namespace MotorBoat
{
if (!_mapStorages.ContainsKey(name))
{
_mapStorages.Add(name, new MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
}
public void DelMap(string name)
{
if (_mapStorages.ContainsKey(name)) _mapStorages.Remove(name);
}
public MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap> this[string ind]
public MapWithSetBoatsGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@@ -40,5 +43,59 @@ namespace MotorBoat
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new StreamWriter(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
string str = "";
using (StreamReader fs = new StreamReader(filename))
{
str = fs.ReadLine();
if (!str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = fs.ReadLine()) != null)
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "PinkMap":
map = new PinkMap();
break;
case "SeaMap":
map = new SeaMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData,StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

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,6 +19,11 @@ namespace MotorBoat
}
public int Insert(T boat)
{
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"
}
}
}