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

This commit is contained in:
Almaz 2024-04-09 15:02:30 +04:00
parent 45691d205f
commit 1bde4734fc
12 changed files with 576 additions and 8 deletions

View File

@ -11,18 +11,26 @@ namespace ProjectCruiser.Drawings;
/// </summary> /// </summary>
public enum DirectionType public enum DirectionType
{ {
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </summary> /// </summary>
Up = 1, Up = 1,
/// <summary> /// <summary>
/// Вниз /// Вниз
/// </summary> /// </summary>
Down = 2, Down = 2,
/// <summary> /// <summary>
/// Влева /// Влева
/// </summary> /// </summary>
Left = 3, Left = 3,
/// <summary> /// <summary>
/// Вправо /// Вправо
/// </summary> /// </summary>

View File

@ -24,6 +24,7 @@ public class DrawningCruiser
/// <summary> /// <summary>
/// Левая координата прорисовки крейсера /// Левая координата прорисовки крейсера
/// </summary> /// </summary>
protected int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя координата прорисовки крейсера /// Верхняя координата прорисовки крейсера
@ -39,6 +40,26 @@ public class DrawningCruiser
/// </summary> /// </summary>
private readonly int _drawingCruiserHeight = 50; private readonly int _drawingCruiserHeight = 50;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningCruiserWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingCruiserHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>

View File

@ -35,6 +35,8 @@
buttonRight = new Button(); buttonRight = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonCreateCruiser = new Button(); buttonCreateCruiser = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -117,11 +119,35 @@
buttonCreateCruiser.UseVisualStyleBackColor = true; buttonCreateCruiser.UseVisualStyleBackColor = true;
buttonCreateCruiser.Click += buttonCreateCruiser_Click; buttonCreateCruiser.Click += buttonCreateCruiser_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(637, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(694, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormCruiser // FormCruiser
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCruiser); Controls.Add(buttonCreateCruiser);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonRight); Controls.Add(buttonRight);
@ -144,5 +170,7 @@
private Button buttonRight; private Button buttonRight;
private Button buttonLeft; private Button buttonLeft;
private Button buttonCreateCruiser; private Button buttonCreateCruiser;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,4 +1,5 @@
using ProjectCruiser.Drawings; using ProjectCruiser.Drawings;
using ProjectCruiser.MovementStrategy;
namespace ProjectCruiser namespace ProjectCruiser
{ {
@ -6,9 +7,12 @@ namespace ProjectCruiser
{ {
private DrawningCruiser? _drawingCruiser; private DrawningCruiser? _drawingCruiser;
private AbstactStrategy? _strategy;
public FormCruiser() public FormCruiser()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
private void Draw() private void Draw()
@ -37,13 +41,13 @@ namespace ProjectCruiser
case nameof(DrawningMilitaryCruiser): case nameof(DrawningMilitaryCruiser):
_drawingCruiser = new DrawningMilitaryCruiser(random.Next(100, 300), _drawingCruiser = new DrawningMilitaryCruiser(random.Next(100, 300),
random.Next(1000, 3000), 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))); Convert.ToBoolean(random.Next(0, 2)));
break; break;
@ -53,7 +57,8 @@ namespace ProjectCruiser
_drawingCruiser.SetPictireSize(pictureBoxCruiser.Width, pictureBoxCruiser.Height); _drawingCruiser.SetPictireSize(pictureBoxCruiser.Width, pictureBoxCruiser.Height);
_drawingCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
@ -102,5 +107,44 @@ namespace ProjectCruiser
} }
} }
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingCruiser == null) { return; }
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return ;
}
_strategy.SetData(new MoveableCruiser(_drawingCruiser), pictureBoxCruiser.Width, pictureBoxCruiser.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,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstactStrategy
{
/// <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 (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns></returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns></returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns></returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns></returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
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 IsTargetDestination();
private bool MoveTo(MovementDirection direction)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(direction) ?? false;
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.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,50 @@
namespace ProjectCruiser.MovementStrategy;
public class MoveToBorder : AbstactStrategy
{
protected override bool IsTargetDestination()
{
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;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.MovementStrategy;
public class MoveToCenter : AbstactStrategy
{
protected override bool IsTargetDestination()
{
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,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectCruiser.Drawings;
namespace ProjectCruiser.MovementStrategy;
/// <summary>
/// Класс реализация IMoveableObject с использованием DrawningCruiser
/// </summary>
public class MoveableCruiser : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCruiser или его наследника
/// </summary>
private readonly DrawningCruiser? _cruiser = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="cruiser"></param>
public MoveableCruiser(DrawningCruiser? cruiser)
{
_cruiser = cruiser;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_cruiser == null || _cruiser.EntityCruiser == null || !_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_cruiser.GetPosX.Value, _cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight);
}
}
public int GetStep => (int)(_cruiser?.EntityCruiser?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_cruiser == null || _cruiser.EntityCruiser == null)
{
return false;
}
return _cruiser.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction"></param>
/// <returns></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 ProjectCruiser.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,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.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"></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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}