diff --git a/Excavator/Excavator/Drawnings/DirectionType.cs b/Excavator/Excavator/Drawnings/DirectionType.cs index 5343884..5fbc009 100644 --- a/Excavator/Excavator/Drawnings/DirectionType.cs +++ b/Excavator/Excavator/Drawnings/DirectionType.cs @@ -5,6 +5,10 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/Excavator/Excavator/Drawnings/DrawningTrackedVehicle.cs b/Excavator/Excavator/Drawnings/DrawningTrackedVehicle.cs index e5f6f3d..9da69cc 100644 --- a/Excavator/Excavator/Drawnings/DrawningTrackedVehicle.cs +++ b/Excavator/Excavator/Drawnings/DrawningTrackedVehicle.cs @@ -45,6 +45,27 @@ public class DrawningTrackedVehicle /// Высота прорисовки экскаватора /// private readonly int _drawningExcavatorHeight = 126; + + + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningExcavatorWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningExcavatorHeight; /// /// Пустой конструктор /// diff --git a/Excavator/Excavator/FormExcavator.Designer.cs b/Excavator/Excavator/FormExcavator.Designer.cs index 2d58d5a..f4bcc9d 100644 --- a/Excavator/Excavator/FormExcavator.Designer.cs +++ b/Excavator/Excavator/FormExcavator.Designer.cs @@ -35,6 +35,8 @@ buttonUp = new Button(); buttonDown = new Button(); buttonCreateTrackedVehicle = new Button(); + ComboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit(); SuspendLayout(); // @@ -46,6 +48,7 @@ pictureBoxExcavator.Size = new Size(824, 407); pictureBoxExcavator.TabIndex = 0; pictureBoxExcavator.TabStop = false; + // // buttonCreateExcavator // @@ -117,11 +120,33 @@ buttonCreateTrackedVehicle.UseVisualStyleBackColor = true; buttonCreateTrackedVehicle.Click += buttonCreateTrackedVehicle_Click; // + // ComboBoxStrategy + // + ComboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + ComboBoxStrategy.FormattingEnabled = true; + ComboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + ComboBoxStrategy.Location = new Point(661, 12); + ComboBoxStrategy.Name = "ComboBoxStrategy"; + ComboBoxStrategy.Size = new Size(151, 28); + ComboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(710, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(102, 27); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormExcavator // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(824, 407); + Controls.Add(buttonStrategyStep); + Controls.Add(ComboBoxStrategy); Controls.Add(buttonCreateTrackedVehicle); Controls.Add(buttonDown); Controls.Add(buttonUp); @@ -144,5 +169,7 @@ private Button buttonUp; private Button buttonDown; private Button buttonCreateTrackedVehicle; + private ComboBox ComboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/Excavator/Excavator/FormExcavator.cs b/Excavator/Excavator/FormExcavator.cs index 10a5607..9631d6b 100644 --- a/Excavator/Excavator/FormExcavator.cs +++ b/Excavator/Excavator/FormExcavator.cs @@ -1,4 +1,5 @@ using Excavator.Drawnings; +using Excavator.MovementStrategy; namespace Excavator; @@ -11,7 +12,10 @@ public partial class FormExcavator : Form /// Поле-объект для прорисовки объекта /// private DrawningTrackedVehicle? _drawningTrackedVehicle; - + /// + ///Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы @@ -19,6 +23,7 @@ public partial class FormExcavator : Form public FormExcavator() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки экскаватора @@ -62,7 +67,8 @@ public partial class FormExcavator : Form _drawningTrackedVehicle.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height); _drawningTrackedVehicle.SetPosition(random.Next(0, 100), random.Next(0, 100)); - + _strategy = null; + ComboBoxStrategy.Enabled = true; Draw(); } @@ -121,6 +127,51 @@ public partial class FormExcavator : Form } } - + + + + /// + /// + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningTrackedVehicle == null) + { + return; + } + + if (ComboBoxStrategy.Enabled) + { + _strategy = ComboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTrackedVehicle(_drawningTrackedVehicle), pictureBoxExcavator.Width, pictureBoxExcavator.Height); + } + + if (_strategy == null) + { + return; + } + + ComboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + ComboBoxStrategy.Enabled = true; + _strategy = null; + } + } } + diff --git a/Excavator/Excavator/MovementStrategy/AbstractStrategy.cs b/Excavator/Excavator/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..59084f4 --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,139 @@ +namespace Excavator.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/Excavator/Excavator/MovementStrategy/IMoveableObject.cs b/Excavator/Excavator/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..e8fb9bd --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace Excavator.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/Excavator/Excavator/MovementStrategy/MoveToBorder.cs b/Excavator/Excavator/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..673df83 --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,51 @@ +namespace Excavator.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/Excavator/Excavator/MovementStrategy/MoveToCenter.cs b/Excavator/Excavator/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..d51bdf3 --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,53 @@ +namespace Excavator.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/Excavator/Excavator/MovementStrategy/MoveableTrackedVehicle.cs b/Excavator/Excavator/MovementStrategy/MoveableTrackedVehicle.cs new file mode 100644 index 0000000..1b010bb --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/MoveableTrackedVehicle.cs @@ -0,0 +1,65 @@ +using Excavator.Drawnings; + + +namespace Excavator.MovementStrategy; +/// +/// Класс-реализация IMoveableObject с использованием DrawningTrackedVehicle +/// +public class MoveableTrackedVehicle : IMoveableObject + +{ + /// + /// Поле-объект класса DrawningTrackedVehicle или его наследника + /// + private readonly DrawningTrackedVehicle? _trackedvehicle = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningCar + public MoveableTrackedVehicle(DrawningTrackedVehicle trackedvehicle) + { + _trackedvehicle = trackedvehicle; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_trackedvehicle == null || _trackedvehicle.EntityTrackedVehicle == null || !_trackedvehicle.GetPosX.HasValue || !_trackedvehicle.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_trackedvehicle.GetPosX.Value, _trackedvehicle.GetPosY.Value, _trackedvehicle.GetWidth, _trackedvehicle.GetHeight); + } + } + + public int GetStep => (int)(_trackedvehicle?.EntityTrackedVehicle?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_trackedvehicle == null || _trackedvehicle.EntityTrackedVehicle == null) + { + return false; + } + + return _trackedvehicle.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/Excavator/Excavator/MovementStrategy/MovementDirection.cs b/Excavator/Excavator/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..14fbd09 --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/MovementDirection.cs @@ -0,0 +1,23 @@ +namespace Excavator.MovementStrategy; +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/Excavator/Excavator/MovementStrategy/ObjectParameters.cs b/Excavator/Excavator/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..24a352d --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,72 @@ +namespace Excavator.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/Excavator/Excavator/MovementStrategy/StrategyStatus.cs b/Excavator/Excavator/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..e4fbb6c --- /dev/null +++ b/Excavator/Excavator/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,19 @@ +namespace Excavator.MovementStrategy; +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Всё готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +}