Compare commits

...

2 Commits

Author SHA1 Message Date
ShuryginDima
c2ae9d68b4 Добавление стратегии 2024-03-11 21:10:39 +03:00
ShuryginDima
fdeb174e90 Добавление родителей и ввод конструкторов 2024-03-10 16:04:36 +03:00
15 changed files with 779 additions and 125 deletions

View File

@ -1,9 +1,14 @@
namespace ProjectSeaplane; namespace ProjectSeaplane.Drawnings;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения
/// </summary> /// </summary>
public enum DirectionType public enum DirectionType
{ {
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </summary> /// </summary>

View File

@ -1,13 +1,16 @@
namespace ProjectSeaplane; using ProjectSeaplane.Entities;
namespace ProjectSeaplane.Drawnings;
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary> /// </summary>
public class DrawningSeaplane public class DrawningPlane
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntitySeaplane? EntitySeaplane { get; private set; } public EntityPlane? EntityPlane { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -20,44 +23,75 @@ public class DrawningSeaplane
private int? _pictureHeight; private int? _pictureHeight;
/// <summary> /// <summary>
/// Левая координата прорисовки гидросамолёта /// Левая координата прорисовки самолёта
/// </summary> /// </summary>
private int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки гидросамолёта /// Верхняя кооридната прорисовки самолёта
/// </summary> /// </summary>
private int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки гидросамолёта /// Ширина прорисовки самолёта
/// </summary> /// </summary>
private readonly int _drawningSeaplaneWidth = 130; private readonly int _drawningPlaneWidth = 130;
/// <summary> /// <summary>
/// Высота прорисовки гидросамолёта /// Высота прорисовки самолёта
/// </summary> /// </summary>
private readonly int _drawningSeaplaneHeight = 50; private readonly int _drawningPlaneHeight = 45;
/// <summary> /// <summary>
/// Инициализация свойств /// Координата X объекта
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> public int? GetPosX => _startPosX;
/// <param name="weight">Вес</param> /// <summary>
/// <param name="bodyColor">Основной цвет</param> /// Координата Y объекта
/// <param name="additionalColor">Дополнительный цвет</param> /// </summary>
/// <param name="floats">Признак наличия поплавков</param> public int? GetPosY => _startPosY;
/// <param name="boat">Признак наличия лодки</param> /// <summary>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool boat) /// Ширина объекта
/// </summary>
public int GetWidth => _drawningPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningPlaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningPlane()
{ {
EntitySeaplane = new EntitySeaplane();
EntitySeaplane.Init(speed, weight, bodyColor, additionalColor, floats, boat);
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningPlane(int speed, double weight, Color bodyColor) : this()
{
EntityPlane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningPlaneWidth">Ширина прорисовки гидросамолёта</param>
/// <param name="drawningPlaneHeight">Высота прорисовки гидросамолёта</param>
protected DrawningPlane(int drawningPlaneWidth, int drawningPlaneHeight) : this()
{
_drawningPlaneWidth = drawningPlaneWidth;
_drawningPlaneHeight = drawningPlaneHeight;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
@ -67,18 +101,16 @@ public class DrawningSeaplane
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
if (height < _drawningPlaneHeight || width < _drawningPlaneWidth)
if (height < _drawningSeaplaneHeight || width < _drawningSeaplaneWidth)
{ {
return false; return false;
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
if (_startPosX.HasValue && _drawningSeaplaneWidth + _startPosX > width) _startPosX = _pictureWidth - _drawningSeaplaneWidth; if (_startPosX.HasValue && _drawningPlaneWidth + _startPosX > width) _startPosX = _pictureWidth - _drawningPlaneWidth;
if (_startPosY.HasValue && _drawningSeaplaneHeight + _startPosY > height) _startPosY = _pictureHeight - _drawningSeaplaneHeight; if (_startPosY.HasValue && _drawningPlaneHeight + _startPosY > height) _startPosY = _pictureHeight - _drawningPlaneHeight;
return true; return true;
} }
@ -97,17 +129,17 @@ public class DrawningSeaplane
{ {
x = 0; x = 0;
} }
if (x + _drawningSeaplaneWidth > _pictureWidth.Value) if (x + _drawningPlaneWidth > _pictureWidth.Value)
{ {
x = _pictureWidth.Value - _drawningSeaplaneWidth; x = _pictureWidth.Value - _drawningPlaneWidth;
} }
if (y < 0) if (y < 0)
{ {
y = 0; y = 0;
} }
if (y + _drawningSeaplaneHeight > _pictureHeight.Value) if (y + _drawningPlaneHeight > _pictureHeight.Value)
{ {
y = _pictureHeight.Value - _drawningSeaplaneHeight; y = _pictureHeight.Value - _drawningPlaneHeight;
} }
_startPosX = x; _startPosX = x;
@ -121,7 +153,7 @@ public class DrawningSeaplane
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns> /// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if (EntitySeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
@ -130,54 +162,52 @@ public class DrawningSeaplane
{ {
//влево //влево
case DirectionType.Left: case DirectionType.Left:
if (_startPosX.Value - EntitySeaplane.Step > 0) if (_startPosX.Value - EntityPlane.Step > 0)
{ {
_startPosX -= (int)EntitySeaplane.Step; _startPosX -= (int)EntityPlane.Step;
} }
return true; return true;
//вверх //вверх
case DirectionType.Up: case DirectionType.Up:
if (_startPosY.Value - EntitySeaplane.Step > 0) if (_startPosY.Value - EntityPlane.Step > 0)
{ {
_startPosY -= (int)EntitySeaplane.Step; _startPosY -= (int)EntityPlane.Step;
} }
return true; return true;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + _drawningSeaplaneWidth + EntitySeaplane.Step < _pictureWidth) if (_startPosX.Value + _drawningPlaneWidth + EntityPlane.Step < _pictureWidth)
{ {
_startPosX += (int)EntitySeaplane.Step; _startPosX += (int)EntityPlane.Step;
} }
return true; return true;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + _drawningSeaplaneHeight + EntitySeaplane.Step < _pictureHeight) if (_startPosY.Value + _drawningPlaneHeight + EntityPlane.Step < _pictureHeight)
{ {
_startPosY += (int)EntitySeaplane.Step; _startPosY += (int)EntityPlane.Step;
} }
return true; return true;
default: default:
return false; return false;
} }
} }
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntitySeaplane == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
Pen pen = new(Color.Black, 2); Pen pen = new(Color.Black, 2);
Brush additionalBrush = new SolidBrush(EntitySeaplane.AdditionalColor);
//Отрисовка основных частей самолёта //Отрисовка основных частей самолёта
Brush br = new SolidBrush(EntitySeaplane.BodyColor); Brush br = new SolidBrush(EntityPlane.BodyColor);
g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 20, 20, 20); g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 20, 20, 20);
g.FillEllipse(br, _startPosX.Value, _startPosY.Value + 20, 20, 20); g.FillEllipse(br, _startPosX.Value, _startPosY.Value + 20, 20, 20);
Point point1 = new Point(_startPosX.Value + 10, _startPosY.Value); Point point1 = new Point(_startPosX.Value + 10, _startPosY.Value);
@ -212,26 +242,5 @@ public class DrawningSeaplane
g.FillEllipse(br, _startPosX.Value + 35, _startPosY.Value + 45, 5, 5); g.FillEllipse(br, _startPosX.Value + 35, _startPosY.Value + 45, 5, 5);
g.FillEllipse(br, _startPosX.Value + 42, _startPosY.Value + 45, 5, 5); g.FillEllipse(br, _startPosX.Value + 42, _startPosY.Value + 45, 5, 5);
g.FillEllipse(br, _startPosX.Value + 87, _startPosY.Value + 45, 5, 5); g.FillEllipse(br, _startPosX.Value + 87, _startPosY.Value + 45, 5, 5);
//Надувнвя лодка
if (EntitySeaplane.Boat)
{
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 15, 30, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 15, 30, 10);
}
//Поплавки
if (EntitySeaplane.Floats)
{
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value + 30, 4, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 30, _startPosY.Value + 30, 4, 15);
g.DrawRectangle(pen, _startPosX.Value + 66, _startPosY.Value + 30, 4, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 66, _startPosY.Value + 30, 4, 15);
g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 40, 70, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 40, 70, 10);
}
} }
} }

View File

@ -0,0 +1,54 @@
using ProjectSeaplane.Entities;
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningSeaplane : DrawningPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="floats">Признак наличия поплавков</param>
/// <param name="boat">Признак наличия лодки</param>
public DrawningSeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool boat) : base(130, 50)
{
EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, floats, boat);
}
public override void DrawTransport(Graphics g)
{
if (EntityPlane == null || EntityPlane is not EntitySeaplane seaplane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black, 2);
Brush additionalBrush = new SolidBrush(seaplane.AdditionalColor);
base.DrawTransport(g);
//Надувнвя лодка
if (seaplane.Boat)
{
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 15, 30, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 15, 30, 10);
}
//Поплавки
if (seaplane.Floats)
{
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value + 30, 4, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 30, _startPosY.Value + 30, 4, 15);
g.DrawRectangle(pen, _startPosX.Value + 66, _startPosY.Value + 30, 4, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 66, _startPosY.Value + 30, 4, 15);
g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 40, 70, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 40, 70, 10);
}
}
}

View File

@ -0,0 +1,40 @@
namespace ProjectSeaplane.Entities;
/// <summary>
/// Класс-сущность "Самолёт"
/// </summary>
public class EntityPlane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения гидросамолёта
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityPlane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,23 +1,12 @@
namespace ProjectSeaplane; namespace ProjectSeaplane.Entities;
/// <summary> /// <summary>
/// Класс-сущность "Гидросамолёт" /// Класс-сущность "Гидросамолёт"
/// </summary> /// </summary>
public class EntitySeaplane public class EntitySeaplane : EntityPlane
{ {
/// <summary> public EntitySeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool boat) : base(speed, weight, bodyColor)
/// Скорость {
/// </summary> }
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary> /// <summary>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
@ -35,11 +24,6 @@ public class EntitySeaplane
/// </summary> /// </summary>
public bool Boat { get; private set; } public bool Boat { get; private set; }
/// <summary>
/// Шаг перемещения гидросамолёта
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// Инициализация полей объекта-класса гидросамолёта /// Инициализация полей объекта-класса гидросамолёта
/// </summary> /// </summary>
@ -49,12 +33,8 @@ public class EntitySeaplane
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="floats">Признак наличия поплавков</param> /// <param name="floats">Признак наличия поплавков</param>
/// <param name="boat">Признак наличия лодки</param> /// <param name="boat">Признак наличия лодки</param>
public void Init(int speed, double weight, Color bodyColor, Color public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool boat)
additionalColor, bool floats, bool boat)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Floats = floats; Floats = floats;
Boat = boat; Boat = boat;

View File

@ -34,6 +34,9 @@
buttonUp = new Button(); buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreatePlane = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSeaplane).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxSeaplane).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -51,9 +54,9 @@
buttonCreateSeaplane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateSeaplane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateSeaplane.Location = new Point(12, 465); buttonCreateSeaplane.Location = new Point(12, 465);
buttonCreateSeaplane.Name = "buttonCreateSeaplane"; buttonCreateSeaplane.Name = "buttonCreateSeaplane";
buttonCreateSeaplane.Size = new Size(75, 23); buttonCreateSeaplane.Size = new Size(196, 23);
buttonCreateSeaplane.TabIndex = 1; buttonCreateSeaplane.TabIndex = 1;
buttonCreateSeaplane.Text = "Создать"; buttonCreateSeaplane.Text = "Создать гидросамолёт";
buttonCreateSeaplane.UseVisualStyleBackColor = true; buttonCreateSeaplane.UseVisualStyleBackColor = true;
buttonCreateSeaplane.Click += ButtonCreateSeaplane_Click; buttonCreateSeaplane.Click += ButtonCreateSeaplane_Click;
// //
@ -105,11 +108,45 @@
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreatePlane
//
buttonCreatePlane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreatePlane.Location = new Point(214, 465);
buttonCreatePlane.Name = "buttonCreatePlane";
buttonCreatePlane.Size = new Size(196, 23);
buttonCreatePlane.TabIndex = 6;
buttonCreatePlane.Text = "Создать самолёт";
buttonCreatePlane.UseVisualStyleBackColor = true;
buttonCreatePlane.Click += ButtonCreatePlane_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(763, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(808, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormSeaplane // FormSeaplane
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(900, 500); ClientSize = new Size(900, 500);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreatePlane);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
@ -130,5 +167,8 @@
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreatePlane;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,4 +1,7 @@
namespace ProjectSeaplane; using ProjectSeaplane.Drawnings;
using ProjectSeaplane.MovementStrategy;
namespace ProjectSeaplane;
/// <summary> /// <summary>
/// Форма работы с объектом "Спортивный автомобиль" /// Форма работы с объектом "Спортивный автомобиль"
/// </summary> /// </summary>
@ -7,46 +10,82 @@ public partial class FormSeaplane : Form
/// <summary> /// <summary>
/// Поле-объект для прорисовки объекта /// Поле-объект для прорисовки объекта
/// </summary> /// </summary>
private DrawningSeaplane? _drawningSeaplane; private DrawningPlane? _drawningPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary> /// <summary>
/// Конструктор формы /// Конструктор формы
/// </summary> /// </summary>
public FormSeaplane() public FormSeaplane()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
/// Метод прорисовки машины /// Метод прорисовки машины
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningSeaplane == null) if (_drawningPlane == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height); Bitmap bmp = new(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningSeaplane.DrawTransport(gr); _drawningPlane.DrawTransport(gr);
pictureBoxSeaplane.Image = bmp; pictureBoxSeaplane.Image = bmp;
} }
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Создать" /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="type">Тип создаваемого объекта</param>
/// <param name="e"></param> private void CreateObject(string type)
private void ButtonCreateSeaplane_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawningSeaplane = new DrawningSeaplane(); switch (type)
{
_drawningSeaplane.Init(random.Next(100, 300), random.Next(1000, 3000), case nameof(DrawningPlane):
_drawningPlane = new DrawningPlane(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(DrawningSeaplane):
_drawningPlane = new DrawningSeaplane(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)),
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))); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningSeaplane.SetPictureSize(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height); break;
_drawningSeaplane.SetPosition(random.Next(10, 100), random.Next(10, 100)); default:
return;
}
_drawningPlane.SetPictureSize(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
_drawningPlane.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
/// <summary>
/// Обработка нажатия кнопки "Создать гидросамолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateSeaplane_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSeaplane));
/// <summary>
/// Обработка нажатия кнопки "Создать самолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreatePlane_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPlane));
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary> /// </summary>
@ -54,7 +93,7 @@ public partial class FormSeaplane : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningSeaplane == null) if (_drawningPlane == null)
{ {
return; return;
} }
@ -63,20 +102,16 @@ public partial class FormSeaplane : Form
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = result = _drawningPlane.MoveTransport(DirectionType.Up);
_drawningSeaplane.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = result = _drawningPlane.MoveTransport(DirectionType.Down);
_drawningSeaplane.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = result = _drawningPlane.MoveTransport(DirectionType.Left);
_drawningSeaplane.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = result = _drawningPlane.MoveTransport(DirectionType.Right);
_drawningSeaplane.MoveTransport(DirectionType.Right);
break; break;
} }
if (result) if (result)
@ -84,4 +119,45 @@ public partial class FormSeaplane : Form
Draw(); Draw();
} }
} }
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveablePlane(_drawningPlane), pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
} }

View File

@ -0,0 +1,138 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Класс перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
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;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,24 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,51 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в угол экрана
/// </summary>
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())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,50 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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();
}
}
}
}

View File

@ -0,0 +1,61 @@
using ProjectSeaplane.Drawnings;
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningPlane
/// </summary>
public class MoveablePlane : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningPlane или его наследника
/// </summary>
private readonly DrawningPlane? _plane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="plane">Объект класса DrawningPlane</param>
public MoveablePlane(DrawningPlane plane)
{
_plane = plane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_plane == null || _plane.EntityPlane == null || !_plane.GetPosX.HasValue || !_plane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_plane.GetPosX.Value, _plane.GetPosY.Value, _plane.GetWidth, _plane.GetHeight);
}
}
public int GetStep => (int)(_plane?.EntityPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_plane == null || _plane.EntityPlane == null)
{
return false;
}
return _plane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
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,
};
}
}

View File

@ -0,0 +1,32 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,72 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина объекта</param>
/// <param name="height">Высота объекта</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -0,0 +1,22 @@
namespace ProjectSeaplane.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}