From d33425108d8d230135725c282ba12d8b8b5be7b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B7=D0=B0=D0=BC=D0=B0=D1=82=20=D0=98=D1=88=D1=82?= =?UTF-8?q?=D1=83=D0=B3=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 11 Mar 2024 20:00:41 +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 --- .../MotorBoat/Drawnings/DirectionType.cs | 4 + MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs | 16 +++ MotorBoat/MotorBoat/FormMotorBoat.Designer.cs | 26 ++++ MotorBoat/MotorBoat/FormMotorBoat.cs | 55 ++++++++ .../MovementStrategy/AbstractStrategy.cs | 119 ++++++++++++++++++ .../MovementStrategy/IMoveableObject.cs | 27 ++++ .../MovementStrategy/MoveToBorder.cs | 44 +++++++ .../MovementStrategy/MoveToCenter.cs | 57 +++++++++ .../MovementStrategy/MoveableBoat.cs | 59 +++++++++ .../MovementStrategy/MovementDirection.cs | 24 ++++ .../MovementStrategy/ObjectParameters.cs | 62 +++++++++ .../MovementStrategy/StrategyStatus.cs | 19 +++ 12 files changed, 512 insertions(+) create mode 100644 MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs diff --git a/MotorBoat/MotorBoat/Drawnings/DirectionType.cs b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs index 7a584f2..30bcde3 100644 --- a/MotorBoat/MotorBoat/Drawnings/DirectionType.cs +++ b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs @@ -6,6 +6,10 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs index f25e29b..ec1a9a8 100644 --- a/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs +++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs @@ -38,6 +38,22 @@ namespace MotorBoat.Drawnings /// private readonly int _drawningBoatHeight = 38; /// + /// Координата Х объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningBoatWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningBoatHeight; + /// /// Пустой конструктор /// private DrawningBoat() diff --git a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs index ff05731..961978e 100644 --- a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs +++ b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs @@ -35,6 +35,8 @@ buttonRight = new Button(); buttonUp = new Button(); buttonCreateBoat = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxMotorBoat).BeginInit(); SuspendLayout(); // @@ -117,11 +119,33 @@ buttonCreateBoat.UseVisualStyleBackColor = true; buttonCreateBoat.Click += ButtonCreateBoat_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(724, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(774, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormMotorBoat // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(861, 447); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateBoat); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -144,5 +168,7 @@ private Button buttonRight; private Button buttonUp; private Button buttonCreateBoat; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/MotorBoat/MotorBoat/FormMotorBoat.cs b/MotorBoat/MotorBoat/FormMotorBoat.cs index 8c83651..8cf446e 100644 --- a/MotorBoat/MotorBoat/FormMotorBoat.cs +++ b/MotorBoat/MotorBoat/FormMotorBoat.cs @@ -8,18 +8,30 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MotorBoat.Drawnings; +using MotorBoat.MovementStrategy; namespace MotorBoat { + /// + /// Форма работы с объектом "Моторная лодка" + /// public partial class FormMotorBoat : Form { + /// + /// Поле для прорисовки объекта + /// private DrawningBoat? _drawningBoat; /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// /// Конструктор формы /// public FormMotorBoat() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки катера @@ -56,6 +68,8 @@ namespace MotorBoat } _drawningBoat.SetPictureSize(pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height); _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } /// @@ -107,5 +121,46 @@ namespace MotorBoat Draw(); } } + + /// + /// + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningBoat == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableBoat(_drawningBoat), + pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } } diff --git a/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs b/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..934d404 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,119 @@ +namespace MotorBoat.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/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs b/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..f16a3c5 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.MovementStrategy; +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..c59364e --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.MovementStrategy; +/// +/// Стратегия перемещения объекта к краю экрана +/// +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + int diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + MoveRight(); + } + + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..5f02253 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.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(); + } + } + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs new file mode 100644 index 0000000..3bddf7c --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs @@ -0,0 +1,59 @@ +using MotorBoat.Drawnings; + +namespace MotorBoat.MovementStrategy; +/// +/// Класс-реализация IMoveableObject с использованием DrawningBoat +/// +public class MoveableBoat : IMoveableObject +{ + /// + /// Поле-объект класса DrawningBoat или его наследника + /// + private readonly DrawningBoat? _boat = null; + /// + /// Конструктор + /// + /// Объект класса DrawningBoat + public MoveableBoat(DrawningBoat boat) + { + _boat = boat; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_boat == null || _boat.EntityBoat == null || + !_boat.GetPosX.HasValue || !_boat.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_boat.GetPosX.Value, + _boat.GetPosY.Value, _boat.GetWidth, _boat.GetHeight); + } + } + public int GetStep => (int)(_boat?.EntityBoat?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_boat == null || _boat.EntityBoat == null) + { + return false; + } + return _boat.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, + }; + } +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs b/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..315da02 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs @@ -0,0 +1,24 @@ +namespace MotorBoat.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs b/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..be6318d --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,62 @@ +namespace MotorBoat.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; + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs b/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..26d73b8 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,19 @@ +namespace MotorBoat.MovementStrategy; +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +}