PIBD-11 Ryabov I.V. LabWork02 Simple #2

Closed
ilyaryabovv wants to merge 3 commits from LabWork02 into LabWork01
16 changed files with 746 additions and 155 deletions

View File

@ -0,0 +1,28 @@
namespace ProjectStormtrooper;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <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,53 @@
using ProjectStormtrooper.Entities;
namespace ProjectStormtrooper.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingStormtrooper : DrawningBaseStormtrooper
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="rockets">Признак наличия ракет</param>
public DrawingStormtrooper(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool rockets) : base(140, 135)
{
EntityBaseStormtrooper = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, bombs, rockets);
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityBaseStormtrooper == null ||EntityBaseStormtrooper is not EntityStormtrooper entityStormtrooper|| !_startPosX.HasValue ||!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(entityStormtrooper.AdditionalColor);
base.DrawTransport(g);
//Ракеты бомбардировщика
if (entityStormtrooper.Rockets)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 20, 15, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 110, 15, 5);
}
//Бомбы бомбардировщика
if (entityStormtrooper.Bombs)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 40, _startPosY.Value + 40, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 40, _startPosY.Value + 90, 10, 10);
}
}
}

View File

@ -1,10 +1,9 @@
namespace ProjectStormtrooper;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingStormtrooper
using ProjectStormtrooper.Entities;
namespace ProjectStormtrooper.Drawnings;
public class DrawningBaseStormtrooper
Review

Имя элемента проекта не соответствует указанному в задании

Имя элемента проекта не соответствует указанному в задании
{
public EntityStormtrooper? EntityStormtrooper { get; private set; }
public EntityBaseStormtrooper? EntityBaseStormtrooper { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -18,12 +17,12 @@ public class DrawingStormtrooper
/// <summary>
/// Левая координата прорисовки бомбардировщика
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки бомбардировщика
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки бомбардировщика
@ -36,27 +35,58 @@ public class DrawingStormtrooper
private readonly int _drawningStormtrooperHeight = 135;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engines">Признак наличия двигателей</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="rockets">Признак наличия ракет</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool engines, bool bombs, bool rockets)
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningStormtrooperWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningStormtrooperHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawningBaseStormtrooper()
{
EntityStormtrooper = new EntityStormtrooper();
EntityStormtrooper.Init(speed, weight, bodyColor, additionalColor,
engines, bombs, rockets);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningBaseStormtrooper(int speed, double weight, Color bodyColor) : this()
{
EntityBaseStormtrooper = new EntityBaseStormtrooper(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningStormtrooperWidth">Ширина прорисовки бомбардировщика</param>
/// <param name="drawningStormtrooperHeight">Высота прорисовки бомбардировщика</param>
protected DrawningBaseStormtrooper(int drawningStormtrooperWidth ,int drawningStormtrooperHeight ) : this()
{
_drawningStormtrooperHeight= drawningStormtrooperHeight;
_drawningStormtrooperWidth= drawningStormtrooperWidth;
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -79,7 +109,7 @@ public class DrawingStormtrooper
else if (_startPosX < 0)
{
_startPosX = 0;
}
}
if (_startPosY + _drawningStormtrooperHeight > _pictureHeight)
{
_startPosY = -_drawningStormtrooperHeight + _pictureHeight;
@ -137,7 +167,7 @@ public class DrawingStormtrooper
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityStormtrooper == null || !_startPosX.HasValue ||
if (EntityBaseStormtrooper == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
@ -146,32 +176,32 @@ public class DrawingStormtrooper
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityStormtrooper.Step > 0)
if (_startPosX.Value - EntityBaseStormtrooper.Step > 0)
{
_startPosX -= (int)EntityStormtrooper.Step;
_startPosX -= (int)EntityBaseStormtrooper.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityStormtrooper.Step > 0)
if (_startPosY.Value - EntityBaseStormtrooper.Step > 0)
{
_startPosY -= (int)EntityStormtrooper.Step;
_startPosY -= (int)EntityBaseStormtrooper.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX + _drawningStormtrooperWidth + EntityStormtrooper.Step < _pictureWidth)
if (_startPosX + _drawningStormtrooperWidth + EntityBaseStormtrooper.Step < _pictureWidth)
{
_startPosX += (int)EntityStormtrooper.Step;
_startPosX += (int)EntityBaseStormtrooper.Step;
};
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY + _drawningStormtrooperHeight + EntityStormtrooper.Step < _pictureHeight)
if (_startPosY + _drawningStormtrooperHeight + EntityBaseStormtrooper.Step < _pictureHeight)
{
_startPosY += (int)EntityStormtrooper.Step;
_startPosY += (int)EntityBaseStormtrooper.Step;
}
return true;
default:
@ -182,16 +212,15 @@ public class DrawingStormtrooper
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityStormtrooper == null || !_startPosX.HasValue ||
if (EntityBaseStormtrooper == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyColorBrush = new SolidBrush(EntityStormtrooper.BodyColor);
Brush additionalBrush = new SolidBrush(EntityStormtrooper.AdditionalColor);
Brush bodyColorBrush = new SolidBrush(EntityBaseStormtrooper.BodyColor);
//Тело бомбардировщика
g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 60, 120, 20);
//Задние крылья бомбардировщика
@ -213,21 +242,6 @@ public class DrawingStormtrooper
Nose[1].X = _startPosX.Value; Nose[1].Y = _startPosY.Value + 70;
Nose[2].X = _startPosX.Value + 20; Nose[2].Y = _startPosY.Value + 60;
g.FillPolygon(bodyColorBrush, Nose);
//Ракеты бомбардировщика
if (EntityStormtrooper.Rockets)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 20, 15, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 110, 15, 5);
}
//Бомбы бомбардировщика
if (EntityStormtrooper.Bombs)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 40, _startPosY.Value + 40, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 40, _startPosY.Value + 90, 10, 10);
}
}
}

View File

@ -0,0 +1,40 @@
namespace ProjectStormtrooper.Entities;
/// <summary>
/// Класс-сущность "Базовый Бомбардировщик"
/// </summary>
public class EntityBaseStormtrooper
{
/// <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 EntityBaseStormtrooper(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,41 @@
namespace ProjectStormtrooper.Entities;
/// <summary>
/// Класс-сущность "Бомбардировщик"
/// </summary>
public class EntityStormtrooper : EntityBaseStormtrooper
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; protected set; }
/// <summary>
/// Признак (опция) наличия ракет
/// </summary>
public bool Rockets { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес бомбардировщика</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="rockets">Признак наличия ракет</param>
public EntityStormtrooper(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool rockets) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Bombs = bombs;
Rockets = rockets;
}
}

View File

@ -1,71 +0,0 @@
namespace ProjectStormtrooper;
/// <summary>
/// Класс-сущность "Бомбардировщик"
/// </summary>
public class EntityStormtrooper
{
/// <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 Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия двигателей
/// </summary>
public bool Engines { get; private set; }
/// <summary>
/// Признак (опция) наличия ракет
/// </summary>
public bool Rockets { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { 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>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engines">Признак наличия двигателей</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="rockets">Признак наличия ракет</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool engines, bool bombs, bool rockets)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Engines = engines;
Bombs = bombs;
Rockets = rockets;
}
}

View File

@ -34,19 +34,22 @@
buttonDown = new Button();
buttonLeft = new Button();
pictureBoxStormtrooper = new PictureBox();
buttonCreateBaseStormtrooper = new Button();
comboBoxStrategy = new ComboBox();
ButtonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit();
SuspendLayout();
//
// buttonCreateStormtrooper
//
buttonCreateStormtrooper.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateStormtrooper.Location = new Point(35, 693);
buttonCreateStormtrooper.Location = new Point(21, 693);
buttonCreateStormtrooper.Name = "buttonCreateStormtrooper";
buttonCreateStormtrooper.Size = new Size(126, 32);
buttonCreateStormtrooper.Size = new Size(260, 32);
buttonCreateStormtrooper.TabIndex = 0;
buttonCreateStormtrooper.Text = "Создать";
buttonCreateStormtrooper.Text = "Создать бомбардировщик";
buttonCreateStormtrooper.UseVisualStyleBackColor = true;
buttonCreateStormtrooper.Click += buttonCreate_Click;
buttonCreateStormtrooper.Click += buttonCreateStormtrooper_Click;
//
// buttonUp
//
@ -106,11 +109,45 @@
pictureBoxStormtrooper.TabStop = false;
pictureBoxStormtrooper.Click += ButtonMove_Click;
//
// buttonCreateBaseStormtrooper
//
buttonCreateBaseStormtrooper.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBaseStormtrooper.Location = new Point(287, 693);
buttonCreateBaseStormtrooper.Name = "buttonCreateBaseStormtrooper";
buttonCreateBaseStormtrooper.Size = new Size(260, 32);
buttonCreateBaseStormtrooper.TabIndex = 6;
buttonCreateBaseStormtrooper.Text = "Создать базовый бомбардировщик";
buttonCreateBaseStormtrooper.UseVisualStyleBackColor = true;
buttonCreateBaseStormtrooper.Click += buttonCreateBaseStormtrooper_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(1127, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// ButtonStrategyStep
//
ButtonStrategyStep.Location = new Point(1173, 41);
ButtonStrategyStep.Name = "ButtonStrategyStep";
ButtonStrategyStep.Size = new Size(75, 23);
ButtonStrategyStep.TabIndex = 8;
ButtonStrategyStep.Text = "Шаг";
ButtonStrategyStep.UseVisualStyleBackColor = true;
ButtonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormStormtrooper
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1260, 737);
Controls.Add(ButtonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBaseStormtrooper);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
@ -131,5 +168,8 @@
private Button buttonDown;
private Button buttonLeft;
private PictureBox pictureBoxStormtrooper;
private Button buttonCreateBaseStormtrooper;
private ComboBox comboBoxStrategy;
private Button ButtonStrategyStep;
}
}

View File

@ -1,4 +1,7 @@
namespace ProjectStormtrooper
using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.MovementStrategy;
namespace ProjectStormtrooper
{
/// <summary>
/// Форма работы с объектом "Бомбардировщик"
@ -8,56 +11,74 @@
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingStormtrooper? _drawningStormtrooper;
private DrawningBaseStormtrooper? _drawningBaseStormtrooper;
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormStormtrooper()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки бомбардировщика
/// </summary>
private void Draw()
{
if (_drawningStormtrooper == null)
if (_drawningBaseStormtrooper == null)
{
return;
}
Bitmap bmp = new(pictureBoxStormtrooper.Width,
pictureBoxStormtrooper.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningStormtrooper.DrawTransport(gr);
_drawningBaseStormtrooper.DrawTransport(gr);
pictureBoxStormtrooper.Image = bmp;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningBaseStormtrooper):
_drawningBaseStormtrooper = new DrawningBaseStormtrooper(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(DrawingStormtrooper):
_drawningBaseStormtrooper = new DrawingStormtrooper(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;
}
_drawningBaseStormtrooper.SetPictureSize(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
_drawningBaseStormtrooper.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 buttonCreate_Click(object sender, EventArgs e)
private void buttonCreateStormtrooper_Click(object sender, EventArgs e)
{
Random random = new();
_drawningStormtrooper = new DrawingStormtrooper();
_drawningStormtrooper.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)), Convert.ToBoolean(random.Next(0, 2)));
_drawningStormtrooper.SetPictureSize(pictureBoxStormtrooper.Width,pictureBoxStormtrooper.Height);
_drawningStormtrooper.SetPosition(random.Next(10, 100), random.Next(10,100));
Draw();
CreateObject(nameof(DrawingStormtrooper));
}
private void buttonCreateBaseStormtrooper_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningBaseStormtrooper));
}
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
@ -65,7 +86,7 @@
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningStormtrooper == null)
if (_drawningBaseStormtrooper == null)
{
return;
}
@ -75,19 +96,19 @@
{
case "buttonUp":
result =
_drawningStormtrooper.MoveTransport(DirectionType.Up);
_drawningBaseStormtrooper.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningStormtrooper.MoveTransport(DirectionType.Down);
_drawningBaseStormtrooper.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningStormtrooper.MoveTransport(DirectionType.Left);
_drawningBaseStormtrooper.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningStormtrooper.MoveTransport(DirectionType.Right);
_drawningBaseStormtrooper.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -95,5 +116,43 @@
Draw();
}
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningBaseStormtrooper == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableStormtrooper(_drawningBaseStormtrooper), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.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 ProjectStormtrooper.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 ProjectStormtrooper.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,31 @@
namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в правый нижний угол
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 ||
objParams.RightBorder + GetStep() >= FieldWidth ||
objParams.TopBorder - GetStep() <= 0
|| objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

@ -0,0 +1,52 @@
using ProjectStormtrooper.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,56 @@
using ProjectStormtrooper.Drawnings;
namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Класс реализация IMoveableObject с использованием DrawningBaseStormtrooper
/// </summary>
public class MoveableStormtrooper : IMoveableObject
{
private DrawningBaseStormtrooper? _stormtrooper ;
public MoveableStormtrooper(DrawningBaseStormtrooper stormtrooper)
{
_stormtrooper = stormtrooper;
}
public ObjectParameters? GetObjectPosition
{
get
{
if( _stormtrooper == null||_stormtrooper.EntityBaseStormtrooper==null || !_stormtrooper.GetPosX.HasValue || !_stormtrooper.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_stormtrooper.GetPosX.Value, _stormtrooper.GetPosY.Value, _stormtrooper.GetWidth, _stormtrooper.GetHeight);
}
}
public int GetStep =>(int)(_stormtrooper?.EntityBaseStormtrooper?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_stormtrooper == null || _stormtrooper.EntityBaseStormtrooper == null)
{
return false;
}
return _stormtrooper.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

@ -1,9 +1,8 @@
namespace ProjectStormtrooper;
namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
public enum MovementDirection
{
/// <summary>
/// Вверх
@ -22,3 +21,4 @@ public enum DirectionType
/// </summary>
Right = 4
}

View File

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