5 Commits

Author SHA1 Message Date
8062cf5a60 lab done 2022-12-01 23:16:23 +04:00
32033b87a5 done 2022-11-25 16:31:33 +04:00
a36cba0895 done 2022-11-25 15:34:30 +04:00
5687431a0f lab#5 2022-11-05 18:38:37 +04:00
0f81ca3cc1 lab4 2022-11-04 23:05:28 +04:00
20 changed files with 1237 additions and 158 deletions

View File

@@ -9,7 +9,15 @@
</PropertyGroup>
<ItemGroup>
<None Include="ContainerShip.csproj" />
<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>

View File

@@ -32,5 +32,9 @@ namespace ContainerShip
{
_ship?.DrawTransport(g);
}
public string GetInfo() => _ship?.GetDataForSave();
public static IDrawingObject Create(string data) => new DrawingObjectShip(data.CreateDrawingShip());
}
}

View File

@@ -106,8 +106,6 @@ namespace ContainerShip
g.FillPolygon(brRed, shipBorder);
//Заливка верхней палубы
g.FillRectangle(brMain, _startPosX + 21, _startPosY + 1, 59, 29);
}
public void ChangeBorders(int width, int height)
{

View File

@@ -8,9 +8,9 @@ namespace ContainerShip
{
internal class EntityContainerShip : EntityShip
{
public Color DopColor { get; private set; }
public bool Crane { get; private set; }
public bool Containers { get; private set; }
public Color DopColor { get; set; }
public bool Crane { get; set; }
public bool Containers { get; set; }
public EntityContainerShip(int speed, float weight, Color bodyColor, Color
dopColor, bool crane, bool containers) :
@@ -21,5 +21,4 @@ namespace ContainerShip
Containers = containers;
}
}
}

View File

@@ -8,18 +8,17 @@ namespace ContainerShip
{
public class EntityShip
{
public int Speed { get; private set; }
public float Weight { get; private set; }
public Color BodyColor { get; private set; }
public int Speed { get; set; }
public float Weight { get; set; }
public Color BodyColor { get; set; }
public int Step => (int)Speed * 100 / (int)Weight;
public EntityShip(int speed, float weight, Color bodyColor)
{
Random random = new Random();
Speed = speed <= 0 ? random.Next(50, 150) : speed;
Weight = weight <= 0 ? random.Next(50, 150) : weight;
Weight = weight <= 0 ? random.Next(1000, 2000) : weight;
BodyColor = bodyColor;
}
}
}

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

@@ -29,8 +29,13 @@
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.button2 = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddShip = new System.Windows.Forms.Button();
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
@@ -40,14 +45,22 @@
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.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.maskedTextBoxPosition);
this.groupBox1.Controls.Add(this.comboBoxSelectorMap);
this.groupBox1.Controls.Add(this.buttonAddShip);
this.groupBox1.Controls.Add(this.buttonRemoveShip);
this.groupBox1.Controls.Add(this.buttonShowStorage);
@@ -57,20 +70,63 @@
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, 450);
this.groupBox1.Size = new System.Drawing.Size(200, 512);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// maskedTextBoxPosition
// groupBox2
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 185);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(188, 23);
this.maskedTextBoxPosition.TabIndex = 19;
this.groupBox2.Controls.Add(this.button2);
this.groupBox2.Controls.Add(this.listBoxMaps);
this.groupBox2.Controls.Add(this.textBoxNewMapName);
this.groupBox2.Controls.Add(this.buttonAddMap);
this.groupBox2.Controls.Add(this.comboBoxSelectorMap);
this.groupBox2.Location = new System.Drawing.Point(6, 22);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(188, 237);
this.groupBox2.TabIndex = 20;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Карты";
//
// button2
//
this.button2.Location = new System.Drawing.Point(6, 208);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(176, 23);
this.button2.TabIndex = 22;
this.button2.Text = "Удалить карту";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 15;
this.listBoxMaps.Location = new System.Drawing.Point(6, 109);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(176, 94);
this.listBoxMaps.TabIndex = 21;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(6, 22);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(176, 23);
this.textBoxNewMapName.TabIndex = 20;
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(6, 80);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(176, 23);
this.buttonAddMap.TabIndex = 19;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// comboBoxSelectorMap
//
@@ -80,15 +136,22 @@
"Простая карта",
"Острова",
"Скалы"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 22);
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 51);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(188, 23);
this.comboBoxSelectorMap.TabIndex = 18;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
this.comboBoxSelectorMap.Size = new System.Drawing.Size(176, 23);
this.comboBoxSelectorMap.TabIndex = 18;
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 294);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(188, 23);
this.maskedTextBoxPosition.TabIndex = 19;
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(6, 135);
this.buttonAddShip.Location = new System.Drawing.Point(6, 265);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(188, 23);
this.buttonAddShip.TabIndex = 17;
@@ -98,7 +161,7 @@
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(6, 214);
this.buttonRemoveShip.Location = new System.Drawing.Point(6, 323);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(188, 23);
this.buttonRemoveShip.TabIndex = 15;
@@ -108,7 +171,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(6, 296);
this.buttonShowStorage.Location = new System.Drawing.Point(6, 376);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(188, 23);
this.buttonShowStorage.TabIndex = 14;
@@ -118,7 +181,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(6, 325);
this.buttonShowOnMap.Location = new System.Drawing.Point(6, 405);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(188, 23);
this.buttonShowOnMap.TabIndex = 13;
@@ -131,7 +194,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, 408);
this.buttonDown.Location = new System.Drawing.Point(89, 470);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 12;
@@ -143,7 +206,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, 408);
this.buttonLeft.Location = new System.Drawing.Point(53, 470);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 11;
@@ -155,7 +218,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, 408);
this.buttonRight.Location = new System.Drawing.Point(125, 470);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 10;
@@ -167,7 +230,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, 372);
this.buttonUp.Location = new System.Drawing.Point(89, 434);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 9;
@@ -177,25 +240,74 @@
// 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, 450);
this.pictureBox.Size = new System.Drawing.Size(600, 512);
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(180, 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.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";
//
// FormMapWithSetShip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.ClientSize = new System.Drawing.Size(800, 536);
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);
this.groupBox1.PerformLayout();
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();
}
@@ -213,5 +325,16 @@
private Button buttonUp;
private ComboBox comboBoxSelectorMap;
private MaskedTextBox maskedTextBoxPosition;
private GroupBox groupBox2;
private Button button2;
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;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -11,65 +12,113 @@ using System.Windows.Forms;
namespace ContainerShip
{
public partial class FormMapWithSetShip : Form
{
private MapWithSetShipGeneric<DrawingObjectShip, AbstractMap> _mapShipCollectionGeneric;
public FormMapWithSetShip()
{
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap()},
{ "Острова", new IslandsMap()},
{ "Скалы", new RocksMap()}
};
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
public FormMapWithSetShip(ILogger<FormMapWithSetShip> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach(var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
private void ReloadMaps()
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for(int i = 0; i < _mapsCollection.Keys.Count; ++i)
{
case "Простая карта":
map = new SimpleMap();
break;
case "Острова":
map = new IslandsMap();
break;
case "Скалы":
map = new RocksMap();
break;
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (map != null)
if(listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
_mapShipCollectionGeneric = new
MapWithSetShipGeneric<DrawingObjectShip, AbstractMap>(
pictureBox.Width, pictureBox.Height, map);
}
else
listBoxMaps.SelectedIndex = 0;
}else if(listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
_mapShipCollectionGeneric = null;
listBoxMaps.SelectedIndex = index;
}
}
private void ButtonAddShip_Click(object sender, EventArgs e)
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (_mapShipCollectionGeneric == null)
if (comboBoxSelectorMap.SelectedIndex == -1 ||
string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}",
comboBoxSelectorMap.SelectedIndex ==
-1 ? "Карта не выбрана" : "Карта не назавана");
return;
}
FormShip form = new();
if (form.ShowDialog() == DialogResult.OK)
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
DrawingObjectShip ship = new(form.SelectedShip);
if (_mapShipCollectionGeneric + ship != -1)
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)
{
var formShipConfig = new FormShipConfig();
formShipConfig.AddEvent(AddShip);
formShipConfig.Show();
}
private void AddShip(DrawingShip ship)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapShipCollectionGeneric.ShowSet();
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("Не удалось добавить объект");
MessageBox.Show("Failed to add object");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка хранилище переполнено: {0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, ship);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
@@ -82,40 +131,56 @@ namespace ContainerShip
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapShipCollectionGeneric - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapShipCollectionGeneric.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 (_mapShipCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapShipCollectionGeneric.ShowSet();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapShipCollectionGeneric == null)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapShipCollectionGeneric.ShowOnMap();
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapShipCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
@@ -137,7 +202,64 @@ namespace ContainerShip
dir = Direction.Right;
break;
}
pictureBox.Image = _mapShipCollectionGeneric.MoveObject(dir);
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)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
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);
}
}
}
}
}

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

@@ -0,0 +1,361 @@
namespace ContainerShip
{
partial class FormShipConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelGray = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxContainers = new System.Windows.Forms.CheckBox();
this.checkBoxCrane = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelSpeed = new System.Windows.Forms.Label();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.labelBaseColor = new System.Windows.Forms.Label();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxContainers);
this.groupBoxConfig.Controls.Add(this.checkBoxCrane);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 12);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(406, 195);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(307, 136);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(91, 56);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(209, 136);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(92, 56);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(209, 17);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(189, 116);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(52, 68);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 3;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(98, 68);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 4;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Lime;
this.panelGreen.Location = new System.Drawing.Point(52, 22);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelPurple
//
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);
this.panelPurple.TabIndex = 5;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(98, 22);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 1;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(6, 68);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 2;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(144, 22);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 1;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(6, 22);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxContainers
//
this.checkBoxContainers.AutoSize = true;
this.checkBoxContainers.Location = new System.Drawing.Point(6, 97);
this.checkBoxContainers.Name = "checkBoxContainers";
this.checkBoxContainers.Size = new System.Drawing.Size(197, 19);
this.checkBoxContainers.TabIndex = 5;
this.checkBoxContainers.Text = "Признак наличия контейнеров";
this.checkBoxContainers.UseVisualStyleBackColor = true;
//
// checkBoxCrane
//
this.checkBoxCrane.AutoSize = true;
this.checkBoxCrane.Location = new System.Drawing.Point(6, 72);
this.checkBoxCrane.Name = "checkBoxCrane";
this.checkBoxCrane.Size = new System.Drawing.Size(158, 19);
this.checkBoxCrane.TabIndex = 4;
this.checkBoxCrane.Text = "Признак наличия крана";
this.checkBoxCrane.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(71, 43);
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(53, 23);
this.numericUpDownWeight.TabIndex = 3;
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(6, 45);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(26, 15);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Вес";
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(71, 17);
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(53, 23);
this.numericUpDownSpeed.TabIndex = 1;
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 19);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(59, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость";
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Location = new System.Drawing.Point(424, 29);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(229, 146);
this.panelObject.TabIndex = 1;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BackColor = System.Drawing.SystemColors.Control;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(126, 2);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(100, 23);
this.labelDopColor.TabIndex = 2;
this.labelDopColor.Text = "Доп. цвет";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(3, 28);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(223, 115);
this.pictureBoxObject.TabIndex = 1;
this.pictureBoxObject.TabStop = false;
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BackColor = System.Drawing.SystemColors.Control;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(3, 2);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(100, 23);
this.labelBaseColor.TabIndex = 0;
this.labelBaseColor.Text = "Цвет";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(427, 184);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 23);
this.buttonOk.TabIndex = 2;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(575, 184);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormShipConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(662, 219);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormShipConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelGray;
private Panel panelBlack;
private Panel panelGreen;
private Panel panelPurple;
private Panel panelBlue;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelRed;
private CheckBox checkBoxContainers;
private CheckBox checkBoxCrane;
private Panel panelObject;
private Label labelDopColor;
private PictureBox pictureBoxObject;
private Label labelBaseColor;
private Button buttonOk;
private Button buttonCancel;
}
}

View File

@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ContainerShip
{
public partial class FormShipConfig : Form
{
DrawingShip _ship = null;
private event Action<DrawingShip> EventAddShip;
public FormShipConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (object sender, EventArgs e) => Close();
}
private void DrawShip()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPosition(5, 5, pictureBoxObject.Width,
pictureBoxObject.Height);
_ship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
public void AddEvent(Action<DrawingShip> ev)
{
if (EventAddShip == null)
{
EventAddShip = new Action<DrawingShip>(ev);
}
else
{
EventAddShip += ev;
}
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_ship = new DrawingShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_ship = new DrawingContainerShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxCrane.Checked, checkBoxContainers.Checked);
break;
}
DrawShip();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship == null)
{
return;
}
_ship.Ship.BodyColor = (Color)e.Data.GetData(typeof(Color));
DrawShip();
}
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship == null || _ship.Ship is not EntityContainerShip containerShip)
{
return;
}
containerShip.DopColor = (Color)e.Data.GetData(typeof(Color));
DrawShip();
}
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_ship);
Close();
}
}
}

View File

@@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -17,5 +17,7 @@ namespace ContainerShip
void DrawingObject(Graphics g);
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
string GetInfo();
}
}

View File

@@ -56,13 +56,9 @@ namespace ContainerShip
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setShip.Count; i++)
foreach (var ship in _setShip.GetShip())
{
var ship = _setShip.Get(i);
if (ship != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
}
return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
}
return new(_pictureWidth, _pictureHeight);
}
@@ -81,11 +77,11 @@ namespace ContainerShip
int j = _setShip.Count - 1;
for (int i = 0; i < _setShip.Count; i++)
{
if (_setShip.Get(i) == null)
if (_setShip[i] == null)
{
for (; j > i; j--)
{
var ship = _setShip.Get(j);
var ship = _setShip[j];
if (ship != null)
{
_setShip.Insert(ship, i);
@@ -112,7 +108,7 @@ namespace ContainerShip
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
for (int j = 0; j < _pictureHeight / _placeSizeHeight; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight + _placeSizeHeight/2, i *
_placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight + _placeSizeHeight / 2);
@@ -141,15 +137,15 @@ namespace ContainerShip
int RowIndex = yNumOfPlaces - 1;
int ColumnIndex = xNumOfPlaces - 1;
for (int i = 0; i < _setShip.Count; i++)
foreach (var ship in _setShip.GetShip())
{
if (_setShip.Get(i) != null)
if (ship != null)
{
(float Left, float Top, float Right, float Bottom) = _setShip.Get(i).GetCurrentPosition();
_setShip.Get(i).SetObject(ColumnIndex * _placeSizeWidth,
(float Left, float Top, float Right, float Bottom) = ship.GetCurrentPosition();
ship.SetObject(ColumnIndex * _placeSizeWidth,
RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top)),
_pictureWidth, _pictureHeight);
_setShip.Get(i).DrawingObject(g);
ship.DrawingObject(g);
}
if (ColumnIndex == 0)
{
@@ -162,6 +158,22 @@ 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);
}
}
}
}

View File

@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip
{
internal class MapsCollection
{
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<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddMap(string name, AbstractMap map)
{
if (_mapStorages.ContainsKey(name))
{
return;
}
MapWithSetShipGeneric<IDrawingObject, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
_mapStorages.Add(name, newMap);
}
public void DelMap(string name)
{
if (_mapStorages.ContainsKey(name))
{
_mapStorages.Remove(name);
}
}
public MapWithSetShipGeneric<IDrawingObject, AbstractMap> this[string
ind]
{
get
{
if (_mapStorages.ContainsKey(ind))
{
return _mapStorages[ind];
}
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

@@ -9,82 +9,76 @@ namespace ContainerShip
internal class SetShipGeneric<T>
where T : class
{
private readonly T[] _places;
public int Count => _places.Length;
private readonly List<T> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public SetShipGeneric(int count)
{
_places = new T[count];
_maxCount = count;
_places = new List<T>();
}
public int Insert(T ship)
{
{
return Insert(ship, 0);
}
public int Insert(T ship, int position)
{
if (position < 0 || position > _places.Length)
if (position < 0 || position > Count || Count == _maxCount)
{
return -1;
}
int emptyCellIndex = -1;
if (_places[position] != null)
{
for (int i = position + 1; i < Count; i++)
{
if (_places[i] == null)
{
emptyCellIndex = i;
break;
}
}
if (emptyCellIndex != -1)
{
for (int i = emptyCellIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
}
}
else
{
_places[position] = ship;
return position;
}
if (emptyCellIndex == -1)
{
return -1;
}
else
{
_places[position] = ship;
return position;
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, ship);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0)
{
return null;
throw new ShipNotFoundException(position);
}
T removedObject = _places[position];
_places[position] = null;
_places.RemoveAt(position);
return removedObject;
}
public T Get(int position)
public T this[int position]
{
if (position >= Count || position < 0)
get
{
return null;
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
set
{
if (position < 0 || position >= Count)
{
return;
}
Insert(value, position);
}
}
public IEnumerable<T> GetShip()
{
foreach (var ship in _places)
{
if (ship != null)
{
yield return ship;
}
else
{
yield break;
}
}
return _places[position];
}
}
}

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"
}
}
}