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

This commit is contained in:
Adelina888 2024-03-09 20:45:03 +04:00
parent b0e1921876
commit d65a7c7cd6
13 changed files with 493 additions and 11 deletions

View File

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

View File

@ -4,7 +4,7 @@ namespace ProjectStormtrooper.Drawnings;
/// <summary> /// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности /// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary> /// </summary>
public class DrawingStormtrooper: DrawingStormtrooperBase public class DrawingStormtrooper: DrawningStormtrooperBase
{ {
@ -41,6 +41,7 @@ public class DrawingStormtrooper: DrawingStormtrooperBase
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(stormtrooper.AdditionalColor); Brush additionalBrush = new SolidBrush(stormtrooper.AdditionalColor);
base.DrawTransport(g);
//ракеты штурмовика //ракеты штурмовика
if (stormtrooper.Rockets) if (stormtrooper.Rockets)
{ {
@ -57,7 +58,7 @@ public class DrawingStormtrooper: DrawingStormtrooperBase
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10); g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10); g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10);
} }
base.DrawTransport(g);
} }

View File

@ -2,7 +2,7 @@
namespace ProjectStormtrooper.Drawnings; namespace ProjectStormtrooper.Drawnings;
public class DrawingStormtrooperBase public class DrawningStormtrooperBase
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
@ -37,10 +37,32 @@ public class DrawingStormtrooperBase
/// </summary> /// </summary>
private readonly int _drawningStormtooperHeight = 140; private readonly int _drawningStormtooperHeight = 140;
/// <summary>
/// Координата Х объекта
/// </summary>
/// <returns></returns>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата У объекта
/// </summary>
/// <returns></returns>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
/// <returns></returns>
public int GetWidth => _drawningStormtrooperWidth;
/// <summary>
/// Высота объекта
/// </summary>
/// <returns></returns>
public int GetHeight => _drawningStormtooperHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
private DrawingStormtrooperBase() private DrawningStormtrooperBase()
{ {
_pictureHeight = null; _pictureHeight = null;
_pictureWidth = null; _pictureWidth = null;
@ -55,7 +77,7 @@ public class DrawingStormtrooperBase
/// <param name="bodyColor">основной цвет</param> /// <param name="bodyColor">основной цвет</param>
public DrawingStormtrooperBase(int speed, double weight, Color bodyColor):this() public DrawningStormtrooperBase(int speed, double weight, Color bodyColor):this()
{ {
EntityStormtrooperBase = new EntityStormtrooperBase(speed, weight, bodyColor); EntityStormtrooperBase = new EntityStormtrooperBase(speed, weight, bodyColor);
@ -66,7 +88,7 @@ public class DrawingStormtrooperBase
/// <param name="drawningStormtrooperWidth"> Ширина прорисовки</param> /// <param name="drawningStormtrooperWidth"> Ширина прорисовки</param>
/// <param name="drawningStormtooperHeight">Высота прорисовки</param> /// <param name="drawningStormtooperHeight">Высота прорисовки</param>
protected DrawingStormtrooperBase(int drawningStormtrooperWidth, int drawningStormtooperHeight) : this() protected DrawningStormtrooperBase(int drawningStormtrooperWidth, int drawningStormtooperHeight) : this()
{ {
_drawningStormtrooperWidth = drawningStormtrooperWidth; _drawningStormtrooperWidth = drawningStormtrooperWidth;
_drawningStormtooperHeight = drawningStormtooperHeight; _drawningStormtooperHeight = drawningStormtooperHeight;

View File

@ -35,6 +35,8 @@
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateStormtrooperBase = new Button(); buttonCreateStormtrooperBase = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -117,11 +119,33 @@
buttonCreateStormtrooperBase.UseVisualStyleBackColor = true; buttonCreateStormtrooperBase.UseVisualStyleBackColor = true;
buttonCreateStormtrooperBase.Click += ButtonCreateStormtrooperBase_Click; buttonCreateStormtrooperBase.Click += ButtonCreateStormtrooperBase_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(792, 8);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(839, 37);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormStormtrooper // FormStormtrooper
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(925, 597); ClientSize = new Size(925, 597);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateStormtrooperBase); Controls.Add(buttonCreateStormtrooperBase);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
@ -144,5 +168,7 @@
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateStormtrooperBase; private Button buttonCreateStormtrooperBase;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,4 +1,5 @@
using ProjectStormtrooper.Drawnings; using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.MovementStrategy;
namespace ProjectStormtrooper; namespace ProjectStormtrooper;
/// <summary> /// <summary>
@ -8,13 +9,18 @@ public partial class FormStormtrooper : Form
{/// <summary> {/// <summary>
/// Поле-объект для прорисовки объекта /// Поле-объект для прорисовки объекта
/// </summary> /// </summary>
private DrawingStormtrooperBase? _drawningStormtrooperBase; private DrawningStormtrooperBase? _drawningStormtrooperBase;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary> /// <summary>
/// Конструктор формы /// Конструктор формы
/// </summary> /// </summary>
public FormStormtrooper() public FormStormtrooper()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
@ -48,8 +54,8 @@ public partial class FormStormtrooper : Form
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)));
break; break;
case nameof(DrawingStormtrooperBase): case nameof(DrawningStormtrooperBase):
_drawningStormtrooperBase = new DrawingStormtrooperBase(random.Next(100, 300), random.Next(1000, 3000), _drawningStormtrooperBase = new DrawningStormtrooperBase(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;
default: default:
@ -58,6 +64,8 @@ public partial class FormStormtrooper : Form
} }
_drawningStormtrooperBase.SetPictureSize(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height); _drawningStormtrooperBase.SetPictureSize(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
_drawningStormtrooperBase.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawningStormtrooperBase.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
@ -72,7 +80,7 @@ public partial class FormStormtrooper : Form
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreateStormtrooperBase_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingStormtrooperBase)); private void ButtonCreateStormtrooperBase_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningStormtrooperBase));
/// <summary> /// <summary>
@ -112,5 +120,41 @@ public partial class FormStormtrooper : Form
} }
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningStormtrooperBase == null)
{
return;
} }
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableStormtrooperBase(_drawningStormtrooperBase), 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,120 @@
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>
/// <returns></returns>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObjects">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObjects,int width, int height)
{
if (moveableObjects == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObjects;
FieldWidth = width;
FieldHeight = height;
}
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,21 @@
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></returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,28 @@
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,52 @@
namespace ProjectStormtrooper.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 ProjectStormtrooper.Drawnings;
namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Класс-реализации IMoveableObject с использованием DrawingStormtrooperBase
/// </summary>
public class MoveableStormtrooperBase : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningStormtrooperBase или его наследников
/// </summary>
private readonly DrawningStormtrooperBase? _stormtrooper = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="Stormtrooper">Объект класса DrawningStormtrooperBase</param>
public MoveableStormtrooperBase(DrawningStormtrooperBase Stormtrooper)
{
_stormtrooper = Stormtrooper;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_stormtrooper == null || _stormtrooper.EntityStormtrooperBase == 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?.EntityStormtrooperBase?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_stormtrooper == null || _stormtrooper.EntityStormtrooperBase == 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,24 @@
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,61 @@
namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координатва х
/// </summary>
private readonly int _x;
/// <summary>
/// Координатва у
/// </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">Координата х</param>
/// <param name="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,19 @@
namespace ProjectStormtrooper.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}