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

This commit is contained in:
VladaM 2024-02-14 18:23:38 +04:00
parent a78b9561d0
commit 8045b73f6b
12 changed files with 555 additions and 10 deletions

View File

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

View File

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

View File

@ -35,6 +35,8 @@
buttonUp = new Button(); buttonUp = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonCreateTanker = new Button(); buttonCreateTanker = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxGasolineTanker).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxGasolineTanker).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -43,14 +45,14 @@
pictureBoxGasolineTanker.Dock = DockStyle.Fill; pictureBoxGasolineTanker.Dock = DockStyle.Fill;
pictureBoxGasolineTanker.Location = new Point(0, 0); pictureBoxGasolineTanker.Location = new Point(0, 0);
pictureBoxGasolineTanker.Name = "pictureBoxGasolineTanker"; pictureBoxGasolineTanker.Name = "pictureBoxGasolineTanker";
pictureBoxGasolineTanker.Size = new Size(945, 474); pictureBoxGasolineTanker.Size = new Size(972, 537);
pictureBoxGasolineTanker.TabIndex = 0; pictureBoxGasolineTanker.TabIndex = 0;
pictureBoxGasolineTanker.TabStop = false; pictureBoxGasolineTanker.TabStop = false;
// //
// ButtonCreateGasolineTanker // ButtonCreateGasolineTanker
// //
ButtonCreateGasolineTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; ButtonCreateGasolineTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateGasolineTanker.Location = new Point(12, 421); ButtonCreateGasolineTanker.Location = new Point(12, 484);
ButtonCreateGasolineTanker.Name = "ButtonCreateGasolineTanker"; ButtonCreateGasolineTanker.Name = "ButtonCreateGasolineTanker";
ButtonCreateGasolineTanker.Size = new Size(153, 35); ButtonCreateGasolineTanker.Size = new Size(153, 35);
ButtonCreateGasolineTanker.TabIndex = 1; ButtonCreateGasolineTanker.TabIndex = 1;
@ -63,7 +65,7 @@
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(884, 421); buttonRight.Location = new Point(911, 484);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35); buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 2; buttonRight.TabIndex = 2;
@ -75,7 +77,7 @@
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(843, 421); buttonDown.Location = new Point(870, 484);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 3; buttonDown.TabIndex = 3;
@ -87,7 +89,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp; buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch; buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(843, 380); buttonUp.Location = new Point(870, 443);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35); buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 4; buttonUp.TabIndex = 4;
@ -99,7 +101,7 @@
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(802, 421); buttonLeft.Location = new Point(829, 484);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35); buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 5; buttonLeft.TabIndex = 5;
@ -109,7 +111,7 @@
// buttonCreateTanker // buttonCreateTanker
// //
buttonCreateTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTanker.Location = new Point(171, 421); buttonCreateTanker.Location = new Point(171, 484);
buttonCreateTanker.Name = "buttonCreateTanker"; buttonCreateTanker.Name = "buttonCreateTanker";
buttonCreateTanker.Size = new Size(153, 35); buttonCreateTanker.Size = new Size(153, 35);
buttonCreateTanker.TabIndex = 6; buttonCreateTanker.TabIndex = 6;
@ -117,11 +119,34 @@
buttonCreateTanker.UseVisualStyleBackColor = true; buttonCreateTanker.UseVisualStyleBackColor = true;
buttonCreateTanker.Click += buttonCreateTanker_Click; buttonCreateTanker.Click += buttonCreateTanker_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.AccessibleRole = AccessibleRole.Sound;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(839, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(885, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormGasolineTanker // FormGasolineTanker
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(945, 474); ClientSize = new Size(972, 537);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTanker); Controls.Add(buttonCreateTanker);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonUp); Controls.Add(buttonUp);
@ -144,5 +169,7 @@
private Button buttonUp; private Button buttonUp;
private Button buttonLeft; private Button buttonLeft;
private Button buttonCreateTanker; private Button buttonCreateTanker;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -9,6 +9,7 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Windows.Forms.VisualStyles; using System.Windows.Forms.VisualStyles;
using GasolineTanker.Drawnings; using GasolineTanker.Drawnings;
using GasolineTanker.MovementStrategy;
namespace GasolineTanker namespace GasolineTanker
{ {
@ -16,9 +17,15 @@ namespace GasolineTanker
{ {
private DrawningTanker? _drawningTanker; private DrawningTanker? _drawningTanker;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
public FormGasolineTanker() public FormGasolineTanker()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
@ -68,6 +75,8 @@ namespace GasolineTanker
else else
{ {
_drawningTanker.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawningTanker.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
} }
@ -122,5 +131,48 @@ namespace GasolineTanker
Draw(); Draw();
} }
} }
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningTanker == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTanker(_drawningTanker), pictureBoxGasolineTanker.Width, pictureBoxGasolineTanker.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,139 @@
namespace GasolineTanker.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 GasolineTanker.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,42 @@
namespace GasolineTanker.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveRight();
}
}
int diffY = FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,51 @@
namespace GasolineTanker.MovementStrategy;
internal 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,64 @@
using GasolineTanker.Drawnings;
namespace GasolineTanker.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningTanker
/// </summary>
public class MoveableTanker : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningTanker или его наследника
/// </summary>
private readonly DrawningTanker? _tanker = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="tanker">Объект класса DrawningTanker</param>
public MoveableTanker(DrawningTanker tanker)
{
_tanker = tanker;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_tanker == null || _tanker.EntityTanker == null || !_tanker.GetPosX.HasValue || !_tanker.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_tanker.GetPosX.Value, _tanker.GetPosY.Value, _tanker.GetWidth, _tanker.GetHeight);
}
}
public int GetStep => (int)(_tanker?.EntityTanker?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_tanker == null || _tanker.EntityTanker == null)
{
return false;
}
return _tanker.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,27 @@
namespace GasolineTanker.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 GasolineTanker.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,22 @@
namespace GasolineTanker.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}