27 Commits

Author SHA1 Message Date
Nikita Potapov
681b60f6a6 fixed varname in ExtentionBoat.GetDataForSave 2022-11-30 08:37:17 +04:00
Nikita Potapov
7d27bcd94f added warn log with remove empty pos error 2022-11-29 09:32:03 +04:00
Nikita Potapov
6ddf4f9380 fixed varname in MapWithSetBoatsGeneric.GetData 2022-11-29 08:56:13 +04:00
Nikita Potapov
f41bd15744 fixed Remove at SetBoatsGeneric 2022-11-27 21:41:07 +04:00
Nikita Potapov
aaf1b043b7 переделал на Serilog 2022-11-26 23:44:01 +04:00
Nikita Potapov
57dab5fc82 ButtonRemoveBoat_Click logging 2022-11-26 23:13:28 +04:00
Nikita Potapov
8659337eb5 listBoxMaps_SelectedIndexChanged logging 2022-11-26 23:05:56 +04:00
Nikita Potapov
271840c48e ButtonDeleteMap_Click logging 2022-11-26 23:04:33 +04:00
Nikita Potapov
fd8617cbf0 LoadToolStripMenuItem_Click logging 2022-11-26 23:01:25 +04:00
Nikita Potapov
c7c8241605 SaveToolStripMenuItem_Click logging 2022-11-26 22:59:39 +04:00
Nikita Potapov
697a62d101 AddBoat logging 2022-11-26 22:56:53 +04:00
Nikita Potapov
3d397d9854 заменены классы ошибок в методе загрузки из файла 2022-11-26 22:38:07 +04:00
Nikita Potapov
38732f72cf логгирование nlog 2022-11-26 22:27:34 +04:00
Nikita Potapov
3a6d87df27 fixed bug with Remove 2022-11-26 20:57:51 +04:00
Nikita Potapov
62a9296290 Генерация исключений 2022-11-26 20:09:04 +04:00
Nikita Potapov
f8ac712f8a Final lab6 2022-11-26 15:26:31 +04:00
Nikita Potapov
8062309a2c чтение через StreamReader 2022-11-26 15:24:41 +04:00
Nikita Potapov
f478227337 запись через StreamWriter 2022-11-26 15:17:00 +04:00
Nikita Potapov
db90912206 FormConfig fixed 2022-11-26 14:54:58 +04:00
Nikita Potapov
eb32a4c319 кнопки Сохранить и Загрузить 2022-11-14 22:47:26 +04:00
Nikita Potapov
aa2d4c26e1 MapsCollection 2022-11-14 21:58:13 +04:00
Nikita Potapov
845a719d29 class ExtentionBoat 2022-11-14 21:35:24 +04:00
Nikita Potapov
01ea98b1c7 Event work 2022-11-14 19:14:12 +04:00
Nikita Potapov
05dcc639bc Форма-конфигуратор, drug-and-drop, раскраска лодок 2022-11-14 18:51:06 +04:00
Nikita Potapov
feeb643efe Этап 3. Форма 2022-11-04 16:32:55 +04:00
Nikita Potapov
df9b91ad28 Этап 2. Класс 2022-11-04 16:01:59 +04:00
Nikita Potapov
f5e4c6742b Этап 1. Смена массива на список 2022-11-04 15:57:06 +04:00
20 changed files with 1474 additions and 168 deletions

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Boats
{
/// <summary>
/// Делегат для передачи объекта-лодки
/// </summary>
public delegate void BoatDelegate(DrawingBoat boat);
}

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 Boats
{
[Serializable]
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 contex) : base(info, contex) { }
}
}

View File

@@ -8,6 +8,29 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appSettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.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>
@@ -23,4 +46,6 @@
</EmbeddedResource>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties jsconfig1_1json__JsonSchema="{" /></VisualStudio></ProjectExtensions>
</Project>

View File

@@ -30,5 +30,7 @@ namespace Boats
{
_boat.DrawTransport(g);
}
public string GetInfo() => _boat?.GetDataForSave();
public static IDrawingObject Create(string data) => new DrawingObjectBoat(data.CreateDrawingBoat());
}
}

View File

@@ -22,7 +22,7 @@ namespace Boats
/// <summary>
/// Цвет корпуса
/// </summary>
public Color BodyColor { get; private set; }
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения лодки
/// </summary>

View File

@@ -11,7 +11,7 @@ namespace Boats
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
public Color DopColor { get; set; }
/// <summary>
/// Признак наличия поплавков
/// </summary>
@@ -37,5 +37,9 @@ namespace Boats
Bobbers = bobbers;
Sail = sail;
}
public void SetDopColor(Color color)
{
DopColor = color;
}
}
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Boats
{
/// <summary>
/// Расширение для класса DrawingBoat
/// </summary>
internal static class ExtentionBoat
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawingBoat CreateDrawingBoat(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2])
);
}
if (strs.Length == 6)
{
return new DrawingCatamaran(
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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingBoat"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawingBoat drawingBoat)
{
var boat = drawingBoat.Boat;
var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntityCatamaran catamaran)
{
return str;
}
return $"{str}{_separatorForObject}{catamaran.DopColor.Name}{_separatorForObject}{catamaran.Bobbers}{_separatorForObject}{catamaran.Sail}";
}
}
}

369
Boats/Boats/FormBoatConfig.Designer.cs generated Normal file
View File

@@ -0,0 +1,369 @@
namespace Boats
{
partial class FormBoatConfig
{
/// <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.panelNavy = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxSail = new System.Windows.Forms.CheckBox();
this.checkBoxBobbers = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.buttonOk = new System.Windows.Forms.Button();
this.panelObject = new System.Windows.Forms.Panel();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
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.checkBoxSail);
this.groupBoxConfig.Controls.Add(this.checkBoxBobbers);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelWeight);
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(551, 243);
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(406, 178);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(119, 48);
this.labelModifiedObject.TabIndex = 6;
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(267, 178);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(119, 48);
this.labelSimpleObject.TabIndex = 1;
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.panelNavy);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(251, 8);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(288, 155);
this.groupBoxColors.TabIndex = 1;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelNavy
//
this.panelNavy.AllowDrop = true;
this.panelNavy.BackColor = System.Drawing.Color.Navy;
this.panelNavy.Location = new System.Drawing.Point(220, 94);
this.panelNavy.Name = "panelNavy";
this.panelNavy.Size = new System.Drawing.Size(50, 50);
this.panelNavy.TabIndex = 6;
//
// panelBlack
//
this.panelBlack.AllowDrop = true;
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(155, 94);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(50, 50);
this.panelBlack.TabIndex = 5;
//
// panelGray
//
this.panelGray.AllowDrop = true;
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(85, 94);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(50, 50);
this.panelGray.TabIndex = 4;
//
// panelWhite
//
this.panelWhite.AllowDrop = true;
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(16, 94);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(50, 50);
this.panelWhite.TabIndex = 3;
//
// panelYellow
//
this.panelYellow.AllowDrop = true;
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(220, 26);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(50, 50);
this.panelYellow.TabIndex = 1;
//
// panelBlue
//
this.panelBlue.AllowDrop = true;
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(155, 26);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(50, 50);
this.panelBlue.TabIndex = 2;
//
// panelGreen
//
this.panelGreen.AllowDrop = true;
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(85, 26);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(50, 50);
this.panelGreen.TabIndex = 1;
//
// panelRed
//
this.panelRed.AllowDrop = true;
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(16, 26);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(50, 50);
this.panelRed.TabIndex = 0;
//
// checkBoxSail
//
this.checkBoxSail.AutoSize = true;
this.checkBoxSail.Location = new System.Drawing.Point(12, 184);
this.checkBoxSail.Name = "checkBoxSail";
this.checkBoxSail.Size = new System.Drawing.Size(206, 24);
this.checkBoxSail.TabIndex = 5;
this.checkBoxSail.Text = "Признак наличия паруса";
this.checkBoxSail.UseVisualStyleBackColor = true;
//
// checkBoxBobbers
//
this.checkBoxBobbers.AutoSize = true;
this.checkBoxBobbers.Location = new System.Drawing.Point(12, 139);
this.checkBoxBobbers.Name = "checkBoxBobbers";
this.checkBoxBobbers.Size = new System.Drawing.Size(233, 24);
this.checkBoxBobbers.TabIndex = 4;
this.checkBoxBobbers.Text = "Признак наличия поплавков";
this.checkBoxBobbers.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(85, 96);
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(102, 27);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(85, 42);
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(102, 27);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(9, 96);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(36, 20);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(9, 44);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(76, 20);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(595, 216);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(119, 29);
this.buttonOk.TabIndex = 7;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Location = new System.Drawing.Point(569, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(315, 183);
this.panelObject.TabIndex = 2;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(26, 67);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(260, 104);
this.pictureBoxObject.TabIndex = 1;
this.pictureBoxObject.TabStop = false;
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(167, 13);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(119, 48);
this.labelDopColor.TabIndex = 3;
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.LabelDopColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(26, 13);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(119, 48);
this.labelBaseColor.TabIndex = 2;
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);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(736, 217);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(119, 29);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormBoatConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(888, 258);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Controls.Add(this.buttonOk);
this.Name = "FormBoatConfig";
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 Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelNavy;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private CheckBox checkBoxSail;
private CheckBox checkBoxBobbers;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Button buttonOk;
private Panel panelObject;
private PictureBox pictureBoxObject;
private Label labelBaseColor;
private Label labelDopColor;
private Button buttonCancel;
}
}

View File

@@ -0,0 +1,194 @@
using System;
using System.CodeDom;
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 Boats
{
/// <summary>
/// Класс формы-конфигуратора
/// </summary>
public partial class FormBoatConfig : Form
{
/// <summary>
/// Переменная - выбранная лодка
/// </summary>
DrawingBoat _boat = null;
/// <summary>
/// Событие
/// </summary>
private event BoatDelegate EventAddBoat;
/// <summary>
/// Конструктор
/// </summary>
public FormBoatConfig()
{
InitializeComponent();
panelRed.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelBlack.MouseDown += PanelColor_MouseDown;
panelNavy.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Отрисовка лодки
/// </summary>
private void DrawBoat()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics g = Graphics.FromImage(bmp);
_boat?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_boat?.DrawTransport(g);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="e"></param>
public void AddEvent(BoatDelegate e)
{
if (EventAddBoat == null)
{
EventAddBoat = new BoatDelegate(e);
}
else
{
EventAddBoat += e;
}
}
/// <summary>
/// Применяем соответствующий объект
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверяем тип получаемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Применяем необходимый объект
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_boat = new DrawingBoat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.Red
);
break;
case "labelModifiedObject":
_boat = new DrawingCatamaran((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.Red,
Color.Blue,
checkBoxBobbers.Checked,
checkBoxSail.Checked
);
break;
}
DrawBoat();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (_boat == null)
return;
_boat.Boat.BodyColor = (Color)e.Data.GetData(typeof(Color).ToString());
DrawBoat();
}
/// <summary>
/// Проверка получаемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_boat == null || _boat is not DrawingCatamaran)
return;
(_boat.Boat as EntityCatamaran).SetDopColor((Color)e.Data.GetData(typeof(Color).ToString()));
DrawBoat();
}
/// <summary>
/// Добавление лодки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddBoat?.Invoke(_boat);
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

@@ -28,7 +28,7 @@
/// </summary>
private void InitializeComponent()
{
this.groupBox = new System.Windows.Forms.GroupBox();
this.groupBoxInstruments = new System.Windows.Forms.GroupBox();
this.ButtonDown = new System.Windows.Forms.Button();
this.ButtonRight = new System.Windows.Forms.Button();
this.ButtonLeft = new System.Windows.Forms.Button();
@@ -38,38 +38,50 @@
this.ButtonShowStorage = new System.Windows.Forms.Button();
this.ButtonRemoveBoat = new System.Windows.Forms.Button();
this.ButtonAddBoat = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.ComboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.groupBox.SuspendLayout();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.ButtonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.ButtonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
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.groupBoxInstruments.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.groupBoxMaps.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox
// groupBoxInstruments
//
this.groupBox.Controls.Add(this.ButtonDown);
this.groupBox.Controls.Add(this.ButtonRight);
this.groupBox.Controls.Add(this.ButtonLeft);
this.groupBox.Controls.Add(this.ButtonUp);
this.groupBox.Controls.Add(this.maskedTextBoxPosition);
this.groupBox.Controls.Add(this.ButtonShowOnMap);
this.groupBox.Controls.Add(this.ButtonShowStorage);
this.groupBox.Controls.Add(this.ButtonRemoveBoat);
this.groupBox.Controls.Add(this.ButtonAddBoat);
this.groupBox.Controls.Add(this.comboBoxSelectorMap);
this.groupBox.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox.Location = new System.Drawing.Point(901, 0);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(250, 589);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
this.groupBoxInstruments.Controls.Add(this.ButtonDown);
this.groupBoxInstruments.Controls.Add(this.ButtonRight);
this.groupBoxInstruments.Controls.Add(this.ButtonLeft);
this.groupBoxInstruments.Controls.Add(this.ButtonUp);
this.groupBoxInstruments.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxInstruments.Controls.Add(this.ButtonShowOnMap);
this.groupBoxInstruments.Controls.Add(this.ButtonShowStorage);
this.groupBoxInstruments.Controls.Add(this.ButtonRemoveBoat);
this.groupBoxInstruments.Controls.Add(this.ButtonAddBoat);
this.groupBoxInstruments.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxInstruments.Location = new System.Drawing.Point(901, 28);
this.groupBoxInstruments.Name = "groupBoxInstruments";
this.groupBoxInstruments.Size = new System.Drawing.Size(250, 783);
this.groupBoxInstruments.TabIndex = 0;
this.groupBoxInstruments.TabStop = false;
this.groupBoxInstruments.Text = "Инструменты";
//
// ButtonDown
//
this.ButtonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonDown.BackgroundImage = global::Boats.Properties.Resources.arrow_down;
this.ButtonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonDown.Location = new System.Drawing.Point(99, 537);
this.ButtonDown.Location = new System.Drawing.Point(99, 716);
this.ButtonDown.Name = "ButtonDown";
this.ButtonDown.Size = new System.Drawing.Size(30, 30);
this.ButtonDown.TabIndex = 10;
@@ -78,10 +90,10 @@
//
// ButtonRight
//
this.ButtonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonRight.BackgroundImage = global::Boats.Properties.Resources.arrow_right;
this.ButtonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonRight.Location = new System.Drawing.Point(135, 537);
this.ButtonRight.Location = new System.Drawing.Point(135, 716);
this.ButtonRight.Name = "ButtonRight";
this.ButtonRight.Size = new System.Drawing.Size(30, 30);
this.ButtonRight.TabIndex = 9;
@@ -90,10 +102,10 @@
//
// ButtonLeft
//
this.ButtonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonLeft.BackgroundImage = global::Boats.Properties.Resources.arrow_left;
this.ButtonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonLeft.Location = new System.Drawing.Point(63, 537);
this.ButtonLeft.Location = new System.Drawing.Point(63, 716);
this.ButtonLeft.Name = "ButtonLeft";
this.ButtonLeft.Size = new System.Drawing.Size(30, 30);
this.ButtonLeft.TabIndex = 8;
@@ -102,10 +114,10 @@
//
// ButtonUp
//
this.ButtonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonUp.BackgroundImage = global::Boats.Properties.Resources.arrow_up;
this.ButtonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonUp.Location = new System.Drawing.Point(99, 501);
this.ButtonUp.Location = new System.Drawing.Point(99, 680);
this.ButtonUp.Name = "ButtonUp";
this.ButtonUp.Size = new System.Drawing.Size(30, 30);
this.ButtonUp.TabIndex = 7;
@@ -114,7 +126,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 168);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 449);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(232, 27);
@@ -122,7 +134,7 @@
//
// ButtonShowOnMap
//
this.ButtonShowOnMap.Location = new System.Drawing.Point(6, 389);
this.ButtonShowOnMap.Location = new System.Drawing.Point(6, 613);
this.ButtonShowOnMap.Name = "ButtonShowOnMap";
this.ButtonShowOnMap.Size = new System.Drawing.Size(232, 40);
this.ButtonShowOnMap.TabIndex = 4;
@@ -132,7 +144,7 @@
//
// ButtonShowStorage
//
this.ButtonShowStorage.Location = new System.Drawing.Point(6, 303);
this.ButtonShowStorage.Location = new System.Drawing.Point(6, 555);
this.ButtonShowStorage.Name = "ButtonShowStorage";
this.ButtonShowStorage.Size = new System.Drawing.Size(232, 40);
this.ButtonShowStorage.TabIndex = 3;
@@ -142,7 +154,7 @@
//
// ButtonRemoveBoat
//
this.ButtonRemoveBoat.Location = new System.Drawing.Point(6, 212);
this.ButtonRemoveBoat.Location = new System.Drawing.Point(6, 496);
this.ButtonRemoveBoat.Name = "ButtonRemoveBoat";
this.ButtonRemoveBoat.Size = new System.Drawing.Size(232, 40);
this.ButtonRemoveBoat.TabIndex = 2;
@@ -152,7 +164,7 @@
//
// ButtonAddBoat
//
this.ButtonAddBoat.Location = new System.Drawing.Point(6, 97);
this.ButtonAddBoat.Location = new System.Drawing.Point(6, 391);
this.ButtonAddBoat.Name = "ButtonAddBoat";
this.ButtonAddBoat.Size = new System.Drawing.Size(232, 40);
this.ButtonAddBoat.TabIndex = 1;
@@ -160,58 +172,172 @@
this.ButtonAddBoat.UseVisualStyleBackColor = true;
this.ButtonAddBoat.Click += new System.EventHandler(this.ButtonAddBoat_Click);
//
// comboBoxSelectorMap
// ComboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
this.ComboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ComboBoxSelectorMap.FormattingEnabled = true;
this.ComboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Океан карта",
"Линии карта"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 26);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(238, 28);
this.comboBoxSelectorMap.TabIndex = 0;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
this.ComboBoxSelectorMap.Location = new System.Drawing.Point(6, 59);
this.ComboBoxSelectorMap.Name = "ComboBoxSelectorMap";
this.ComboBoxSelectorMap.Size = new System.Drawing.Size(220, 28);
this.ComboBoxSelectorMap.TabIndex = 0;
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, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(901, 589);
this.pictureBox.Size = new System.Drawing.Size(901, 783);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// groupBoxMaps
//
this.groupBoxMaps.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxMaps.Controls.Add(this.ButtonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.ButtonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.ComboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(907, 26);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(232, 318);
this.groupBoxMaps.TabIndex = 11;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// ButtonDeleteMap
//
this.ButtonDeleteMap.Location = new System.Drawing.Point(6, 272);
this.ButtonDeleteMap.Name = "ButtonDeleteMap";
this.ButtonDeleteMap.Size = new System.Drawing.Size(220, 40);
this.ButtonDeleteMap.TabIndex = 4;
this.ButtonDeleteMap.Text = "Удалить карту";
this.ButtonDeleteMap.UseVisualStyleBackColor = true;
this.ButtonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(6, 153);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(220, 104);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.listBoxMaps_SelectedIndexChanged);
//
// ButtonAddMap
//
this.ButtonAddMap.Location = new System.Drawing.Point(6, 93);
this.ButtonAddMap.Name = "ButtonAddMap";
this.ButtonAddMap.Size = new System.Drawing.Size(220, 40);
this.ButtonAddMap.TabIndex = 2;
this.ButtonAddMap.Text = "Добавить карту";
this.ButtonAddMap.UseVisualStyleBackColor = true;
this.ButtonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(6, 26);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(220, 27);
this.textBoxNewMapName.TabIndex = 0;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
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(1151, 28);
this.menuStrip.TabIndex = 12;
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(59, 24);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Text = "Сохранить";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.LoadToolStripMenuItem.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(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1151, 589);
this.ClientSize = new System.Drawing.Size(1151, 811);
this.Controls.Add(this.groupBoxMaps);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.groupBoxInstruments);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetBoats";
this.Text = "Карта с набором элементов";
this.groupBox.ResumeLayout(false);
this.groupBox.PerformLayout();
this.groupBoxInstruments.ResumeLayout(false);
this.groupBoxInstruments.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox groupBox;
private GroupBox groupBoxInstruments;
private MaskedTextBox maskedTextBoxPosition;
private Button ButtonShowOnMap;
private Button ButtonShowStorage;
private Button ButtonRemoveBoat;
private Button ButtonAddBoat;
private ComboBox comboBoxSelectorMap;
private ComboBox ComboBoxSelectorMap;
private PictureBox pictureBox;
private Button ButtonDown;
private Button ButtonRight;
private Button ButtonLeft;
private Button ButtonUp;
private GroupBox groupBoxMaps;
private Button ButtonDeleteMap;
private ListBox listBoxMaps;
private Button ButtonAddMap;
private TextBox textBoxNewMapName;
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;
@@ -12,6 +13,20 @@ namespace Boats
{
public partial class FormMapWithSetBoats : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Линии карта", new LineMap() },
{ "Океан карта", new OceanMap() },
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
/// <summary>
/// Объект от класса карты с набором объектов
/// </summary>
@@ -19,9 +34,36 @@ namespace Boats
/// <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 _mapsDict)
{
ComboBoxSelectorMap.Items.Add(elem.Key);
}
}
/// <summary>
/// Заполнение listBoxMaps
/// </summary>
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
}
}
/// <summary>
/// Выбор карты
@@ -31,7 +73,7 @@ namespace Boats
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
switch (ComboBoxSelectorMap.Text)
{
case "Простая карта":
map = new SimpleMap();
@@ -60,29 +102,9 @@ namespace Boats
/// <param name="e"></param>
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
if (_mapBoatsCollectionGeneric == null)
{
return;
}
FormBoat form = new();
if (form.ShowDialog() == DialogResult.OK)
{
bool added = false;
if (form.SelectedBoat != null)
{
DrawingObjectBoat boat = new(form.SelectedBoat);
if (_mapBoatsCollectionGeneric + boat != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapBoatsCollectionGeneric.ShowSet();
added = true;
}
}
if (!added)
{
MessageBox.Show("Не удалось добавить объект");
}
}
var formBoatConfig = new FormBoatConfig();
formBoatConfig.AddEvent(new BoatDelegate(AddBoatListener));
formBoatConfig.Show();
}
/// <summary>
/// Удаление объекта
@@ -91,6 +113,10 @@ namespace Boats
/// <param name="e"></param>
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
@@ -101,15 +127,29 @@ namespace Boats
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
pos -= 1;
if (_mapBoatsCollectionGeneric - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapBoatsCollectionGeneric.ShowSet();
var deletedBoat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedBoat != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект {deletedBoat.GetType().Name}");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation($"Не удалось удалить объект по позиции {pos}: объект равен null");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (BoatNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
@@ -119,11 +159,11 @@ namespace Boats
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapBoatsCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapBoatsCollectionGeneric.ShowSet();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Вывод карты
@@ -132,11 +172,11 @@ namespace Boats
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapBoatsCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapBoatsCollectionGeneric.ShowOnMap();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// <summary>
/// Перемещение
@@ -145,11 +185,11 @@ namespace Boats
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapBoatsCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
// Получаем имя кнопки
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
@@ -167,7 +207,136 @@ namespace Boats
dir = Direction.Right;
break;
}
pictureBox.Image = _mapBoatsCollectionGeneric.MoveObject(dir);
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (ComboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(ComboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? ""}");
ReloadMaps();
}
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem?.ToString() ?? ""}");
}
/// <summary>
/// Listener для добавления новой лодки из формы
/// </summary>
/// <param name="drawingBoat"></param>
private void AddBoatListener(DrawingBoat drawingBoat)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawingObjectBoat boat = new(drawingBoat);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {drawingBoat.GetType().Name}");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Обработка нажатия "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Сохранение прошло успешно. Файл: {saveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить файл '{saveFileDialog.FileName}'. Ошибка: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Открытие файла '{openFileDialog.FileName}' прошло успешно");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось открыть файл {openFileDialog.FileName}. Ошибка: {ex.Message}");
}
}
}
}
}

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>152, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>319, 17</value>
</metadata>
</root>

View File

@@ -38,5 +38,10 @@ namespace Boats
/// </summary>
/// <returns></returns>
(float Left, float Top, float Right, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@@ -43,7 +43,7 @@ namespace Boats
/// Массив точек установки лодок в гавани
/// </summary>
private Point[]? _placesPoints;
private readonly int _placesCount = 14;
private readonly int _placesCount = 18;
/// <summary>
/// Конструктор
/// </summary>
@@ -101,13 +101,9 @@ namespace Boats
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setBoats.Count; i++)
foreach (var boat in _setBoats.GetBoats())
{
var boat = _setBoats.Get(i);
if (boat != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, boat);
}
return _map.CreateMap(_pictureWidth, _pictureHeight, boat);
}
return new(_pictureWidth, _pictureHeight);
}
@@ -132,11 +128,11 @@ namespace Boats
int j = _setBoats.Count - 1;
for (int i = 0; i < _setBoats.Count; i++)
{
if (_setBoats.Get(i) == null)
if (_setBoats[i] == null)
{
for (; j > i; j--)
{
var boat = _setBoats.Get(j);
var boat = _setBoats[j];
if (boat != null)
{
_setBoats.Insert(boat, i);
@@ -158,7 +154,7 @@ namespace Boats
private void DrawBackground(Graphics g)
{
bool pointsInit = false;
// Если массив точек null, значит рисуем фон первый раз и
// если массив точек null, то рисуем фон первый раз
// инициализируем массив для его заполнения
if (_placesPoints == null)
{
@@ -195,16 +191,16 @@ namespace Boats
g.FillRectangle(Brushes.Brown, _pictureWidth - x - w, y, w, pirsSize);
if (pointsInit)
{
_placesPoints[9 + i] = new Point(x + 5, y - _placeSizeHeight + 5);
_placesPoints[4 - i] = new Point(_pictureWidth - x - w + 5, y - _placeSizeHeight + 5);
_placesPoints[11 + i] = new Point(x + 5, y - _placeSizeHeight + 5);
_placesPoints[6 - i] = new Point(_pictureWidth - x - w + 5, y - _placeSizeHeight + 5);
}
y += h + pirsSize;
i++;
}
if (pointsInit)
{
_placesPoints[9 + i] = new Point(x + 5, y - _placeSizeHeight + 5);
_placesPoints[4 - i] = new Point(_pictureWidth - x - w + 5, y - _placeSizeHeight + 5);
_placesPoints[11 + i] = new Point(x + 5, y - _placeSizeHeight + 5);
_placesPoints[6 - i] = new Point(_pictureWidth - x - w + 5, y - _placeSizeHeight + 5);
}
// вертикальные
@@ -217,14 +213,14 @@ namespace Boats
g.FillRectangle(Brushes.Brown, x, y, pirsSize, h);
if (pointsInit)
{
_placesPoints[8 - i] = new Point(x - w + 5, y + 5);
_placesPoints[10 - i] = new Point(x - w + 5, y + 5);
}
x += w + pirsSize;
i++;
}
if (pointsInit)
{
_placesPoints[8 - i] = new Point(x - w + 5, y + 5);
_placesPoints[10 - i] = new Point(x - w + 5, y + 5);
}
}
/// <summary>
@@ -233,12 +229,39 @@ namespace Boats
/// <param name="g"></param>
private void DrawBoats(Graphics g)
{
for (int i = 0; i < _setBoats.Count; i++)
int i = 0;
foreach (var boat in _setBoats.GetBoats())
{
// Установка позиции
_setBoats.Get(i)?.SetObject(_placesPoints[i].X, _placesPoints[i].Y,
boat.SetObject(_placesPoints[i].X, _placesPoints[i].Y,
_pictureWidth, _pictureHeight);
_setBoats.Get(i)?.DrawingObject(g);
boat.DrawingObject(g);
i++;
}
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var boat in _setBoats.GetBoats())
{
data += $"{boat.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setBoats.Insert(DrawingObjectBoat.Create(rec) as T);
}
}
}

View File

@@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace Boats
{
/// <summary>
/// Класс для хранения коллекции карт
/// </summary>
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записи коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
// Добавление карты
MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
_mapStorages.Add(name, newMap);
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
// Удаление карты
if (!_mapStorages.ContainsKey(name))
{
return;
}
_mapStorages.Remove(name);
}
/// <summary>
/// Доступ к гавани
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> this[string index]
{
get
{
// Получение объекта
if (_mapStorages.ContainsKey(index))
{
return _mapStorages[index];
}
return null;
}
}
/// <summary>
/// Сохранение информации по лодкам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine($"MapsCollection");
foreach (var storage in _mapStorages)
{
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
}
}
}
/// <summary>
/// Загрузка нформации по лодкам в гавани из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = File.OpenText(filename))
{
string? currentLine = sr.ReadLine();
if (currentLine == null || !currentLine.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
currentLine = sr.ReadLine();
while (currentLine != null)
{
var elem = currentLine.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "OceanMap":
map = new OceanMap();
break;
case "LineMap":
map = new LineMap();
break;
}
_mapStorages.Add(
elem[0],
new MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map)
);
_mapStorages[elem[0]].LoadData(
elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
currentLine = sr.ReadLine();
}
}
}
}
}

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
namespace Boats
{
internal static class Program
@@ -11,7 +17,30 @@ namespace Boats
// 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: "appSettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -16,18 +16,23 @@ namespace Boats
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T[] _places;
private readonly List<T> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
public int Count => _places.Count;
/// <summary>
/// Максимальное количество элементов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetBoatsGeneric(int count)
{
_places = new T[count];
_places = new List<T>();
_maxCount = count;
}
/// <summary>
/// Добавление объекта в набор
@@ -36,6 +41,10 @@ namespace Boats
/// <returns></returns>
public int Insert(T boat)
{
// Проверка на _maxCount
// Если достигли максимального значения - выбрасываем исключение
if (Count == _maxCount)
throw new StorageOverflowException(_maxCount);
// Вставка в начало набора
return Insert(boat, 0);
}
@@ -48,42 +57,9 @@ namespace Boats
public int Insert(T boat, int position)
{
// Проверка позиции
if (position < 0 || position >= _places.Length)
if (position < 0 || position >= _maxCount - 1)
return -1;
// Проверка, что элемент массива по этой позиции пустой
if (_places[position] != null)
{
// Если нет, проверим, что после вставляемого элемента в массиве есть пустой элемент
int i = position + 1;
int nullIndex = -1;
while (i < _places.Length)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
i++;
}
// Если свободной нет, то выходим
if (nullIndex < 0)
{
return -1;
}
else
{
// Если есть, сдвигаем все объекты, находящиеся
// справа от позиции до первого пустого элемента
i = nullIndex - 1;
while (i >= position)
{
_places[i + 1] = _places[i];
i--;
}
}
}
// Вставка по позиции
_places[position] = boat;
_places.Insert(position, boat);
return position;
}
/// <summary>
@@ -94,28 +70,49 @@ namespace Boats
public T Remove(int position)
{
// Проверка позиции
if (position < 0 || position >= _places.Length)
return null;
if (_places[position] == null)
{
return null;
}
// Удаление объекта из массива, присовив элементу массива значение null
// Если позиция неверная (пустой быть не может, потому что у нас список),
// то выбрасываем исключение
if (position < 0 || position >= Count)
throw new BoatNotFoundException(position);
T boat = _places[position];
_places[position] = null;
_places.RemoveAt(position);
return boat;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns>Возвращает объект по позиции</returns>
public T Get(int position)
public T this[int position]
{
// Проверка позиции
if (position < 0 || position >= _places.Length)
return null;
return _places[position];
get
{
// Проверка позиции
if (position < 0 || position >= Count)
return null;
return _places[position];
}
set
{
// Проверка позиции
if (position < 0 || position >= Count)
return;
// Вставка по позиции
_places[position] = value;
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetBoats()
{
foreach (var boat in _places)
{
if (boat != null)
{
yield return boat;
}
else
{
yield break;
}
}
}
}
}

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 Boats
{
[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": "Boats"
}
}
}