From ec5f6e654ca1771c98791e65af77d8037b8938a6 Mon Sep 17 00:00:00 2001 From: LESN1K Date: Sun, 10 Mar 2024 13:50:57 +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 --- ProjectMonorail/FormMonorail.Designer.cs | 26 ++++ ProjectMonorail/FormMonorail.cs | 59 +++++++- .../Monorail/Drawnings/DirectionType.cs | 5 + .../Monorail/Drawnings/DrawingMonorail.cs | 23 +++ .../MovementStrategy/AbstractStrategy.cs | 133 ++++++++++++++++++ .../MovementStrategy/IMoveableObject.cs | 25 ++++ .../Monorail/MovementStrategy/MoveToCenter.cs | 52 +++++++ .../MovementStrategy/MoveToRightDownBorder.cs | 36 +++++ .../MovementStrategy/MoveableMonorail.cs | 61 ++++++++ .../MovementStrategy/MovementDirection.cs | 29 ++++ .../MovementStrategy/ObjectParameters.cs | 74 ++++++++++ .../MovementStrategy/StrategyStatus.cs | 23 +++ 12 files changed, 545 insertions(+), 1 deletion(-) create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/IMoveableObject.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToRightDownBorder.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveableMonorail.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/MovementDirection.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectMonorail/Scripts/Monorail/MovementStrategy/StrategyStatus.cs diff --git a/ProjectMonorail/FormMonorail.Designer.cs b/ProjectMonorail/FormMonorail.Designer.cs index 61d6b4e..2f42482 100644 --- a/ProjectMonorail/FormMonorail.Designer.cs +++ b/ProjectMonorail/FormMonorail.Designer.cs @@ -35,6 +35,8 @@ pictureBoxMonorail = new PictureBox(); buttonCreateModernMonorail = new Button(); buttonCreateMonorail = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit(); SuspendLayout(); // @@ -118,11 +120,33 @@ buttonCreateMonorail.UseVisualStyleBackColor = true; buttonCreateMonorail.Click += buttonCreateMonorail_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(680, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(704, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormMonorail // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(813, 474); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateMonorail); Controls.Add(buttonCreateModernMonorail); Controls.Add(buttonMove_Up); @@ -145,5 +169,7 @@ private PictureBox pictureBoxMonorail; private Button buttonCreateModernMonorail; private Button buttonCreateMonorail; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectMonorail/FormMonorail.cs b/ProjectMonorail/FormMonorail.cs index b86977a..63dc9c2 100644 --- a/ProjectMonorail/FormMonorail.cs +++ b/ProjectMonorail/FormMonorail.cs @@ -1,14 +1,30 @@ using ProjectMonorail.Scripts.Monorail.Drawnings; +using ProjectMonorail.Scripts.Monorail.MovementStrategy; namespace ProjectMonorail { + /// + /// Форма работы с объектом "Монорельс" + /// public partial class FormMonorail : Form { + /// + /// Поле-объект для прорисовки объекта + /// private DrawingMonorail? _drawningMonorail; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + /// + /// Конструктор формы + /// public FormMonorail() { InitializeComponent(); + _strategy = null; } /// @@ -72,7 +88,7 @@ namespace ProjectMonorail 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)), randomTrack, - (randomTrack? Convert.ToBoolean(random.Next(0, 2)) : true)); + (randomTrack ? Convert.ToBoolean(random.Next(0, 2)) : true)); break; default: return; @@ -80,6 +96,8 @@ namespace ProjectMonorail _drawningMonorail.SetPictureSize(pictureBoxMonorail.Width, pictureBoxMonorail.Height); _drawningMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } @@ -102,5 +120,44 @@ namespace ProjectMonorail CreateObject(nameof(DrawingMonorail)); } + /// + /// + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningMonorail == null) return; + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToRightDownBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableMonorail(_drawningMonorail), pictureBoxMonorail.Width, pictureBoxMonorail.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } } diff --git a/ProjectMonorail/Scripts/Monorail/Drawnings/DirectionType.cs b/ProjectMonorail/Scripts/Monorail/Drawnings/DirectionType.cs index 1851297..867b820 100644 --- a/ProjectMonorail/Scripts/Monorail/Drawnings/DirectionType.cs +++ b/ProjectMonorail/Scripts/Monorail/Drawnings/DirectionType.cs @@ -5,6 +5,11 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/ProjectMonorail/Scripts/Monorail/Drawnings/DrawingMonorail.cs b/ProjectMonorail/Scripts/Monorail/Drawnings/DrawingMonorail.cs index aadc1e3..11ef869 100644 --- a/ProjectMonorail/Scripts/Monorail/Drawnings/DrawingMonorail.cs +++ b/ProjectMonorail/Scripts/Monorail/Drawnings/DrawingMonorail.cs @@ -43,6 +43,29 @@ namespace ProjectMonorail.Scripts.Monorail.Drawnings /// private readonly int _drawningMonorailHeight = 40; + /// + /// Координаты X объекта + /// + public int? GetPositionX => _startPositionX; + + /// + /// Координаты Y объекта + /// + public int? GetPositionY => _startPositionY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningMonorailWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningMonorailHeight; + + /// + /// Пустой конструкотор + /// private DrawingMonorail() { _pictureWidth = null; diff --git a/ProjectMonorail/Scripts/Monorail/MovementStrategy/AbstractStrategy.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..76249ae --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,133 @@ +namespace ProjectMonorail.Scripts.Monorail.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; + } + } +} diff --git a/ProjectMonorail/Scripts/Monorail/MovementStrategy/IMoveableObject.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..40f7999 --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,25 @@ +namespace ProjectMonorail.Scripts.Monorail.MovementStrategy +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// I + public interface IMoveableObject + { + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); + } +} diff --git a/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToCenter.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..17d522f --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,52 @@ +namespace ProjectMonorail.Scripts.Monorail.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/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToRightDownBorder.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToRightDownBorder.cs new file mode 100644 index 0000000..849a140 --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveToRightDownBorder.cs @@ -0,0 +1,36 @@ +namespace ProjectMonorail.Scripts.Monorail.MovementStrategy +{ + /// + /// Стратегия перемещения объекта в левый нижний угл экрана + /// + public class MoveToRightDownBorder : 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.LeftBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + MoveRight(); + } + + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } + + } +} diff --git a/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveableMonorail.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveableMonorail.cs new file mode 100644 index 0000000..47c4e8e --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MoveableMonorail.cs @@ -0,0 +1,61 @@ +using ProjectMonorail.Scripts.Monorail.Drawnings; + +namespace ProjectMonorail.Scripts.Monorail.MovementStrategy +{ + /// + /// Класс-реализация IMoveableObject с использованием DrawingMonorail + /// + public class MoveableMonorail : IMoveableObject + { + /// + /// Поле-объект класса DrawingMonorail или его наследника + /// + private readonly DrawingMonorail _drawingMonorail; + + /// + /// Конструктор + /// + /// Объект класса DrawingMonorail + public MoveableMonorail(DrawingMonorail drawingMonorail) + { + _drawingMonorail = drawingMonorail; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_drawingMonorail == null || _drawingMonorail.EntityMonorail == null || !_drawingMonorail.GetPositionX.HasValue || !_drawingMonorail.GetPositionY.HasValue) return null; + return new ObjectParameters(_drawingMonorail.GetPositionX.Value, _drawingMonorail.GetPositionY.Value, _drawingMonorail.GetWidth, _drawingMonorail.GetHeight); + } + } + + public int GetStep => (int)(_drawingMonorail?.EntityMonorail?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_drawingMonorail == null || _drawingMonorail.EntityMonorail == null) + { + return false; + } + return _drawingMonorail.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/ProjectMonorail/Scripts/Monorail/MovementStrategy/MovementDirection.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..c03904b --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/MovementDirection.cs @@ -0,0 +1,29 @@ +namespace ProjectMonorail.Scripts.Monorail.MovementStrategy +{ + /// + /// Направление перемещения + /// + public enum MovementDirection + { + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 + + } +} diff --git a/ProjectMonorail/Scripts/Monorail/MovementStrategy/ObjectParameters.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..fb8f09b --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,74 @@ +namespace ProjectMonorail.Scripts.Monorail.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/ProjectMonorail/Scripts/Monorail/MovementStrategy/StrategyStatus.cs b/ProjectMonorail/Scripts/Monorail/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..c6a9558 --- /dev/null +++ b/ProjectMonorail/Scripts/Monorail/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,23 @@ +namespace ProjectMonorail.Scripts.Monorail.MovementStrategy +{ + /// + /// Статус выполнения операции перемещения + /// + public enum StrategyStatus + { + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish + } +} \ No newline at end of file