Compare commits

...

2 Commits

15 changed files with 732 additions and 118 deletions

View File

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

View File

@ -0,0 +1,65 @@
using ProjectAirFighter.Entities;
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirFighter : DrawningWarPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес истребителя</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engines">Признак наличия двигателей</param>
/// <param name="extraWings">Признак наличия дополнительных крыльев</param>
/// <param name="rockets">Признак наличия ракет</param>
public DrawningAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool engines, bool extraWings, bool rockets) : base(150, 150)
{
EntityWarPlane = new EntityAirFighter(speed, weight, bodyColor, additionalColor, engines, extraWings, rockets);
}
public override void DrawTransport(Graphics g)
{
if (EntityWarPlane == null || EntityWarPlane is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
base.DrawTransport(g);
Pen additionalPen = new(airFighter.AdditionalColor);
Brush additionalBrush = new SolidBrush(airFighter.AdditionalColor);
// отрисовка двигателей
if (airFighter.Engines)
{
g.FillEllipse(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 30, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 120, 10, 10);
}
// отрисовка дополнительных крыльев
if (airFighter.ExtraWings)
{
g.DrawLine(additionalPen, _startPosX.Value + 65, _startPosY.Value + 70, _startPosX.Value + 90, _startPosY.Value + 20);
g.DrawLine(additionalPen, _startPosX.Value + 90, _startPosY.Value + 20, _startPosX.Value + 110, _startPosY.Value + 20);
g.DrawLine(additionalPen, _startPosX.Value + 110, _startPosY.Value + 20, _startPosX.Value + 85, _startPosY.Value + 70);
g.DrawLine(additionalPen, _startPosX.Value + 65, _startPosY.Value + 80, _startPosX.Value + 90, _startPosY.Value + 130);
g.DrawLine(additionalPen, _startPosX.Value + 90, _startPosY.Value + 130, _startPosX.Value + 110, _startPosY.Value + 130);
g.DrawLine(additionalPen, _startPosX.Value + 110, _startPosY.Value + 130, _startPosX.Value + 85, _startPosY.Value + 80);
}
// отрисовка ракет
if (airFighter.Rockets)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 32, _startPosY.Value + 4, 8, 6);
g.DrawLine(additionalPen, _startPosX.Value + 32, _startPosY.Value + 4, _startPosX.Value + 26, _startPosY.Value + 7);
g.DrawLine(additionalPen, _startPosX.Value + 26, _startPosY.Value + 7, _startPosX.Value + 32, _startPosY.Value + 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 32, _startPosY.Value + 140, 8, 6);
g.DrawLine(additionalPen, _startPosX.Value + 32, _startPosY.Value + 146, _startPosX.Value + 26, _startPosY.Value + 143);
g.DrawLine(additionalPen, _startPosX.Value + 26, _startPosY.Value + 143, _startPosX.Value + 32, _startPosY.Value + 140);
}
}
}

View File

@ -1,14 +1,13 @@
namespace ProjectAirFighter;
using ProjectAirFighter.Entities;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirFighter
namespace ProjectAirFighter.Drawnings;
public class DrawningWarPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirFighter? EntityAirFighter { get; private set; }
public EntityWarPlane? EntityWarPlane { get; protected set; }
/// <summary>
/// Ширина окна
@ -23,12 +22,12 @@ public class DrawningAirFighter
/// <summary>
/// Левая координата прорисовки истребителя
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки истребителя
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки истребителя
@ -41,25 +40,58 @@ public class DrawningAirFighter
private readonly int _drawningPlaneHeight = 150;
/// <summary>
/// Инициализация полей объекта-класса истребителя
/// Координата X объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес истребителя</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engines">Признак наличия двигателей</param>
/// <param name="extraWings">Признак наличия дополнительных крыльев</param>
/// <param name="rockets">Признак наличия ракет</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool engines, bool extraWings, bool rockets)
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningPlaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningWarPlane()
{
EntityAirFighter = new EntityAirFighter();
EntityAirFighter.Init(speed, weight, bodyColor, additionalColor, engines, extraWings, rockets);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес истребителя</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningWarPlane(int speed, double weight, Color bodyColor) : this()
{
EntityWarPlane = new EntityWarPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningPlaneWidth">Ширина прорисовки истребителя</param>
/// <param name="drawningPlaneHeight">Высота прорисовки истребителя</param>
protected DrawningWarPlane(int drawningPlaneWidth, int drawningPlaneHeight) : this()
{
_drawningPlaneWidth = drawningPlaneWidth;
_drawningPlaneHeight = drawningPlaneHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -79,7 +111,7 @@ public class DrawningAirFighter
if (_startPosY.Value + _drawningPlaneHeight > height) { _startPosY = height - _drawningPlaneHeight; }
}
_pictureWidth = width;
_pictureHeight = height;
_pictureHeight = height;
return true;
}
@ -125,7 +157,7 @@ public class DrawningAirFighter
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityAirFighter == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityWarPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -134,30 +166,30 @@ public class DrawningAirFighter
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityAirFighter.Step > 0)
if (_startPosX.Value - EntityWarPlane.Step > 0)
{
_startPosX -= (int)EntityAirFighter.Step;
_startPosX -= (int)EntityWarPlane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityAirFighter.Step > 0)
if (_startPosY.Value - EntityWarPlane.Step > 0)
{
_startPosY -= (int)EntityAirFighter.Step;
_startPosY -= (int)EntityWarPlane.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + EntityAirFighter.Step + _drawningPlaneWidth < _pictureWidth)
if (_startPosX.Value + EntityWarPlane.Step + _drawningPlaneWidth < _pictureWidth)
{
_startPosX += (int)EntityAirFighter.Step;
_startPosX += (int)EntityWarPlane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityAirFighter.Step + _drawningPlaneHeight < _pictureHeight)
if (_startPosY.Value + EntityWarPlane.Step + _drawningPlaneHeight < _pictureHeight)
{
_startPosY += (int)EntityAirFighter.Step;
_startPosY += (int)EntityWarPlane.Step;
}
return true;
default:
@ -169,9 +201,9 @@ public class DrawningAirFighter
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityAirFighter == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityWarPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
@ -182,11 +214,11 @@ public class DrawningAirFighter
Point point1 = new Point(_startPosX.Value, _startPosY.Value + 75);
Point point2 = new Point(_startPosX.Value + 20, _startPosY.Value + 70);
Point point3 = new Point(_startPosX.Value + 20, _startPosY.Value + 80);
Point[] triangle = {point1, point2, point3};
Point[] triangle = { point1, point2, point3 };
g.FillPolygon(brBlack, triangle);
Pen br = new(EntityAirFighter.BodyColor);
Brush hd = new SolidBrush(EntityAirFighter.BodyColor);
Pen br = new(EntityWarPlane.BodyColor);
Brush hd = new SolidBrush(EntityWarPlane.BodyColor);
// отрисовка корпуса истребителя
g.FillRectangle(hd, _startPosX.Value + 20, _startPosY.Value + 70, 130, 10);
@ -205,37 +237,5 @@ public class DrawningAirFighter
g.DrawLine(br, _startPosX.Value + 150, _startPosY.Value + 80, _startPosX.Value + 150, _startPosY.Value + 95);
g.DrawLine(br, _startPosX.Value + 150, _startPosY.Value + 95, _startPosX.Value + 135, _startPosY.Value + 85);
g.DrawLine(br, _startPosX.Value + 135, _startPosY.Value + 85, _startPosX.Value + 135, _startPosY.Value + 80);
Pen additionalPen = new(EntityAirFighter.AdditionalColor);
Brush additionalBrush = new SolidBrush(EntityAirFighter.AdditionalColor);
// отрисовка двигателей
if (EntityAirFighter.Engines)
{
g.FillEllipse(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 30, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 120, 10, 10);
}
// отрисовка дополнительных крыльев
if (EntityAirFighter.ExtraWings)
{
g.DrawLine(additionalPen, _startPosX.Value + 65, _startPosY.Value + 70, _startPosX.Value + 90, _startPosY.Value + 20);
g.DrawLine(additionalPen, _startPosX.Value + 90, _startPosY.Value + 20, _startPosX.Value + 110, _startPosY.Value + 20);
g.DrawLine(additionalPen, _startPosX.Value + 110, _startPosY.Value + 20, _startPosX.Value + 85, _startPosY.Value + 70);
g.DrawLine(additionalPen, _startPosX.Value + 65, _startPosY.Value + 80, _startPosX.Value + 90, _startPosY.Value + 130);
g.DrawLine(additionalPen, _startPosX.Value + 90, _startPosY.Value + 130, _startPosX.Value + 110, _startPosY.Value + 130);
g.DrawLine(additionalPen, _startPosX.Value + 110, _startPosY.Value + 130, _startPosX.Value + 85, _startPosY.Value + 80);
}
// отрисовка ракет
if (EntityAirFighter.Rockets)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 32, _startPosY.Value + 4, 8, 6);
g.DrawLine(additionalPen, _startPosX.Value + 32, _startPosY.Value + 4, _startPosX.Value + 26, _startPosY.Value + 7);
g.DrawLine(additionalPen, _startPosX.Value + 26, _startPosY.Value + 7, _startPosX.Value + 32, _startPosY.Value + 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 32, _startPosY.Value + 140, 8, 6);
g.DrawLine(additionalPen, _startPosX.Value + 32, _startPosY.Value + 146, _startPosX.Value + 26, _startPosY.Value + 143);
g.DrawLine(additionalPen, _startPosX.Value + 26, _startPosY.Value + 143, _startPosX.Value + 32, _startPosY.Value + 140);
}
}
}

View File

@ -1,25 +1,10 @@
namespace ProjectAirFighter;
namespace ProjectAirFighter.Entities;
/// <summary>
/// Класс-сущность "Истребитель"
/// </summary>
public class EntityAirFighter
public class EntityAirFighter : EntityWarPlane
{
/// <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>
@ -41,12 +26,7 @@ public class EntityAirFighter
public bool Rockets { get; private set; }
/// <summary>
/// Шаг перемещения истребителя
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса истребителя
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес истребителя</param>
@ -55,11 +35,8 @@ public class EntityAirFighter
/// <param name="engines">Признак наличия двигателей</param>
/// <param name="extraWings">Признак наличия дополнительных крыльев</param>
/// <param name="rockets">Признак наличия ракет</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool engines, bool extraWings, bool rockets)
public EntityAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool engines, bool extraWings, bool rockets) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Engines = engines;
ExtraWings = extraWings;

View File

@ -0,0 +1,40 @@
namespace ProjectAirFighter.Entities;
/// <summary>
/// Класс-сущность "Военный самолет"
/// </summary>
public class EntityWarPlane
{
/// <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 EntityWarPlane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -34,6 +34,9 @@
buttonUp = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonCreateWarPlane = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirFighter).BeginInit();
SuspendLayout();
//
@ -53,9 +56,9 @@
buttonCreateAirFighter.Location = new Point(14, 626);
buttonCreateAirFighter.Margin = new Padding(3, 4, 3, 4);
buttonCreateAirFighter.Name = "buttonCreateAirFighter";
buttonCreateAirFighter.Size = new Size(86, 31);
buttonCreateAirFighter.Size = new Size(228, 31);
buttonCreateAirFighter.TabIndex = 1;
buttonCreateAirFighter.Text = "Создать";
buttonCreateAirFighter.Text = "Создать истребитель";
buttonCreateAirFighter.UseVisualStyleBackColor = true;
buttonCreateAirFighter.Click += ButtonCreateAirFighter_Click;
//
@ -111,11 +114,46 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonCreateWarPlane
//
buttonCreateWarPlane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateWarPlane.Location = new Point(248, 626);
buttonCreateWarPlane.Margin = new Padding(3, 4, 3, 4);
buttonCreateWarPlane.Name = "buttonCreateWarPlane";
buttonCreateWarPlane.Size = new Size(228, 31);
buttonCreateWarPlane.TabIndex = 6;
buttonCreateWarPlane.Text = "Создать военный самолет";
buttonCreateWarPlane.UseVisualStyleBackColor = true;
buttonCreateWarPlane.Click += ButtonCreateWarPlane_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(719, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(775, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormAirFighter
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 673);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateWarPlane);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
@ -137,5 +175,8 @@
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateWarPlane;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,7 @@
namespace ProjectAirFighter;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.MovementStrategy;
namespace ProjectAirFighter;
/// <summary>
/// Форма работы с объектом "истребитель"
@ -8,7 +11,12 @@ public partial class FormAirFighter : Form
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAirFighter? _drawningAirFighter;
private DrawningWarPlane? _drawningWarPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
@ -16,6 +24,7 @@ public partial class FormAirFighter : Form
public FormAirFighter()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -23,35 +32,55 @@ public partial class FormAirFighter : Form
/// </summary>
private void Draw()
{
if (_drawningAirFighter == null)
if (_drawningWarPlane == null)
{
return;
}
Bitmap bmp = new(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAirFighter.DrawTransport(gr);
_drawningWarPlane.DrawTransport(gr);
pictureBoxAirFighter.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningWarPlane):
_drawningWarPlane = new DrawningWarPlane(random.Next(300, 600), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningAirFighter):
_drawningWarPlane = new DrawningAirFighter(random.Next(300, 600), 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)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningWarPlane.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
_drawningWarPlane.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать истребитель"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateAirFighter_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAirFighter = new DrawningAirFighter();
_drawningAirFighter.Init(random.Next(300, 600), 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)), Convert.ToBoolean(random.Next(0, 2)));
_drawningAirFighter.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
_drawningAirFighter.SetPosition(random.Next(10, 100), random.Next(10, 100));
private void ButtonCreateAirFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirFighter));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать военный самолет"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateWarPlane_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningWarPlane));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
@ -60,7 +89,7 @@ public partial class FormAirFighter : Form
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningAirFighter == null)
if (_drawningWarPlane == null)
{
return;
}
@ -70,16 +99,16 @@ public partial class FormAirFighter : Form
switch (name)
{
case "buttonUp":
result = _drawningAirFighter.MoveTransport(DirectionType.Up);
result = _drawningWarPlane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningAirFighter.MoveTransport(DirectionType.Down);
result = _drawningWarPlane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningAirFighter.MoveTransport(DirectionType.Left);
result = _drawningWarPlane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningAirFighter.MoveTransport(DirectionType.Right);
result = _drawningWarPlane.MoveTransport(DirectionType.Right);
break;
}
@ -88,4 +117,46 @@ public partial class FormAirFighter : Form
Draw();
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningWarPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableWarPlane(_drawningWarPlane), pictureBoxAirFighter.Width, pictureBoxAirFighter.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,135 @@
namespace ProjectAirFighter.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 ProjectAirFighter.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,36 @@
namespace ProjectAirFighter.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.LeftBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,53 @@
namespace ProjectAirFighter.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,57 @@
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningWarPlane
/// </summary>
public class MoveableWarPlane : IMoveableObject
{
private readonly DrawningWarPlane? _warPlane = null;
public MoveableWarPlane(DrawningWarPlane warPlane)
{
_warPlane = warPlane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_warPlane == null || _warPlane.EntityWarPlane == null || !_warPlane.GetPosX.HasValue || !_warPlane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_warPlane.GetPosX.Value, _warPlane.GetPosY.Value, _warPlane.GetWidth, _warPlane.GetHeight);
}
}
public int GetStep => (int)(_warPlane?.EntityWarPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_warPlane == null || _warPlane.EntityWarPlane == null)
{
return false;
}
return _warPlane.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,24 @@
namespace ProjectAirFighter.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,69 @@
namespace ProjectAirFighter.MovementStrategy;
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,17 @@
namespace ProjectAirFighter.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}