Добавление стратегии

This commit is contained in:
Evgehil 2024-03-03 21:39:43 +04:00
parent afb87d1e2f
commit 7a8cf90158
16 changed files with 802 additions and 139 deletions

View File

@ -4,12 +4,17 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Project_airbus; namespace Project_airbus.Drawings;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения
/// </summary> /// </summary>
public enum DirectionType public enum DirectionType
{ {
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </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.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Project_airbus; namespace Project_airbus.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности public class DrawingAirplan
/// </summary>
public class DrawingAirbus
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityAirbus? EntityAirbus { get; private set; } public EntityAirplan? EntityAirplan { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -26,42 +25,50 @@ public class DrawingAirbus
private int? _pictureHeight; private int? _pictureHeight;
/// <summary> /// <summary>
/// Левая координата прорисовки самолета(аэробуса) /// Левая координата прорисовки самолета
/// </summary> /// </summary>
private int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя координата прорисовки самолета(аэробуса) /// Верхняя координата прорисовки самолета
/// </summary> /// </summary>
private int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки самолета(аэробуса) /// Ширина прорисовки самолета
/// </summary> /// </summary>
private readonly int _drawingAirbusWidth = 130; private readonly int _drawingAirplanWidth = 130;
/// <summary> /// <summary>
/// Высота прорисовки самолета(аэробуса) /// Высота прорисовки самолета
/// </summary> /// </summary>
private readonly int _drawingAirbusHeight = 60; private readonly int _drawingAirplanHeight = 60;
/// <summary> /// <summary>
/// Инициализация свойств /// Координата X объекта
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> public int? GetPosX => _startPosX;
/// <param name="weight">Вес самолета</param>
/// <param name="bodyAirbus">Основной цвет</param> /// <summary>
/// <param name="additionalColor">Дополнительный цвет</param> /// Координата Y объекта
/// <param name="bodySection">Признак наличия отсека</param> /// </summary>
/// <param name="motor">Признак наличия дополнительных двигателей</param> public int? GetPosY => _startPosY;
public void Init(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor)
/// <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; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = 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> /// <summary>
/// Установка границ поля /// Установка границ поля
@ -79,24 +107,24 @@ public class DrawingAirbus
public bool SetPictureSize(int wigth, int height) public bool SetPictureSize(int wigth, int height)
{ {
if(wigth < _drawingAirbusWidth || height < _drawingAirbusHeight) { return false; }; if (wigth < _drawingAirplanWidth || height < _drawingAirplanHeight) { return false; };
_pictureWidth = wigth; _pictureWidth = wigth;
_pictureHeight = height; _pictureHeight = height;
if(_startPosX !=null || _startPosY != null) 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; _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; _startPosY = 0;
} }
@ -105,7 +133,6 @@ public class DrawingAirbus
} }
/// <summary> /// <summary>
/// Установка позиции /// Установка позиции
/// </summary> /// </summary>
@ -118,11 +145,11 @@ public class DrawingAirbus
return; 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; _startPosX = 0;
} }
@ -131,11 +158,11 @@ public class DrawingAirbus
_startPosX = x; _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; _startPosY = 0;
} }
@ -153,34 +180,34 @@ public class DrawingAirbus
/// <returns>true - перемещение выполнено, false - перемещение невозможно</returns> /// <returns>true - перемещение выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if (EntityAirbus == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityAirplan == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
switch (direction) switch (direction)
{ {
case DirectionType.Left: 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; return true;
case DirectionType.Right: 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; return true;
case DirectionType.Down: 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; return true;
case DirectionType.Up: //вверх case DirectionType.Up: //вверх
if (_startPosY - EntityAirbus.step > 0) if (_startPosY - EntityAirplan.step > 0)
{ {
_startPosY -= (int)EntityAirbus.step; _startPosY -= (int)EntityAirplan.step;
} }
return true; return true;
default: default:
@ -188,20 +215,17 @@ public class DrawingAirbus
} }
} }
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <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; return;
} }
Pen pen = new(Color.Black); 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); 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.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); 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> /// <summary>
/// Класс-сущность "Самолет(Aэробус)" /// Класс-сущность "Самолет(Aэробус)"
/// </summary> /// </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>
/// Дополнительный цвет(для опциональных элементов) /// Дополнительный цвет(для опциональных элементов)
/// </summary> /// </summary>
@ -35,11 +20,6 @@ public class EntityAirbus
/// </summary> /// </summary>
public bool Motor { get; private set; } public bool Motor { get; private set; }
/// <summary>
/// Шаг перемещения самолета(аэробуса)
/// </summary>
public double step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// Инициализация полей объекта-класса самолета(аэробуса) /// Инициализация полей объекта-класса самолета(аэробуса)
/// </summary> /// </summary>
@ -48,16 +28,11 @@ public class EntityAirbus
/// <param name="bodyAirbus">Основной цвет</param> /// <param name="bodyAirbus">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodySection">ПРизнак наличия отсека</param> /// <param name="bodySection">ПРизнак наличия отсека</param>
/// <param name="motor">ПРизнак наличия дополнительных двигателей</param> /// <param name="motor">Признак наличия дополнительных двигателей</param>
public void Init(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor) 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; AdditionalColor = additionalColor;
BodySection = bodySection; BodySection = bodySection;
Motor = motor; 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(); buttonRight = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonCreateAirplan = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirbus).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirbus).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -53,9 +56,9 @@
buttonCreateAirbus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateAirbus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirbus.Location = new Point(12, 330); buttonCreateAirbus.Location = new Point(12, 330);
buttonCreateAirbus.Name = "buttonCreateAirbus"; buttonCreateAirbus.Name = "buttonCreateAirbus";
buttonCreateAirbus.Size = new Size(79, 43); buttonCreateAirbus.Size = new Size(162, 43);
buttonCreateAirbus.TabIndex = 7; buttonCreateAirbus.TabIndex = 7;
buttonCreateAirbus.Text = "Создать"; buttonCreateAirbus.Text = "Создать аэробас";
buttonCreateAirbus.UseVisualStyleBackColor = true; buttonCreateAirbus.UseVisualStyleBackColor = true;
buttonCreateAirbus.Click += ButtonCreateAirbus_Click; buttonCreateAirbus.Click += ButtonCreateAirbus_Click;
// //
@ -111,11 +114,45 @@
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_CLick; 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 // FormAirbus
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(752, 385); ClientSize = new Size(752, 385);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateAirplan);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonRight); Controls.Add(buttonRight);
@ -136,5 +173,8 @@
private Button buttonRight; private Button buttonRight;
private Button buttonLeft; private Button buttonLeft;
private Button buttonDown; 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 public partial class FormAirbus : Form
{ {
/// <summary> /// <summary>
/// Поле-объект для прорисовки поля /// Поле-объект для прорисовки поля
/// </summary> /// </summary>
private DrawingAirbus? _drawingAirbus; private DrawingAirplan? _drawingAirplan;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary> /// <summary>
/// Конструктор формы /// Конструктор формы
@ -14,6 +24,7 @@
public FormAirbus() public FormAirbus()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
@ -21,39 +32,60 @@
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawingAirbus == null) if (_drawingAirplan == null)
{ {
return; return;
} }
Bitmap bmb = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height); Bitmap bmb = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmb); Graphics gr = Graphics.FromImage(bmb);
_drawingAirbus.DrawTransport(gr); _drawingAirplan.DrawTransport(gr);
pictureBoxAirbus.Image = bmb; pictureBoxAirbus.Image = bmb;
} }
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Создать" /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="type">Тип создаваемого объекта</param>
/// <param name="e"></param> private void CreateObject(string type)
private void ButtonCreateAirbus_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawingAirbus = new DrawingAirbus(); switch (type)
_drawingAirbus.Init(random.Next(100, 300), random.Next(1000, 3000), {
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)),
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))); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawingAirbus.SetPictureSize(pictureBoxAirbus.Width, pictureBoxAirbus.Height); break;
_drawingAirbus.SetPosition(random.Next(10, 100), random.Next(10, 100)); default:
return;
Draw();
} }
_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) => CreateObject(nameof(DrawingAirbus));
/// <summary>
/// Обработка нажатия кнопки "Создать Самолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirplan_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingAirplan));
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
@ -62,7 +94,7 @@
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_CLick(object sender, EventArgs e) private void ButtonMove_CLick(object sender, EventArgs e)
{ {
if (_drawingAirbus == null) if (_drawingAirplan == null)
{ {
return; return;
} }
@ -71,20 +103,65 @@
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawingAirbus.MoveTransport(DirectionType.Up); result = _drawingAirplan.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawingAirbus.MoveTransport(DirectionType.Down); result = _drawingAirplan.MoveTransport(DirectionType.Down);
break; break;
case "buttonRight": case "buttonRight":
result = _drawingAirbus.MoveTransport(DirectionType.Right); result = _drawingAirplan.MoveTransport(DirectionType.Right);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawingAirbus.MoveTransport(DirectionType.Left); result = _drawingAirplan.MoveTransport(DirectionType.Left);
break; break;
} }
Draw(); 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> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework> <TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>