From d65a7c7cd6af8339e8f4b2bbd0c3f0b7704702a3 Mon Sep 17 00:00:00 2001 From: Adelina888 Date: Sat, 9 Mar 2024 20:45:03 +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 --- .../Drawnings/DirectionType.cs | 4 + .../Drawnings/DrawingStormtrooper.cs | 5 +- .../Drawnings/DrawingStormtrooperBase.cs | 30 ++++- .../FormStormtrooper.Designer.cs | 26 ++++ ProjectStormtrooper/FormStormtrooper.cs | 54 +++++++- .../MovementStrategy/AbstractStrategy.cs | 120 ++++++++++++++++++ .../MovementStrategy/IMoveableObjects.cs | 21 +++ .../MovementStrategy/MoveToBorder.cs | 28 ++++ .../MovementStrategy/MoveToCenter.cs | 52 ++++++++ .../MoveableStormtrooperBase.cs | 60 +++++++++ .../MovementStrategy/MovementDirection.cs | 24 ++++ .../MovementStrategy/ObjectParameters.cs | 61 +++++++++ .../MovementStrategy/StrategyStatus.cs | 19 +++ 13 files changed, 493 insertions(+), 11 deletions(-) create mode 100644 ProjectStormtrooper/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectStormtrooper/MovementStrategy/IMoveableObjects.cs create mode 100644 ProjectStormtrooper/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectStormtrooper/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectStormtrooper/MovementStrategy/MoveableStormtrooperBase.cs create mode 100644 ProjectStormtrooper/MovementStrategy/MovementDirection.cs create mode 100644 ProjectStormtrooper/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectStormtrooper/MovementStrategy/StrategyStatus.cs diff --git a/ProjectStormtrooper/Drawnings/DirectionType.cs b/ProjectStormtrooper/Drawnings/DirectionType.cs index 75dddcd..5d2dfc9 100644 --- a/ProjectStormtrooper/Drawnings/DirectionType.cs +++ b/ProjectStormtrooper/Drawnings/DirectionType.cs @@ -5,6 +5,10 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs b/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs index 854b998..9db8277 100644 --- a/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs +++ b/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs @@ -4,7 +4,7 @@ namespace ProjectStormtrooper.Drawnings; /// /// Класс отвечающий за прорисовку и перемещение объекта-сущности /// -public class DrawingStormtrooper: DrawingStormtrooperBase +public class DrawingStormtrooper: DrawningStormtrooperBase { @@ -41,6 +41,7 @@ public class DrawingStormtrooper: DrawingStormtrooperBase Pen pen = new(Color.Black); Brush additionalBrush = new SolidBrush(stormtrooper.AdditionalColor); + base.DrawTransport(g); //ракеты штурмовика if (stormtrooper.Rockets) { @@ -57,7 +58,7 @@ public class DrawingStormtrooper: DrawingStormtrooperBase g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10); g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10); } - base.DrawTransport(g); + } diff --git a/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs b/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs index ce9ef1d..ee891db 100644 --- a/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs +++ b/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs @@ -2,7 +2,7 @@ namespace ProjectStormtrooper.Drawnings; -public class DrawingStormtrooperBase +public class DrawningStormtrooperBase { /// /// Класс-сущность @@ -37,10 +37,32 @@ public class DrawingStormtrooperBase /// private readonly int _drawningStormtooperHeight = 140; + + /// + /// Координата Х объекта + /// + /// + public int? GetPosX => _startPosX; + /// + /// Координата У объекта + /// + /// + + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + /// + public int GetWidth => _drawningStormtrooperWidth; + /// + /// Высота объекта + /// + /// + public int GetHeight => _drawningStormtooperHeight; /// /// Пустой конструктор /// - private DrawingStormtrooperBase() + private DrawningStormtrooperBase() { _pictureHeight = null; _pictureWidth = null; @@ -55,7 +77,7 @@ public class DrawingStormtrooperBase /// основной цвет - public DrawingStormtrooperBase(int speed, double weight, Color bodyColor):this() + public DrawningStormtrooperBase(int speed, double weight, Color bodyColor):this() { EntityStormtrooperBase = new EntityStormtrooperBase(speed, weight, bodyColor); @@ -66,7 +88,7 @@ public class DrawingStormtrooperBase /// Ширина прорисовки /// Высота прорисовки - protected DrawingStormtrooperBase(int drawningStormtrooperWidth, int drawningStormtooperHeight) : this() + protected DrawningStormtrooperBase(int drawningStormtrooperWidth, int drawningStormtooperHeight) : this() { _drawningStormtrooperWidth = drawningStormtrooperWidth; _drawningStormtooperHeight = drawningStormtooperHeight; diff --git a/ProjectStormtrooper/FormStormtrooper.Designer.cs b/ProjectStormtrooper/FormStormtrooper.Designer.cs index da58e52..b755050 100644 --- a/ProjectStormtrooper/FormStormtrooper.Designer.cs +++ b/ProjectStormtrooper/FormStormtrooper.Designer.cs @@ -35,6 +35,8 @@ buttonDown = new Button(); buttonRight = new Button(); buttonCreateStormtrooperBase = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit(); SuspendLayout(); // @@ -117,11 +119,33 @@ buttonCreateStormtrooperBase.UseVisualStyleBackColor = true; buttonCreateStormtrooperBase.Click += ButtonCreateStormtrooperBase_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(792, 8); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(839, 37); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormStormtrooper // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(925, 597); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateStormtrooperBase); Controls.Add(buttonRight); Controls.Add(buttonDown); @@ -144,5 +168,7 @@ private Button buttonDown; private Button buttonRight; private Button buttonCreateStormtrooperBase; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectStormtrooper/FormStormtrooper.cs b/ProjectStormtrooper/FormStormtrooper.cs index 9485dc3..f329f41 100644 --- a/ProjectStormtrooper/FormStormtrooper.cs +++ b/ProjectStormtrooper/FormStormtrooper.cs @@ -1,4 +1,5 @@ using ProjectStormtrooper.Drawnings; +using ProjectStormtrooper.MovementStrategy; namespace ProjectStormtrooper; /// @@ -8,13 +9,18 @@ public partial class FormStormtrooper : Form {/// /// Поле-объект для прорисовки объекта /// - private DrawingStormtrooperBase? _drawningStormtrooperBase; + private DrawningStormtrooperBase? _drawningStormtrooperBase; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы /// public FormStormtrooper() { InitializeComponent(); + _strategy = null; } /// @@ -48,8 +54,8 @@ public partial class FormStormtrooper : Form Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); break; - case nameof(DrawingStormtrooperBase): - _drawningStormtrooperBase = new DrawingStormtrooperBase(random.Next(100, 300), random.Next(1000, 3000), + case nameof(DrawningStormtrooperBase): + _drawningStormtrooperBase = new DrawningStormtrooperBase(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); break; default: @@ -58,6 +64,8 @@ public partial class FormStormtrooper : Form } _drawningStormtrooperBase.SetPictureSize(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height); _drawningStormtrooperBase.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } @@ -72,7 +80,7 @@ public partial class FormStormtrooper : Form /// /// /// - private void ButtonCreateStormtrooperBase_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingStormtrooperBase)); + private void ButtonCreateStormtrooperBase_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningStormtrooperBase)); /// @@ -101,7 +109,7 @@ public partial class FormStormtrooper : Form result = _drawningStormtrooperBase.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningStormtrooperBase .MoveTransport(DirectionType.Right); + result = _drawningStormtrooperBase.MoveTransport(DirectionType.Right); break; } @@ -112,5 +120,41 @@ public partial class FormStormtrooper : Form } + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningStormtrooperBase == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableStormtrooperBase(_drawningStormtrooperBase), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height); + } + + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } + diff --git a/ProjectStormtrooper/MovementStrategy/AbstractStrategy.cs b/ProjectStormtrooper/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..c29ecca --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,120 @@ +namespace ProjectStormtrooper.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 moveableObjects,int width, int height) + { + if (moveableObjects == null) + { + _state = StrategyStatus.NotInit; + return; + } + _state = StrategyStatus.InProgress; + _moveableObject = moveableObjects; + 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/ProjectStormtrooper/MovementStrategy/IMoveableObjects.cs b/ProjectStormtrooper/MovementStrategy/IMoveableObjects.cs new file mode 100644 index 0000000..8906846 --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/IMoveableObjects.cs @@ -0,0 +1,21 @@ +namespace ProjectStormtrooper.MovementStrategy; +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координат объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// + /// + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectStormtrooper/MovementStrategy/MoveToBorder.cs b/ProjectStormtrooper/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..2c35822 --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,28 @@ +namespace ProjectStormtrooper.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.LeftBorder - GetStep() <= 0 || objParams.RightBorder + GetStep() >= FieldWidth || + objParams.TopBorder - GetStep() <= 0 || objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + int x = objParams.RightBorder; + if (x + GetStep() < FieldWidth) MoveRight(); + int y = objParams.DownBorder; + if (y + GetStep() < FieldHeight) MoveDown(); + } +} diff --git a/ProjectStormtrooper/MovementStrategy/MoveToCenter.cs b/ProjectStormtrooper/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..ce16452 --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,52 @@ +namespace ProjectStormtrooper.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/ProjectStormtrooper/MovementStrategy/MoveableStormtrooperBase.cs b/ProjectStormtrooper/MovementStrategy/MoveableStormtrooperBase.cs new file mode 100644 index 0000000..8dfb492 --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/MoveableStormtrooperBase.cs @@ -0,0 +1,60 @@ +using ProjectStormtrooper.Drawnings; + +namespace ProjectStormtrooper.MovementStrategy; +/// +/// Класс-реализации IMoveableObject с использованием DrawingStormtrooperBase +/// +public class MoveableStormtrooperBase : IMoveableObject +{ + /// + /// Поле-объект класса DrawningStormtrooperBase или его наследников + /// + private readonly DrawningStormtrooperBase? _stormtrooper = null; + /// + /// Конструктор + /// + /// Объект класса DrawningStormtrooperBase + public MoveableStormtrooperBase(DrawningStormtrooperBase Stormtrooper) + { + _stormtrooper = Stormtrooper; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_stormtrooper == null || _stormtrooper.EntityStormtrooperBase == null || !_stormtrooper.GetPosX.HasValue || !_stormtrooper.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_stormtrooper.GetPosX.Value,_stormtrooper.GetPosY.Value,_stormtrooper.GetWidth,_stormtrooper.GetHeight); + } + } + + public int GetStep => (int)(_stormtrooper?.EntityStormtrooperBase?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_stormtrooper == null || _stormtrooper.EntityStormtrooperBase == null) + { + return false; + } + return _stormtrooper.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/ProjectStormtrooper/MovementStrategy/MovementDirection.cs b/ProjectStormtrooper/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..f043020 --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/MovementDirection.cs @@ -0,0 +1,24 @@ +namespace ProjectStormtrooper.MovementStrategy; +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4, + +} diff --git a/ProjectStormtrooper/MovementStrategy/ObjectParameters.cs b/ProjectStormtrooper/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..ede43be --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,61 @@ +namespace ProjectStormtrooper.MovementStrategy; +/// +/// Параметры-координаты объекта +/// +public class ObjectParameters +{ + /// + /// Координатва х + /// + private readonly int _x; + /// + /// Координатва у + /// + 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; + /// + /// Конструктор + /// + /// Координата х + /// Координа у + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/ProjectStormtrooper/MovementStrategy/StrategyStatus.cs b/ProjectStormtrooper/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..796cb9a --- /dev/null +++ b/ProjectStormtrooper/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,19 @@ +namespace ProjectStormtrooper.MovementStrategy; +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +}