diff --git a/ProjectCleaningCar/ProjectCleaningCar/Drawning/DirectionType.cs b/ProjectCleaningCar/ProjectCleaningCar/Drawning/DirectionType.cs
index 04acd65..3c26aa5 100644
--- a/ProjectCleaningCar/ProjectCleaningCar/Drawning/DirectionType.cs
+++ b/ProjectCleaningCar/ProjectCleaningCar/Drawning/DirectionType.cs
@@ -4,6 +4,10 @@
///
public enum DirectionType
{
+ ///
+ /// Неизвестное направление
+ ///
+ Unknow = -1,
///
/// Вверх
///
diff --git a/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCar.cs b/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCar.cs
index e53dc68..25c45ca 100644
--- a/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCar.cs
+++ b/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCar.cs
@@ -1,7 +1,9 @@
using ProjectCleaningCar.Entities;
namespace ProjectCleaningCar.Drawning;
-
+///
+/// Класс, отвечающий за прорисовку базового объекта-сущности
+///
public class DrawningCar
{
///
@@ -31,7 +33,23 @@ public class DrawningCar
///
/// Высота прорисовки машины
///
- private readonly int _drawningCarHeight = 80;
+ private readonly int _drawningCarHeight = 65;
+ ///
+ /// Координата X объекта
+ ///
+ public int? GetPosX => _startPosX;
+ ///
+ /// Координата Y объекта
+ ///
+ public int? GetPosY => _startPosY;
+ ///
+ /// Ширина объекта
+ ///
+ public int GetWidth => _drawningCarWidth;
+ ///
+ /// Высота объекта
+ ///
+ public int GetHeight => _drawningCarHeight;
///
/// Пустой конструктор
///
diff --git a/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCleaningCar.cs b/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCleaningCar.cs
index 7e4c4a3..05ca635 100644
--- a/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCleaningCar.cs
+++ b/ProjectCleaningCar/ProjectCleaningCar/Drawning/DrawningCleaningCar.cs
@@ -2,7 +2,7 @@
namespace ProjectCleaningCar.Drawning;
///
-/// Класс, отвечающий за прорисовку и перемещение объекта сущности
+/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
///
public class DrawningCleaningCar : DrawningCar
{
@@ -17,7 +17,7 @@ public class DrawningCleaningCar : DrawningCar
/// Подметательная щётка
/// Проблескового маячок
public DrawningCleaningCar(int speed, double weight, Color bodyColor, Color
-additionalColor, bool tank, bool sweepingBrush, bool flashlight) : base(130, 90)
+additionalColor, bool tank, bool sweepingBrush, bool flashlight) : base(132, 65)
{
EntityCar = new EntityCleaningCar(speed, weight, bodyColor, additionalColor,
tank, sweepingBrush, flashlight);
@@ -48,10 +48,10 @@ tank, sweepingBrush, flashlight);
if (cleaningCar.SweepingBrush)
{
Pen additionalPen = new(cleaningCar.AdditionalColor);
- g.DrawEllipse(additionalPen, _startPosX.Value + 125, _startPosY.Value + 50, 18, 18);
- g.FillEllipse(additionalBrush, _startPosX.Value + 125, _startPosY.Value + 50, 18, 18);
- g.FillEllipse(bodyBrush, _startPosX.Value + 129, _startPosY.Value + 54, 10, 10);
- g.DrawLine(pen, _startPosX.Value + 120, _startPosY.Value + 50, _startPosX.Value + 135, _startPosY.Value + 60); ////////!!!!!
+ g.DrawEllipse(additionalPen, _startPosX.Value + 122, _startPosY.Value + 45, 18, 18);
+ g.FillEllipse(additionalBrush, _startPosX.Value + 122, _startPosY.Value + 45, 18, 18);
+ g.FillEllipse(bodyBrush, _startPosX.Value + 126, _startPosY.Value + 49, 10, 10);
+ g.DrawLine(pen, _startPosX.Value + 117, _startPosY.Value + 45, _startPosX.Value + 131, _startPosY.Value + 54);
}
//проблесковый маячок
if (cleaningCar.Flashlight)
diff --git a/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.Designer.cs b/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.Designer.cs
index d180adc..d27cb84 100644
--- a/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.Designer.cs
+++ b/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.Designer.cs
@@ -35,6 +35,8 @@
buttonUp = new Button();
buttonDown = new Button();
buttonCreateCar = new Button();
+ comboBoxStrategy = new ComboBox();
+ buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCleaningCar).BeginInit();
SuspendLayout();
//
@@ -109,6 +111,7 @@
//
// buttonCreateCar
//
+ buttonCreateCar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateCar.Location = new Point(210, 421);
buttonCreateCar.Name = "buttonCreateCar";
buttonCreateCar.Size = new Size(192, 32);
@@ -117,11 +120,35 @@
buttonCreateCar.UseVisualStyleBackColor = true;
buttonCreateCar.Click += ButtonCreateCar_Click;
//
+ // comboBoxStrategy
+ //
+ comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
+ comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
+ comboBoxStrategy.FormattingEnabled = true;
+ comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
+ comboBoxStrategy.Location = new Point(710, 12);
+ comboBoxStrategy.Name = "comboBoxStrategy";
+ comboBoxStrategy.Size = new Size(102, 23);
+ comboBoxStrategy.TabIndex = 7;
+ //
+ // buttonStrategyStep
+ //
+ buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
+ buttonStrategyStep.Location = new Point(742, 41);
+ buttonStrategyStep.Name = "buttonStrategyStep";
+ buttonStrategyStep.Size = new Size(70, 21);
+ buttonStrategyStep.TabIndex = 8;
+ buttonStrategyStep.Text = "Шаг";
+ buttonStrategyStep.UseVisualStyleBackColor = true;
+ buttonStrategyStep.Click += ButtonStrategyStep_Click;
+ //
// FormCleaningCar
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(824, 465);
+ Controls.Add(buttonStrategyStep);
+ Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCar);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
@@ -144,5 +171,7 @@
private Button buttonUp;
private Button buttonDown;
private Button buttonCreateCar;
+ private ComboBox comboBoxStrategy;
+ private Button buttonStrategyStep;
}
}
\ No newline at end of file
diff --git a/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.cs b/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.cs
index 9a2216c..f0604e8 100644
--- a/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.cs
+++ b/ProjectCleaningCar/ProjectCleaningCar/FormCleaningCar.cs
@@ -1,4 +1,5 @@
using ProjectCleaningCar.Drawning;
+using ProjectCleaningCar.MovementStrategy;
namespace ProjectCleaningCar;
///
@@ -11,11 +12,16 @@ public partial class FormCleaningCar : Form
///
private DrawningCar? _drawningCar;
///
+ /// Стратегия перемещения
+ ///
+ private AbstractStrategy? _strategy;
+ ///
/// Конструктор формы
///
public FormCleaningCar()
{
InitializeComponent();
+ _strategy = null;
}
///
/// Метод прорисовки машины
@@ -70,6 +76,9 @@ public partial class FormCleaningCar : Form
}
_drawningCar.SetPictureSize(pictureBoxCleaningCar.Width, pictureBoxCleaningCar.Height);
_drawningCar.SetPosition(random.Next(0, 200), random.Next(0, 200));
+ _strategy = null;
+ comboBoxStrategy.Enabled = true;
+ Draw();
}
///
/// Перемещение объекта по форме (нажатие кнопок навигации)
@@ -104,4 +113,45 @@ public partial class FormCleaningCar : Form
Draw();
}
}
-}
+ ///
+ /// Обработка нажатия кнопки "Шаг"
+ ///
+ ///
+ ///
+ private void ButtonStrategyStep_Click(object sender, EventArgs e)
+ {
+ if (_drawningCar == null)
+ {
+ return;
+ }
+ if (comboBoxStrategy.Enabled)
+ {
+ _strategy = comboBoxStrategy.SelectedIndex switch
+ {
+ 0 => new MoveToCenter(),
+ 1 => new MoveToBorder(),
+ _ => null,
+ };
+ if (_strategy == null)
+ {
+ return;
+ }
+ _strategy.SetData(new MoveableCar(_drawningCar),
+ pictureBoxCleaningCar.Width, pictureBoxCleaningCar.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/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/AbstractStrategy.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/AbstractStrategy.cs
new file mode 100644
index 0000000..b8cbd5e
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/AbstractStrategy.cs
@@ -0,0 +1,120 @@
+namespace ProjectCleaningCar.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/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/IMoveableObject.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/IMoveableObject.cs
new file mode 100644
index 0000000..f1f42c5
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/IMoveableObject.cs
@@ -0,0 +1,21 @@
+namespace ProjectCleaningCar.MovementStrategy;
+///
+/// Интерфейс для работы с перемещаемым объектом
+///
+public interface IMoveableObject
+{
+ ///
+ /// Получение координаты объекта
+ ///
+ ObjectParameters? GetObjectPosition { get; }
+ ///
+ /// Шаг объекта
+ ///
+ int GetStep { get; }
+ ///
+ /// Попытка переместить объект в указанном направлении
+ ///
+ /// Направление
+ /// true - объект перемещен, false - перемещение невозможно
+ bool TryMoveObject(MovementDirection direction);
+}
diff --git a/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveToBorder.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveToBorder.cs
new file mode 100644
index 0000000..2cd33b8
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveToBorder.cs
@@ -0,0 +1,49 @@
+namespace ProjectCleaningCar.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;
+ if (Math.Abs(diffX) > GetStep())
+ {
+ if (diffX < 0)
+ {
+ MoveLeft();
+ }
+ else
+ {
+ MoveRight();
+ }
+ }
+ int diffY = objParams.DownBorder;
+ if (Math.Abs(diffY) > GetStep())
+ {
+ if (diffY < 0)
+ {
+ MoveUp();
+ }
+ else
+ {
+ MoveDown();
+ }
+ }
+ }
+}
diff --git a/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveToCenter.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveToCenter.cs
new file mode 100644
index 0000000..d77ab1b
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveToCenter.cs
@@ -0,0 +1,50 @@
+namespace ProjectCleaningCar.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/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveableCar.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveableCar.cs
new file mode 100644
index 0000000..2feffd2
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MoveableCar.cs
@@ -0,0 +1,57 @@
+using ProjectCleaningCar.Drawning;
+
+namespace ProjectCleaningCar.MovementStrategy;
+///
+/// Класс-реализация IMoveableObject с использованием DrawningCar
+///
+public class MoveableCar : IMoveableObject
+{
+ ///
+ /// Поле-объект класса DrawningCar или его наследника
+ ///
+ private readonly DrawningCar? _car = null;
+ ///
+ /// Конструктор
+ ///
+ /// Объект класса DrawningCar
+ public MoveableCar(DrawningCar car)
+ {
+ _car = car;
+ }
+ public ObjectParameters? GetObjectPosition
+ {
+ get
+ {
+ if (_car == null || _car.EntityCar == null || !_car.GetPosX.HasValue || !_car.GetPosY.HasValue)
+ {
+ return null;
+ }
+ return new ObjectParameters(_car.GetPosX.Value, _car.GetPosY.Value, _car.GetWidth, _car.GetHeight);
+ }
+ }
+ public int GetStep => (int)(_car?.EntityCar?.Step ?? 0);
+ public bool TryMoveObject(MovementDirection direction)
+ {
+ if (_car == null || _car.EntityCar == null)
+ {
+ return false;
+ }
+ return _car.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/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MovementDirection.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MovementDirection.cs
new file mode 100644
index 0000000..8fed15b
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/MovementDirection.cs
@@ -0,0 +1,23 @@
+namespace ProjectCleaningCar.MovementStrategy;
+///
+/// Направление перемещения
+///
+public enum MovementDirection
+{
+ ///
+ /// Вверх
+ ///
+ Up = 1,
+ ///
+ /// Вниз
+ ///
+ Down = 2,
+ ///
+ /// Влево
+ ///
+ Left = 3,
+ ///
+ /// Вправо
+ ///
+ Right = 4
+}
diff --git a/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/ObjectParameters.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/ObjectParameters.cs
new file mode 100644
index 0000000..242dbc3
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/ObjectParameters.cs
@@ -0,0 +1,61 @@
+namespace ProjectCleaningCar.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/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/StrategyStatus.cs b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/StrategyStatus.cs
new file mode 100644
index 0000000..190344e
--- /dev/null
+++ b/ProjectCleaningCar/ProjectCleaningCar/MovementStrategy/StrategyStatus.cs
@@ -0,0 +1,19 @@
+namespace ProjectCleaningCar.MovementStrategy;
+///
+/// Статус выполнения операции перемещения
+///
+public enum StrategyStatus
+{
+ ///
+ /// Все готово к началу
+ ///
+ NotInit,
+ ///
+ /// Выполняется
+ ///
+ InProgress,
+ ///
+ /// Завершено
+ ///
+ Finish
+}