Лабораторная работа №2

This commit is contained in:
LivelyPuer 2024-04-11 13:28:54 +04:00
parent f78bc58e13
commit fc86d0a67c
14 changed files with 577 additions and 93 deletions

View File

@ -5,6 +5,7 @@
/// </summary> /// </summary>
public enum DirectionType public enum DirectionType
{ {
Unknow = -1,
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </summary> /// </summary>

View File

@ -22,7 +22,7 @@ public class DrawningAirBomber : DrawningBomber
//TO DO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //TO DO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs, bool v) : base(200, 160) public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs) : base(200, 160)
{ {
EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, fuelTanks, bombs); EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, fuelTanks, bombs);
} }

View File

@ -44,7 +44,22 @@ public class DrawningBomber
/// </summary> /// </summary>
private readonly int _drawningAirBomberHeight = 160; private readonly int _drawningAirBomberHeight = 160;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningAirBomberWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningAirBomberHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
@ -214,16 +229,16 @@ public class DrawningBomber
g.FillPolygon(brGray, new Point[] g.FillPolygon(brGray, new Point[]
{ {
new Point(_startPosX.Value + 95, _startPosY.Value), new Point(_startPosX.Value + 95, _startPosY.Value),
new Point(_startPosX.Value + 115, _startPosY.Value + 5), new Point(_startPosX.Value + 110, _startPosY.Value + 5),
new Point(_startPosX.Value + 125, _startPosY.Value + 85) new Point(_startPosX.Value + 118, _startPosY.Value + 85)
}); });
////левое крыло ////левое крыло
g.FillPolygon(brGray, new Point[] g.FillPolygon(brGray, new Point[]
{ {
new Point(_startPosX.Value + 95, _startPosY.Value + 85), new Point(_startPosX.Value + 95, _startPosY.Value + 85),
new Point(_startPosX.Value + 115, _startPosY.Value + 135), new Point(_startPosX.Value + 110, _startPosY.Value + 135),
new Point(_startPosX.Value + 121, _startPosY.Value + 85) new Point(_startPosX.Value + 115, _startPosY.Value + 85)
}); });
//задние крылья //задние крылья

View File

@ -5,9 +5,7 @@
/// </summary> /// </summary>
public class EntityAirBomber : EntityBomber public class EntityAirBomber : EntityBomber
{ {
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs) : base(speed, weight, bodyColor)
{
}
/// <summary> /// <summary>
@ -41,7 +39,7 @@ public class EntityAirBomber : EntityBomber
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param> /// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
/// <param name="bombs">Признак наличия бомб</param> /// <param name="bombs">Признак наличия бомб</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs) public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs): base(speed, weight, bodyColor)
{ {
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
FuelTanks = fuelTanks; FuelTanks = fuelTanks;

View File

@ -1,4 +1,8 @@
namespace ProjectAirBomber using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
using System.Xml.Linq;
namespace ProjectAirBomber
{ {
partial class FormAirBomber partial class FormAirBomber
{ {
@ -31,30 +35,32 @@
pictureBoxAirBomber = new PictureBox(); pictureBoxAirBomber = new PictureBox();
buttonCreateAirBomber = new Button(); buttonCreateAirBomber = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonUp = new Button(); buttonCreateCar = new Button();
buttonCreateBomber = new Button(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxAirBomber // pictureBoxElectroTrans
// //
pictureBoxAirBomber.Dock = DockStyle.Fill; pictureBoxAirBomber.Dock = DockStyle.Fill;
pictureBoxAirBomber.Location = new Point(0, 0); pictureBoxAirBomber.Location = new Point(0, 0);
pictureBoxAirBomber.Name = "pictureBoxAirBomber"; pictureBoxAirBomber.Name = "pictureBoxElectroTrans";
pictureBoxAirBomber.Size = new Size(880, 510); pictureBoxAirBomber.Size = new Size(923, 597);
pictureBoxAirBomber.TabIndex = 0; pictureBoxAirBomber.TabIndex = 0;
pictureBoxAirBomber.TabStop = false; pictureBoxAirBomber.TabStop = false;
// //
// buttonCreateAirBomber // buttonCreateElectroTrans
// //
buttonCreateAirBomber.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateAirBomber.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirBomber.Location = new Point(12, 475); buttonCreateAirBomber.Location = new Point(12, 562);
buttonCreateAirBomber.Name = "buttonCreateAirBomber"; buttonCreateAirBomber.Name = "buttonCreateAirBomber";
buttonCreateAirBomber.Size = new Size(233, 23); buttonCreateAirBomber.Size = new Size(223, 23);
buttonCreateAirBomber.TabIndex = 1; buttonCreateAirBomber.TabIndex = 1;
buttonCreateAirBomber.Text = "Создать военный самолёт"; buttonCreateAirBomber.Text = "Создать бомбардировщик";
buttonCreateAirBomber.UseVisualStyleBackColor = true; buttonCreateAirBomber.UseVisualStyleBackColor = true;
buttonCreateAirBomber.Click += ButtonCreateAirBomber_Click; buttonCreateAirBomber.Click += ButtonCreateAirBomber_Click;
// //
@ -63,22 +69,34 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft; buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(750, 469); buttonLeft.Location = new Point(787, 550);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35); buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true; buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click; buttonLeft.Click += ButtonMove_Click;
// //
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(828, 509);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown // buttonDown
// //
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown; buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch; buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(786, 469); buttonDown.Location = new Point(828, 550);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 3; buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click; buttonDown.Click += ButtonMove_Click;
// //
@ -87,50 +105,60 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight; buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch; buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(822, 469); buttonRight.Location = new Point(869, 550);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35); buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 4; buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonUp // buttonCreateCar
// //
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCreateCar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonUp.BackgroundImage = Properties.Resources.arrowUp; buttonCreateCar.Location = new Point(250, 562);
buttonUp.BackgroundImageLayout = ImageLayout.Stretch; buttonCreateCar.Name = "buttonCreateTrans";
buttonUp.Location = new Point(786, 433); buttonCreateCar.Size = new Size(223, 23);
buttonUp.Name = "buttonUp"; buttonCreateCar.TabIndex = 6;
buttonUp.Size = new Size(35, 35); buttonCreateCar.Text = "Создать военный самолет";
buttonUp.TabIndex = 5; buttonCreateCar.UseVisualStyleBackColor = true;
buttonUp.UseVisualStyleBackColor = true; buttonCreateCar.Click += ButtonCreateBomber_Click;
buttonUp.Click += ButtonMove_Click;
// //
// buttonCreateBomber // comboBoxStrategy
// //
buttonCreateBomber.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
buttonCreateBomber.Location = new Point(261, 475); comboBoxStrategy.FormattingEnabled = true;
buttonCreateBomber.Name = "buttonCreateBomber"; comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
buttonCreateBomber.Size = new Size(233, 23); comboBoxStrategy.Location = new Point(790, 12);
buttonCreateBomber.TabIndex = 6; comboBoxStrategy.Name = "comboBoxStrategy";
buttonCreateBomber.Text = "Создать самолёт"; comboBoxStrategy.Size = new Size(121, 23);
buttonCreateBomber.UseVisualStyleBackColor = true; comboBoxStrategy.TabIndex = 7;
buttonCreateBomber.Click += buttonCreateBomber_Click;
// //
// FormAirBomber // buttonStrategyStep
//
buttonStrategyStep.Location = new Point(836, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormElectroTrans
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(880, 510); ClientSize = new Size(923, 597);
Controls.Add(buttonCreateBomber); Controls.Add(buttonStrategyStep);
Controls.Add(buttonUp); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCar);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreateAirBomber); Controls.Add(buttonCreateAirBomber);
Controls.Add(pictureBoxAirBomber); Controls.Add(pictureBoxAirBomber);
Name = "FormAirBomber"; Name = "FormElectroTrans";
Text = "Бомбардировщик"; Text = "Электропоезд";
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
@ -140,9 +168,11 @@
private PictureBox pictureBoxAirBomber; private PictureBox pictureBoxAirBomber;
private Button buttonCreateAirBomber; private Button buttonCreateAirBomber;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonUp; private Button buttonCreateCar;
private Button buttonCreateBomber; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,90 +1,87 @@
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.MovementStrategy;
namespace ProjectAirBomber; namespace ProjectAirBomber;
/// <summary>
/// Форма работы с объектом "Бомбардировщик"
/// </summary>
public partial class FormAirBomber : Form public partial class FormAirBomber : Form
{ {
/// <summary> /// <summary>
/// Поле-объект для прорисовки объекта /// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary> /// </summary>
private DrawningBomber? _drawningBomber; private DrawningBomber? _drawingBomber;
/// <summary> /// <summary>
/// Конструктор формы /// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary> /// </summary>
private AbstractStrategy? _strategy;
public FormAirBomber() public FormAirBomber()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
/// Метод прорисовки бомбардировщика /// Ìåòîä ïðîðèñîâêè ìàøèíû
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningBomber == null) if (_drawingBomber == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height); Bitmap bmp = new(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningBomber.DrawTransport(gr); _drawingBomber.DrawTransport(gr);
pictureBoxAirBomber.Image = bmp; pictureBoxAirBomber.Image = bmp;
} }
private void CreateObject(string type) private void CreateObject(string type)
{ {
Random random = new(); Random random = new();
switch (type) switch (type)
{ {
case nameof(DrawningBomber): case nameof(DrawningBomber):
_drawningBomber = new DrawningBomber(random.Next(100, 300), random.Next(1000, 3000), _drawingBomber = new DrawningBomber(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)));
break; break;
case nameof(DrawningAirBomber): case nameof(DrawningAirBomber):
_drawningBomber = new DrawningAirBomber(random.Next(100, 300), random.Next(1000, 3000), _drawingBomber = new DrawningAirBomber(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)), Convert.ToBoolean(random.Next(0, 2)));
break; break;
default: default:
return; return;
} }
_drawningBomber.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height); _drawingBomber.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
_drawningBomber.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingBomber.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Создать военный самолёт" /// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü ñïîðòèâíûé àâòîìîáèëü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreateAirBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirBomber)); private void ButtonCreateAirBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirBomber));
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Создать самолёт" /// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîìîáèëü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreateBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBomber));
private void buttonCreateBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBomber));
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè)
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <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 (_drawningBomber == null) if (_drawingBomber == null)
{ {
return; return;
} }
@ -94,16 +91,16 @@ public partial class FormAirBomber : Form
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawningBomber.MoveTransport(DirectionType.Up); result = _drawingBomber.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawningBomber.MoveTransport(DirectionType.Down); result = _drawingBomber.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawningBomber.MoveTransport(DirectionType.Left); result = _drawingBomber.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawningBomber.MoveTransport(DirectionType.Right); result = _drawingBomber.MoveTransport(DirectionType.Right);
break; break;
} }
@ -112,8 +109,46 @@ public partial class FormAirBomber : Form
Draw(); Draw();
} }
} }
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingBomber == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTrans(_drawingBomber), pictureBoxAirBomber.Width, pictureBoxAirBomber.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,123 @@

namespace ProjectAirBomber.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,22 @@

namespace ProjectAirBomber.MovementStrategy;
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,52 @@
using ProjectAirBomber.MovementStrategy;
namespace ProjectAirBomber.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth
&& objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight
&& objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth - 5;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight - 5;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,50 @@

namespace ProjectAirBomber.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();
}
}
}
}

View File

@ -0,0 +1,60 @@
using ProjectAirBomber.Drawnings;
namespace ProjectAirBomber.MovementStrategy;
public class MoveableTrans : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningTrans или его наследника
/// </summary>
private readonly DrawningBomber? _bomber = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="bomber">Объект класса DrawningTrans</param>
public MoveableTrans(DrawningBomber bomber)
{
_bomber = bomber;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_bomber == null || _bomber.EntityBomber == null ||
!_bomber.GetPosX.HasValue || !_bomber.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_bomber.GetPosX.Value,
_bomber.GetPosY.Value, _bomber.GetWidth, _bomber.GetHeight);
}
}
public int GetStep => (int)(_bomber?.EntityBomber?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_bomber == null || _bomber.EntityBomber == null)
{
return false;
}
return _bomber.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,21 @@
namespace ProjectAirBomber.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,60 @@
namespace ProjectAirBomber.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 ProjectAirBomber.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}