ISEbd-11_Sharonov_I.A.Lab02_Simple #2

Closed
357Sharonov wants to merge 4 commits from Lab02 into Lab01
16 changed files with 847 additions and 170 deletions

View File

@ -0,0 +1,34 @@
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknown = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4,
}

View File

@ -1,13 +1,13 @@
namespace ProjectSeaplane;
/// <summary>
/// Отрисовка и перемещение
/// </summary>
public class DrawingSeaplane
using ProjectSeaplane.Entities;
namespace ProjectSeaplane.Drawnings;
public class DrawingBasicSeaplane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntitySeaplane? EntitySeaplane { get; private set; }
/// Класс-сущность
/// </summary>
public EntityBasicSeaplane? EntityBasicSeaplane { get; protected set; }
Review

Имя элемента проекта не соответствует указанному в задании

Имя элемента проекта не соответствует указанному в задании
/// <summary>
/// Ширина окна
@ -22,41 +22,77 @@ public class DrawingSeaplane
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawningSeaplaneWidth = 155;
private readonly int _drawningSeaplaneWidth = 170;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawningSeaplaneHeight = 70;
private readonly int _drawningSeaplaneHeight = 90;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="landingGear">Тип "шасси" (0 - поплавки, 1 - лодочный тип)</param>
/// <param name="radar">Признак наличия радара </param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool landingGear, bool radar)
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningSeaplaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningSeaplaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawingBasicSeaplane()
{
EntitySeaplane = new EntitySeaplane();
EntitySeaplane.Init(speed, weight, bodyColor, additionalColor, landingGear, radar);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawingBasicSeaplane(int speed, double weight, Color bodyColor) : this()
{
EntityBasicSeaplane = new EntityBasicSeaplane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningSeaplaneWidth">Ширина прорисовки автомобиля</param>
/// <param name="drawningSeaplaneHeight">Высота прорисовки автомобиля</param>
protected DrawingBasicSeaplane(int drawningSeaplaneWidth, int drawningSeaplaneHeight) : this()
{
_drawningSeaplaneWidth = drawningSeaplaneWidth;
_drawningSeaplaneHeight = drawningSeaplaneHeight;
}
/// <summary>
/// Установка границ поля
@ -78,14 +114,14 @@ public class DrawingSeaplane
if (_startPosX + _drawningSeaplaneWidth > width)
{
_startPosX = width - (_drawningSeaplaneWidth + 1);
}
if (_startPosY + _drawningSeaplaneWidth > height)
{
_startPosY = height - (_drawningSeaplaneHeight + 1);
}
}
@ -142,7 +178,7 @@ public class DrawingSeaplane
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntitySeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityBasicSeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -151,32 +187,32 @@ public class DrawingSeaplane
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntitySeaplane.Step > 0)
if (_startPosX.Value - EntityBasicSeaplane.Step > 0)
{
_startPosX -= (int)EntitySeaplane.Step;
_startPosX -= (int)EntityBasicSeaplane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntitySeaplane.Step > 0)
if (_startPosY.Value - EntityBasicSeaplane.Step > 0)
{
_startPosY -= (int)EntitySeaplane.Step;
_startPosY -= (int)EntityBasicSeaplane.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX + (int)EntitySeaplane.Step < _pictureWidth - _drawningSeaplaneWidth)
if (_startPosX + (int)EntityBasicSeaplane.Step < _pictureWidth - _drawningSeaplaneWidth)
{
_startPosX += (int)EntitySeaplane.Step;
_startPosX += (int)EntityBasicSeaplane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY + (int)EntitySeaplane.Step < _pictureHeight - _drawningSeaplaneHeight)
if (_startPosY + (int)EntityBasicSeaplane.Step < _pictureHeight - _drawningSeaplaneHeight)
{
_startPosY += (int)EntitySeaplane.Step;
_startPosY += (int)EntityBasicSeaplane.Step;
}
return true;
default:
@ -188,16 +224,16 @@ public class DrawingSeaplane
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntitySeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityBasicSeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Pen penKraya = new(Color.Black, 2);
Brush additionalBrush = new SolidBrush(EntitySeaplane.AdditionalColor);
//Начинаем рисовать
@ -217,14 +253,11 @@ public class DrawingSeaplane
Point point6 = new Point(_startPosX.Value + 45, _startPosY.Value + 30);
Point point7 = new Point(_startPosX.Value + 55, _startPosY.Value + 30);
Point point8 = new Point(_startPosX.Value + 50, _startPosY.Value + 22);
Point[] Radar =
{
point5, point6 , point7 , point8
};
//Кисти для основного цвета и дополнительного
Brush brBody = new SolidBrush(EntitySeaplane.BodyColor);
Brush brAdditional = new SolidBrush(EntitySeaplane.AdditionalColor);
//Кисти для основного цвета
Brush brBody = new SolidBrush(EntityBasicSeaplane.BodyColor);
Brush brBlack = new SolidBrush(Color.Black);
Brush brWhity = new SolidBrush(Color.GhostWhite);
//Хвост
g.FillPolygon(brBody, Hvost);
@ -239,12 +272,12 @@ public class DrawingSeaplane
g.FillEllipse(brBody, _startPosX.Value - 5, _startPosY.Value + 30, 100, 24);
g.DrawEllipse(penKraya, _startPosX.Value, _startPosY.Value + 27, 17, 6);
g.FillEllipse(brAdditional, _startPosX.Value, _startPosY.Value + 27, 17, 6);
g.FillEllipse(brBlack, _startPosX.Value, _startPosY.Value + 27, 17, 6);
//Крыло
g.FillEllipse(brAdditional, _startPosX.Value + 45, _startPosY.Value + 43, 50, 7);
g.FillEllipse(brBlack, _startPosX.Value + 45, _startPosY.Value + 43, 50, 7);
//Иллюминаторы
@ -256,41 +289,9 @@ public class DrawingSeaplane
}
//Поплавки
if (EntitySeaplane.LandingGear)
{
g.FillEllipse(brAdditional, _startPosX.Value + 60, _startPosY.Value + 50, 20, 7);
g.DrawLine(penKraya, _startPosX.Value + 70, _startPosY.Value + 48, _startPosX.Value + 70, _startPosY.Value + 52);
}
else
{
g.FillEllipse(brAdditional, _startPosX.Value + 60, _startPosY.Value + 60, 70, 10);
g.FillEllipse(brAdditional, _startPosX.Value + 10, _startPosY.Value + 60, 20, 10);
g.DrawLine(penKraya, _startPosX.Value + 20, _startPosY.Value + 53, _startPosX.Value + 20, _startPosY.Value + 63);
g.DrawLine(penKraya, _startPosX.Value + 110, _startPosY.Value + 53, _startPosX.Value + 90, _startPosY.Value + 63);
g.DrawLine(penKraya, _startPosX.Value + 70, _startPosY.Value + 53, _startPosX.Value + 90, _startPosY.Value + 63);
}
if (EntitySeaplane.Radar)
{
g.FillEllipse(brAdditional, _startPosX.Value + 30, _startPosY.Value + 12, 40, 15);
g.FillPolygon(brAdditional, Radar);
}
else
{
}
//Пилоты
g.FillEllipse(brWhity, _startPosX.Value + 115, _startPosY.Value + 34, 20, 8);
}
}

View File

@ -0,0 +1,71 @@
using ProjectSeaplane.Entities;
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// Отрисовка и перемещение
/// </summary>
public class DrawingSeaplane : DrawingBasicSeaplane
{
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawningSeaplaneWidth = 170;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawningSeaplaneHeight = 90;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="landingGear">Тип "шасси" (0 - поплавки, 1 - лодочный тип)</param>
/// <param name="radar">Признак наличия радара </param>
public DrawingSeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool landingGear, bool radar) : base(155, 70)
{
EntityBasicSeaplane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, landingGear, radar);
}
public override void DrawTransport(Graphics g)
{
if (EntityBasicSeaplane == null || EntityBasicSeaplane is not EntitySeaplane seaplane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Brush brAdditional = new SolidBrush(seaplane.AdditionalColor);
Pen penKraya = new(Color.Black, 2);
if (seaplane.LandingGear)
{
g.FillEllipse(brAdditional, _startPosX.Value + 60, _startPosY.Value + 60, 70, 10);
g.FillEllipse(brAdditional, _startPosX.Value + 10, _startPosY.Value + 60, 20, 10);
g.DrawLine(penKraya, _startPosX.Value + 20, _startPosY.Value + 53, _startPosX.Value + 20, _startPosY.Value + 63);
g.DrawLine(penKraya, _startPosX.Value + 110, _startPosY.Value + 53, _startPosX.Value + 90, _startPosY.Value + 63);
g.DrawLine(penKraya, _startPosX.Value + 70, _startPosY.Value + 53, _startPosX.Value + 90, _startPosY.Value + 63);
}
//Чет надо но не понял
base.DrawTransport(g);
//also
if (seaplane.Radar)
{
Point point5 = new Point(_startPosX.Value + 50, _startPosY.Value + 22);
Point point6 = new Point(_startPosX.Value + 45, _startPosY.Value + 30);
Point point7 = new Point(_startPosX.Value + 55, _startPosY.Value + 30);
Point point8 = new Point(_startPosX.Value + 50, _startPosY.Value + 22);
Point[] Radar =
{
point5, point6 , point7 , point8
};
g.FillEllipse(brAdditional, _startPosX.Value + 30, _startPosY.Value + 12, 40, 15);
g.FillPolygon(brAdditional, Radar);
}
}
}

View File

@ -0,0 +1,37 @@
namespace ProjectSeaplane.Entities;
/// <summary>
/// Класс-сущность "Простой Гидросамолет"
/// </summary>
public class EntityBasicSeaplane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Расстояние шага передвижения
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityBasicSeaplane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,37 @@

namespace ProjectSeaplane.Entities;
/// <summary>
/// Класс-сущность "Гидросамолет"
/// </summary>
public class EntitySeaplane : EntityBasicSeaplane
{
/// <summary>
/// Дополнительный (для опциональных частей)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Тип "шасси" (0 - лодочный, 1 - поплавковый)
/// </summary>
public bool LandingGear { get; private set; }
/// <summary>
/// Признак наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="landingGear">Тип "шасси"</param>
/// <param name="radar">При</param>
public EntitySeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool landingGear, bool radar) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
LandingGear = landingGear;
Radar = radar;
}
}

View File

@ -1,54 +0,0 @@
namespace ProjectSeaplane;
/// <summary>
/// Класс-сущность Гидросамолета
/// </summary>
public class EntitySeaplane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный (для опциональных частей)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Тип "шасси" (0 - лодочный, 1 - поплавковый)
/// </summary>
public bool LandingGear { get; private set; }
/// <summary>
/// Признак наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Расстояние шага передвижения
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
///
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="landingGear">Тип "шасси"</param>
/// <param name="radar">При</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool landingGear, bool radar)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
LandingGear = landingGear;
Radar = radar;
}
}

View File

@ -29,11 +29,14 @@
private void InitializeComponent()
{
pictureBoxSeaplane = new PictureBox();
buttonCreate = new Button();
ButtonCreateSeaplane = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonUp = new Button();
buttonRight = new Button();
ButtonCreateBasicSeaplane = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSeaplane).BeginInit();
SuspendLayout();
//
@ -42,20 +45,20 @@
pictureBoxSeaplane.Dock = DockStyle.Fill;
pictureBoxSeaplane.Location = new Point(0, 0);
pictureBoxSeaplane.Name = "pictureBoxSeaplane";
pictureBoxSeaplane.Size = new Size(590, 379);
pictureBoxSeaplane.Size = new Size(757, 379);
pictureBoxSeaplane.TabIndex = 0;
pictureBoxSeaplane.TabStop = false;
//
// buttonCreate
// ButtonCreateSeaplane
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 349);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
ButtonCreateSeaplane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateSeaplane.Location = new Point(12, 349);
ButtonCreateSeaplane.Name = "ButtonCreateSeaplane";
ButtonCreateSeaplane.Size = new Size(256, 23);
ButtonCreateSeaplane.TabIndex = 1;
ButtonCreateSeaplane.Text = "Создать гидросамолет с обвесами";
ButtonCreateSeaplane.UseVisualStyleBackColor = true;
ButtonCreateSeaplane.Click += ButtonCreateSeaplane_Click;
//
// buttonLeft
//
@ -63,7 +66,7 @@
buttonLeft.BackColor = Color.Snow;
buttonLeft.BackgroundImage = Properties.Resources.arrow11;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(465, 337);
buttonLeft.Location = new Point(632, 337);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
@ -76,7 +79,7 @@
buttonDown.BackColor = Color.Snow;
buttonDown.BackgroundImage = Properties.Resources.arrow4;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(506, 337);
buttonDown.Location = new Point(673, 337);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 4;
@ -89,7 +92,7 @@
buttonUp.BackColor = Color.Snow;
buttonUp.BackgroundImage = Properties.Resources.arrow2;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(506, 297);
buttonUp.Location = new Point(673, 297);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 5;
@ -102,23 +105,57 @@
buttonRight.BackColor = Color.Snow;
buttonRight.BackgroundImage = Properties.Resources.arrow3;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(547, 337);
buttonRight.Location = new Point(714, 337);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 7;
buttonRight.UseVisualStyleBackColor = false;
buttonRight.Click += ButtonMove_Click;
//
// ButtonCreateBasicSeaplane
//
ButtonCreateBasicSeaplane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateBasicSeaplane.Location = new Point(288, 349);
ButtonCreateBasicSeaplane.Name = "ButtonCreateBasicSeaplane";
ButtonCreateBasicSeaplane.Size = new Size(234, 23);
ButtonCreateBasicSeaplane.TabIndex = 8;
ButtonCreateBasicSeaplane.Text = "Создать гидросамолет без обвесов";
ButtonCreateBasicSeaplane.UseVisualStyleBackColor = true;
ButtonCreateBasicSeaplane.Click += ButtonCreateBasicSeaplane_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(632, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(113, 23);
comboBoxStrategy.TabIndex = 9;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(673, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(72, 27);
buttonStrategyStep.TabIndex = 10;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormSeaplane
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(590, 379);
ClientSize = new Size(757, 379);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(ButtonCreateBasicSeaplane);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(ButtonCreateSeaplane);
Controls.Add(pictureBoxSeaplane);
Name = "FormSeaplane";
Text = "Гидросамолет";
@ -129,10 +166,13 @@
#endregion
private PictureBox pictureBoxSeaplane;
private Button buttonCreate;
private Button ButtonCreateSeaplane;
private Button buttonLeft;
private Button buttonDown;
private Button buttonUp;
private Button buttonRight;
private Button ButtonCreateBasicSeaplane;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,7 @@
namespace ProjectSeaplane
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.MovementStrategy;
namespace ProjectSeaplane
/// <summary>
/// Форма работы с объектом "Гидросамолет"
/// </summary>
@ -11,11 +14,16 @@
public FormSeaplane()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingSeaplane? _drawingSeaplane;
private DrawingBasicSeaplane? _drawingSeaplane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Метод прорисовки самолета
/// </summary>
@ -36,20 +44,50 @@
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
private void CreateObject(string type)
{
Random random = new();
_drawingSeaplane = new DrawingSeaplane();
_drawingSeaplane.Init(random.Next(100, 300), random.Next(1000, 3000),
switch (type)
{
case nameof(DrawingBasicSeaplane):
_drawingSeaplane = new DrawingBasicSeaplane(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawingSeaplane):
_drawingSeaplane = new DrawingSeaplane(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)));
break;
default:
return;
}
_drawingSeaplane.SetPictureSize(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
_drawingSeaplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать гидросамолет с обвесами"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateSeaplane_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingSeaplane));
}
/// <summary>
/// Обработка нажатия кнопки "Создать гидросамолет без обвесов"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateBasicSeaplane_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingBasicSeaplane));
}
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
@ -84,7 +122,48 @@
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingSeaplane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableSeaplane(_drawingSeaplane), pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,141 @@

namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus 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 = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,24 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,52 @@
namespace ProjectSeaplane.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? 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()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
if (diffX < 0)
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldWidth;
if (Math.Abs(diffY) > GetStep())
{
if (diffX > 0)
{
MoveUp();
}
if (diffY < 0)
{
MoveDown();
}
}
}
}

View File

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

View File

@ -0,0 +1,66 @@
using ProjectSeaplane.Drawnings;
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием Seaplane
/// </summary>
public class MoveableSeaplane : IMoveableObject
{
/// <summary>
/// Поле-объект класса Seaplane или его наследника
/// </summary>
private readonly DrawingBasicSeaplane? _seaplane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="seaplane">Объект класса Seaplane</param>
public MoveableSeaplane(DrawingBasicSeaplane Seaplane)
{
_seaplane = Seaplane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_seaplane == null || _seaplane.EntityBasicSeaplane == null || !_seaplane.GetPosX.HasValue || !_seaplane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_seaplane.GetPosX.Value, _seaplane.GetPosY.Value, _seaplane.GetWidth, _seaplane.GetHeight);
}
}
public int GetStep => (int)(_seaplane?.EntityBasicSeaplane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_seaplane == null || _seaplane.EntityBasicSeaplane == null)
{
return false;
}
return _seaplane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknown,
};
}
}

View File

@ -1,30 +1,31 @@
namespace ProjectSeaplane;

namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
/// Вправо
/// </summary>
Right = 4,
}

View File

@ -0,0 +1,72 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
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

@ -0,0 +1,22 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}