From a8c7158463d696193ae6a559b23173f27793bb6e Mon Sep 17 00:00:00 2001 From: MariaBelkina <89656988623@mail.ru> Date: Sun, 24 Mar 2024 21:13:20 +0400 Subject: [PATCH] =?UTF-8?q?=D0=91=D0=BE=D0=BB=D0=B5=D0=B5-=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=B5=D0=B5=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=B5?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Drawnings/DirectionType.cs | 5 + .../Drawnings/DrawningBulldozer.cs | 10 +- .../Drawnings/DrawningDozer.cs | 23 +- .../Entities/EntityBulldozer.cs | 39 +--- .../ProjectBulldozer/Entities/EntityDozer.cs | 4 +- .../FormBulldozer.Designer.cs | 69 ++++-- .../ProjectBulldozer/FormBulldozer.cs | 211 ++++++++++++------ .../MovementStrategy/AbstractStrategy.cs | 139 ++++++++++++ .../MovementStrategy/IMoveableObject.cs | 30 +++ .../MovementStrategy/MoveToBorder.cs | 43 ++++ .../MovementStrategy/MoveToCenter.cs | 63 ++++++ .../MovementStrategy/MoveableDozer.cs | 66 ++++++ .../MovementStrategy/MovementDirection.cs | 30 +++ .../MovementStrategy/ObjectParameters.cs | 78 +++++++ .../MovementStrategy/StrategyStatus.cs | 28 +++ ProjectBulldozer/ProjectBulldozer/NewClass.cs | 18 -- .../ProjectBulldozer/ProjectBulldozer.csproj | 4 - 17 files changed, 724 insertions(+), 136 deletions(-) create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/IMoveableObject.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveableDozer.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/MovementDirection.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectBulldozer/ProjectBulldozer/MovementStrategy/StrategyStatus.cs delete mode 100644 ProjectBulldozer/ProjectBulldozer/NewClass.cs diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DirectionType.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DirectionType.cs index 2fb2c1b..b3792f9 100644 --- a/ProjectBulldozer/ProjectBulldozer/Drawnings/DirectionType.cs +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DirectionType.cs @@ -8,6 +8,11 @@ namespace ProjectBulldozer.Drawnings; public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningBulldozer.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningBulldozer.cs index e8e388a..fd24cf3 100644 --- a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningBulldozer.cs +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningBulldozer.cs @@ -37,6 +37,11 @@ public class DrawningBulldozer : DrawningDozer Brush bodyBrush = new SolidBrush(EntityDozer.BodyColor); Brush additionalBrush = new SolidBrush(EntityDozer.AdditionalColor); //BULDOZER + _startPosX += 0; + _startPosY += 0; + base.DrawTransport(g); + _startPosX -= 0; + _startPosY -= 0; //caterpillar if (bulldozer.Caterpillar) { @@ -58,10 +63,5 @@ public class DrawningBulldozer : DrawningDozer g.DrawRectangle(pen, _startPosX.Value + 125, _startPosY.Value, 25, 90); g.DrawLine(pen, _startPosX.Value + 140, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value + 90); } - _startPosX += 0; - _startPosY += 0; - base.DrawTransport(g); - _startPosX -= 0; - _startPosY -= 0; } } diff --git a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningDozer.cs b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningDozer.cs index 35a3f0b..a1102be 100644 --- a/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningDozer.cs +++ b/ProjectBulldozer/ProjectBulldozer/Drawnings/DrawningDozer.cs @@ -47,6 +47,27 @@ public class DrawningDozer /// private readonly int _drawningBulldozerHeight = 90; + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningBulldozerWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningBulldozerHeight; + + /// /// Пустой конструктор. /// @@ -75,7 +96,7 @@ public class DrawningDozer /// /// Ширина прорисовки бульдозера /// Высота прорисовки бульдозера - protected DrawningDozer (int drawningBulldozerWidth, int drawningBulldozerHeigh) + protected DrawningDozer (int drawningBulldozerWidth, int drawningBulldozerHeigh) :this() { _drawningBulldozerWidth = drawningBulldozerWidth; //???????? diff --git a/ProjectBulldozer/ProjectBulldozer/Entities/EntityBulldozer.cs b/ProjectBulldozer/ProjectBulldozer/Entities/EntityBulldozer.cs index 4141c71..db024f8 100644 --- a/ProjectBulldozer/ProjectBulldozer/Entities/EntityBulldozer.cs +++ b/ProjectBulldozer/ProjectBulldozer/Entities/EntityBulldozer.cs @@ -9,27 +9,9 @@ namespace ProjectBulldozer.Entities; /// /// Класс-сущность "Бульдозер" /// -public class EntityBulldozer +public class EntityBulldozer : EntityDozer { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - - /// - /// Дополнительный цвет - /// - public Color AdditionalColor { get; private set; } + /// /// Признак (опция) наличие отвала(ковша) @@ -40,12 +22,12 @@ public class EntityBulldozer /// Признак (опция) наличие гусеницы /// public bool Caterpillar { get; private set; } - +/* /// /// Шаг перемещения бульдозера /// - public double Step => Speed * 100 / Weight; - + public double Step => Speed * 100 / Weight;*/ +/* /// ///Инициализация полей объекта-класса бульдозера /// @@ -55,12 +37,13 @@ public class EntityBulldozer ///Дополнительный цвет ///Признак наличия отвала ///Признак наличия гусеницы - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool blade, bool caterpillar) + public void EntityBulldozer(bool blade, bool caterpillar) base(speed, ) + { + Blade = blade; + Caterpillar = caterpillar; + }*/ + public EntityBulldozer(int speed, double weight, Color bodyColor, Color additionalColor, bool blade, bool caterpillar) : base(speed, weight, bodyColor, additionalColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; Blade = blade; Caterpillar = caterpillar; } diff --git a/ProjectBulldozer/ProjectBulldozer/Entities/EntityDozer.cs b/ProjectBulldozer/ProjectBulldozer/Entities/EntityDozer.cs index 4000e75..89ec3e7 100644 --- a/ProjectBulldozer/ProjectBulldozer/Entities/EntityDozer.cs +++ b/ProjectBulldozer/ProjectBulldozer/Entities/EntityDozer.cs @@ -37,13 +37,13 @@ public class EntityDozer public double Step => Speed * 100 / Weight; /// - /// Конструктор сущности + /// Конструктор /// ///Скорость ///Вес ///Основной цвет ///Дополнительный цвет - public EntityDozer(int speed, double weight, Color bodyColor, Color additionalColor) + public EntityDozer(int speed, double weight, Color bodyColor, Color additionalColor) { Speed = speed; Weight = weight; diff --git a/ProjectBulldozer/ProjectBulldozer/FormBulldozer.Designer.cs b/ProjectBulldozer/ProjectBulldozer/FormBulldozer.Designer.cs index 02d6b42..53ecbad 100644 --- a/ProjectBulldozer/ProjectBulldozer/FormBulldozer.Designer.cs +++ b/ProjectBulldozer/ProjectBulldozer/FormBulldozer.Designer.cs @@ -29,11 +29,14 @@ private void InitializeComponent() { pictureBoxBulldozer = new PictureBox(); - buttonCreate = new Button(); + ButtonCreateBulldozer = new Button(); buttonRight = new Button(); buttonUp = new Button(); buttonLeft = new Button(); buttonDown = new Button(); + ButtonCreateDozer = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).BeginInit(); SuspendLayout(); // @@ -47,17 +50,17 @@ pictureBoxBulldozer.TabIndex = 0; pictureBoxBulldozer.TabStop = false; // - // buttonCreate + // ButtonCreateBulldozer // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point); - buttonCreate.Location = new Point(12, 371); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(150, 46); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; + ButtonCreateBulldozer.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + ButtonCreateBulldozer.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point); + ButtonCreateBulldozer.Location = new Point(12, 371); + ButtonCreateBulldozer.Name = "ButtonCreateBulldozer"; + ButtonCreateBulldozer.Size = new Size(325, 46); + ButtonCreateBulldozer.TabIndex = 1; + ButtonCreateBulldozer.Text = "Создать крутой бульдозер"; + ButtonCreateBulldozer.UseVisualStyleBackColor = true; + ButtonCreateBulldozer.Click += ButtonCreateBulldozer_Click; // // buttonRight // @@ -107,16 +110,53 @@ buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += ButtonMove_Click; // + // ButtonCreateDozer + // + ButtonCreateDozer.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + ButtonCreateDozer.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point); + ButtonCreateDozer.Location = new Point(343, 371); + ButtonCreateDozer.Name = "ButtonCreateDozer"; + ButtonCreateDozer.Size = new Size(248, 46); + ButtonCreateDozer.TabIndex = 6; + ButtonCreateDozer.Text = "Создать бульдозер"; + ButtonCreateDozer.UseVisualStyleBackColor = true; + ButtonCreateDozer.Click += ButtonCreateDozer_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(620, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(242, 40); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonStrategyStep.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point); + buttonStrategyStep.Location = new Point(760, 58); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(102, 38); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormBulldozer // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(874, 429); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(ButtonCreateDozer); Controls.Add(buttonDown); Controls.Add(buttonLeft); Controls.Add(buttonUp); Controls.Add(buttonRight); - Controls.Add(buttonCreate); + Controls.Add(ButtonCreateBulldozer); Controls.Add(pictureBoxBulldozer); Name = "FormBulldozer"; Text = "FormBulldozer"; @@ -128,10 +168,13 @@ #endregion private PictureBox pictureBoxBulldozer; - private Button buttonCreate; + private Button ButtonCreateBulldozer; private Button buttonRight; private Button buttonUp; private Button buttonLeft; private Button buttonDown; + private Button ButtonCreateDozer; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectBulldozer/ProjectBulldozer/FormBulldozer.cs b/ProjectBulldozer/ProjectBulldozer/FormBulldozer.cs index 8a40569..b828ba9 100644 --- a/ProjectBulldozer/ProjectBulldozer/FormBulldozer.cs +++ b/ProjectBulldozer/ProjectBulldozer/FormBulldozer.cs @@ -4,95 +4,176 @@ using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ProjectBulldozer.Drawnings; +using ProjectBulldozer.MovementStrategy; -namespace ProjectBulldozer +namespace ProjectBulldozer; + +/// +/// Форма работы с объектом "Бульдозер" +/// +public partial class FormBulldozer : Form { - public partial class FormBulldozer : Form + /// + /// Поле-объект для прорисовки объекта + /// + private DrawningDozer? _drawningDozer; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + /// + /// Конструктор формы + /// + public FormBulldozer() { - private DrawningBulldozer? _drawningBulldozer; - //private EntityBulldozer? _entityBulldozer; - public FormBulldozer() + InitializeComponent(); + _strategy = null; + } + + /// + /// Метод прорисовки транспорта + /// + private void Draw() + { + if (_drawningDozer == null) { - InitializeComponent(); + return; } - private void Draw() + Bitmap bmp = new(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawningDozer.DrawTransport(gr); + pictureBoxBulldozer.Image = bmp; + } + + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) { - if (_drawningBulldozer == null) - { + case nameof(DrawningDozer): + _drawningDozer = new DrawningDozer(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(170, 256), random.Next(170, 256), random.Next(30, 140)), + Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120))); + break; + case nameof(DrawningBulldozer): + _drawningDozer = new DrawningBulldozer(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(170, 256), random.Next(170, 256), random.Next(30, 140)), + Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120)), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: return; - } - - Bitmap bmp = new(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height); - Graphics gr = Graphics.FromImage(bmp); - _drawningBulldozer.DrawTransport(gr); - pictureBoxBulldozer.Image = bmp; } - /// - /// Обработка нажатия кнопки "Создать" - /// - /// - /// - private void buttonCreate_Click(object sender, EventArgs e) + _drawningDozer.SetPictureSize(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height); + _drawningDozer.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать крутой бульдозер" + /// + /// + /// + private void ButtonCreateBulldozer_Click(object sender, EventArgs e) => + CreateObject(nameof(DrawningBulldozer)); + + /// + /// Обработка нажатия кнопки "Создать бульдозер" + /// + /// + /// + private void ButtonCreateDozer_Click(object sender, EventArgs e) => + CreateObject(nameof(DrawningDozer)); + + /// + /// Перемещение объекта по форме (нажатие кнопок навигации) + /// + /// + /// + private void ButtonMove_Click(object sender, EventArgs e) + { + if (_drawningDozer == null) + { + return; + } + + string name = ((Button)sender)?.Name ?? string.Empty; + bool result = false; + switch (name) + { + case "buttonUp": + result = _drawningDozer.MoveTransport(DirectionType.Up); + break; + case "buttonDown": + result = _drawningDozer.MoveTransport(DirectionType.Down); + break; + case "buttonLeft": + result = _drawningDozer.MoveTransport(DirectionType.Left); + break; + case "buttonRight": + result = _drawningDozer.MoveTransport(DirectionType.Right); + break; + } + if (result) { - Random random = new(); - _drawningBulldozer = new DrawningBulldozer(); - //_entityBulldozer = new EntityBulldozer(); - /*_entityBulldozer.Init(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(170, 256), random.Next(170, 210), random.Next(30, 140)), - Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));*/ - //_drawningBulldozer.Init(_entityBulldozer); - _drawningBulldozer.Init(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(170, 256), random.Next(170, 256), random.Next(30, 140)), - Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - //_drawningBulldozer.Init(150, 2000, Color.FromArgb(240, 200, 50), Color.FromArgb(30, 30, 70), true, false); - _drawningBulldozer.SetPictureSize(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height); - //_drawningBulldozer.SetPosition(pictureBoxBulldozer.Width - random.Next(150, 250), pictureBoxBulldozer.Height - random.Next(100, 200)); - _drawningBulldozer.SetPosition(random.Next(10, 100), random.Next(10, 100)); Draw(); } + } - /// - /// Перемещение объекта по форме (нажатие кнопок навигации) - /// - /// - /// - private void ButtonMove_Click(object sender, EventArgs e) + + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningDozer == null) { - if (_drawningBulldozer == null) + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) { return; } - string name = ((Button)sender)?.Name ?? string.Empty; - bool result = false; - switch (name) - { - case "buttonUp": - result = _drawningBulldozer.MoveTransport(DirectionType.Up); - break; - case "buttonDown": - result = _drawningBulldozer.MoveTransport(DirectionType.Down); - break; - case "buttonLeft": - result = _drawningBulldozer.MoveTransport(DirectionType.Left); - break; - case "buttonRight": - result = _drawningBulldozer.MoveTransport(DirectionType.Right); - break; - } - if (result) - { - Draw(); - } + _strategy.SetData(new MoveableDozer(_drawningDozer), pictureBoxBulldozer.Width, + pictureBoxBulldozer.Height); } + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } } } diff --git a/ProjectBulldozer/ProjectBulldozer/MovementStrategy/AbstractStrategy.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..41a7392 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.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/ProjectBulldozer/ProjectBulldozer/MovementStrategy/IMoveableObject.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..96ba494 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещён, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToBorder.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..7017e52 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.RightBorder + GetStep() >= FieldWidth && objParams.LeftBorder + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + int diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + MoveRight(); + } + + int diffY = objParams.BottomBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } +} diff --git a/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToCenter.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..c261ca7 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.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 >= 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/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveableDozer.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveableDozer.cs new file mode 100644 index 0000000..09cae42 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MoveableDozer.cs @@ -0,0 +1,66 @@ +using ProjectBulldozer.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием DrawningDozer +/// +public class MoveableDozer : IMoveableObject +{ + /// + /// Поле-объект класса DrawningDozer или его наследника + /// + private readonly DrawningDozer? _dozer = null; + + /// + /// Констректор + /// + /// Объект класса DrawningDozer + public MoveableDozer(DrawningDozer dozer) + { + _dozer = dozer; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_dozer == null || _dozer.EntityDozer == null || + !_dozer.GetPosX.HasValue || !_dozer.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_dozer.GetPosX.Value, _dozer.GetPosY.Value, + _dozer.GetWidth, _dozer.GetHeight); + } + } + + public int GetStep => (int)(_dozer?.EntityDozer?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_dozer != null || _dozer.EntityDozer == null) + { + return false; + } + + return _dozer.MoveTransport(GetDirectionType(direction)); + } + + 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/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MovementDirection.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..023a111 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/MovementDirection.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Вллево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} diff --git a/ProjectBulldozer/ProjectBulldozer/MovementStrategy/ObjectParameters.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..ae34bde --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.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 BottomBorder => _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/ProjectBulldozer/ProjectBulldozer/MovementStrategy/StrategyStatus.cs b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..42a9925 --- /dev/null +++ b/ProjectBulldozer/ProjectBulldozer/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBulldozer.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Всё готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} diff --git a/ProjectBulldozer/ProjectBulldozer/NewClass.cs b/ProjectBulldozer/ProjectBulldozer/NewClass.cs deleted file mode 100644 index d017313..0000000 --- a/ProjectBulldozer/ProjectBulldozer/NewClass.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectBulldozer -{ - internal class NewClass - { - private int closedField; - public double Property { private get; set; } - public void NewMethod() - { - //Новый метод. - } - } -} diff --git a/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj b/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj index 24f6cce..13ee123 100644 --- a/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj +++ b/ProjectBulldozer/ProjectBulldozer/ProjectBulldozer.csproj @@ -23,8 +23,4 @@ - - - - \ No newline at end of file