5 Commits

Author SHA1 Message Date
82bfa7374e lab#8 done 2022-12-08 21:22:20 +04:00
48eef0fb16 корректировка abstractmap 2022-12-05 19:11:03 +04:00
bd479e2faf lab8 2022-12-04 23:27:35 +04:00
8062cf5a60 lab done 2022-12-01 23:16:23 +04:00
32033b87a5 done 2022-11-25 16:31:33 +04:00
18 changed files with 699 additions and 53 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ContainerShip
{
internal abstract class AbstractMap
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawingObject _drawningObject = null;
protected int[,] _map = null;
@@ -217,5 +217,32 @@ namespace ContainerShip
protected abstract void GenerateMap();
protected abstract void DrawWaterPart(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,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -14,7 +14,7 @@ namespace ContainerShip
_ship = ship;
}
public float Step => _ship?.Ship?.Step ?? 0;
public DrawingShip GetShip => _ship;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _ship?.GetCurrentPosition() ?? default;
@@ -32,5 +32,53 @@ namespace ContainerShip
{
_ship?.DrawTransport(g);
}
public string GetInfo() => _ship?.GetDataForSave();
public static IDrawingObject Create(string data) => new DrawingObjectShip(data.CreateDrawingShip());
public bool Equals(IDrawingObject? other)
{
if (other == null)
{
return false;
}
var otherShip = other as DrawingObjectShip;
if (otherShip == null)
{
return false;
}
var ship = _ship.Ship;
var otherShipShip = otherShip._ship.Ship;
if (ship.Speed != otherShipShip.Speed)
{
return false;
}
if (ship.Weight != otherShipShip.Weight)
{
return false;
}
if (ship.BodyColor != otherShipShip.BodyColor)
{
return false;
}
if (ship is EntityContainerShip containerShip && otherShipShip is EntityContainerShip otherContainerShip)
{
if (containerShip.DopColor != otherContainerShip.DopColor)
{
return false;
}
if (containerShip.Crane != otherContainerShip.Crane)
{
return false;
}
if (containerShip.Containers != otherContainerShip.Containers)
{
return false;
}
}
return true;
}
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip
{
internal static class ExtentionShip
{
private static readonly char _separatorForObject = ':';
public static DrawingShip CreateDrawingShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawingContainerShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
public static string GetDataForSave(this DrawingShip drawningShip)
{
var ship = drawningShip.Ship;
var str =
$"{ship.Speed}{_separatorForObject}{ship.Weight}{_separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityContainerShip containerShip)
{
return str;
}
return
$"{str}{_separatorForObject}{containerShip.DopColor.Name}{_separatorForObject}{containerShip.Crane}{_separatorForObject}{containerShip.Containers}";
}
}
}

View File

@@ -45,13 +45,24 @@
this.buttonRight = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonSortByType);
this.groupBox1.Controls.Add(this.buttonSortByColor);
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.maskedTextBoxPosition);
this.groupBox1.Controls.Add(this.buttonAddShip);
@@ -63,9 +74,9 @@
this.groupBox1.Controls.Add(this.buttonRight);
this.groupBox1.Controls.Add(this.buttonUp);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(600, 0);
this.groupBox1.Location = new System.Drawing.Point(600, 24);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 525);
this.groupBox1.Size = new System.Drawing.Size(200, 666);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
@@ -132,11 +143,11 @@
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 51);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(176, 23);
this.comboBoxSelectorMap.TabIndex = 18;
this.comboBoxSelectorMap.TabIndex = 18;
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 294);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 374);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(188, 23);
@@ -144,7 +155,7 @@
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(6, 265);
this.buttonAddShip.Location = new System.Drawing.Point(6, 345);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(188, 23);
this.buttonAddShip.TabIndex = 17;
@@ -154,7 +165,7 @@
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(6, 323);
this.buttonRemoveShip.Location = new System.Drawing.Point(6, 403);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(188, 23);
this.buttonRemoveShip.TabIndex = 15;
@@ -164,7 +175,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(6, 376);
this.buttonShowStorage.Location = new System.Drawing.Point(6, 456);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(188, 23);
this.buttonShowStorage.TabIndex = 14;
@@ -174,7 +185,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(6, 405);
this.buttonShowOnMap.Location = new System.Drawing.Point(6, 485);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(188, 23);
this.buttonShowOnMap.TabIndex = 13;
@@ -187,7 +198,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::ContainerShip.Properties.Resources.ArrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(89, 483);
this.buttonDown.Location = new System.Drawing.Point(89, 624);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 12;
@@ -199,7 +210,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::ContainerShip.Properties.Resources.ArrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(53, 483);
this.buttonLeft.Location = new System.Drawing.Point(53, 624);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 11;
@@ -211,7 +222,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::ContainerShip.Properties.Resources.ArrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(125, 483);
this.buttonRight.Location = new System.Drawing.Point(125, 624);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 10;
@@ -223,7 +234,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::ContainerShip.Properties.Resources.ArrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(89, 447);
this.buttonUp.Location = new System.Drawing.Point(89, 588);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 9;
@@ -233,19 +244,83 @@
// 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(600, 525);
this.pictureBox.Size = new System.Drawing.Size(600, 666);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(800, 24);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripMenuItem,
this.loadToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.saveToolStripMenuItem.Text = "Сохранение";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// loadToolStripMenuItem
//
this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
this.loadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.loadToolStripMenuItem.Text = "Загрузка";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(6, 305);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(188, 34);
this.buttonSortByColor.TabIndex = 21;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(6, 265);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(188, 34);
this.buttonSortByType.TabIndex = 22;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// FormMapWithSetShip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 525);
this.ClientSize = new System.Drawing.Size(800, 690);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetShip";
this.Text = "FormMapWithSetShip";
this.groupBox1.ResumeLayout(false);
@@ -253,7 +328,10 @@
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -276,5 +354,13 @@
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private Button buttonAddMap;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -20,10 +21,12 @@ namespace ContainerShip
};
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
public FormMapWithSetShip()
public FormMapWithSetShip(ILogger<FormMapWithSetShip> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach(var elem in _mapsDict)
@@ -50,7 +53,7 @@ namespace ContainerShip
listBoxMaps.SelectedIndex = index;
}
}
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 ||
@@ -58,17 +61,22 @@ namespace ContainerShip
{
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.LogInformation("Нет такой карты {0}", comboBoxSelectorMap.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void ButtonAddShip_Click(object sender, EventArgs e)
@@ -80,48 +88,76 @@ namespace ContainerShip
private void AddShip(DrawingShip ship)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawingObjectShip objectShip = new(ship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + objectShip != -1)
{
MessageBox.Show("Object added");
_logger.LogInformation("Добавлен корабль {@Ship}", ship);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Failed to add object");
_logger.LogInformation("Не удалось добавить объект");
}
}
DrawingObjectShip objectShip = new(ship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + objectShip != -1)
catch (StorageOverflowException ex)
{
MessageBox.Show("Object added");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogWarning("Ошибка хранилище переполнено: {0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
catch (ArgumentException ex)
{
MessageBox.Show("Failed to add object");
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, ship);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
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();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Ship}", pos);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект не существует", pos);
}
}
else
catch (ShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
@@ -168,10 +204,10 @@ namespace ContainerShip
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
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)
{
@@ -182,10 +218,70 @@ namespace ContainerShip
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)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}': {1}", saveFileDialog.FileName, ex.Message);
}
}
}
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($"Не получилось загрузить файл:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ??
string.Empty].Sort(new ShipCompareByType());
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new ShipCompareByColor());
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="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root>

View File

@@ -146,7 +146,7 @@
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(144, 68);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
@@ -212,9 +212,19 @@
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(71, 43);
this.numericUpDownWeight.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(53, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// labelWeight
//
@@ -228,9 +238,19 @@
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(71, 17);
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(53, 23);
this.numericUpDownSpeed.TabIndex = 1;
this.numericUpDownSpeed.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// labelSpeed
//

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ContainerShip
{
internal interface IDrawingObject
internal interface IDrawingObject : IEquatable<IDrawingObject>
{
public float Step { get; }
@@ -17,5 +17,7 @@ namespace ContainerShip
void DrawingObject(Graphics g);
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
string GetInfo();
}
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace ContainerShip
{
internal class MapWithSetShipGeneric<T, U>
where T : class, IDrawingObject
where T : class, IDrawingObject, IEquatable<T>
where U : AbstractMap
{
@@ -158,5 +158,26 @@ namespace ContainerShip
}
}
}
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var ship in _setShip.GetShip().Reverse())
{
data += $"{ship.GetInfo()}{separatorData}";
}
return data;
}
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setShip.Insert(DrawingObjectShip.Create(rec) as T);
}
}
public void Sort(IComparer<T> comparer)
{
_setShip.SortSet(comparer);
}
}
}

View File

@@ -8,16 +8,20 @@ namespace ContainerShip
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetShipGeneric<DrawingObjectShip, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetShipGeneric<IDrawingObject, 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, MapWithSetShipGeneric<DrawingObjectShip, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetShipGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -28,7 +32,7 @@ namespace ContainerShip
{
return;
}
MapWithSetShipGeneric<DrawingObjectShip, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
MapWithSetShipGeneric<IDrawingObject, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
_mapStorages.Add(name, newMap);
}
@@ -40,7 +44,7 @@ namespace ContainerShip
}
}
public MapWithSetShipGeneric<DrawingObjectShip, AbstractMap> this[string
public MapWithSetShipGeneric<IDrawingObject, AbstractMap> this[string
ind]
{
get
@@ -52,5 +56,65 @@ namespace ContainerShip
return null;
}
}
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
bool isFirst = true;
string str;
while ((str = sr.ReadLine()) != null)
{
if (isFirst)
{
if (!str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
isFirst = false;
}
else
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "Простая карта":
map = new SimpleMap();
break;
case "Острова":
map = new IslandsMap();
break;
case "Скалы":
map = new RocksMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetShipGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}
}

View File

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

View File

@@ -7,9 +7,8 @@ using System.Threading.Tasks;
namespace ContainerShip
{
internal class SetShipGeneric<T>
where T : class
where T : class, IEquatable<T>
{
private readonly List<T> _places;
public int Count => _places.Count;
@@ -29,10 +28,14 @@ namespace ContainerShip
public int Insert(T ship, int position)
{
if (position < 0 || position > Count || Count == _maxCount)
if (_places.Contains(ship))
{
return -1;
}
if (position < 0 || position > Count || Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, ship);
return position;
}
@@ -41,7 +44,7 @@ namespace ContainerShip
{
if (position >= Count || position < 0)
{
return null;
throw new ShipNotFoundException(position);
}
T removedObject = _places[position];
_places.RemoveAt(position);
@@ -81,5 +84,13 @@ namespace ContainerShip
}
}
}
public void SortSet(IComparer<T> comparer)
{
if(comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip
{
internal class ShipCompareByColor : IComparer<IDrawingObject>
{
public int Compare(IDrawingObject? x, IDrawingObject? 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 DrawingObjectShip;
var yShip = y as DrawingObjectShip;
if (xShip == null && yShip == null)
{
return 0;
}
if (xShip == null && yShip != null)
{
return 1;
}
if (xShip != null && yShip == null)
{
return -1;
}
string xShipColor = xShip.GetShip.Ship.BodyColor.Name;
string yShipColor = yShip.GetShip.Ship.BodyColor.Name;
if (xShipColor != yShipColor)
{
return xShipColor.CompareTo(yShipColor);
}
if (xShip.GetShip.Ship is EntityContainerShip xContainerShip && yShip.GetShip.Ship is EntityContainerShip yContainerShip)
{
string xShipDopColor = xContainerShip.DopColor.Name;
string yShipDopColor = yContainerShip.DopColor.Name;
var dopColorCompare = xShipDopColor.CompareTo(yShipDopColor);
if (dopColorCompare != 0)
{
return dopColorCompare;
}
}
var speedCompare = xShip.GetShip.Ship.Speed.CompareTo(yShip.GetShip.Ship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xShip.GetShip.Ship.Weight.CompareTo(yShip.GetShip.Ship.Weight);
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip
{
internal class ShipCompareByType : IComparer<IDrawingObject>
{
public int Compare(IDrawingObject? x, IDrawingObject? 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 DrawingObjectShip;
var yShip = y as DrawingObjectShip;
if (xShip == null && yShip == null)
{
return 0;
}
if (xShip == null && yShip != null)
{
return 1;
}
if (xShip != null && yShip == null)
{
return -1;
}
if (xShip.GetShip.GetType().Name != yShip.GetShip.GetType().Name)
{
if (xShip.GetShip.GetType().Name == "DrawingShip")
{
return -1;
}
return 1;
}
var speedCompare =
xShip.GetShip.Ship.Speed.CompareTo(yShip.GetShip.Ship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xShip.GetShip.Ship.Weight.CompareTo(yShip.GetShip.Ship.Weight);
}
}
}

View File

@@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ContainerShip
{
[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,20 @@
using System.Runtime.Serialization;
namespace ContainerShip
{
[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

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "ContainerShip"
}
}
}