diff --git a/MotorBoat/MotorBoat/AbstractStrategy.cs b/MotorBoat/MotorBoat/AbstractStrategy.cs
new file mode 100644
index 0000000..56db9f7
--- /dev/null
+++ b/MotorBoat/MotorBoat/AbstractStrategy.cs
@@ -0,0 +1,136 @@
+using MotorBoat.MovementStrategy;
+using MotorBoat;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.MovementStrategy
+{
+ ///
+ /// Класс-стратегия перемещения объекта
+ ///
+ public abstract class AbstractStrategy
+ {
+ ///
+ /// Перемещаемый объект
+ ///
+ private IMoveableObject? _moveableObject;
+ ///
+ /// Статус перемещения
+ ///
+ private Status _state = Status.NotInit;
+ ///
+ /// Ширина поля
+ ///
+ protected int FieldWidth { get; private set; }
+ ///
+ /// Высота поля
+ ///
+ protected int FieldHeight { get; private set; }
+ ///
+ /// Статус перемещения
+ ///
+ public Status GetStatus() { return _state; }
+ ///
+ /// Установка данных
+ ///
+ /// Перемещаемый объект
+ /// Ширина поля
+ /// Высота поля
+ public void SetData(IMoveableObject moveableObject, int width, int height)
+ {
+ if (moveableObject == null)
+ {
+ _state = Status.NotInit;
+ return;
+ }
+ _state = Status.InProgress;
+ _moveableObject = moveableObject;
+ FieldWidth = width;
+ FieldHeight = height;
+ }
+ ///
+ /// Шаг перемещения
+ ///
+ public void MakeStep()
+ {
+ if (_state != Status.InProgress)
+ {
+ return;
+ }
+ if (IsTargetDestinaion())
+ {
+ _state = Status.Finish;
+ return;
+ }
+ MoveToTarget();
+ }
+ ///
+ /// Перемещение влево
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveLeft() => MoveTo(DirectionType.Left);
+ ///
+ /// Перемещение вправо
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveRight() => MoveTo(DirectionType.Right);
+ ///
+ /// Перемещение вверх
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveUp() => MoveTo(DirectionType.Up);
+ ///
+ /// Перемещение вниз
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveDown() => MoveTo(DirectionType.Down);
+ ///
+ /// Параметры объекта
+ ///
+ protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
+
+ ///
+ /// Шаг объекта
+ ///
+ ///
+ protected int? GetStep()
+ {
+ if (_state != Status.InProgress)
+ {
+ return null;
+ }
+ return _moveableObject?.GetStep;
+ }
+ ///
+ /// Перемещение к цели
+ ///
+ protected abstract void MoveToTarget();
+ ///
+ /// Достигнута ли цель
+ ///
+ ///
+ protected abstract bool IsTargetDestinaion();
+ ///
+ /// Попытка перемещения в требуемом направлении
+ ///
+ /// Направление
+ /// Результат попытки (true - удалось переместиться, false - неудача)
+ private bool MoveTo(DirectionType directionType)
+ {
+ if (_state != Status.InProgress)
+ {
+ return false;
+ }
+ if (_moveableObject?.CheckCanMove(directionType) ?? false)
+ {
+ _moveableObject.MoveObject(directionType);
+ return true;
+ }
+ return false;
+ }
+ }
+}
+
diff --git a/MotorBoat/MotorBoat/DrawningBoat.cs b/MotorBoat/MotorBoat/DrawningBoat.cs
new file mode 100644
index 0000000..597b678
--- /dev/null
+++ b/MotorBoat/MotorBoat/DrawningBoat.cs
@@ -0,0 +1,209 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using MotorBoat.Entities;
+using MotorBoat;
+
+namespace MotorBoat.DrawningObjects
+{
+ ///
+ /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
+ ///
+ public class DrawningBoat
+ {
+ ///
+ /// Класс-сущность
+ ///
+ public EntityBoat? EntityBoat { get; protected set; }
+
+ ///
+ /// Ширина окна
+ ///
+ private int _pictureWidth = 800;
+
+ ///
+ /// Высота окна
+ ///
+ private int _pictureHeight = 450;
+
+ ///
+ /// Левая координата прорисовки
+ ///
+ protected int _startPosX;
+
+ ///
+ /// Верхняя кооридната прорисовки
+ ///
+ protected int _startPosY;
+
+ ///
+ /// Ширина прорисовки
+ ///
+ protected readonly int _boatWeight = 165;
+
+ ///
+ /// Высота прорисовки
+ ///
+ protected readonly int _boatHeight = 80;
+
+ ///
+ /// Конструктор
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ /// Ширина картинки
+ /// Высота картинки
+ /// true - объект создан, false - проверка не пройдена,
+ ///нельзя создать объект в этих размерах
+ public DrawningBoat(int speed, double weight, Color bodyColor, int width, int height)
+ {
+ if (width < _boatWeight || height < _boatHeight)
+ {
+ return;
+ }
+ _pictureWidth = width;
+ _pictureHeight = height;
+ EntityBoat = new EntityBoat(speed, weight, bodyColor);
+ }
+
+ ///
+ /// Конструктор
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ /// Ширина картинки
+ /// Высота картинки
+ /// Ширина прорисовки автомобиля
+ /// Высота прорисовки автомобиля
+ protected DrawningBoat(int speed, double weight, Color bodyColor, int
+ width, int height, int boatWidth, int boatHeight)
+ {
+ if (width <= _boatWeight || height <= _boatHeight)
+ return;
+ _pictureWidth = width;
+ _pictureHeight = height;
+ _boatWeight = boatWidth;
+ _boatHeight = boatHeight;
+ EntityBoat = new EntityBoat(speed, weight, bodyColor);
+ }
+ ///
+ /// Установка позиции
+ ///
+ /// Координата X
+ /// Координата Y
+ public void SetPosition(int x, int y)
+ {
+ if (x >= 0 && x + _boatWeight <= _pictureWidth && y >= 0 && y + _boatHeight <= _pictureHeight)
+ {
+ _startPosX = x;
+ _startPosY = y;
+ }
+ }
+
+ ///
+ /// Прорисовка объекта
+ ///
+ ///
+ public virtual void DrawTransport(Graphics g)
+ {
+ if (EntityBoat == null)
+ {
+ return;
+ }
+ Pen pen = new(Color.Black, 1);
+
+ Brush mainBrush = new SolidBrush(EntityBoat.BodyColor);
+
+ // корпус
+ Point[] hull = new Point[]
+ {
+ new Point(_startPosX + 5, _startPosY + 0),
+ new Point(_startPosX + 120, _startPosY + 0),
+ new Point(_startPosX + 160, _startPosY + 35),
+ new Point(_startPosX + 120, _startPosY + 70),
+ new Point(_startPosX + 5, _startPosY + 70),
+ };
+ g.FillPolygon(mainBrush, hull);
+ g.DrawPolygon(pen, hull);
+
+ // осн часть
+ Brush blockBrush = new SolidBrush(Color.Olive);
+ g.FillRectangle(blockBrush, _startPosX + 20, _startPosY + 15, 80, 40);
+ g.DrawRectangle(pen, _startPosX + 20, _startPosY + 15, 80, 40);
+ }
+ ///
+ /// Координата X объекта
+ ///
+ public int GetPosX => _startPosX;
+ ///
+ /// Координата Y объекта
+ /// ///
+ public int GetPosY => _startPosY;
+ ///
+ /// Ширина объекта
+ ///
+ public int GetWidth => _boatWeight;
+ ///
+ /// Высота объекта
+ ///
+ public int GetHeight => _boatHeight;
+ ///
+ /// Проверка, что объект может переместится по указанному направлению
+ ///
+ /// Направление
+ /// true - можно переместится по указанному направлению
+ public bool CanMove(DirectionType direction)
+ {
+ if (EntityBoat == null)
+ {
+ return false;
+ }
+ return direction switch
+ {
+ //влево
+ DirectionType.Left => _startPosX - EntityBoat.Step > 0,
+ //вверх
+ DirectionType.Up => _startPosY - EntityBoat.Step > 0,
+ //вправо
+ DirectionType.Right => _startPosX + EntityBoat.Step + _boatWeight < _pictureWidth,
+ //вниз
+ DirectionType.Down => _startPosY + EntityBoat.Step + _boatHeight < _pictureHeight,
+ _ => false,
+ };
+ }
+ ///
+ /// Изменение направления перемещения
+ ///
+ /// Направление
+ public void MoveTransport(DirectionType direction)
+ {
+ if (!CanMove(direction) || EntityBoat == null)
+ {
+ return;
+ }
+ switch (direction)
+ {
+ //влево
+ case DirectionType.Left:
+ _startPosX -= (int)EntityBoat.Step;
+ break;
+ //вверх
+ case DirectionType.Up:
+ _startPosY -= (int)EntityBoat.Step;
+ break;
+ //вправо
+ case DirectionType.Right:
+ _startPosX += (int)EntityBoat.Step;
+ break;
+ //вниз
+ case DirectionType.Down:
+ _startPosY += (int)EntityBoat.Step;
+ break;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/DrawningMotorBoat.cs b/MotorBoat/MotorBoat/DrawningMotorBoat.cs
index 5714f70..82beac7 100644
--- a/MotorBoat/MotorBoat/DrawningMotorBoat.cs
+++ b/MotorBoat/MotorBoat/DrawningMotorBoat.cs
@@ -3,142 +3,34 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using MotorBoat;
+using MotorBoat.DrawningObjects;
+using MotorBoat.Entities;
-namespace MotorBoat
+namespace MotorBoat.DrawningObjects
{
/// .
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
///
- public class DrawningMotorboat
+ public class DrawningMotorBoat : DrawningBoat
{
///
- /// Класс-сущность
- ///
- public EntityMotorBoat? EntityMotorBoat { get; private set; }
-
- ///
- /// Ширина окна
- ///
- private int _pictureWight = 800;
-
- ///
- /// Высота окна
- ///
- private int _pictureHeight = 450;
-
- ///
- /// Левая координата прорисовки катера
- ///
- private int _startPosX = 0;
-
- ///
- /// Правая координата прорисовки катера
- ///
- private int _startPosY = 0;
-
- ///
- /// Ширина прорисовки катера
- ///
- private readonly int _boatWight = 165;
-
- ///
- /// Высота прорисовки катера
- ///
- private readonly int _boatHeight = 80;
-
- ///
- /// Инициализация свойств
+ /// Конструктор
///
/// Скорость
/// Вес
- /// Цвет корпуса
+ /// Основной цвет
/// Дополнительный цвет
- /// Признак наличия двигателя в корме
- /// Признак наличия защитного стекла впереди
+ /// Признак наличия стекла спереди
+ /// Признак наличия двигателя
/// Ширина картинки
- /// Выслота картинки
- /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах
- public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool engine, bool glass, int width, int height)
+ /// Высота картинки
+ public DrawningMotorBoat(int speed, double weight, Color bodyColor, Color additionalColor, bool glass,
+ bool engine, int width, int height) : base (speed, weight, bodyColor, width, height, 165, 80)
{
- if (width <= _boatWight || height <= _boatHeight)
- return false;
- _pictureWight = width;
- _pictureHeight = height;
- EntityMotorBoat = new EntityMotorBoat();
- EntityMotorBoat.Init(speed, weight, bodyColor, additionalColor, engine, glass);
- return true;
- }
-
- ///
- /// Установка позиции
- ///
- /// Координата X
- /// Координата Y
- public void SetPosition(int x, int y)
- {
- if (EntityMotorBoat == null) return;
- while (x + _boatWight > _pictureWight)
+ if (EntityBoat != null)
{
- x -= (int)EntityMotorBoat.Step;
- }
- while (x < 0)
- {
- x += (int)EntityMotorBoat.Step;
- }
- while (y + _boatHeight > _pictureHeight)
- {
- y -= (int)EntityMotorBoat.Step;
- }
- while (y < 0)
- {
- y += (int)EntityMotorBoat.Step;
- }
- _startPosX = x;
- _startPosY = y;
- }
-
- ///
- /// Изменение направления перемещения
- ///
- /// Направление
- public void MoveTransport(DirectionType direction)
- {
- if (EntityMotorBoat == null)
- return;
-
- switch (direction)
- {
- //влево
- case DirectionType.Left:
- if (_startPosX - EntityMotorBoat.Step > 0)
- {
- _startPosX -= (int)EntityMotorBoat.Step;
- }
- break;
-
- //вверх
- case DirectionType.Up:
- if (_startPosY - EntityMotorBoat.Step > 0)
- {
- _startPosY -= (int)EntityMotorBoat.Step;
- }
- break;
-
- //вправо
- case DirectionType.Right:
- if (_startPosX + _boatWight + EntityMotorBoat.Step < _pictureWight)
- {
- _startPosX += (int)EntityMotorBoat.Step;
- }
- break;
-
- //вниз
- case DirectionType.Down:
- if (_startPosY + _boatHeight + EntityMotorBoat.Step < _pictureHeight)
- {
- _startPosY += (int)EntityMotorBoat.Step;
- }
- break;
+ EntityBoat = new EntityMotorBoat(speed, weight, bodyColor, additionalColor, glass, engine);
}
}
@@ -146,42 +38,32 @@ namespace MotorBoat
/// Прорисовка объекта
///
///
- public void DrawTransport(Graphics g)
+ public override void DrawTransport(Graphics g)
{
- if (EntityMotorBoat == null)
+ if (EntityBoat is not EntityMotorBoat motorBoat)
{
return;
}
+
Pen pen = new(Color.Black, 1);
- Brush mainBrush = new SolidBrush(EntityMotorBoat.BodyColor);
+ Brush additionalBrush = new SolidBrush(motorBoat.AdditionalColor);
- // корпус
- Point[] hull = new Point[]
+ if (motorBoat.Glass)
{
- new Point(_startPosX + 5, _startPosY + 0),
- new Point(_startPosX + 120, _startPosY + 0),
- new Point(_startPosX + 160, _startPosY + 35),
- new Point(_startPosX + 120, _startPosY + 70),
- new Point(_startPosX + 5, _startPosY + 70),
- };
- g.FillPolygon(mainBrush, hull);
- g.DrawPolygon(pen, hull);
+ // стекло впереди
+ Brush glassBrush = new SolidBrush(Color.LightBlue);
+ g.FillEllipse(glassBrush, _startPosX + 20, _startPosY + 15, 100, 40);
+ g.DrawEllipse(pen, _startPosX + 20, _startPosY + 15, 100, 40);
+ }
- // стекло впереди
- Brush glassBrush = new SolidBrush(Color.LightBlue);
- g.FillEllipse(glassBrush, _startPosX + 20, _startPosY + 15, 100, 40);
- g.DrawEllipse(pen, _startPosX + 20, _startPosY + 15, 100, 40);
+ base.DrawTransport(g);
- // осн часть
- Brush blockBrush = new SolidBrush(EntityMotorBoat.AdditionalColor);
- g.FillRectangle(blockBrush, _startPosX + 20, _startPosY + 15, 80, 40);
- g.DrawRectangle(pen, _startPosX + 20, _startPosY + 15, 80, 40);
-
- // двигатель
- Brush engineBrush = new
- SolidBrush(EntityMotorBoat.AdditionalColor);
- g.FillRectangle(engineBrush, _startPosX + 0, _startPosY + 10, 5, 50);
- g.DrawRectangle(pen, _startPosX + 0, _startPosY + 10, 5, 50);
+ if (motorBoat.Engine)
+ {
+ // двигатель
+ g.FillRectangle(additionalBrush, _startPosX + 0, _startPosY + 10, 5, 50);
+ g.DrawRectangle(pen, _startPosX + 0, _startPosY + 10, 5, 50);
+ }
}
}
-}
\ No newline at end of file
+}
diff --git a/MotorBoat/MotorBoat/DrawningObjectBoat.cs b/MotorBoat/MotorBoat/DrawningObjectBoat.cs
new file mode 100644
index 0000000..3dfeb4d
--- /dev/null
+++ b/MotorBoat/MotorBoat/DrawningObjectBoat.cs
@@ -0,0 +1,39 @@
+using MotorBoat.MovementStrategy;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using MotorBoat.DrawningObjects;
+
+namespace MotorBoat.MovementStrategy
+{
+ ///
+ /// Реализация интерфейса IDrawningObject для работы с объектом DrawningBoat (паттерн Adapter)
+ ///
+ public class DrawningObjectBoat : IMoveableObject
+ {
+ private readonly DrawningBoat? _drawningBoat = null;
+ public DrawningObjectBoat(DrawningBoat drawningBoat)
+ {
+ _drawningBoat = drawningBoat;
+ }
+ public ObjectParameters? GetObjectPosition
+ {
+ get
+ {
+ if (_drawningBoat == null || _drawningBoat.EntityBoat == null)
+ {
+ return null;
+ }
+ return new ObjectParameters(_drawningBoat.GetPosX,
+ _drawningBoat.GetPosY, _drawningBoat.GetWidth, _drawningBoat.GetHeight);
+ }
+ }
+ public int GetStep => (int)(_drawningBoat?.EntityBoat?.Step ?? 0);
+ public bool CheckCanMove(DirectionType direction) =>
+ _drawningBoat?.CanMove(direction) ?? false;
+ public void MoveObject(DirectionType direction) =>
+ _drawningBoat?.MoveTransport(direction);
+ }
+}
diff --git a/MotorBoat/MotorBoat/EntityBoat.cs b/MotorBoat/MotorBoat/EntityBoat.cs
new file mode 100644
index 0000000..a41ec86
--- /dev/null
+++ b/MotorBoat/MotorBoat/EntityBoat.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.Entities
+{
+ ///
+ /// Класс-сущность лодка
+ ///
+ public class EntityBoat
+ {
+ ///
+ /// Скорость
+ ///
+ public int Speed { get; private set; }
+
+ ///
+ /// Вес
+ ///
+ public double Weight { get; private set; }
+
+ ///
+ /// Основной цвет
+ ///
+ public Color BodyColor { get; private set; }
+
+ ///
+ /// Шаг перемещения
+ ///
+ public double Step => (double)Speed * 100 / Weight;
+
+ ///
+ /// Конструктор с параметрами
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ public EntityBoat(int speed, double weight, Color bodyColor)
+ {
+ Speed = speed;
+ Weight = weight;
+ BodyColor = bodyColor;
+ }
+ }
+}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/EntityMotorBoat.cs b/MotorBoat/MotorBoat/EntityMotorBoat.cs
index 05ce1ab..1f3d488 100644
--- a/MotorBoat/MotorBoat/EntityMotorBoat.cs
+++ b/MotorBoat/MotorBoat/EntityMotorBoat.cs
@@ -3,26 +3,15 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using MotorBoat.Entities;
-namespace MotorBoat
+namespace MotorBoat.Entities
{
- public class EntityMotorBoat
+ ///
+ /// Класс-сущность моторная лодка
+ ///
+ public class EntityMotorBoat : EntityBoat
{
- ///
- /// Скорость
- ///
- public int Speed { get; private set; }
-
- ///
- /// Вес
- ///
- public double Weight { get; private set; }
-
- ///
- /// Основной цвет
- ///
- public Color BodyColor { get; private set; }
-
///
/// Дополнительный цвет
///
@@ -38,11 +27,6 @@ namespace MotorBoat
///
public bool Glass { get; private set; }
- ///
- /// Шаг перемещения моторной лодки
- ///
- public double Step => (double)Speed * 100 / Weight;
-
///
/// Инициализация полей объекта-класса моторной лодки
///
@@ -53,11 +37,9 @@ namespace MotorBoat
/// Признак наличия двигателя в корме
/// Признак наличия защитного стекла впереди
- public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool engine, bool glass)
+ public EntityMotorBoat(int speed, double weight, Color bodyColor, Color additionalColor, bool engine, bool glass) :
+ base (speed, weight, bodyColor)
{
- Speed = speed;
- Weight = weight;
- BodyColor = bodyColor;
AdditionalColor = additionalColor;
Engine = engine;
Glass = glass;
diff --git a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs
index 4cccdbb..cb6d225 100644
--- a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs
+++ b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs
@@ -34,6 +34,9 @@
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
+ ButonCreateMotorBoat = new Button();
+ comboBoxStrategy = new ComboBox();
+ ButtonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMotorBoat).BeginInit();
SuspendLayout();
//
@@ -50,11 +53,11 @@
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
- buttonCreate.Location = new Point(12, 409);
+ buttonCreate.Location = new Point(189, 412);
buttonCreate.Name = "buttonCreate";
- buttonCreate.Size = new Size(90, 40);
+ buttonCreate.Size = new Size(171, 37);
buttonCreate.TabIndex = 1;
- buttonCreate.Text = "Создать";
+ buttonCreate.Text = "Создать лодку";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
@@ -106,11 +109,44 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
+ // ButonCreateMotorBoat
+ //
+ ButonCreateMotorBoat.Location = new Point(12, 412);
+ ButonCreateMotorBoat.Name = "ButonCreateMotorBoat";
+ ButonCreateMotorBoat.Size = new Size(171, 37);
+ ButonCreateMotorBoat.TabIndex = 6;
+ ButonCreateMotorBoat.Text = "Создать моторную лодку";
+ ButonCreateMotorBoat.UseVisualStyleBackColor = true;
+ ButonCreateMotorBoat.Click += ButonCreateMotorBoat_Click;
+ //
+ // comboBoxStrategy
+ //
+ comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
+ comboBoxStrategy.FormattingEnabled = true;
+ comboBoxStrategy.Items.AddRange(new object[] { "Перемещение в центр", "Перемещение в правый нижний угол" });
+ comboBoxStrategy.Location = new Point(749, 12);
+ comboBoxStrategy.Name = "comboBoxStrategy";
+ comboBoxStrategy.Size = new Size(121, 23);
+ comboBoxStrategy.TabIndex = 7;
+ //
+ // ButtonStep
+ //
+ ButtonStep.Location = new Point(795, 41);
+ ButtonStep.Name = "ButtonStep";
+ ButtonStep.Size = new Size(75, 23);
+ ButtonStep.TabIndex = 8;
+ ButtonStep.Text = "Шаг";
+ ButtonStep.UseVisualStyleBackColor = true;
+ ButtonStep.Click += ButtonStep_Click;
+ //
// FormMotorBoat
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
+ Controls.Add(ButtonStep);
+ Controls.Add(comboBoxStrategy);
+ Controls.Add(ButonCreateMotorBoat);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
@@ -133,5 +169,8 @@
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
+ private Button ButonCreateMotorBoat;
+ private ComboBox comboBoxStrategy;
+ private Button ButtonStep;
}
}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/FormMotorBoat.cs b/MotorBoat/MotorBoat/FormMotorBoat.cs
index ddd8d4d..ba3b289 100644
--- a/MotorBoat/MotorBoat/FormMotorBoat.cs
+++ b/MotorBoat/MotorBoat/FormMotorBoat.cs
@@ -1,3 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Drawing;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using MotorBoat;
+using MotorBoat.MovementStrategy;
+using MotorBoat.DrawningObjects;
+
namespace MotorBoat
{
public partial class FormMotorBoat : Form
@@ -5,7 +18,12 @@ namespace MotorBoat
///
/// -
///
- private DrawningMotorboat? _drawningMotorboat;
+ private DrawningBoat? _drawningBoat;
+
+ ///
+ ///
+ ///
+ private AbstractStrategy? _abstractStrategy;
///
///
@@ -20,42 +38,56 @@ namespace MotorBoat
///
private void Draw()
{
- if (_drawningMotorboat == null)
+ if (_drawningBoat == null)
{
return;
}
Bitmap bmp = new(pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height);
Graphics gr = Graphics.FromImage(bmp);
- _drawningMotorboat.DrawTransport(gr);
+ _drawningBoat.DrawTransport(gr);
pictureBoxMotorBoat.Image = bmp;
}
///
- /// ""
+ /// " "
///
///
///
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
- _drawningMotorboat = new DrawningMotorboat();
- _drawningMotorboat.Init(random.Next(100, 300), random.Next(1000, 3000),
+ _drawningBoat = new DrawningBoat(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
- 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)),
pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height);
- _drawningMotorboat.SetPosition(random.Next(10, 100), random.Next(10, 100));
+ _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
///
- ///
+ /// " "
+ ///
+ ///
+ ///
+ private void ButonCreateMotorBoat_Click(object sender, EventArgs e)
+ {
+ Random random = new();
+ _drawningBoat = new DrawningMotorBoat(random.Next(100, 300), random.Next(1000, 3000),
+ Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
+ 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)),
+ pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height);
+ _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
+ Draw();
+ }
+
+ ///
+ ///
///
///
///
private void ButtonMove_Click(object sender, EventArgs e)
{
- if (_drawningMotorboat == null)
+ if (_drawningBoat == null)
{
return;
}
@@ -63,19 +95,63 @@ namespace MotorBoat
switch (name)
{
case "buttonUp":
- _drawningMotorboat.MoveTransport(DirectionType.Up);
+ _drawningBoat.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
- _drawningMotorboat.MoveTransport(DirectionType.Down);
+ _drawningBoat.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
- _drawningMotorboat.MoveTransport(DirectionType.Left);
+ _drawningBoat.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
- _drawningMotorboat.MoveTransport(DirectionType.Right);
+ _drawningBoat.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
+
+ ///
+ /// ""
+ ///
+ ///
+ ///
+ private void ButtonStep_Click(object sender, EventArgs e)
+ {
+ if (_drawningBoat == null)
+ {
+ return;
+ }
+ if (comboBoxStrategy.Enabled)
+ {
+ _abstractStrategy = comboBoxStrategy.SelectedIndex
+ switch
+ {
+ 0 => new MoveToCenter(),
+ 1 => new MoveToBorder(),
+ _ => null,
+ };
+ if (_abstractStrategy == null)
+ {
+ return;
+ }
+ _abstractStrategy.SetData(new
+ DrawningObjectBoat(_drawningBoat), pictureBoxMotorBoat.Width,
+ pictureBoxMotorBoat.Height);
+ comboBoxStrategy.Enabled = false;
+ }
+ if (_abstractStrategy == null)
+ {
+ return;
+ }
+ _abstractStrategy.MakeStep();
+ Draw();
+ if (_abstractStrategy.GetStatus() == Status.Finish)
+ {
+ comboBoxStrategy.Enabled = true;
+ _abstractStrategy = null;
+ }
+
+ }
+
}
}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/IMovableObject.cs b/MotorBoat/MotorBoat/IMovableObject.cs
new file mode 100644
index 0000000..6558866
--- /dev/null
+++ b/MotorBoat/MotorBoat/IMovableObject.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using MotorBoat.MovementStrategy;
+using MotorBoat;
+
+namespace MotorBoat.MovementStrategy
+{
+ ///
+ /// Интерфейс для работы с перемещаемым объектом
+ ///
+ public interface IMoveableObject
+ {
+ ///
+ /// Получение координаты X объекта
+ ///
+ ObjectParameters? GetObjectPosition { get; }
+ ///
+ /// Шаг объекта
+ ///
+ int GetStep { get; }
+ ///
+ /// Проверка, можно ли переместиться по нужному направлению
+ ///
+ ///
+ ///
+ bool CheckCanMove(DirectionType direction);
+ ///
+ /// Изменение направления пермещения объекта
+ ///
+ /// Направление
+ void MoveObject(DirectionType direction);
+ }
+}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/MoveToBorder.cs b/MotorBoat/MotorBoat/MoveToBorder.cs
new file mode 100644
index 0000000..b451e92
--- /dev/null
+++ b/MotorBoat/MotorBoat/MoveToBorder.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using MotorBoat.MovementStrategy;
+
+namespace MotorBoat.MovementStrategy
+{
+ ///
+ /// Стратегия перемещения объекта в правый нижний край формы
+ ///
+ public class MoveToBorder : AbstractStrategy
+ {
+ protected override bool IsTargetDestinaion()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return false;
+ }
+ return objParams.RightBorder <= FieldWidth &&
+ objParams.RightBorder + GetStep() >= FieldWidth &&
+ objParams.DownBorder <= FieldHeight &&
+ objParams.DownBorder + GetStep() >= FieldHeight;
+
+ }
+ protected override void MoveToTarget()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return;
+ }
+ var diffX = objParams.RightBorder - FieldWidth;
+ if (Math.Abs(diffX) > GetStep())
+ {
+ if (diffX > 0)
+ {
+ MoveLeft();
+ }
+ else
+ {
+ MoveRight();
+ }
+ }
+ var diffY = objParams.DownBorder - FieldHeight;
+ if (Math.Abs(diffY) > GetStep())
+ {
+ if (diffY > 0)
+ {
+ MoveUp();
+ }
+ else
+ {
+ MoveDown();
+ }
+ }
+ }
+ }
+}
diff --git a/MotorBoat/MotorBoat/MoveToCenter.cs b/MotorBoat/MotorBoat/MoveToCenter.cs
new file mode 100644
index 0000000..2ec5948
--- /dev/null
+++ b/MotorBoat/MotorBoat/MoveToCenter.cs
@@ -0,0 +1,60 @@
+using MotorBoat.MovementStrategy;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.MovementStrategy
+{
+ ///
+ /// Стратегия перемещения объекта в центр экрана
+ ///
+ public class MoveToCenter : AbstractStrategy
+ {
+ protected override bool IsTargetDestinaion()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return false;
+ }
+ return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
+ objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
+ objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
+ objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
+ }
+ protected override void MoveToTarget()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return;
+ }
+ var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
+ if (Math.Abs(diffX) > GetStep())
+ {
+ if (diffX > 0)
+ {
+ MoveLeft();
+ }
+ else
+ {
+ MoveRight();
+ }
+ }
+ var 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/MotorBoat/MotorBoat/ObjectParameters.cs b/MotorBoat/MotorBoat/ObjectParameters.cs
new file mode 100644
index 0000000..22f72c2
--- /dev/null
+++ b/MotorBoat/MotorBoat/ObjectParameters.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.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;
+ ///
+ /// Конструктор
+ ///
+ /// Координата X
+ /// Координата Y
+ /// Ширина
+ /// Высота
+ public ObjectParameters(int x, int y, int width, int height)
+ {
+ _x = x;
+ _y = y;
+ _width = width;
+ _height = height;
+ }
+ }
+}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/Status.cs b/MotorBoat/MotorBoat/Status.cs
new file mode 100644
index 0000000..c34a366
--- /dev/null
+++ b/MotorBoat/MotorBoat/Status.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.MovementStrategy
+{
+ ///
+ /// Статус выполнения операции перемещения
+ ///
+ public enum Status
+ {
+ NotInit,
+ InProgress,
+ Finish
+ }
+}