Вторая часть Lab02

This commit is contained in:
ivans 2024-03-13 02:37:58 +04:00
parent 2ff4ee77d3
commit a8847944db
15 changed files with 676 additions and 333 deletions

View File

@ -4,6 +4,10 @@
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknown = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -7,7 +7,7 @@ public class DrawingBasicSeaplane
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBasicSeaplane? EntityBasicSeaplane { get; private set; }
public EntityBasicSeaplane? EntityBasicSeaplane { get; protected set; }
/// <summary>
/// Ширина окна
@ -22,37 +22,76 @@ public class DrawingBasicSeaplane
/// <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>
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()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public void Init(int speed, double weight, Color bodyColor)
public DrawingBasicSeaplane(int speed, double weight, Color bodyColor) : this()
{
EntityBasicSeaplane = new EntityBasicSeaplane(speed, weight, bodyColor);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningSeaplaneWidth">Ширина прорисовки автомобиля</param>
/// <param name="drawningSeaplaneHeight">Высота прорисовки автомобиля</param>
protected DrawingBasicSeaplane(int drawningSeaplaneWidth, int drawningSeaplaneHeight) : this()
{
_drawningSeaplaneWidth = drawningSeaplaneWidth;
_drawningSeaplaneHeight = drawningSeaplaneHeight;
}
/// <summary>
@ -185,7 +224,7 @@ public class DrawingBasicSeaplane
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityBasicSeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
@ -214,12 +253,9 @@ public class DrawingBasicSeaplane
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(EntityBasicSeaplane.BodyColor);
Brush brBlack = new SolidBrush(Color.Black);
Brush brWhity = new SolidBrush(Color.GhostWhite);

View File

@ -4,45 +4,21 @@ namespace ProjectSeaplane.Drawnings;
/// <summary>
/// Отрисовка и перемещение
/// </summary>
public class DrawingSeaplane
public class DrawingSeaplane : DrawingBasicSeaplane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntitySeaplane? EntitySeaplane { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private 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>
/// Инициализация свойств
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
@ -50,223 +26,21 @@ public class DrawingSeaplane
/// <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 DrawingSeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool landingGear, bool radar) : base(155, 70)
{
EntitySeaplane = new EntitySeaplane();
EntitySeaplane.Init(speed, weight, bodyColor, additionalColor, landingGear, radar);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (_drawningSeaplaneWidth < width && _drawningSeaplaneHeight < height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null && _startPosY != null)
{
if (_startPosX + _drawningSeaplaneWidth > width)
{
_startPosX = width - (_drawningSeaplaneWidth + 1);
}
if (_startPosY + _drawningSeaplaneWidth > height)
{
_startPosY = height - (_drawningSeaplaneHeight + 1);
}
EntityBasicSeaplane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, landingGear, radar);
}
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
public override void DrawTransport(Graphics g)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
if (EntityBasicSeaplane == null || EntityBasicSeaplane is not EntitySeaplane seaplane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
_startPosX = x;
_startPosY = y;
if (_startPosX < 0)
{
_startPosX = 0;
}
if (_startPosY < 0)
{
_startPosY = 0;
}
if (_startPosX + _drawningSeaplaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningSeaplaneWidth;
}
if (_startPosY - _drawningSeaplaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningSeaplaneHeight;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntitySeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntitySeaplane.Step > 0)
{
_startPosX -= (int)EntitySeaplane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntitySeaplane.Step > 0)
{
_startPosY -= (int)EntitySeaplane.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX + (int)EntitySeaplane.Step < _pictureWidth - _drawningSeaplaneWidth)
{
_startPosX += (int)EntitySeaplane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY + (int)EntitySeaplane.Step < _pictureHeight - _drawningSeaplaneHeight)
{
_startPosY += (int)EntitySeaplane.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntitySeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush brAdditional = new SolidBrush(seaplane.AdditionalColor);
Pen penKraya = new(Color.Black, 2);
Brush additionalBrush = new SolidBrush(EntitySeaplane.AdditionalColor);
//Начинаем рисовать
//Полигон для хвоста
Point point1 = new Point(_startPosX.Value, _startPosY.Value);
Point point2 = new Point(_startPosX.Value + 35, _startPosY.Value + 35);
Point point3 = new Point(_startPosX.Value, _startPosY.Value + 35);
Point point4 = new Point(_startPosX.Value, _startPosY.Value);
Point[] Hvost =
{
point1, point2 , point3 , point4
};
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
};
//Кисти для основного цвета и дополнительного
Brush brBody = new SolidBrush(EntitySeaplane.BodyColor);
Brush brAdditional = new SolidBrush(EntitySeaplane.AdditionalColor);
Brush brWhity = new SolidBrush(Color.GhostWhite);
//Хвост
g.FillPolygon(brBody, Hvost);
//Тело
g.FillRectangle(brBody, _startPosX.Value + 30, _startPosY.Value + 30, 85, 25);
g.FillEllipse(brBody, _startPosX.Value + 45, _startPosY.Value + 30, 110, 24);
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(brAdditional, _startPosX.Value + 45, _startPosY.Value + 43, 50, 7);
//Иллюминаторы
for (int i = 0; i < 80; i += 10)
{
g.FillEllipse(brWhity, _startPosX.Value + 30 + i, _startPosY.Value + 34, 6, 6);
}
//Поплавки
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
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);
@ -275,24 +49,23 @@ public class DrawingSeaplane
g.DrawLine(penKraya, _startPosX.Value + 70, _startPosY.Value + 53, _startPosX.Value + 90, _startPosY.Value + 63);
}
if (EntitySeaplane.Radar)
//Чет надо но не понял
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);
}
else
{
}
//Пилоты
g.FillEllipse(brWhity, _startPosX.Value + 115, _startPosY.Value + 34, 20, 8);
}
}

View File

@ -26,16 +26,12 @@ public class EntityBasicSeaplane
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="landingGear">Тип "шасси"</param>
/// <param name="radar">При</param>
Random random = new();
public EntityBasicSeaplane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,21 +1,11 @@
namespace ProjectSeaplane.Entities;

namespace ProjectSeaplane.Entities;
/// <summary>
/// Класс-сущность Гидросамолета
/// Класс-сущность "Гидросамолет"
/// </summary>
public class EntitySeaplane
public class EntitySeaplane : 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>
@ -28,27 +18,21 @@ public class EntitySeaplane
/// Признак наличия радара
/// </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)
Random random = new();
public EntitySeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool landingGear, bool radar) : base(0, 0, Color.Brown)
{
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,5 @@
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.MovementStrategy;
namespace ProjectSeaplane
/// <summary>
@ -13,24 +14,29 @@ namespace ProjectSeaplane
public FormSeaplane()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingSeaplane? _drawingSeaplane;
private DrawingBasicSeaplane? _drawingBasicSeaplane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Метод прорисовки самолета
/// </summary>
private void Draw()
{
if (_drawingSeaplane == null)
if (_drawingBasicSeaplane == null)
{
return;
}
Bitmap bmp = new(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingSeaplane.DrawTransport(gr);
_drawingBasicSeaplane.DrawTransport(gr);
pictureBoxSeaplane.Image = bmp;
}
/// <summary>
@ -38,27 +44,57 @@ namespace ProjectSeaplane
/// </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):
_drawingBasicSeaplane = 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):
_drawingBasicSeaplane = 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)));
_drawingSeaplane.SetPictureSize(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
_drawingSeaplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Convert.ToBoolean(random.Next(1, 2)), Convert.ToBoolean(random.Next(1, 2)));
break;
default:
return;
}
_drawingBasicSeaplane.SetPictureSize(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
_drawingBasicSeaplane.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>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingSeaplane == null)
if (_drawingBasicSeaplane == null)
{
return;
}
@ -68,16 +104,16 @@ namespace ProjectSeaplane
switch (name)
{
case "buttonUp":
result = _drawingSeaplane.MoveTransport(DirectionType.Up);
result = _drawingBasicSeaplane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawingSeaplane.MoveTransport(DirectionType.Down);
result = _drawingBasicSeaplane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawingSeaplane.MoveTransport(DirectionType.Left);
result = _drawingBasicSeaplane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawingSeaplane.MoveTransport(DirectionType.Right);
result = _drawingBasicSeaplane.MoveTransport(DirectionType.Right);
break;
}
@ -86,7 +122,48 @@ namespace ProjectSeaplane
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingBasicSeaplane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableSeaplane(_drawingBasicSeaplane), 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,26 @@

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,14 @@
namespace ProjectSeaplane.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
throw new NotImplementedException();
}
protected override void MoveToTarget()
{
throw new NotImplementedException();
}
}

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,73 @@
using ProjectSeaplane.Drawnings;
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием Seaplane
/// </summary>
public class MoveableSeaplane : IMoveableObject
{
/// <summary>
/// Поле-объект класса Seaplane или его наследника
/// </summary>
private readonly DrawingSeaplane? _seaplane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="seaplane">Объект класса Seaplane</param>
public MoveableSeaplane(DrawingSeaplane seaplane)
{
_seaplane = seaplane;
}
/// <summary>
/// АВТОКОРРЕКЦИЯ
/// </summary>
/// <param name="drawingBasicSeaplane"></param>
public MoveableSeaplane(DrawingBasicSeaplane drawingBasicSeaplane)
{
}
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

@ -0,0 +1,31 @@

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