Plbd-11_Gorskov_E.M._LabWork02_Simple #2

Closed
Evgeniu wants to merge 1 commits from LabWork02 into LabWork01
16 changed files with 802 additions and 139 deletions

View File

@ -4,12 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_airbus;
namespace Project_airbus.Drawings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_airbus.Entities;
namespace Project_airbus.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingAirbus : DrawingAirplan
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyAirbus">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodySection">Признак наличия отсека</param>
/// <param name="motor">Признак наличия дополнительных двигателей</param>
public DrawingAirbus(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor) : base(130, 60)
{
EntityAirplan = new EntityAirbus(speed, weight, bodyAirbus, additionalColor, bodySection, motor);
}
public override void DrawTransport(Graphics g)
{
if (EntityAirplan == null || EntityAirplan is not EntityAirbus airbus || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(airbus.AdditionalColor);
base.DrawTransport(g);
//Дополнительный отсек сверху
if (airbus.BodySection)
{
g.DrawLine(pen, _startPosX.Value + 25, _startPosY.Value + 20, _startPosX.Value + 50, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 50, _startPosY.Value + 12, _startPosX.Value + 70, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 70, _startPosY.Value + 12, _startPosX.Value + 80, _startPosY.Value + 20);
}
// Двигатели под крылом
if (airbus.Motor)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 31, _startPosY.Value + 32, 12, 4);
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 32, 12, 4);
}
}
}

View File

@ -1,19 +1,18 @@
using System;
using Project_airbus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_airbus;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingAirbus
namespace Project_airbus.Drawings;
public class DrawingAirplan
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirbus? EntityAirbus { get; private set; }
public EntityAirplan? EntityAirplan { get; protected set; }
/// <summary>
/// Ширина окна
@ -26,42 +25,50 @@ public class DrawingAirbus
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолета(аэробуса)
/// Левая координата прорисовки самолета
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки самолета(аэробуса)
/// Верхняя координата прорисовки самолета
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки самолета(аэробуса)
/// Ширина прорисовки самолета
/// </summary>
private readonly int _drawingAirbusWidth = 130;
private readonly int _drawingAirplanWidth = 130;
/// <summary>
/// Высота прорисовки самолета(аэробуса)
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawingAirbusHeight = 60;
private readonly int _drawingAirplanHeight = 60;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyAirbus">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodySection">Признак наличия отсека</param>
/// <param name="motor">Признак наличия дополнительных двигателей</param>
public void Init(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor)
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawingAirplanWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingAirplanHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawingAirplan()
{
EntityAirbus = new EntityAirbus();
EntityAirbus.Init(speed, weight, bodyAirbus, additionalColor, bodySection, motor);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
@ -69,6 +76,27 @@ public class DrawingAirbus
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyAirbus">Основной цвет</param>
public DrawingAirplan(int speed, double weight, Color bodyAirbus) : this()
{
EntityAirplan = new EntityAirplan(speed, weight, bodyAirbus);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawingAirbusWidth">Ширина прорисовки самолета</param>
/// <param name="drawingAirbusHeight">Высота прорисовки самолета</param>
protected DrawingAirplan(int drawingAirbusWidth, int drawingAirbusHeight) : this()
{
_drawingAirplanWidth = drawingAirbusWidth;
_drawingAirplanHeight = drawingAirbusHeight;
}
/// <summary>
/// Установка границ поля
@ -79,32 +107,31 @@ public class DrawingAirbus
public bool SetPictureSize(int wigth, int height)
{
if(wigth < _drawingAirbusWidth || height < _drawingAirbusHeight) { return false; };
_pictureWidth = wigth;
_pictureHeight = height;
if(_startPosX !=null || _startPosY != null)
if (wigth < _drawingAirplanWidth || height < _drawingAirplanHeight) { return false; };
_pictureWidth = wigth;
_pictureHeight = height;
if (_startPosX != null || _startPosY != null)
{
if(_startPosX + _drawingAirbusWidth > _pictureWidth)
if (_startPosX + _drawingAirplanWidth > _pictureWidth)
{
_startPosX = -_drawingAirbusWidth + _pictureWidth;
_startPosX = -_drawingAirplanWidth + _pictureWidth;
}
else if(_startPosX < 0)
else if (_startPosX < 0)
{
_startPosX = 0;
}
if(_startPosY + _drawingAirbusHeight > _pictureHeight)
if (_startPosY + _drawingAirplanHeight > _pictureHeight)
{
_startPosY = - _drawingAirbusHeight + _pictureHeight;
_startPosY = -_drawingAirplanHeight + _pictureHeight;
}
else if(_startPosY < 0)
else if (_startPosY < 0)
{
_startPosY = 0;
}
}
return true;
}
}
/// <summary>
/// Установка позиции
@ -118,11 +145,11 @@ public class DrawingAirbus
return;
}
if (x+_drawingAirbusWidth > _pictureWidth)
if (x + _drawingAirplanWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawingAirbusWidth;
_startPosX = _pictureWidth - _drawingAirplanWidth;
}
else if(x < 0)
else if (x < 0)
{
_startPosX = 0;
}
@ -131,11 +158,11 @@ public class DrawingAirbus
_startPosX = x;
}
if(y + _drawingAirbusHeight > _pictureHeight)
if (y + _drawingAirplanHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawingAirbusHeight;
_startPosY = _pictureHeight - _drawingAirplanHeight;
}
else if(y < 0)
else if (y < 0)
{
_startPosY = 0;
}
@ -153,34 +180,34 @@ public class DrawingAirbus
/// <returns>true - перемещение выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityAirbus == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityAirplan == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityAirbus.step > 0)
if (_startPosX.Value - EntityAirplan.step > 0)
{
_startPosX -= (int)EntityAirbus.step;
_startPosX -= (int)EntityAirplan.step;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + _drawingAirbusWidth + EntityAirbus.step < _pictureWidth)
if (_startPosX.Value + _drawingAirplanWidth + EntityAirplan.step < _pictureWidth)
{
_startPosX += (int)EntityAirbus.step;
_startPosX += (int)EntityAirplan.step;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + _drawingAirbusHeight + EntityAirbus.step < _pictureHeight)
if (_startPosY.Value + _drawingAirplanHeight + EntityAirplan.step < _pictureHeight)
{
_startPosY += (int)EntityAirbus.step;
_startPosY += (int)EntityAirplan.step;
}
return true;
case DirectionType.Up: //вверх
if (_startPosY - EntityAirbus.step > 0)
if (_startPosY - EntityAirplan.step > 0)
{
_startPosY -= (int)EntityAirbus.step;
_startPosY -= (int)EntityAirplan.step;
}
return true;
default:
@ -188,20 +215,17 @@ public class DrawingAirbus
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityAirbus == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityAirplan == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Pen additionalpen = new(EntityAirbus.AdditionalColor);
Brush additionalBrush = new SolidBrush(EntityAirbus.AdditionalColor);
//корпус
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 20, 100, 20);
@ -230,23 +254,5 @@ public class DrawingAirbus
//переднее шасси
g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 40, _startPosX.Value + 90, _startPosY.Value + 45);
g.FillEllipse(darkBrush, _startPosX.Value + 87, _startPosY.Value + 45, 6, 6);
//Дополнительный отсек сверху
if (EntityAirbus.BodySection)
{
g.DrawLine(additionalpen, _startPosX.Value + 25, _startPosY.Value + 20, _startPosX.Value + 50, _startPosY.Value + 12);
g.DrawLine(additionalpen, _startPosX.Value + 50, _startPosY.Value + 12, _startPosX.Value + 70, _startPosY.Value + 12);
g.DrawLine(additionalpen, _startPosX.Value + 70, _startPosY.Value + 12, _startPosX.Value + 80, _startPosY.Value + 20);
}
// Двигатели под крылом
if (EntityAirbus.Motor)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 31, _startPosY.Value + 32, 12, 4);
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 32, 12, 4);
}
}
}

View File

@ -1,25 +1,10 @@
namespace Project_airbus;
namespace Project_airbus.Entities;
/// <summary>
/// Класс-сущность "Самолет(Aэробус)"
/// </summary>
public class EntityAirbus
public class EntityAirbus : EntityAirplan
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес самолета
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyAirbus { get; private set; }
/// <summary>
/// Дополнительный цвет(для опциональных элементов)
/// </summary>
@ -28,18 +13,13 @@ public class EntityAirbus
/// <summary>
/// Признак(опция) наличия отсека
/// </summary>
public bool BodySection { get; private set; }
public bool BodySection { get; private set; }
/// <summary>
/// ПРизнак(опция) наличия дополнительных двигателей
/// </summary>
public bool Motor { get; private set; }
/// <summary>
/// Шаг перемещения самолета(аэробуса)
/// </summary>
public double step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса самолета(аэробуса)
/// </summary>
@ -48,16 +28,11 @@ public class EntityAirbus
/// <param name="bodyAirbus">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodySection">ПРизнак наличия отсека</param>
/// <param name="motor">ПРизнак наличия дополнительных двигателей</param>
public void Init(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor)
/// <param name="motor">Признак наличия дополнительных двигателей</param>
public EntityAirbus(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor) :base(speed, weight, bodyAirbus)
{
Speed = speed;
Weight = weight;
BodyAirbus = bodyAirbus;
AdditionalColor = additionalColor;
BodySection = bodySection;
Motor = motor;
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_airbus.Entities;
/// <summary>
/// Класс-сущность "Самолёт"
/// </summary>
public class EntityAirplan
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес самолета
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyAirbus { get; private set; }
/// <summary>
/// Шаг перемещения самолета(аэробуса)
/// </summary>
public double step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyAirbus">Основной цвет</param>
public EntityAirplan(int speed, double weight, Color bodyAirbus)
{
Speed = speed;
Weight = weight;
BodyAirbus = bodyAirbus;
}
}

View File

@ -35,6 +35,9 @@
buttonRight = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonCreateAirplan = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirbus).BeginInit();
SuspendLayout();
//
@ -53,9 +56,9 @@
buttonCreateAirbus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirbus.Location = new Point(12, 330);
buttonCreateAirbus.Name = "buttonCreateAirbus";
buttonCreateAirbus.Size = new Size(79, 43);
buttonCreateAirbus.Size = new Size(162, 43);
buttonCreateAirbus.TabIndex = 7;
buttonCreateAirbus.Text = "Создать";
buttonCreateAirbus.Text = "Создать аэробас";
buttonCreateAirbus.UseVisualStyleBackColor = true;
buttonCreateAirbus.Click += ButtonCreateAirbus_Click;
//
@ -111,11 +114,45 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_CLick;
//
// buttonCreateAirplan
//
buttonCreateAirplan.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirplan.Location = new Point(198, 330);
buttonCreateAirplan.Name = "buttonCreateAirplan";
buttonCreateAirplan.Size = new Size(162, 43);
buttonCreateAirplan.TabIndex = 12;
buttonCreateAirplan.Text = "Создать самолёт";
buttonCreateAirplan.UseVisualStyleBackColor = true;
buttonCreateAirplan.Click += buttonCreateAirplan_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(612, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(128, 28);
comboBoxStrategy.TabIndex = 13;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(647, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(92, 30);
buttonStrategyStep.TabIndex = 14;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormAirbus
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(752, 385);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateAirplan);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonRight);
@ -136,5 +173,8 @@
private Button buttonRight;
private Button buttonLeft;
private Button buttonDown;
private Button buttonCreateAirplan;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,12 +1,22 @@
namespace Project_airbus
using Project_airbus.Drawings;
using Project_airbus.MovementStrategy;
namespace Project_airbus
{
/// <summary>
/// Форма работы с объектом "Аэробас"
/// </summary>
public partial class FormAirbus : Form
{
/// <summary>
/// Поле-объект для прорисовки поля
/// </summary>
private DrawingAirbus? _drawingAirbus;
private DrawingAirplan? _drawingAirplan;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
@ -14,6 +24,7 @@
public FormAirbus()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -21,39 +32,60 @@
/// </summary>
private void Draw()
{
if (_drawingAirbus == null)
if (_drawingAirplan == null)
{
return;
}
Bitmap bmb = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmb);
_drawingAirbus.DrawTransport(gr);
_drawingAirplan.DrawTransport(gr);
pictureBoxAirbus.Image = bmb;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawingAirplan):
_drawingAirplan = new DrawingAirplan(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(DrawingAirbus):
_drawingAirplan = new DrawingAirbus(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;
}
_drawingAirplan.SetPictureSize(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawingAirplan.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 ButtonCreateAirbus_Click(object sender, EventArgs e)
{
Random random = new();
_drawingAirbus = new DrawingAirbus();
_drawingAirbus.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)));
_drawingAirbus.SetPictureSize(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawingAirbus.SetPosition(random.Next(10, 100), random.Next(10, 100));
private void ButtonCreateAirbus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingAirbus));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать Самолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirplan_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingAirplan));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
@ -62,7 +94,7 @@
/// <param name="e"></param>
private void ButtonMove_CLick(object sender, EventArgs e)
{
if (_drawingAirbus == null)
if (_drawingAirplan == null)
{
return;
}
@ -71,20 +103,65 @@
switch (name)
{
case "buttonUp":
result = _drawingAirbus.MoveTransport(DirectionType.Up);
result = _drawingAirplan.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawingAirbus.MoveTransport(DirectionType.Down);
result = _drawingAirplan.MoveTransport(DirectionType.Down);
break;
case "buttonRight":
result = _drawingAirbus.MoveTransport(DirectionType.Right);
result = _drawingAirplan.MoveTransport(DirectionType.Right);
break;
case "buttonLeft":
result = _drawingAirbus.MoveTransport(DirectionType.Left);
result = _drawingAirplan.MoveTransport(DirectionType.Left);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingAirplan == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableAirplan(_drawingAirplan), pictureBoxAirbus.Width, pictureBoxAirbus.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,139 @@
namespace Project_airbus.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 Project_airbus.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,55 @@
namespace Project_airbus.MovementStrategy;
/// <summary>
/// Стратегия перемещения к краю экрана
/// </summary>
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.ObjectMiddleHorizontal - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,54 @@
namespace Project_airbus.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,64 @@
using Project_airbus.Drawings;
namespace Project_airbus.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningAirplan
/// </summary>
public class MoveableAirplan : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningAirplan или его наследника
/// </summary>
private readonly DrawingAirplan? _airplan = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="airplan">Объект класса DrawningAirplan</param>
public MoveableAirplan(DrawingAirplan airplan)
{
_airplan = airplan;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_airplan == null || _airplan.EntityAirplan == null || !_airplan.GetPosX.HasValue || !_airplan.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_airplan.GetPosX.Value, _airplan.GetPosY.Value, _airplan.GetWidth, _airplan.GetHeight);
}
}
public int GetStep => (int)(_airplan?.EntityAirplan?.step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_airplan == null || _airplan.EntityAirplan == null)
{
return false;
}
return _airplan.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.Unknow,
};
}
}

View File

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

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>