diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs index 44c4914..28e2f32 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs @@ -8,6 +8,11 @@ namespace ProjectElectricLocomotive.Drawnings; public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs index a5afd18..f48b627 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -37,13 +37,35 @@ public class DrawningLocomotive /// /// Ширина прорисовки локомотива /// - private readonly int _drawningElectricLocomotiveWidth = 83; + private readonly int _drawningLocomotiveWidth = 83; /// /// Высота прорисовки локомотива /// - private readonly int _drawningElectricLocomotiveHeight = 40; + private readonly int _drawningLocomotiveHeight = 40; + + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLocomotiveWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningLocomotiveHeight; + + /// /// Пустой конструктор @@ -70,12 +92,12 @@ public class DrawningLocomotive /// /// Конструктор для наследников /// - /// Ширина прорисовки локомотива - /// Высота прорисовки локомотива - protected DrawningLocomotive(int drawningElectricLocomotiveWidth, int drawningElectricLocomotiveHeight) : this() + /// Ширина прорисовки локомотива + /// Высота прорисовки локомотива + protected DrawningLocomotive(int drawningLocomotiveWidth, int drawningLocomotiveHeight) : this() { - _drawningElectricLocomotiveWidth = drawningElectricLocomotiveWidth; - _drawningElectricLocomotiveHeight = drawningElectricLocomotiveHeight; + _drawningLocomotiveWidth = drawningLocomotiveWidth; + _drawningLocomotiveHeight = drawningLocomotiveHeight; } /// @@ -86,19 +108,19 @@ public class DrawningLocomotive /// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах public bool SetPictureSize(int width, int height) { - if (_drawningElectricLocomotiveHeight > height || _drawningElectricLocomotiveWidth > width) + if (_drawningLocomotiveHeight > height || _drawningLocomotiveWidth > width) { return false; } _pictureWidth = width; _pictureHeight = height; - if (_startPosY.HasValue && _startPosY + _drawningElectricLocomotiveHeight < _pictureHeight) + if (_startPosY.HasValue && _startPosY + _drawningLocomotiveHeight < _pictureHeight) { - _startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; + _startPosY = _pictureHeight - _drawningLocomotiveHeight; } - if (_startPosX.HasValue && _startPosX + _drawningElectricLocomotiveWidth < _pictureWidth) + if (_startPosX.HasValue && _startPosX + _drawningLocomotiveWidth < _pictureWidth) { - _startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; + _startPosX = _pictureWidth - _drawningLocomotiveWidth; } return true; } @@ -121,13 +143,13 @@ public class DrawningLocomotive - if (_drawningElectricLocomotiveHeight + y > _pictureHeight) + if (_drawningLocomotiveHeight + y > _pictureHeight) { - _startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; + _startPosY = _pictureHeight - _drawningLocomotiveHeight; } - if (_drawningElectricLocomotiveWidth + x > _pictureWidth) + if (_drawningLocomotiveWidth + x > _pictureWidth) { - _startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; + _startPosX = _pictureWidth - _drawningLocomotiveWidth; } if (x < 0) { @@ -172,14 +194,14 @@ public class DrawningLocomotive return true; //вправо case DirectionType.Right: - if (_startPosX.Value + _drawningElectricLocomotiveWidth + EntityLocomotive.Step < _pictureWidth) + if (_startPosX.Value + _drawningLocomotiveWidth + EntityLocomotive.Step < _pictureWidth) { _startPosX += (int)EntityLocomotive.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + _drawningElectricLocomotiveHeight + EntityLocomotive.Step < _pictureHeight) + if (_startPosY.Value + _drawningLocomotiveHeight + EntityLocomotive.Step < _pictureHeight) { _startPosY += (int)EntityLocomotive.Step; } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs index dcf94c2..b758749 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs @@ -35,6 +35,8 @@ buttonRight = new Button(); buttonUp = new Button(); buttonCreateLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); SuspendLayout(); // @@ -121,11 +123,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(733, 24); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(764, 72); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(90, 33); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormElectricLocomotive // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(866, 479); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateLocomotive); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -148,5 +172,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/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs index 52bc870..305f806 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs @@ -1,4 +1,5 @@ using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.MovementStrategy; using System; using System.Collections.Generic; using System.ComponentModel; @@ -13,11 +14,20 @@ namespace ProjectElectricLocomotive; public partial class FormElectricLocomotive : Form { + /// + /// Поле-объект для прорисовки объекта + /// private DrawningLocomotive? _drawningLocomotive; + private AbstractStrategy? _strategy; + + /// + /// Конструктор формы + /// public FormElectricLocomotive() { InitializeComponent(); + _strategy = null; } /// @@ -36,6 +46,10 @@ public partial class FormElectricLocomotive : Form pictureBoxElectricLocomotive.Image = bmp; } + /// + /// Создание объекта класса-перемещения + /// + /// private void CreateObject(string type) { Random random = new(); @@ -55,7 +69,9 @@ public partial class FormElectricLocomotive : Form return; } _drawningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); - _drawningLocomotive.SetPosition(random.Next(10,100), random.Next(10,100)); + _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } @@ -112,7 +128,37 @@ public partial class FormElectricLocomotive : Form } } - + /// + /// + /// + /// + /// + 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), pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + } + if (_strategy == null) return; + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..3b2a3d2 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/IMoveableObject.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..209f702 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public interface IMoveableObject +{ + /// + /// Получение координат объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// True - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovableLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovableLocomotive.cs new file mode 100644 index 0000000..d45a96a --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovableLocomotive.cs @@ -0,0 +1,67 @@ +using ProjectElectricLocomotive.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject c использованием 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, + }; + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..d4f70a9 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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()) + { + if (diffX > 0) MoveLeft(); + else MoveRight(); + } + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) MoveUp(); + else MoveDown(); + } + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..7d3da73 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..1d38253 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вверх + /// + Down = 2, + + /// + /// Вверх + /// + Left = 3, + + /// + /// Вверх + /// + Right = 4, + +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..5b3cc06 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..19f2183 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public enum StrategyStatus +{ + /// + /// Всё готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + + /// + /// Завершено + /// + Finish +}