Добавление стратегии

This commit is contained in:
Ilya Ryabov 2024-02-18 19:26:51 +04:00
parent d70125006c
commit 2f4c58fbc6
12 changed files with 514 additions and 1 deletions

View File

@ -5,6 +5,10 @@
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное значение
/// </summary>
Unknow= -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -35,6 +35,26 @@ public class DrawningBaseStormtrooper
/// </summary>
private readonly int _drawningStormtrooperHeight = 135;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningStormtrooperWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningStormtrooperHeight;
/// <summary>
/// Пустой конструктор
/// </summary>

View File

@ -35,6 +35,8 @@
buttonLeft = new Button();
pictureBoxStormtrooper = new PictureBox();
buttonCreateBaseStormtrooper = new Button();
comboBoxStrategy = new ComboBox();
ButtonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit();
SuspendLayout();
//
@ -118,11 +120,33 @@
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);
@ -145,5 +169,7 @@
private Button buttonLeft;
private PictureBox pictureBoxStormtrooper;
private Button buttonCreateBaseStormtrooper;
private ComboBox comboBoxStrategy;
private Button ButtonStrategyStep;
}
}

View File

@ -1,4 +1,5 @@
using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.MovementStrategy;
namespace ProjectStormtrooper
{
@ -12,12 +13,15 @@ namespace ProjectStormtrooper
/// </summary>
private DrawningBaseStormtrooper? _drawningBaseStormtrooper;
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormStormtrooper()
{
InitializeComponent();
_strategy = null;
}
@ -62,6 +66,8 @@ namespace ProjectStormtrooper
_drawningBaseStormtrooper.SetPictureSize(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
_drawningBaseStormtrooper.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
@ -86,6 +92,7 @@ namespace ProjectStormtrooper
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningBaseStormtrooper == null)
{
return;
@ -117,6 +124,43 @@ namespace ProjectStormtrooper
}
}
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,140 @@
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;
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,53 @@
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

@ -0,0 +1,25 @@

namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </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,18 @@

namespace ProjectStormtrooper.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}