Compare commits

...

25 Commits

Author SHA1 Message Date
7b6adc2828 ужас 2023-12-24 01:16:42 +04:00
f8eb440279 кошмар 2023-12-24 01:10:45 +04:00
ea7d59908e all 2023-12-20 09:58:42 +04:00
6c507a6877 Хорошо когда собака друг, плохо когда друг собака 2023-12-19 22:39:15 +04:00
8e6becc7b1 опять треш 2023-12-19 18:44:22 +04:00
a58085b4d1 lab 7 надеюсь готова 2023-12-19 18:27:50 +04:00
7e81c6ca04 треш 2023-12-05 01:54:50 +04:00
9379418cf7 тут что то доделано 2023-12-05 00:33:53 +04:00
c549fc6a3c laba6 2023-11-22 10:49:19 +04:00
71b1caa094 почти 6 2023-11-22 02:44:28 +04:00
814b0b8252 лаба 5 надеюсь готовая 2023-11-22 02:04:16 +04:00
cc83e1aa48 почти 5 2023-11-21 22:54:36 +04:00
8bcd0f4089 что то сделала 2023-11-15 11:44:37 +04:00
213ec2a858 всё сломала и вроде починила 2023-11-06 21:01:25 +04:00
7ab4e0f118 слепила новую форму 2023-11-06 19:40:12 +04:00
ccf9eb19d8 4 лаба готовая 2023-11-06 18:06:51 +04:00
54db2e3780 создала новый generic класс 2023-10-25 08:45:58 +04:00
a03be5f062 создала ветку 2023-10-25 07:59:41 +04:00
f9da881a3c лаба 3 готовая 2023-10-25 07:50:15 +04:00
239d88ff26 лаба 3 готовая 2023-10-24 23:08:47 +04:00
41ab07e21a создала generic классы 2023-10-23 22:55:50 +04:00
b19ff39870 лаба 2 точно точно готовая 2023-10-23 21:05:23 +04:00
4ccd1c4123 лаба 2 точно готовая 2023-10-11 10:53:06 +04:00
4ca5cd73fa лаба 2 готовая 2023-10-10 22:21:57 +04:00
559be80c38 лаба 2 готовая 2023-10-10 22:19:01 +04:00
34 changed files with 3019 additions and 154 deletions

View File

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.MovementStrategy;
namespace Catamaran.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int
height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false -неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

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

View File

@ -1,6 +1,6 @@
namespace Catamaran
{
partial class Catamaran
partial class FormCatamaran
{
/// <summary>
/// Required designer variable.
@ -29,11 +29,15 @@
private void InitializeComponent()
{
this.pictureBoxCatamaran = new System.Windows.Forms.PictureBox();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonCreateCatamaran = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStrategyStep = new System.Windows.Forms.Button();
this.buttonCreateSailCatamaran = new System.Windows.Forms.Button();
this.buttonSelectCatamaran = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCatamaran)).BeginInit();
this.SuspendLayout();
//
@ -47,16 +51,16 @@
this.pictureBoxCatamaran.TabIndex = 0;
this.pictureBoxCatamaran.TabStop = false;
//
// buttonCreate
// buttonCreateCatamaran
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 426);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
this.buttonCreateCatamaran.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateCatamaran.Location = new System.Drawing.Point(140, 398);
this.buttonCreateCatamaran.Name = "buttonCreateCatamaran";
this.buttonCreateCatamaran.Size = new System.Drawing.Size(122, 51);
this.buttonCreateCatamaran.TabIndex = 1;
this.buttonCreateCatamaran.Text = "Создать катамаран";
this.buttonCreateCatamaran.UseVisualStyleBackColor = true;
this.buttonCreateCatamaran.Click += new System.EventHandler(this.buttonCreateCatamaran_Click);
//
// buttonUp
//
@ -106,16 +110,64 @@
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// Catamaran
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"До центра",
"До края"});
this.comboBoxStrategy.Location = new System.Drawing.Point(711, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(151, 23);
this.comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
this.buttonStrategyStep.Location = new System.Drawing.Point(787, 41);
this.buttonStrategyStep.Name = "buttonStrategyStep";
this.buttonStrategyStep.Size = new System.Drawing.Size(75, 23);
this.buttonStrategyStep.TabIndex = 7;
this.buttonStrategyStep.Text = "Шаг";
this.buttonStrategyStep.UseVisualStyleBackColor = true;
this.buttonStrategyStep.Click += new System.EventHandler(this.buttonStrategyStep_Click);
//
// buttonCreateSailCatamaran
//
this.buttonCreateSailCatamaran.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateSailCatamaran.Location = new System.Drawing.Point(12, 398);
this.buttonCreateSailCatamaran.Name = "buttonCreateSailCatamaran";
this.buttonCreateSailCatamaran.Size = new System.Drawing.Size(122, 51);
this.buttonCreateSailCatamaran.TabIndex = 8;
this.buttonCreateSailCatamaran.Text = "Создать катамаран с парусом";
this.buttonCreateSailCatamaran.UseVisualStyleBackColor = true;
this.buttonCreateSailCatamaran.Click += new System.EventHandler(this.buttonCreateSailCatamaran_Click);
//
// buttonSelectCatamaran
//
this.buttonSelectCatamaran.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSelectCatamaran.Location = new System.Drawing.Point(268, 398);
this.buttonSelectCatamaran.Name = "buttonSelectCatamaran";
this.buttonSelectCatamaran.Size = new System.Drawing.Size(167, 51);
this.buttonSelectCatamaran.TabIndex = 11;
this.buttonSelectCatamaran.Text = "Выбрать катамаран";
this.buttonSelectCatamaran.UseVisualStyleBackColor = true;
this.buttonSelectCatamaran.Click += new System.EventHandler(this.buttonSelectCatamaran_Click);
//
// FormCatamaran
//
this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.buttonSelectCatamaran);
this.Controls.Add(this.buttonCreateSailCatamaran);
this.Controls.Add(this.buttonStrategyStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonCreateCatamaran);
this.Controls.Add(this.pictureBoxCatamaran);
this.Name = "Catamaran";
this.Name = "FormCatamaran";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Катамаран";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCatamaran)).EndInit();
@ -126,12 +178,15 @@
#endregion
private Button buttonCreate;
private Button buttonCreateCatamaran;
private PictureBox pictureBoxCatamaran;
private Button buttonUp;
private Button buttonRight;
private Button buttonLeft;
private Button buttonDown;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
private Button buttonCreateSailCatamaran;
private Button buttonSelectCatamaran;
}
}

View File

@ -1,12 +1,38 @@
using Catamaran.DrawningObjects;
using Catamaran.MovementStrategy;
namespace Catamaran
{
public partial class Catamaran : Form
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Êàòàìàðàí"
/// </summary>
public partial class FormCatamaran : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïğîğèñîâêè îáúåêòà
/// </summary>
private DrawningCatamaran? _drawningCatamaran;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Âûáðàííûé êàòàìàðàí
/// </summary>
public DrawningCatamaran? SelectedCatamaran { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormCatamaran()
{
InitializeComponent();
_strategy = null;
SelectedCatamaran = null;
}
/// <summary>
/// Ìåòîä ïğîğèñîâêè êàòàìàğàíà
/// </summary>
@ -22,16 +48,68 @@ namespace Catamaran
_drawningCatamaran.DrawTransport(gr);
pictureBoxCatamaran.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü êàòàìàðàí ñ ïîïëàâêàìè"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public Catamaran()
private void buttonCreateSailCatamaran_Click(object sender, EventArgs e)
{
InitializeComponent();
Random random = new();
//¸ TODO âûáîð îñíîâíîãî öâåòà
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
//TODO âûáîð äîïîëíèòåëüíîãî öâåòà
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDopColor.Color;
}
_drawningCatamaran = new DrawningSailCatamaran(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxCatamaran.Width, pictureBoxCatamaran.Height);
_drawningCatamaran.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Ñîçäàíèå ïðîñòîãî êàòàìàðàíà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCatamaran_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningCatamaran = new DrawningCatamaran(random.Next(100, 300),
random.Next(1000, 3000), color,
pictureBoxCatamaran.Width, pictureBoxCatamaran.Height);
_drawningCatamaran.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Èçìåíåíèå ïîëîæåíèÿ êàòàìàðàíà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningCatamaran == null)
@ -42,41 +120,69 @@ namespace Catamaran
switch (name)
{
case "buttonUp":
_drawningCatamaran.MoveTransport(Direction.Up);
_drawningCatamaran.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningCatamaran.MoveTransport(Direction.Down);
_drawningCatamaran.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningCatamaran.MoveTransport(Direction.Left);
_drawningCatamaran.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningCatamaran.MoveTransport(Direction.Right);
_drawningCatamaran.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void buttonCreate_Click(object sender, EventArgs e)
/// <summary>
/// Øàã ñòðàòåãèè ïåðåìåùåíèÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
Random random = new();
_drawningCatamaran = new DrawningCatamaran();
_drawningCatamaran.Init(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), pictureBoxCatamaran.Width, pictureBoxCatamaran.Height);
_drawningCatamaran.SetPosition(random.Next(10, 100),
random.Next(10, 100));
if (_drawningCatamaran == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawningCatamaran.GetMoveableObject,
pictureBoxCatamaran.Width, pictureBoxCatamaran.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
/// <summary>
/// Âûáîð êàòàìàðàíà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectCatamaran_Click(object sender, EventArgs e)
{
SelectedCatamaran = _drawningCatamaran;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -0,0 +1,49 @@
using Catamaran.DrawningObjects;
using Catamaran.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Generics
{
internal class CatamaranCompareByColor : IComparer<DrawningCatamaran?>
{
public int Compare(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityCatamaran.BodyColor.Name.CompareTo(y.EntityCatamaran.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityCatamaran is EntitySailCatamaran xEntitySailCatamaran && y.EntityCatamaran is EntitySailCatamaran yEntitySailCatamaran)
{
var BodyColorCompare = xEntitySailCatamaran.BodyColor.Name.CompareTo(yEntitySailCatamaran.BodyColor.Name);
if (BodyColorCompare != 0)
{
return BodyColorCompare;
}
var AdditionalColorCompare = xEntitySailCatamaran.AdditionalColor.Name.CompareTo(yEntitySailCatamaran.AdditionalColor.Name);
if (AdditionalColorCompare != 0)
{
return AdditionalColorCompare;
}
}
var speedCompare = x.EntityCatamaran.Speed.CompareTo(y.EntityCatamaran.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityCatamaran.Weight.CompareTo(y.EntityCatamaran.Weight);
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
namespace Catamaran.Generics
{
internal class CatamaranCompareByType : IComparer<DrawningCatamaran?>
{
public int Compare(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityCatamaran.Speed.CompareTo(y.EntityCatamaran.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityCatamaran.Weight.CompareTo(y.EntityCatamaran.Weight);
}
}
}

View File

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

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Generics
{
internal class CatamaransCollectionInfo : IEquatable<CatamaransCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public CatamaransCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(CatamaransCollectionInfo? other)
{
// TODO прописать логику сравнения по свойству Name
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic.Logging;
using Catamaran.DrawningObjects;
using Catamaran.MovementStrategy;
namespace Catamaran.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningCatamaran
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class CatamaransGenericCollection<T, U>
where T : DrawningCatamaran
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 200;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 150;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCatamarans => _collection.GetCatamarans();
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public CatamaransGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator +(CatamaransGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return collect?._collection.Insert(obj, new DrawningCatamaranEqutables()) ?? false;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(CatamaransGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowCatamarans()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
{
// TODO получение объекта
// TODO установка позиции
// TODO прорисовка объекта
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int diff = 1, currWidth = 0, i = 0;
foreach (var catamaran in _collection.GetCatamarans())
{
currWidth++;
if (currWidth > width)
{
diff++;
currWidth = 1;
}
if (catamaran != null)
{
catamaran._pictureWidth = _pictureWidth;
catamaran._pictureHeight = _pictureHeight;
catamaran.SetPosition(i % width * _placeSizeWidth + _placeSizeWidth / 40,
(height - diff) * _placeSizeHeight + _placeSizeHeight / 15);
catamaran.DrawTransport(g);
}
i++;
}
}
}
}
}

View File

@ -0,0 +1,180 @@
using Catamaran.DrawningObjects;
using Catamaran.MovementStrategy;
using System.Text;
namespace Catamaran.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class CatamaransGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<CatamaransCollectionInfo, CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran>> _catamaranStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<CatamaransCollectionInfo> Keys => _catamaranStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public CatamaransGenericStorage(int pictureWidth, int pictureHeight)
{
_catamaranStorages = new Dictionary<CatamaransCollectionInfo,
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
_catamaranStorages.Add(new CatamaransCollectionInfo(name, string.Empty), new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_catamaranStorages.ContainsKey(new CatamaransCollectionInfo(name, string.Empty)))
return;
_catamaranStorages.Remove(new CatamaransCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>?
this[string ind]
{
get
{
// TODO Продумать логику получения набора
CatamaransCollectionInfo indObj = new CatamaransCollectionInfo(ind, string.Empty);
if (_catamaranStorages.ContainsKey(indObj))
return _catamaranStorages[indObj];
return null;
}
}
/// <summary>
/// Сохранение информации по катамаранам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<CatamaransCollectionInfo, CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catamaranStorages)
{
StringBuilder records = new();
foreach (DrawningCatamaran? elem in record.Value.GetCatamarans)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CatamaranStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("CatamaranStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_catamaranStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningCatamaran? catamaran =
elem?.CreateDrawningCatamaran(_separatorForObject, _pictureWidth, _pictureHeight);
if (catamaran != null)
{
if (!(collection + catamaran))
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_catamaranStorages.Add(new CatamaransCollectionInfo(record[0],string.Empty), collection);
}
}
}
}

View File

@ -9,7 +9,7 @@ namespace Catamaran
/// <summary>
/// Направление перемещения
/// </summary>
public enum Direction
public enum DirectionType
{
/// <summary>
/// Вверх

View File

@ -3,34 +3,36 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.Entities;
using Catamaran.MovementStrategy;
namespace Catamaran
namespace Catamaran.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawningCatamaran
public class DrawningCatamaran
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityCatamaran? EntityCatamaran { get; private set; }
public EntityCatamaran? EntityCatamaran { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
public int _pictureHeight;
/// <summary>
/// Левая координата прорисовки катамарана
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки катамарана
/// Верхняя координата прорисовки катамарана
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки катамарана
/// </summary>
@ -40,34 +42,75 @@ namespace Catamaran
/// </summary>
private readonly int _CatamaranHeight = 120;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _CatamaranWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _CatamaranHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectCatamaran(this);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="sail">Признак наличия паруса</param>
/// <param name="floatDetail">Признак наличия поплавков</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool sail, bool floatDetail, int width, int height)
public DrawningCatamaran(int speed, double weight, Color bodyColor, int width, int height)
{
if (width >= _CatamaranWidth && height >= _CatamaranHeight)
{
_pictureWidth = width;
_pictureHeight = height;
EntityCatamaran = new EntityCatamaran();
EntityCatamaran.Init(speed, weight, bodyColor, additionalColor, sail, floatDetail);
return true;
EntityCatamaran = new EntityCatamaran(speed, weight, bodyColor);
return;
}
else
{
return false; // Возвращаем false, если размеры формы недостаточны
return;
}
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="catamaranWidth">Ширина прорисовки катамарана</param>
/// <param name="catamaranHeight">Высота прорисовки катамарана</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
protected DrawningCatamaran(int speed, double weight, Color bodyColor, int width, int height, int catamaranWidth, int catamaranHeight)
{
if (width >= _CatamaranWidth && height >= _CatamaranHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_CatamaranWidth = catamaranWidth;
_CatamaranHeight = catamaranHeight;
EntityCatamaran = new EntityCatamaran(speed, weight, bodyColor);
return;
}
else
{
return;
}
}
/// <summary>
/// Установка позиции
@ -76,48 +119,73 @@ namespace Catamaran
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x >= 0 && x + _CatamaranWidth <= _pictureWidth && y >= 0 && y + _CatamaranHeight <= _pictureHeight)
if (x < 0 || x + _CatamaranWidth > _pictureWidth)
{
_startPosX = x;
_startPosY = y;
x = 0;
}
if (y < 0 || y + _CatamaranHeight > _pictureHeight)
{
y = 0;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityCatamaran == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityCatamaran.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityCatamaran.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityCatamaran.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityCatamaran.Step < _pictureHeight,
_ => false
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (EntityCatamaran == null)
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityCatamaran == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
case DirectionType.Left:
if (_startPosX - EntityCatamaran.Step > 0)
{
_startPosX -= (int)EntityCatamaran.Step;
}
break;
//вверх
case Direction.Up:
case DirectionType.Up:
if (_startPosY - EntityCatamaran.Step > 0)
{
_startPosY -= (int)EntityCatamaran.Step;
}
break;
// вправо
case Direction.Right:
if (_startPosX + _CatamaranWidth + EntityCatamaran.Step < _pictureWidth )
case DirectionType.Right:
if (_startPosX + EntityCatamaran.Step + _CatamaranWidth < _pictureWidth)
{
_startPosX += (int)EntityCatamaran.Step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + _CatamaranHeight + EntityCatamaran.Step < _pictureHeight)
case DirectionType.Down:
if (_startPosY + EntityCatamaran.Step + _CatamaranHeight < _pictureHeight)
{
_startPosY += (int)EntityCatamaran.Step;
}
@ -128,43 +196,15 @@ namespace Catamaran
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityCatamaran == null)
{
return;
}
Pen pen = new(Color.Black, 3);
Brush additionalBrush = new
SolidBrush(EntityCatamaran.AdditionalColor);
Brush bodyBrush = new
SolidBrush(EntityCatamaran.BodyColor);
//поплавки
if (EntityCatamaran.Float)
{
Point[] floatDetail1 = new Point[]
{
new Point(_startPosX, _startPosY + 40),
new Point(_startPosX + 170, _startPosY + 40),
new Point(_startPosX + 190, _startPosY + 55),
new Point(_startPosX + 170, _startPosY + 70),
new Point(_startPosX, _startPosY + 70),
};
Point[] floatDetail2 = new Point[]
{
new Point(_startPosX, _startPosY + 90),
new Point(_startPosX + 170, _startPosY + 90),
new Point(_startPosX + 190, _startPosY + 105),
new Point(_startPosX + 170, _startPosY + 120),
new Point(_startPosX, _startPosY + 120),
};
g.FillPolygon(additionalBrush, floatDetail1);
g.FillPolygon(additionalBrush, floatDetail2);
g.DrawPolygon(pen, floatDetail1);
g.DrawPolygon(pen, floatDetail2);
}
SolidBrush(EntityCatamaran.BodyColor);
//основание катамарана
Point[] hull = new Point[]
{
@ -178,23 +218,21 @@ namespace Catamaran
g.FillPolygon(bodyBrush, hull);
g.DrawPolygon(pen, hull);
SolidBrush brushBrown = new SolidBrush(Color.Brown);
g.FillEllipse(brushBrown, _startPosX + 30, _startPosY + 60, 100, 40);
//парус
if (EntityCatamaran.Sail)
{
Point[] sail = new Point[]
{
new Point(_startPosX + 30, _startPosY + 80),
new Point(_startPosX + 70, _startPosY+10),
new Point(_startPosX + 145, _startPosY + 80),
};
g.DrawPolygon(pen, sail);
g.FillPolygon(additionalBrush, sail);
g.DrawPolygon(pen, sail);
g.DrawRectangle(pen, _startPosX + 70, _startPosY, 3, 85);
g.FillEllipse(brushBrown, _startPosX + 30, _startPosY + 60, 100, 40);
}
public void SetColor(Color color)
{
if (EntityCatamaran == null)
{
return;
}
EntityCatamaran.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Catamaran.Generics
{
internal class DrawningCatamaranEqutables : IEqualityComparer<DrawningCatamaran?>
{
public bool Equals(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCatamaran.Speed != y.EntityCatamaran.Speed)
{
return false;
}
if (x.EntityCatamaran.Weight != y.EntityCatamaran.Weight)
{
return false;
}
if (x.EntityCatamaran.BodyColor != y.EntityCatamaran.BodyColor)
{
return false;
}
if (x is DrawningSailCatamaran && y is DrawningSailCatamaran)
{
// TODO доделать логику сравнения дополнительных параметров
EntitySailCatamaran EntityX = (EntitySailCatamaran)x.EntityCatamaran;
EntitySailCatamaran EntityY = (EntitySailCatamaran)y.EntityCatamaran;
if (EntityX.Sail != EntityY.Sail)
return false;
if (EntityX.FloatDetail != EntityY.FloatDetail)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCatamaran obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
namespace Catamaran.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCatamaran (паттерн Adapter)
/// </summary>
public class DrawningObjectCatamaran : IMoveableObject
{
private readonly DrawningCatamaran? _drawningCatamaran = null;
public DrawningObjectCatamaran(DrawningCatamaran drawningCatamaran)
{
_drawningCatamaran = drawningCatamaran;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningCatamaran == null || _drawningCatamaran.EntityCatamaran ==
null)
{
return null;
}
return new ObjectParameters(_drawningCatamaran.GetPosX,
_drawningCatamaran.GetPosY, _drawningCatamaran.GetWidth, _drawningCatamaran.GetHeight);
}
}
public int GetStep => (int)(_drawningCatamaran?.EntityCatamaran?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningCatamaran?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningCatamaran?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.Entities;
namespace Catamaran.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningSailCatamaran : DrawningCatamaran
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="sail">Признак наличия паруса</param>
/// <param name="floatDetail">Признак наличия поплавков</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningSailCatamaran(int speed, double weight, Color bodyColor, Color
additionalColor, bool sail, bool floatDetail, int width, int height) :
base(speed, weight, bodyColor, width, height, 190, 120)
{
if (EntityCatamaran != null)
{
EntityCatamaran = new EntitySailCatamaran(speed, weight, bodyColor,
additionalColor, sail, floatDetail);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityCatamaran is not EntitySailCatamaran sailCatamaran)
{
return;
}
Pen pen = new(Color.Black, 3);
Brush additionalBrush = new
SolidBrush(sailCatamaran.AdditionalColor);
//поплавки
if (sailCatamaran.FloatDetail)
{
Point[] floatDetail1 = new Point[]
{
new Point(_startPosX, _startPosY + 40),
new Point(_startPosX + 170, _startPosY + 40),
new Point(_startPosX + 190, _startPosY + 55),
new Point(_startPosX + 170, _startPosY + 70),
new Point(_startPosX, _startPosY + 70),
};
Point[] floatDetail2 = new Point[]
{
new Point(_startPosX, _startPosY + 90),
new Point(_startPosX + 170, _startPosY + 90),
new Point(_startPosX + 190, _startPosY + 105),
new Point(_startPosX + 170, _startPosY + 120),
new Point(_startPosX, _startPosY + 120),
};
g.FillPolygon(additionalBrush, floatDetail1);
g.FillPolygon(additionalBrush, floatDetail2);
g.DrawPolygon(pen, floatDetail1);
g.DrawPolygon(pen, floatDetail2);
}
base.DrawTransport(g);
//парус
if (sailCatamaran.Sail)
{
Point[] sail = new Point[]
{
new Point(_startPosX + 30, _startPosY + 80),
new Point(_startPosX + 70, _startPosY+10),
new Point(_startPosX + 145, _startPosY + 80),
};
g.DrawPolygon(pen, sail);
g.FillPolygon(additionalBrush, sail);
g.DrawPolygon(pen, sail);
g.DrawRectangle(pen, _startPosX + 70, _startPosY, 3, 85);
}
}
public void SetAddColor(Color color)
{
((EntitySailCatamaran)EntityCatamaran).AdditionalColor = color;
}
}
}

View File

@ -4,9 +4,12 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran
namespace Catamaran.Entities
{
internal class EntityCatamaran
/// <summary>
/// Класс-сущность "Катамаран"
/// </summary>
public class EntityCatamaran
{
/// <summary>
/// Скорость
@ -19,41 +22,28 @@ namespace Catamaran
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия паруса
/// </summary>
public bool Sail { get; private set; }
/// <summary>
/// Признак (опция) наличия поплавков
/// </summary>
public bool Float { get; private set; }
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения катамарана
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса катамарана
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="sail">Признак наличия паруса</param>
/// <param name="floatDetail">Признак наличия поплавков</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool sail, bool floatDetail)
public EntityCatamaran(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Sail = sail;
Float = floatDetail;
}
public void setBodyColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Entities
{
/// <summary>
/// Класс-сущность "Катамаран с парусом"
/// </summary>
public class EntitySailCatamaran : EntityCatamaran
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия паруса
/// </summary>
public bool Sail { get; private set; }
/// <summary>
/// Признак (опция) наличия поплавков
/// </summary>
public bool FloatDetail { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса катамарана с парусом
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес катамарана</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="sail">Признак наличия паруса</param>
/// <param name="floatDetail">Признак наличия поплавков</param>
public EntitySailCatamaran(int speed, double weight, Color bodyColor, Color
additionalColor, bool sail, bool floatDetail) : base (speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Sail = sail;
FloatDetail = floatDetail;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.Entities;
namespace Catamaran.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityCatamaran
/// </summary>
public static class ExtentionDrawningCatamaran
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningCatamaran? CreateDrawningCatamaran(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningCatamaran(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningSailCatamaran(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCatamaran">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningCatamaran drawningCatamaran,
char separatorForObject)
{
var catamaran = drawningCatamaran.EntityCatamaran;
if (catamaran == null)
{
return string.Empty;
}
var str = $"{catamaran.Speed}{separatorForObject}{catamaran.Weight}{separatorForObject}{catamaran.BodyColor.Name}";
if (catamaran is not EntitySailCatamaran sailCatamaran)
{
return str;
}
return
$"{str}{separatorForObject}{sailCatamaran.AdditionalColor.Name}{separatorForObject}{sailCatamaran.Sail}{separatorForObject}{sailCatamaran.FloatDetail}";
}
}
}

View File

@ -0,0 +1,268 @@
namespace Catamaran
{
partial class FormCatamaranCollection
{
/// <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.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.groupBoxSets = new System.Windows.Forms.GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.buttonDelObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.buttonAddObject = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveCatamaran = new System.Windows.Forms.Button();
this.ButtonAddCatamaran = new System.Windows.Forms.Button();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.groupBoxTools.SuspendLayout();
this.groupBoxSets.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 1);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(736, 459);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.ButtonSortByColor);
this.groupBoxTools.Controls.Add(this.ButtonSortByType);
this.groupBoxTools.Controls.Add(this.groupBoxSets);
this.groupBoxTools.Controls.Add(this.maskedTextBoxNumber);
this.groupBoxTools.Controls.Add(this.ButtonRefreshCollection);
this.groupBoxTools.Controls.Add(this.ButtonRemoveCatamaran);
this.groupBoxTools.Controls.Add(this.ButtonAddCatamaran);
this.groupBoxTools.Controls.Add(this.menuStrip);
this.groupBoxTools.Location = new System.Drawing.Point(739, 1);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(147, 460);
this.groupBoxTools.TabIndex = 1;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(0, 287);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(139, 23);
this.ButtonSortByColor.TabIndex = 7;
this.ButtonSortByColor.Text = "Сортировка по цвету";
this.ButtonSortByColor.UseVisualStyleBackColor = true;
this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// ButtonSortByType
//
this.ButtonSortByType.Location = new System.Drawing.Point(1, 255);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(140, 23);
this.ButtonSortByType.TabIndex = 6;
this.ButtonSortByType.Text = "Сортировка по типу";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBoxSets
//
this.groupBoxSets.Controls.Add(this.textBoxStorageName);
this.groupBoxSets.Controls.Add(this.buttonDelObject);
this.groupBoxSets.Controls.Add(this.listBoxStorages);
this.groupBoxSets.Controls.Add(this.buttonAddObject);
this.groupBoxSets.Location = new System.Drawing.Point(3, 46);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(138, 203);
this.groupBoxSets.TabIndex = 4;
this.groupBoxSets.TabStop = false;
this.groupBoxSets.Text = "Наборы";
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(6, 22);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(130, 23);
this.textBoxStorageName.TabIndex = 4;
//
// buttonDelObject
//
this.buttonDelObject.Location = new System.Drawing.Point(3, 167);
this.buttonDelObject.Name = "buttonDelObject";
this.buttonDelObject.Size = new System.Drawing.Size(134, 27);
this.buttonDelObject.TabIndex = 3;
this.buttonDelObject.Text = "Удалить набор";
this.buttonDelObject.UseVisualStyleBackColor = true;
this.buttonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(6, 82);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(132, 79);
this.listBoxStorages.TabIndex = 2;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged);
//
// buttonAddObject
//
this.buttonAddObject.Location = new System.Drawing.Point(6, 51);
this.buttonAddObject.Name = "buttonAddObject";
this.buttonAddObject.Size = new System.Drawing.Size(131, 25);
this.buttonAddObject.TabIndex = 1;
this.buttonAddObject.Text = "Добавить набор";
this.buttonAddObject.UseVisualStyleBackColor = true;
this.buttonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(0, 356);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(137, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(0, 425);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(140, 34);
this.ButtonRefreshCollection.TabIndex = 2;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// ButtonRemoveCatamaran
//
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(0, 385);
this.ButtonRemoveCatamaran.Name = "ButtonRemoveCatamaran";
this.ButtonRemoveCatamaran.Size = new System.Drawing.Size(140, 34);
this.ButtonRemoveCatamaran.TabIndex = 1;
this.ButtonRemoveCatamaran.Text = "Удалить катамаран";
this.ButtonRemoveCatamaran.UseVisualStyleBackColor = true;
this.ButtonRemoveCatamaran.Click += new System.EventHandler(this.ButtonRemoveCatamaran_Click);
//
// ButtonAddCatamaran
//
this.ButtonAddCatamaran.Location = new System.Drawing.Point(0, 316);
this.ButtonAddCatamaran.Name = "ButtonAddCatamaran";
this.ButtonAddCatamaran.Size = new System.Drawing.Size(137, 34);
this.ButtonAddCatamaran.TabIndex = 0;
this.ButtonAddCatamaran.Text = "Добавить катамаран";
this.ButtonAddCatamaran.UseVisualStyleBackColor = true;
this.ButtonAddCatamaran.Click += new System.EventHandler(this.ButtonAddCatamaran_Click);
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(3, 19);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(141, 24);
this.menuStrip.TabIndex = 5;
this.menuStrip.Text = "menuStrip";
//
// ToolStripMenuItem
//
this.ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.ToolStripMenuItem.Name = "ToolStripMenuItem";
this.ToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
//
// FormCatamaranCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(885, 461);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.pictureBoxCollection);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormCatamaranCollection";
this.Text = "Набор катамаранов";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
this.groupBoxSets.ResumeLayout(false);
this.groupBoxSets.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private GroupBox groupBoxTools;
private Button ButtonAddCatamaran;
private Button ButtonRefreshCollection;
private Button ButtonRemoveCatamaran;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBoxSets;
private Button buttonAddObject;
private Button buttonDelObject;
private ListBox listBoxStorages;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -0,0 +1,319 @@
using Microsoft.Extensions.Logging;
using Catamaran.DrawningObjects;
using Catamaran.Exceptions;
using Catamaran.Generics;
using Catamaran.MovementStrategy;
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 Catamaran
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningCatamaran
/// </summary>
public partial class FormCatamaranCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly CatamaransGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormCatamaranCollection(ILogger<FormCatamaranCollection> logger)
{
InitializeComponent();
_storage = new CatamaransGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxStorages
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
}
private void AddCatamaran(DrawningCatamaran drawningCatamaran)
{
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
if (obj + drawningCatamaran)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowCatamarans();
_logger.LogInformation($"Объект добавлен");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCatamarans();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ??string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddCatamaran_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
var formBoatConfig = new FormCatamaranConfig();
// TODO Call method AddEvent from FormCatamaranConfig
var FormCatamaranConfig = new FormCatamaranConfig();
FormCatamaranConfig.AddEvent(AddCatamaran);
FormCatamaranConfig.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>listBoxStorages
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveCatamaran_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowCatamarans();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (CatamaranNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Нет объекта{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (FormatException)
{
_logger.LogWarning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs
e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowCatamarans();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
ReloadObjects();
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareCatamarans(new CatamaranCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareCatamarans(new CatamaranCompareByColor()); // TODO продумать логику
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareCatamarans(IComparer<DrawningCatamaran?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowCatamarans();
}
}
}

View File

@ -0,0 +1,72 @@
<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>
<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="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>254, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -0,0 +1,414 @@
namespace Catamaran
{
partial class FormCatamaranConfig
{
/// <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.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelRed = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.checkBoxSail = new System.Windows.Forms.CheckBox();
this.checkBoxFloatDetails = 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.panel1 = new System.Windows.Forms.Panel();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.labelAddColor = new System.Windows.Forms.Label();
this.labelBodyColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.groupBoxParameters.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
this.groupBoxParameters.Controls.Add(this.groupBoxColor);
this.groupBoxParameters.Controls.Add(this.checkBoxSail);
this.groupBoxParameters.Controls.Add(this.checkBoxFloatDetails);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Location = new System.Drawing.Point(18, 9);
this.groupBoxParameters.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxParameters.Size = new System.Drawing.Size(524, 260);
this.groupBoxParameters.TabIndex = 0;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelModifiedObject.Location = new System.Drawing.Point(399, 205);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(106, 28);
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.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelSimpleObject.Location = new System.Drawing.Point(274, 205);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(109, 28);
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);
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelWhite);
this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Location = new System.Drawing.Point(274, 28);
this.groupBoxColor.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxColor.Size = new System.Drawing.Size(231, 162);
this.groupBoxColor.TabIndex = 6;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Tomato;
this.panelRed.Location = new System.Drawing.Point(6, 29);
this.panelRed.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 1;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.CornflowerBlue;
this.panelBlue.Location = new System.Drawing.Point(125, 29);
this.panelBlue.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
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);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Gold;
this.panelYellow.Location = new System.Drawing.Point(187, 29);
this.panelYellow.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
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);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(5, 86);
this.panelWhite.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 1;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(65, 86);
this.panelGray.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 1;
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(125, 86);
this.panelBlack.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 1;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Violet;
this.panelPurple.Location = new System.Drawing.Point(187, 86);
this.panelPurple.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
this.panelPurple.TabIndex = 1;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.LightGreen;
this.panelGreen.Location = new System.Drawing.Point(65, 29);
this.panelGreen.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 0;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxSail
//
this.checkBoxSail.AutoSize = true;
this.checkBoxSail.Location = new System.Drawing.Point(13, 148);
this.checkBoxSail.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxSail.Name = "checkBoxSail";
this.checkBoxSail.Size = new System.Drawing.Size(164, 19);
this.checkBoxSail.TabIndex = 5;
this.checkBoxSail.Text = "Признак наличия паруса";
this.checkBoxSail.UseVisualStyleBackColor = true;
//
// checkBoxFloatDetails
//
this.checkBoxFloatDetails.AutoSize = true;
this.checkBoxFloatDetails.Location = new System.Drawing.Point(13, 114);
this.checkBoxFloatDetails.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxFloatDetails.Name = "checkBoxFloatDetails";
this.checkBoxFloatDetails.Size = new System.Drawing.Size(185, 19);
this.checkBoxFloatDetails.TabIndex = 4;
this.checkBoxFloatDetails.Text = "Признак наличия поплавков";
this.checkBoxFloatDetails.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(94, 60);
this.numericUpDownWeight.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(51, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(94, 28);
this.numericUpDownSpeed.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(59, 23);
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(13, 68);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(26, 15);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(13, 36);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(59, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость";
//
// panel1
//
this.panel1.AllowDrop = true;
this.panel1.Controls.Add(this.buttonCancel);
this.panel1.Controls.Add(this.buttonOk);
this.panel1.Controls.Add(this.labelAddColor);
this.panel1.Controls.Add(this.labelBodyColor);
this.panel1.Controls.Add(this.pictureBoxObject);
this.panel1.Location = new System.Drawing.Point(560, 9);
this.panel1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(312, 263);
this.panel1.TabIndex = 0;
this.panel1.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panel1.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(175, 223);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(108, 24);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(38, 223);
this.buttonOk.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(108, 24);
this.buttonOk.TabIndex = 11;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// labelAddColor
//
this.labelAddColor.AllowDrop = true;
this.labelAddColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAddColor.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelAddColor.Location = new System.Drawing.Point(175, 22);
this.labelAddColor.Name = "labelAddColor";
this.labelAddColor.Size = new System.Drawing.Size(109, 28);
this.labelAddColor.TabIndex = 10;
this.labelAddColor.Text = "Доп. цвет";
this.labelAddColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAddColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelAddColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelBodyColor
//
this.labelBodyColor.AllowDrop = true;
this.labelBodyColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBodyColor.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelBodyColor.Location = new System.Drawing.Point(38, 22);
this.labelBodyColor.Name = "labelBodyColor";
this.labelBodyColor.Size = new System.Drawing.Size(109, 28);
this.labelBodyColor.TabIndex = 9;
this.labelBodyColor.Text = "Цвет";
this.labelBodyColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBodyColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelBodyColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(15, 58);
this.pictureBoxObject.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(282, 160);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// FormCatamaranConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 277);
this.Controls.Add(this.panel1);
this.Controls.Add(this.groupBoxParameters);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormCatamaranConfig";
this.Text = "FormShipConfig";
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private GroupBox groupBoxColor;
private Panel panelRed;
private Panel panelBlue;
private Panel panelYellow;
private Panel panelWhite;
private Panel panelGray;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelGreen;
private CheckBox checkBoxSail;
private CheckBox checkBoxFloatDetails;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panel1;
private Button buttonOk;
private Label labelAddColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,173 @@
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;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
using Catamaran.Generics;
using Catamaran.MovementStrategy;
namespace Catamaran
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormCatamaranConfig : Form
{
/// <summary>
/// Переменная-выбранный катамаран
/// </summary>
DrawningCatamaran? _catamaran = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningCatamaran>? EventAddCatamaran;
/// <summary>
/// Конструктор
/// </summary>
public FormCatamaranConfig()
{
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;
// TODO buttonCancel.Click with lambda
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать катамаран
/// </summary>
private void DrawCatamaran()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_catamaran?.SetPosition(5, 5);
_catamaran?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
internal void AddEvent(Action<DrawningCatamaran> ev)
{
if (EventAddCatamaran == null)
{
EventAddCatamaran = ev;
}
else
{
EventAddCatamaran += ev;
}
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </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) ?? false)
{
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)
{
ILogger<FormCatamaranCollection> logger = new NullLogger<FormCatamaranCollection>();
FormCatamaranCollection form = new FormCatamaranCollection(logger);
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_catamaran = new DrawningCatamaran((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_catamaran = new DrawningSailCatamaran((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxSail.Checked,
checkBoxFloatDetails.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawCatamaran();
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_catamaran == null)
return;
switch (((Label)sender).Name)
{
case "labelBodyColor":
_catamaran.SetColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAddColor":
if (!(_catamaran is DrawningSailCatamaran))
return;
(_catamaran as DrawningSailCatamaran).SetAddColor((Color)e.Data.GetData(typeof(Color)));
break;
}
DrawCatamaran();
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddCatamaran?.Invoke(_catamaran);
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

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
namespace Catamaran.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,57 @@
using Catamaran.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Catamaran
{
internal static class Program
@ -8,10 +13,31 @@ namespace Catamaran
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Catamaran());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormCatamaranCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCatamaranCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,124 @@
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(_maxCount);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый катамаран</param>
/// <returns></returns>
public bool Insert(T catamaran, IEqualityComparer<T?>? equal = null)
{
return Insert(catamaran, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="boat">Добавляемая лодка</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T catamaran, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new CatamaranNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(catamaran, equal))
throw new ArgumentException("Данный объект уже есть в коллекции");
_places.Insert(0, catamaran);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (!(position >= 0 && position < Count))
throw new CatamaranNotFoundException(position);
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
// TODO проверка позиции
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set
{
// TODO проверка позиции
// TODO проверка свободных мест в списке
// TODO вставка в список по позиции
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
return;
_places.Insert(position, value);
return;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetCatamarans(int? maxCatamarans = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxCatamarans.HasValue && i == maxCatamarans.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Catamaran.Exceptions
{
[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,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>