diff --git a/MotorBoat/MotorBoat/DirectionType.cs b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs
similarity index 75%
rename from MotorBoat/MotorBoat/DirectionType.cs
rename to MotorBoat/MotorBoat/Drawnings/DirectionType.cs
index b735a41..30bcde3 100644
--- a/MotorBoat/MotorBoat/DirectionType.cs
+++ b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs
@@ -1,4 +1,4 @@
-namespace MotorBoat
+namespace MotorBoat.Drawnings
{
///
@@ -6,6 +6,10 @@
///
public enum DirectionType
{
+ ///
+ /// Неизвестное направление
+ ///
+ Unknow = -1,
///
/// Вверх
///
diff --git a/MotorBoat/MotorBoat/DrawningMotorBoat.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs
similarity index 57%
rename from MotorBoat/MotorBoat/DrawningMotorBoat.cs
rename to MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs
index 47cbe84..ec1a9a8 100644
--- a/MotorBoat/MotorBoat/DrawningMotorBoat.cs
+++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs
@@ -1,14 +1,18 @@
-namespace MotorBoat
+using MotorBoat.Entities;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.Drawnings
{
- ///
- /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
- ///
- public class DrawningMotorBoat
+ public class DrawningBoat
{
///
/// Класс-сущность
///
- public EntityMotorBoat? EntityMotorBoat { get; private set; }
+ public EntityBoat? EntityBoat { get; protected set; }
///
/// Ширина окна
///
@@ -20,39 +24,67 @@
///
/// Левая координата прорисовки лодки
///
- private int? _startPosX;
+ protected int? _startPosX;
///
/// Верхняя кооридната прорисовки лодки
///
- private int? _startPosY;
+ protected int? _startPosY;
///
/// Ширина прорисовки лодки
///
- private readonly int _drawningBoatWidth = 153;
+ private readonly int _drawningBoatWidth = 143;
///
/// Высота прорисовки лодки
///
- private readonly int _drawningBoatHeight = 75;
+ private readonly int _drawningBoatHeight = 38;
///
- /// Инициализация свойств
+ /// Координата Х объекта
///
- /// Скорость
- /// Вес
- /// Основной цвет
- /// Дополнительный цвет
- /// Признак наличия защитного стекла
- /// Признак наличия мотора
- public void Init(int speed, double weight, Color bodyColor, Color additionalColor,
- bool protectiveGlass, bool engine)
+ public int? GetPosX => _startPosX;
+ ///
+ /// Координата Y объекта
+ ///
+ public int? GetPosY => _startPosY;
+ ///
+ /// Ширина объекта
+ ///
+ public int GetWidth => _drawningBoatWidth;
+ ///
+ /// Высота объекта
+ ///
+ public int GetHeight => _drawningBoatHeight;
+ ///
+ /// Пустой конструктор
+ ///
+ private DrawningBoat()
{
- EntityMotorBoat = new EntityMotorBoat();
- EntityMotorBoat.Init(speed, weight, bodyColor, additionalColor, protectiveGlass, engine);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
///
+ /// Конструктор
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ public DrawningBoat(int speed, double weight, Color bodyColor) : this()
+ {
+ EntityBoat = new EntityBoat(speed, weight, bodyColor);
+ }
+
+ ///
+ /// Конструктор для наследников
+ ///
+ /// Ширина прорисовки лодки
+ /// Высота прорисовки лодки
+ protected DrawningBoat(int drawningBoatWidth, int drawningBoatHeight) : this()
+ {
+ _drawningBoatWidth = drawningBoatWidth;
+ _drawningBoatHeight = drawningBoatHeight;
+ }
+ ///
/// Установка границ поля
///
/// Ширина поля
@@ -68,10 +100,10 @@
if (_startPosX != null && _startPosY != null)
{
if (_startPosX.Value < 0)
- {
+ {
_startPosX = 0;
}
- if (_startPosY.Value < 0)
+ if (_startPosY.Value < 0)
{
_startPosY = 0;
}
@@ -126,7 +158,7 @@
/// невозможно
public bool MoveTransport(DirectionType direction)
{
- if (EntityMotorBoat == null || !_startPosX.HasValue || !_startPosY.HasValue)
+ if (EntityBoat == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@@ -134,30 +166,30 @@
{
//влево
case DirectionType.Left:
- if (_startPosX.Value - EntityMotorBoat.Step > 0)
+ if (_startPosX.Value - EntityBoat.Step > 0)
{
- _startPosX -= (int)EntityMotorBoat.Step;
+ _startPosX -= (int)EntityBoat.Step;
}
return true;
//вверх
case DirectionType.Up:
- if (_startPosY.Value - EntityMotorBoat.Step > 0)
+ if (_startPosY.Value - EntityBoat.Step > 0)
{
- _startPosY -= (int)EntityMotorBoat.Step;
+ _startPosY -= (int)EntityBoat.Step;
}
return true;
//вправо
case DirectionType.Right:
- if (_startPosX.Value + _drawningBoatWidth + EntityMotorBoat.Step < _pictureWidth)
+ if (_startPosX.Value + _drawningBoatWidth + EntityBoat.Step < _pictureWidth)
{
- _startPosX += (int)EntityMotorBoat.Step;
+ _startPosX += (int)EntityBoat.Step;
}
return true;
//вниз
case DirectionType.Down:
- if (_startPosY.Value + _drawningBoatHeight + EntityMotorBoat.Step < _pictureHeight)
+ if (_startPosY.Value + _drawningBoatHeight + EntityBoat.Step < _pictureHeight)
{
- _startPosY += (int)EntityMotorBoat.Step;
+ _startPosY += (int)EntityBoat.Step;
}
return true;
default:
@@ -169,26 +201,25 @@
/// Прорисовка объекта
///
///
- public void DrawTransport(Graphics g)
+ public virtual void DrawTransport(Graphics g)
{
- if (EntityMotorBoat == null || !_startPosX.HasValue ||
+ if (EntityBoat == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
- Brush brushBodyColor = new SolidBrush(EntityMotorBoat.BodyColor);
- Brush brushAdditionalColor = new SolidBrush(EntityMotorBoat.AdditionalColor);
+ Brush brushBodyColor = new SolidBrush(EntityBoat.BodyColor);
- Point[] body =
+ Point[] body =
{
- new Point(_startPosX.Value + 10, _startPosY.Value + 25),
- new Point(_startPosX.Value + 110, _startPosY.Value + 25),
- new Point(_startPosX.Value + 155, _startPosY.Value + 45),
- new Point(_startPosX.Value + 110, _startPosY.Value + 65),
- new Point(_startPosX.Value + 10, _startPosY.Value + 65),
- new Point(_startPosX.Value + 10, _startPosY.Value + 25)
+ new Point(_startPosX.Value, _startPosY.Value),
+ new Point(_startPosX.Value + 100, _startPosY.Value),
+ new Point(_startPosX.Value + 145, _startPosY.Value + 20),
+ new Point(_startPosX.Value + 100, _startPosY.Value + 40),
+ new Point(_startPosX.Value, _startPosY.Value + 40),
+ new Point(_startPosX.Value, _startPosY.Value)
};
// корпус
@@ -196,34 +227,11 @@
g.DrawPolygon(pen, body);
//боковина лодки
- g.DrawEllipse(pen, _startPosX.Value + 25, _startPosY.Value + 30, 30, 30);
- g.DrawEllipse(pen, _startPosX.Value + 70, _startPosY.Value + 30, 30, 30);
- g.DrawLine(pen, _startPosX.Value + 37, _startPosY.Value + 30, _startPosX.Value + 83, _startPosY.Value + 30);
- g.DrawLine(pen, _startPosX.Value + 37, _startPosY.Value + 60, _startPosX.Value + 83, _startPosY.Value + 60);
- g.FillRectangle(brushBodyColor, _startPosX.Value + 37, _startPosY.Value + 31, 50, 29);
-
-
- //защитное стекло спереди
- if (EntityMotorBoat.ProtectiveGlass)
- {
- Point[] glass =
- {
- new Point(_startPosX.Value + 105, _startPosY.Value + 25),
- new Point(_startPosX.Value + 100, _startPosY.Value),
- new Point(_startPosX.Value + 90, _startPosY.Value),
- new Point(_startPosX.Value + 90, _startPosY.Value + 25),
- new Point(_startPosX.Value + 105, _startPosY.Value + 25)
- };
- g.FillPolygon(brushAdditionalColor, glass);
- g.DrawPolygon(pen, glass);
- }
-
- //мотор
- if (EntityMotorBoat.Engine)
- {
- g.FillRectangle(brushAdditionalColor, _startPosX.Value, _startPosY.Value + 50, 10, 25);
- g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 10, 25);
- }
+ g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 5, 30, 30);
+ g.DrawEllipse(pen, _startPosX.Value + 60, _startPosY.Value + 5, 30, 30);
+ g.DrawLine(pen, _startPosX.Value + 27, _startPosY.Value + 5, _startPosX.Value + 73, _startPosY.Value + 5);
+ g.DrawLine(pen, _startPosX.Value + 27, _startPosY.Value + 35, _startPosX.Value + 73, _startPosY.Value + 35);
+ g.FillRectangle(brushBodyColor, _startPosX.Value + 27, _startPosY.Value + 6, 50, 29);
}
diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs b/MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs
new file mode 100644
index 0000000..81d3781
--- /dev/null
+++ b/MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs
@@ -0,0 +1,65 @@
+using MotorBoat.Entities;
+
+namespace MotorBoat.Drawnings
+{
+ ///
+ /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
+ ///
+ public class DrawningMotorBoat : DrawningBoat
+ {
+ ///
+ /// Конструктор
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ /// Дополнительный цвет
+ /// Признак наличия защитного стекла
+ /// Признак наличия мотора
+ public DrawningMotorBoat(int speed, double weight, Color bodyColor, Color additionalColor,
+ bool protectiveGlass, bool engine) : base(153, 75)
+ {
+ EntityBoat = new EntityMotorBoat(speed, weight, bodyColor, additionalColor, protectiveGlass, engine);
+ }
+ ///
+ /// Прорисовка объекта
+ ///
+ ///
+ public override void DrawTransport(Graphics g)
+ {
+ if (EntityBoat == null || EntityBoat is not EntityMotorBoat motorBoat
+ || !_startPosX.HasValue || !_startPosY.HasValue)
+ {
+ return;
+ }
+ Pen pen = new(Color.Black);
+ Brush brushAdditionalColor = new SolidBrush(motorBoat.AdditionalColor);
+
+ //защитное стекло спереди
+ if (motorBoat.ProtectiveGlass)
+ {
+ Point[] glass =
+ {
+ new Point(_startPosX.Value + 105, _startPosY.Value + 25),
+ new Point(_startPosX.Value + 100, _startPosY.Value),
+ new Point(_startPosX.Value + 90, _startPosY.Value),
+ new Point(_startPosX.Value + 90, _startPosY.Value + 25),
+ new Point(_startPosX.Value + 105, _startPosY.Value + 25)
+ };
+ g.FillPolygon(brushAdditionalColor, glass);
+ g.DrawPolygon(pen, glass);
+ }
+ _startPosX += 10;
+ _startPosY += 25;
+ base.DrawTransport(g);
+ _startPosX -= 10;
+ _startPosY -= 25;
+ //мотор
+ if (motorBoat.Engine)
+ {
+ g.FillRectangle(brushAdditionalColor, _startPosX.Value, _startPosY.Value + 50, 10, 25);
+ g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 10, 25);
+ }
+ }
+ }
+}
diff --git a/MotorBoat/MotorBoat/Entities/EntityBoat.cs b/MotorBoat/MotorBoat/Entities/EntityBoat.cs
new file mode 100644
index 0000000..3390697
--- /dev/null
+++ b/MotorBoat/MotorBoat/Entities/EntityBoat.cs
@@ -0,0 +1,43 @@
+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 => Speed * 100 / Weight;
+ ///
+ /// Конструктор сущности
+ ///
+ /// Скорость
+ /// Вес лодки
+ /// Основной цвет
+ public EntityBoat(int speed, double weight, Color bodyColor)
+ {
+ Speed = speed;
+ Weight = weight;
+ BodyColor = bodyColor;
+ }
+ }
+}
diff --git a/MotorBoat/MotorBoat/EntityMotorBoat.cs b/MotorBoat/MotorBoat/Entities/EntityMotorBoat.cs
similarity index 70%
rename from MotorBoat/MotorBoat/EntityMotorBoat.cs
rename to MotorBoat/MotorBoat/Entities/EntityMotorBoat.cs
index 2757fdd..8d522e2 100644
--- a/MotorBoat/MotorBoat/EntityMotorBoat.cs
+++ b/MotorBoat/MotorBoat/Entities/EntityMotorBoat.cs
@@ -1,22 +1,10 @@
-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; }
///
/// Дополнительный цвет (для опциональных элементов)
///
@@ -42,12 +30,9 @@
/// Дополнительный цвет
/// Признак наличия защитного стекла
/// Признак наличия мотора
- public void Init(int speed, double weight, Color bodyColor, Color additionalColor,
- bool protectiveGlass, bool engine)
+ public EntityMotorBoat(int speed, double weight, Color bodyColor, Color additionalColor,
+ bool protectiveGlass, bool engine) : base(speed, weight, bodyColor)
{
- Speed = speed;
- Weight = weight;
- BodyColor = bodyColor;
AdditionalColor = additionalColor;
ProtectiveGlass = protectiveGlass;
Engine = engine;
diff --git a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs
index 5a6e469..961978e 100644
--- a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs
+++ b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs
@@ -29,11 +29,14 @@
private void InitializeComponent()
{
pictureBoxMotorBoat = new PictureBox();
- buttonCreate = new Button();
+ buttonCreateMotorBoat = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
+ buttonCreateBoat = new Button();
+ comboBoxStrategy = new ComboBox();
+ buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMotorBoat).BeginInit();
SuspendLayout();
//
@@ -46,16 +49,16 @@
pictureBoxMotorBoat.TabIndex = 0;
pictureBoxMotorBoat.TabStop = false;
//
- // buttonCreate
+ // buttonCreateMotorBoat
//
- buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
- buttonCreate.Location = new Point(12, 412);
- buttonCreate.Name = "buttonCreate";
- buttonCreate.Size = new Size(75, 23);
- buttonCreate.TabIndex = 1;
- buttonCreate.Text = "Создать";
- buttonCreate.UseVisualStyleBackColor = true;
- buttonCreate.Click += ButtonCreateMotorBoat_Click;
+ buttonCreateMotorBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
+ buttonCreateMotorBoat.Location = new Point(12, 412);
+ buttonCreateMotorBoat.Name = "buttonCreateMotorBoat";
+ buttonCreateMotorBoat.Size = new Size(174, 23);
+ buttonCreateMotorBoat.TabIndex = 1;
+ buttonCreateMotorBoat.Text = "Создать моторную лодку";
+ buttonCreateMotorBoat.UseVisualStyleBackColor = true;
+ buttonCreateMotorBoat.Click += ButtonCreateMotorBoat_Click;
//
// buttonLeft
//
@@ -105,16 +108,50 @@
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
+ // buttonCreateBoat
+ //
+ buttonCreateBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
+ buttonCreateBoat.Location = new Point(203, 412);
+ buttonCreateBoat.Name = "buttonCreateBoat";
+ buttonCreateBoat.Size = new Size(174, 23);
+ buttonCreateBoat.TabIndex = 6;
+ buttonCreateBoat.Text = "Создать лодку";
+ buttonCreateBoat.UseVisualStyleBackColor = true;
+ buttonCreateBoat.Click += ButtonCreateBoat_Click;
+ //
+ // comboBoxStrategy
+ //
+ comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
+ comboBoxStrategy.FormattingEnabled = true;
+ comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
+ comboBoxStrategy.Location = new Point(724, 12);
+ comboBoxStrategy.Name = "comboBoxStrategy";
+ comboBoxStrategy.Size = new Size(121, 23);
+ comboBoxStrategy.TabIndex = 7;
+ //
+ // buttonStrategyStep
+ //
+ buttonStrategyStep.Location = new Point(774, 41);
+ buttonStrategyStep.Name = "buttonStrategyStep";
+ buttonStrategyStep.Size = new Size(75, 23);
+ buttonStrategyStep.TabIndex = 8;
+ buttonStrategyStep.Text = "Шаг";
+ buttonStrategyStep.UseVisualStyleBackColor = true;
+ buttonStrategyStep.Click += buttonStrategyStep_Click;
+ //
// FormMotorBoat
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(861, 447);
+ Controls.Add(buttonStrategyStep);
+ Controls.Add(comboBoxStrategy);
+ Controls.Add(buttonCreateBoat);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
- Controls.Add(buttonCreate);
+ Controls.Add(buttonCreateMotorBoat);
Controls.Add(pictureBoxMotorBoat);
Name = "FormMotorBoat";
Text = "Моторная лодка";
@@ -125,10 +162,13 @@
#endregion
private PictureBox pictureBoxMotorBoat;
- private Button buttonCreate;
+ private Button buttonCreateMotorBoat;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
+ private Button buttonCreateBoat;
+ private ComboBox comboBoxStrategy;
+ private Button buttonStrategyStep;
}
}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/FormMotorBoat.cs b/MotorBoat/MotorBoat/FormMotorBoat.cs
index 8ff553a..8cf446e 100644
--- a/MotorBoat/MotorBoat/FormMotorBoat.cs
+++ b/MotorBoat/MotorBoat/FormMotorBoat.cs
@@ -7,54 +7,83 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
+using MotorBoat.Drawnings;
+using MotorBoat.MovementStrategy;
namespace MotorBoat
{
+ ///
+ /// Форма работы с объектом "Моторная лодка"
+ ///
public partial class FormMotorBoat : Form
{
- private DrawningMotorBoat? _drawningMotorBoat;
+ ///
+ /// Поле для прорисовки объекта
+ ///
+ private DrawningBoat? _drawningBoat;
+ ///
+ /// Стратегия перемещения
+ ///
+ private AbstractStrategy? _strategy;
///
/// Конструктор формы
///
public FormMotorBoat()
{
InitializeComponent();
+ _strategy = null;
}
///
/// Метод прорисовки катера
///
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 CreateObject(string type)
+ {
+ Random random = new Random();
+ switch (type)
+ {
+ case nameof(DrawningBoat):
+ _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)));
+ break;
+ case nameof(DrawningMotorBoat):
+ _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)));
+ break;
+ default:
+ return;
+ }
+ _drawningBoat.SetPictureSize(pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height);
+ _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
+ _strategy = null;
+ comboBoxStrategy.Enabled = true;
+ Draw();
+ }
///
- /// Обработка нажатия кнопки "Создать"
+ /// Обработка нажатия кнопки "Создать моторную лодку"
///
///
///
- private void ButtonCreateMotorBoat_Click(object sender, EventArgs e)
- {
- Random random = new();
- _drawningMotorBoat = new DrawningMotorBoat();
- _drawningMotorBoat.Init(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)));
- _drawningMotorBoat.SetPictureSize(pictureBoxMotorBoat.Width,
- pictureBoxMotorBoat.Height);
- _drawningMotorBoat.SetPosition(random.Next(10, 100), random.Next(10,
- 100));
- Draw();
- }
+ private void ButtonCreateMotorBoat_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMotorBoat));
+ ///
+ /// Обработка нажатия кнопки "Создать лодку"
+ ///
+ ///
+ ///
+ private void ButtonCreateBoat_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBoat));
///
/// Перемещение объекта по форме (нажатие кнопок навигации)
///
@@ -62,7 +91,7 @@ namespace MotorBoat
///
private void ButtonMove_Click(object sender, EventArgs e)
{
- if (_drawningMotorBoat == null)
+ if (_drawningBoat == null)
{
return;
}
@@ -72,19 +101,19 @@ namespace MotorBoat
{
case "buttonUp":
result =
- _drawningMotorBoat.MoveTransport(DirectionType.Up);
+ _drawningBoat.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
- _drawningMotorBoat.MoveTransport(DirectionType.Down);
+ _drawningBoat.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
- _drawningMotorBoat.MoveTransport(DirectionType.Left);
+ _drawningBoat.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
- _drawningMotorBoat.MoveTransport(DirectionType.Right);
+ _drawningBoat.MoveTransport(DirectionType.Right);
break;
}
if (result)
@@ -92,5 +121,46 @@ namespace MotorBoat
Draw();
}
}
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ private void buttonStrategyStep_Click(object sender, EventArgs e)
+ {
+ if (_drawningBoat == null)
+ {
+ return;
+ }
+ if (comboBoxStrategy.Enabled)
+ {
+ _strategy = comboBoxStrategy.SelectedIndex switch
+ {
+ 0 => new MoveToCenter(),
+ 1 => new MoveToBorder(),
+ _ => null,
+ };
+ if (_strategy == null)
+ {
+ return;
+ }
+ _strategy.SetData(new MoveableBoat(_drawningBoat),
+ pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height);
+ }
+ if (_strategy == null)
+ {
+ return;
+ }
+ comboBoxStrategy.Enabled = false;
+ _strategy.MakeStep();
+ Draw();
+ if (_strategy.GetStatus() == StrategyStatus.Finish)
+ {
+ comboBoxStrategy.Enabled = true;
+ _strategy = null;
+ }
+ }
+
}
}
diff --git a/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs b/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs
new file mode 100644
index 0000000..934d404
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs
@@ -0,0 +1,119 @@
+namespace MotorBoat.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/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs b/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs
new file mode 100644
index 0000000..f16a3c5
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs
@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.MovementStrategy;
+///
+/// Интерфейс для работы с перемещаемым объектом
+///
+public interface IMoveableObject
+{
+ ///
+ /// Получение координаты объекта
+ ///
+ ObjectParameters? GetObjectPosition { get; }
+ ///
+ /// Шаг объекта
+ ///
+ int GetStep { get; }
+ ///
+ /// Попытка переместить объект в указанном направлении
+ ///
+ /// Направление
+ /// true - объект перемещен, false - перемещение невозможно
+ bool TryMoveObject(MovementDirection direction);
+}
diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs
new file mode 100644
index 0000000..c59364e
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs
@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MotorBoat.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 - FieldWidth;
+ if (Math.Abs(diffX) > GetStep())
+ {
+ MoveRight();
+ }
+
+ int diffY = objParams.DownBorder - FieldHeight;
+ if (Math.Abs(diffY) > GetStep())
+ {
+ MoveDown();
+ }
+ }
+}
diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs
new file mode 100644
index 0000000..5f02253
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.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 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/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs
new file mode 100644
index 0000000..3bddf7c
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs
@@ -0,0 +1,59 @@
+using MotorBoat.Drawnings;
+
+namespace MotorBoat.MovementStrategy;
+///
+/// Класс-реализация IMoveableObject с использованием DrawningBoat
+///
+public class MoveableBoat : IMoveableObject
+{
+ ///
+ /// Поле-объект класса DrawningBoat или его наследника
+ ///
+ private readonly DrawningBoat? _boat = null;
+ ///
+ /// Конструктор
+ ///
+ /// Объект класса DrawningBoat
+ public MoveableBoat(DrawningBoat boat)
+ {
+ _boat = boat;
+ }
+ public ObjectParameters? GetObjectPosition
+ {
+ get
+ {
+ if (_boat == null || _boat.EntityBoat == null ||
+ !_boat.GetPosX.HasValue || !_boat.GetPosY.HasValue)
+ {
+ return null;
+ }
+ return new ObjectParameters(_boat.GetPosX.Value,
+ _boat.GetPosY.Value, _boat.GetWidth, _boat.GetHeight);
+ }
+ }
+ public int GetStep => (int)(_boat?.EntityBoat?.Step ?? 0);
+ public bool TryMoveObject(MovementDirection direction)
+ {
+ if (_boat == null || _boat.EntityBoat == null)
+ {
+ return false;
+ }
+ return _boat.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/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs b/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs
new file mode 100644
index 0000000..315da02
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs
@@ -0,0 +1,24 @@
+namespace MotorBoat.MovementStrategy;
+
+///
+/// Направление перемещения
+///
+public enum MovementDirection
+{
+ ///
+ /// Вверх
+ ///
+ Up = 1,
+ ///
+ /// Вниз
+ ///
+ Down = 2,
+ ///
+ /// Влево
+ ///
+ Left = 3,
+ ///
+ /// Вправо
+ ///
+ Right = 4
+}
diff --git a/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs b/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs
new file mode 100644
index 0000000..be6318d
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs
@@ -0,0 +1,62 @@
+namespace MotorBoat.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;
+ }
+}
\ No newline at end of file
diff --git a/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs b/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs
new file mode 100644
index 0000000..26d73b8
--- /dev/null
+++ b/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs
@@ -0,0 +1,19 @@
+namespace MotorBoat.MovementStrategy;
+///
+/// Статус выполнения операции перемещения
+///
+public enum StrategyStatus
+{
+ ///
+ /// Все готово к началу
+ ///
+ NotInit,
+ ///
+ /// Выполняется
+ ///
+ InProgress,
+ ///
+ /// Завершено
+ ///
+ Finish
+}