diff --git a/HoistingCrane/HoistingCrane/Drawning/DirectionType.cs b/HoistingCrane/HoistingCrane/Drawning/DirectionType.cs index 2643ba7..a9f0e52 100644 --- a/HoistingCrane/HoistingCrane/Drawning/DirectionType.cs +++ b/HoistingCrane/HoistingCrane/Drawning/DirectionType.cs @@ -1,10 +1,14 @@ namespace HoistingCrane.Drawning; -public enum DirectionType : byte //Создали не класс(class), а перечисление (enum) +public enum DirectionType //Создали не класс(class), а перечисление (enum) { //Перечислим основные траектории движния нашего автомобиля. Сразу же зададим значения. /// - /// Вверх1 + /// Неизвестное направление + /// + Unknow = -1, + /// + /// Вверх /// Up = 1, /// diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs index fd24ee4..f949f68 100644 --- a/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs @@ -5,10 +5,6 @@ namespace HoistingCrane.Drawning; //В данном классе мы будем думать над полем игры, размерами персонажа, размерами объектов и т.д. public class DrawningHoistingCrane : DrawningTrackedVehicle { - /// - /// Класс - сущность - /// - public EntityHoistingCrane? EntityHoistingCrane { get; private set; } /// /// Ширина окна @@ -24,6 +20,7 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle /// Ширина прорисовки автомобиля /// private readonly int _drawingCarWidth = 115; + /// /// Высота прорисовки автомобиля /// @@ -42,10 +39,16 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle } - + //Метод изменения траектории движения из дочернего класса - - + public void CreateMovement() + { + if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return false; + } + EntityTrackedVehicle.MoveTransport(direction); + } /// /// Метод отрисовки объекта diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs index a7e9b85..aa2709b 100644 --- a/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs @@ -7,10 +7,6 @@ namespace HoistingCrane.Drawning { - - - - /// /// Класс - сущность /// @@ -44,6 +40,11 @@ namespace HoistingCrane.Drawning /// private readonly int _drawingCarHeight = 63; + public int? GetPosX => _startPosX; + public int? GetPosY => _startPosY; + public int GetWidth => _drawingCarWidth; + public int GetHeight => _drawingCarHeight; + /// @@ -164,7 +165,7 @@ namespace HoistingCrane.Drawning /// /// /// - public bool MoveTransport(DirectionType direction) + protected bool MoveTransport(DirectionType direction) { if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue) { diff --git a/HoistingCrane/HoistingCrane/FormHoistingCrane.Designer.cs b/HoistingCrane/HoistingCrane/FormHoistingCrane.Designer.cs index 09f3617..d6cea84 100644 --- a/HoistingCrane/HoistingCrane/FormHoistingCrane.Designer.cs +++ b/HoistingCrane/HoistingCrane/FormHoistingCrane.Designer.cs @@ -31,6 +31,8 @@ namespace HoistingCrane ButtonUp = new Button(); ButtonDown = new Button(); buttonCreateTrackedVehicle = new Button(); + comboStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxHoistingCrane).BeginInit(); SuspendLayout(); // @@ -109,15 +111,37 @@ namespace HoistingCrane buttonCreateTrackedVehicle.Name = "buttonCreateTrackedVehicle"; buttonCreateTrackedVehicle.Size = new Size(194, 23); buttonCreateTrackedVehicle.TabIndex = 6; - buttonCreateTrackedVehicle.Text = "Создать бронебойную машину"; + buttonCreateTrackedVehicle.Text = "Создать гусеничную машину"; buttonCreateTrackedVehicle.UseVisualStyleBackColor = true; buttonCreateTrackedVehicle.Click += buttonCreateTrackedVehicle_Click; // + // comboStrategy + // + comboStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboStrategy.FormattingEnabled = true; + comboStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboStrategy.Location = new Point(697, 42); + comboStrategy.Name = "comboStrategy"; + comboStrategy.Size = new Size(121, 23); + comboStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(743, 71); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormHoistingCrane // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(818, 515); + Controls.Add(buttonStrategyStep); + Controls.Add(comboStrategy); Controls.Add(buttonCreateTrackedVehicle); Controls.Add(ButtonDown); Controls.Add(ButtonUp); @@ -140,5 +164,7 @@ namespace HoistingCrane private Button ButtonUp; private Button ButtonDown; private Button buttonCreateTrackedVehicle; + private ComboBox comboStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/FormHoistingCrane.cs b/HoistingCrane/HoistingCrane/FormHoistingCrane.cs index 6c45118..43b8875 100644 --- a/HoistingCrane/HoistingCrane/FormHoistingCrane.cs +++ b/HoistingCrane/HoistingCrane/FormHoistingCrane.cs @@ -1,4 +1,5 @@ using HoistingCrane.Drawning; +using HoistingCrane.MovementStrategy; namespace HoistingCrane { @@ -6,10 +7,11 @@ namespace HoistingCrane { private DrawningTrackedVehicle? _drawning; - + private AbstractStrategy? _abstractStrategy; public FormHoistingCrane() { InitializeComponent(); + _abstractStrategy = null; } private void Draw() @@ -50,19 +52,21 @@ namespace HoistingCrane { case nameof(DrawningHoistingCrane): - _drawning = new DrawningHoistingCrane(rand.Next(100, 300),rand.Next(1000, 3000),Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)), + _drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)), Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)), true, true); - break; + break; case nameof(DrawningTrackedVehicle): _drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256))); - break; + break; default: return; } _drawning.SetPictureSize(pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height); _drawning.SetPosition(rand.Next(0, 100), rand.Next(0, 100)); + + comboStrategy.Enabled = true; Draw(); } @@ -98,6 +102,42 @@ namespace HoistingCrane } - + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawning == null) + { + return; + } + + if (comboStrategy.Enabled) + { + _abstractStrategy = comboStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_abstractStrategy == null) + { + return; + } + _abstractStrategy.SetData(new MoveableCar(_drawning), pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height); + } + + if (_abstractStrategy == null) + { + return; + } + + comboStrategy.Enabled = false; + _abstractStrategy.MakeStep(); + Draw(); + + if (_abstractStrategy.GetStatus() == StrategyStatus.Finish) + { + comboStrategy.Enabled = true; + _abstractStrategy = null; + } + } } } diff --git a/HoistingCrane/HoistingCrane/MovementStrategy/AbstractStrategy.cs b/HoistingCrane/HoistingCrane/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..43e18e9 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,139 @@ +namespace HoistingCrane.MovementStrategy +{ + public abstract class AbstractStrategy + { + /// + /// Перемещаемый объект + /// + private IMoveableObjects? _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(IMoveableObjects 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 (IsTargetDestination()) + { + _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 IsTargetDestination(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (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/HoistingCrane/HoistingCrane/MovementStrategy/IMoveableObjects.cs b/HoistingCrane/HoistingCrane/MovementStrategy/IMoveableObjects.cs new file mode 100644 index 0000000..9ce6732 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/IMoveableObjects.cs @@ -0,0 +1,24 @@ +namespace HoistingCrane.MovementStrategy +{ + public interface IMoveableObjects + { + /// + /// Получение позиции объекта + /// + ObjectParameters? GetObjectPosition { get; } + + + /// + /// Получение шага объекта + /// + int GetStep { get; } + + + /// + /// Попытка переместить объект в указанном направлении + /// + /// направление + /// + bool TryMoveObject(MovementDirection direction); + } +} diff --git a/HoistingCrane/HoistingCrane/MovementStrategy/MoveToBorder.cs b/HoistingCrane/HoistingCrane/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..99cb56b --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,51 @@ +namespace HoistingCrane.MovementStrategy +{ + public class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestination() + { + 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/HoistingCrane/HoistingCrane/MovementStrategy/MoveToCenter.cs b/HoistingCrane/HoistingCrane/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..aea7661 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,52 @@ +namespace HoistingCrane.MovementStrategy +{ + public class MoveToCenter : AbstractStrategy + { + protected override bool IsTargetDestination() + { + 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/HoistingCrane/HoistingCrane/MovementStrategy/MoveableCar.cs b/HoistingCrane/HoistingCrane/MovementStrategy/MoveableCar.cs new file mode 100644 index 0000000..7139b75 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/MoveableCar.cs @@ -0,0 +1,63 @@ +using HoistingCrane.Drawning; + +namespace HoistingCrane.MovementStrategy +{ + public class MoveableCar : IMoveableObjects + { + /// + /// Поле-объект класса DrawningAirplane или его наследника + /// + private readonly DrawningTrackedVehicle? drawningTrackedVehicle = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningAirplane + public MoveableCar(DrawningTrackedVehicle drawningTrackedVehicle) + { + this.drawningTrackedVehicle = drawningTrackedVehicle; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (drawningTrackedVehicle == null || drawningTrackedVehicle.EntityTrackedVehicle == null || !drawningTrackedVehicle.GetPosX.HasValue || !drawningTrackedVehicle.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(drawningTrackedVehicle.GetPosX.Value, drawningTrackedVehicle.GetPosY.Value, drawningTrackedVehicle.GetWidth, drawningTrackedVehicle.GetHeight); + } + } + + + public int GetStep => (int)(drawningTrackedVehicle?.EntityTrackedVehicle?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (drawningTrackedVehicle == null || drawningTrackedVehicle.EntityTrackedVehicle == null) + { + return false; + } + + return drawningTrackedVehicle.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/HoistingCrane/HoistingCrane/MovementStrategy/MovementDirection.cs b/HoistingCrane/HoistingCrane/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..8d81015 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/MovementDirection.cs @@ -0,0 +1,25 @@ +namespace HoistingCrane.MovementStrategy +{ + public enum MovementDirection + { + //Перечислим основные траектории движния нашего автомобиля. Сразу же зададим значения. + /// + /// Вверх1 + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 + + + } +} diff --git a/HoistingCrane/HoistingCrane/MovementStrategy/ObjectParameters.cs b/HoistingCrane/HoistingCrane/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..57257e5 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,70 @@ +namespace HoistingCrane.MovementStrategy +{ + public class ObjectParameters + { + /// + /// Начальная координата х + /// + private readonly int _x; + + /// + /// Начальная координата y + /// + private readonly int _y; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Центральная координата по горизонтали + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Центральная координата по вертикали + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// Координата по х + /// Координата по у + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int _x, int _y, int _width, int _height) + { + this._x = _x; + this._y = _y; + this._width = _width; + this._height = _height; + } + } +} diff --git a/HoistingCrane/HoistingCrane/MovementStrategy/StrategyStatus.cs b/HoistingCrane/HoistingCrane/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..9635b97 --- /dev/null +++ b/HoistingCrane/HoistingCrane/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace HoistingCrane.MovementStrategy +{ + public enum StrategyStatus + { + /// + /// Всё готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish + + + } +}