diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs index 2e9b21f..789f590 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs @@ -4,18 +4,26 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// Up = 1, + /// /// Вниз /// Down = 2, + /// /// Влево /// Left = 3, + /// /// Вправо /// diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs index af79ad4..cda06db 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs @@ -33,6 +33,27 @@ public class DrawningLocomotive /// private readonly int _drawningLocomotiveHeight = 40; + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLocomotiveWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningLocomotiveHeight; + + /// /// Пустой конструктор /// diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs index c9c6f40..831d23a 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs @@ -35,6 +35,8 @@ buttonRight = new Button(); buttonUp = new Button(); buttonCreateLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyLocomotive).BeginInit(); SuspendLayout(); // @@ -117,11 +119,33 @@ buttonCreateLocomotive.UseVisualStyleBackColor = true; buttonCreateLocomotive.Click += ButtonCreateLocomotive_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" }); + comboBoxStrategy.Location = new Point(637, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(151, 28); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(694, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormWarmlyLocomotive // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateLocomotive); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -144,5 +168,7 @@ private Button buttonRight; private Button buttonUp; private Button buttonCreateLocomotive; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs index 31aa6f3..9065f4e 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs @@ -1,4 +1,5 @@ using WarmlyLocomotive.Drawnings; +using WarmlyLocomotive.MovementStrategy; namespace WarmlyLocomotive; @@ -12,12 +13,18 @@ public partial class FormWarmlyLocomotive : Form /// private DrawningLocomotive? _drawningLocomotive; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// /// Конструктор формы /// public FormWarmlyLocomotive() { InitializeComponent(); + _strategy = null; } /// @@ -59,6 +66,8 @@ public partial class FormWarmlyLocomotive : Form } _drawningLocomotive.SetPictureSize(pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } @@ -111,4 +120,44 @@ public partial class FormWarmlyLocomotive : Form Draw(); } } -} + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningLocomotive == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableLocomotive(_drawningLocomotive), + pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..b70cfd2 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,140 @@ +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..1d2a1cd --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..473df0f --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,58 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Стратегия перемещения объекта в правый кран экрана +/// +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; + + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + + if (objParams == null) + { + return; + } + + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth; + + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + int diffY = objParams.ObjectMiddleVertical - FieldHeight; + + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..7c38ef0 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,58 @@ +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs new file mode 100644 index 0000000..c3522ba --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs @@ -0,0 +1,64 @@ +using WarmlyLocomotive.Drawnings; + +namespace WarmlyLocomotive.MovementStrategy; + +// +/// Класс-реализация IMoveableObject с использованием DrawningLocomotive +/// +public class MoveableLocomotive : IMoveableObject +{ + /// + /// Поле-объект класса DrawningLocomotive или его наследника + /// + private readonly DrawningLocomotive? _locomotive = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningLocomotive + public MoveableLocomotive(DrawningLocomotive locomotive) + { + _locomotive = locomotive; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_locomotive == null || _locomotive.EntityLocomotive == null || !_locomotive.GetPosX.HasValue || !_locomotive.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_locomotive.GetPosX.Value, _locomotive.GetPosY.Value, _locomotive.GetWidth, _locomotive.GetHeight); + } + } + + + public int GetStep => (int)(_locomotive?.EntityLocomotive?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_locomotive == null || _locomotive.EntityLocomotive == null) + { + return false; + } + return _locomotive.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/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..02d2563 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs @@ -0,0 +1,27 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..e29a2d6 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,73 @@ +namespace WarmlyLocomotive.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/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..26ed74c --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} \ No newline at end of file