From 7a8cf901586dd9f51dfdc632000ebdc94b536d23 Mon Sep 17 00:00:00 2001 From: Evgehil Date: Sun, 3 Mar 2024 21:39:43 +0400 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=D1=82=D1=80=D0=B0=D1=82=D0=B5=D0=B3?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ => Drawings}/DirectionType.cs | 7 +- .../Project_airbus/Drawings/DrawingAirbus.cs | 57 ++++++ .../DrawingAirplan.cs} | 164 +++++++++--------- .../{ => Entities}/EntityAirbus.cs | 35 +--- .../Project_airbus/Entities/EntityAirplan.cs | 46 +++++ .../Project_airbus/FormAirbus.Designer.cs | 44 ++++- Project_airbus/Project_airbus/FormAirbus.cs | 129 +++++++++++--- .../MovementStrategy/AbstractStrategy.cs | 139 +++++++++++++++ .../MovementStrategy/IMoveableObject.cs | 24 +++ .../MovementStrategy/MoveToBorder.cs | 55 ++++++ .../MovementStrategy/MoveToCenter.cs | 54 ++++++ .../MovementStrategy/MoveableAirplan.cs | 64 +++++++ .../MovementStrategy/MovementDirection.cs | 27 +++ .../MovementStrategy/ObjectParameters.cs | 72 ++++++++ .../MovementStrategy/StrategyStatus.cs | 22 +++ .../Project_airbus/Project_airbus.csproj | 2 +- 16 files changed, 802 insertions(+), 139 deletions(-) rename Project_airbus/Project_airbus/{ => Drawings}/DirectionType.cs (79%) create mode 100644 Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs rename Project_airbus/Project_airbus/{DrawingAirbus.cs => Drawings/DrawingAirplan.cs} (57%) rename Project_airbus/Project_airbus/{ => Entities}/EntityAirbus.cs (58%) create mode 100644 Project_airbus/Project_airbus/Entities/EntityAirplan.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/AbstractStrategy.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/IMoveableObject.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/MoveToBorder.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/MoveToCenter.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/MoveableAirplan.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/MovementDirection.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/ObjectParameters.cs create mode 100644 Project_airbus/Project_airbus/MovementStrategy/StrategyStatus.cs diff --git a/Project_airbus/Project_airbus/DirectionType.cs b/Project_airbus/Project_airbus/Drawings/DirectionType.cs similarity index 79% rename from Project_airbus/Project_airbus/DirectionType.cs rename to Project_airbus/Project_airbus/Drawings/DirectionType.cs index 8737ecc..bd57169 100644 --- a/Project_airbus/Project_airbus/DirectionType.cs +++ b/Project_airbus/Project_airbus/Drawings/DirectionType.cs @@ -4,12 +4,17 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Project_airbus; +namespace Project_airbus.Drawings; /// /// Направление перемещения /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs b/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs new file mode 100644 index 0000000..dc37a0a --- /dev/null +++ b/Project_airbus/Project_airbus/Drawings/DrawingAirbus.cs @@ -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; + +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawingAirbus : DrawingAirplan +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес самолета + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия отсека + /// Признак наличия дополнительных двигателей + 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); + } + } + +} + diff --git a/Project_airbus/Project_airbus/DrawingAirbus.cs b/Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs similarity index 57% rename from Project_airbus/Project_airbus/DrawingAirbus.cs rename to Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs index 20e7e1d..48537d1 100644 --- a/Project_airbus/Project_airbus/DrawingAirbus.cs +++ b/Project_airbus/Project_airbus/Drawings/DrawingAirplan.cs @@ -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; -/// -/// Класс, отвечающий за прорисовку и перемещение объекта-сущности -/// -public class DrawingAirbus +namespace Project_airbus.Drawings; + +public class DrawingAirplan { /// /// Класс-сущность /// - public EntityAirbus? EntityAirbus { get; private set; } + public EntityAirplan? EntityAirplan { get; protected set; } /// /// Ширина окна @@ -26,42 +25,50 @@ public class DrawingAirbus private int? _pictureHeight; /// - /// Левая координата прорисовки самолета(аэробуса) + /// Левая координата прорисовки самолета /// - private int? _startPosX; + protected int? _startPosX; /// - /// Верхняя координата прорисовки самолета(аэробуса) + /// Верхняя координата прорисовки самолета /// - private int? _startPosY; + protected int? _startPosY; /// - /// Ширина прорисовки самолета(аэробуса) + /// Ширина прорисовки самолета /// - private readonly int _drawingAirbusWidth = 130; + private readonly int _drawingAirplanWidth = 130; /// - /// Высота прорисовки самолета(аэробуса) + /// Высота прорисовки самолета /// - private readonly int _drawingAirbusHeight = 60; - - - - + private readonly int _drawingAirplanHeight = 60; /// - /// Инициализация свойств + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта /// - /// Скорость - /// Вес самолета - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия отсека - /// Признак наличия дополнительных двигателей - public void Init(int speed, double weight, Color bodyAirbus, Color additionalColor, bool bodySection, bool motor) + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawingAirplanWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawingAirplanHeight; + + /// + /// Пустой конструктор + /// + 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 } + /// + /// Конструктор + /// + /// Скорость + /// Вес самолета + /// Основной цвет + public DrawingAirplan(int speed, double weight, Color bodyAirbus) : this() + { + EntityAirplan = new EntityAirplan(speed, weight, bodyAirbus); + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки самолета + /// Высота прорисовки самолета + protected DrawingAirplan(int drawingAirbusWidth, int drawingAirbusHeight) : this() + { + _drawingAirplanWidth = drawingAirbusWidth; + _drawingAirplanHeight = drawingAirbusHeight; + } /// /// Установка границ поля @@ -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; - - } + } /// /// Установка позиции @@ -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 /// true - перемещение выполнено, false - перемещение невозможно 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 } } - /// /// Прорисовка объекта /// /// - 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); - } - } } - - diff --git a/Project_airbus/Project_airbus/EntityAirbus.cs b/Project_airbus/Project_airbus/Entities/EntityAirbus.cs similarity index 58% rename from Project_airbus/Project_airbus/EntityAirbus.cs rename to Project_airbus/Project_airbus/Entities/EntityAirbus.cs index 9cf108a..9b5057a 100644 --- a/Project_airbus/Project_airbus/EntityAirbus.cs +++ b/Project_airbus/Project_airbus/Entities/EntityAirbus.cs @@ -1,25 +1,10 @@ -namespace Project_airbus; +namespace Project_airbus.Entities; /// /// Класс-сущность "Самолет(Aэробус)" /// -public class EntityAirbus +public class EntityAirbus : EntityAirplan { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес самолета - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyAirbus { get; private set; } - /// /// Дополнительный цвет(для опциональных элементов) /// @@ -28,18 +13,13 @@ public class EntityAirbus /// /// Признак(опция) наличия отсека /// - public bool BodySection { get; private set; } + public bool BodySection { get; private set; } /// /// ПРизнак(опция) наличия дополнительных двигателей /// public bool Motor { get; private set; } - /// - /// Шаг перемещения самолета(аэробуса) - /// - public double step => Speed * 100 / Weight; - /// /// Инициализация полей объекта-класса самолета(аэробуса) /// @@ -48,16 +28,11 @@ public class EntityAirbus /// Основной цвет /// Дополнительный цвет /// ПРизнак наличия отсека - /// ПРизнак наличия дополнительных двигателей - 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; BodySection = bodySection; Motor = motor; } - - } diff --git a/Project_airbus/Project_airbus/Entities/EntityAirplan.cs b/Project_airbus/Project_airbus/Entities/EntityAirplan.cs new file mode 100644 index 0000000..f42c811 --- /dev/null +++ b/Project_airbus/Project_airbus/Entities/EntityAirplan.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Project_airbus.Entities; + +/// +/// Класс-сущность "Самолёт" +/// +public class EntityAirplan +{ + /// + /// Скорость + /// + public int Speed { get; private set; } + + /// + /// Вес самолета + /// + public double Weight { get; private set; } + + /// + /// Основной цвет + /// + public Color BodyAirbus { get; private set; } + + /// + /// Шаг перемещения самолета(аэробуса) + /// + public double step => Speed * 100 / Weight; + + /// + /// Конструктор сущности + /// + /// Скорость + /// Вес самолета + /// Основной цвет + public EntityAirplan(int speed, double weight, Color bodyAirbus) + { + Speed = speed; + Weight = weight; + BodyAirbus = bodyAirbus; + } +} diff --git a/Project_airbus/Project_airbus/FormAirbus.Designer.cs b/Project_airbus/Project_airbus/FormAirbus.Designer.cs index 26dab4f..728b269 100644 --- a/Project_airbus/Project_airbus/FormAirbus.Designer.cs +++ b/Project_airbus/Project_airbus/FormAirbus.Designer.cs @@ -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; } } \ No newline at end of file diff --git a/Project_airbus/Project_airbus/FormAirbus.cs b/Project_airbus/Project_airbus/FormAirbus.cs index 0f83d04..26d7aa6 100644 --- a/Project_airbus/Project_airbus/FormAirbus.cs +++ b/Project_airbus/Project_airbus/FormAirbus.cs @@ -1,12 +1,22 @@ -namespace Project_airbus +using Project_airbus.Drawings; +using Project_airbus.MovementStrategy; + +namespace Project_airbus { + /// + /// Форма работы с объектом "Аэробас" + /// public partial class FormAirbus : Form { - /// /// Поле-объект для прорисовки поля /// - private DrawingAirbus? _drawingAirbus; + private DrawingAirplan? _drawingAirplan; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы @@ -14,6 +24,7 @@ public FormAirbus() { InitializeComponent(); + _strategy = null; } /// @@ -21,39 +32,60 @@ /// 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; } - - /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + 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(); + } + + /// + /// Обработка нажатия кнопки "Создать Аэробас" /// /// /// - 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(); - - } + /// + /// Обработка нажатия кнопки "Создать Самолёт" + /// + /// + /// + private void buttonCreateAirplan_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingAirplan)); /// /// Перемещение объекта по форме (нажатие кнопок навигации) @@ -62,7 +94,7 @@ /// 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(); } + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + 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; + } + } } + } + diff --git a/Project_airbus/Project_airbus/MovementStrategy/AbstractStrategy.cs b/Project_airbus/Project_airbus/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..49807e4 --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,139 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Класс-стратегия перемещения объекта +/// +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotInit; + + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + + /// + /// Статус перемещения + /// + public StrategyStatus GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + 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; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (IsTargetDestinaion()) + { + _state = StrategyStatus.Finish; + return; + } + + MoveToTarget(); + } + + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(MovementDirection.Right); + + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(MovementDirection.Up); + + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveDown() => MoveTo(MovementDirection.Down); + + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} \ No newline at end of file diff --git a/Project_airbus/Project_airbus/MovementStrategy/IMoveableObject.cs b/Project_airbus/Project_airbus/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..03a54a6 --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} \ No newline at end of file diff --git a/Project_airbus/Project_airbus/MovementStrategy/MoveToBorder.cs b/Project_airbus/Project_airbus/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..1df757b --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,55 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Стратегия перемещения к краю экрана +/// +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder <= FieldWidth && + objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder <= FieldHeight && + objParams.DownBorder + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + var diffX = objParams.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(); + } + } + } + } +} \ No newline at end of file diff --git a/Project_airbus/Project_airbus/MovementStrategy/MoveToCenter.cs b/Project_airbus/Project_airbus/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..d655559 --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,54 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Стратегия перемещения объекта в центр экрана +/// +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(); + } + } + } +} diff --git a/Project_airbus/Project_airbus/MovementStrategy/MoveableAirplan.cs b/Project_airbus/Project_airbus/MovementStrategy/MoveableAirplan.cs new file mode 100644 index 0000000..035e933 --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/MoveableAirplan.cs @@ -0,0 +1,64 @@ +using Project_airbus.Drawings; + +namespace Project_airbus.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием DrawningAirplan +/// +public class MoveableAirplan : IMoveableObject +{ + /// + /// Поле-объект класса DrawningAirplan или его наследника + /// + private readonly DrawingAirplan? _airplan = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningAirplan + 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)); + } + + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + 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, + }; + } +} \ No newline at end of file diff --git a/Project_airbus/Project_airbus/MovementStrategy/MovementDirection.cs b/Project_airbus/Project_airbus/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..a677f4f --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/MovementDirection.cs @@ -0,0 +1,27 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} \ No newline at end of file diff --git a/Project_airbus/Project_airbus/MovementStrategy/ObjectParameters.cs b/Project_airbus/Project_airbus/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..8ad3f70 --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,72 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Параметры-координаты объекта +/// +public class ObjectParameters +{ + /// + /// Координата X + /// + private readonly int _x; + + /// + /// Координата Y + /// + private readonly int _y; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/Project_airbus/Project_airbus/MovementStrategy/StrategyStatus.cs b/Project_airbus/Project_airbus/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..c09a24a --- /dev/null +++ b/Project_airbus/Project_airbus/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace Project_airbus.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} \ No newline at end of file diff --git a/Project_airbus/Project_airbus/Project_airbus.csproj b/Project_airbus/Project_airbus/Project_airbus.csproj index fc9a993..e0361e4 100644 --- a/Project_airbus/Project_airbus/Project_airbus.csproj +++ b/Project_airbus/Project_airbus/Project_airbus.csproj @@ -2,7 +2,7 @@ WinExe - net7.0-windows + net6.0-windows enable true enable -- 2.25.1