реализация стратегии перемещения

This commit is contained in:
DarkScarletDoom 2024-03-12 19:45:27 +04:00
parent 5d72860a96
commit 6bc2e6f582
12 changed files with 543 additions and 0 deletions

View File

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

View File

@ -39,6 +39,28 @@ namespace LocomativeProject.Drawnings
/// </summary>
private readonly int _drawningBaseLocomotiveHeight = 60;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBaseLocomotiveWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningBaseLocomotiveHeight;
/// <summary>
/// Пустой конструктор
/// </summary>

View File

@ -37,6 +37,8 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateLocomotive = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.buttonStrategyStep = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocomotive)).BeginInit();
this.SuspendLayout();
@ -129,11 +131,35 @@
this.buttonCreateLocomotive.UseVisualStyleBackColor = true;
this.buttonCreateLocomotive.Click += new System.EventHandler(this.ButtonCreateLocomotive_Click);
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"К центру",
"К краю"});
this.comboBox1.Location = new System.Drawing.Point(667, 12);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 23);
this.comboBox1.TabIndex = 8;
//
// buttonStrategyStep
//
this.buttonStrategyStep.Location = new System.Drawing.Point(713, 41);
this.buttonStrategyStep.Name = "buttonStrategyStep";
this.buttonStrategyStep.Size = new System.Drawing.Size(75, 23);
this.buttonStrategyStep.TabIndex = 9;
this.buttonStrategyStep.Text = "Шаг";
this.buttonStrategyStep.UseVisualStyleBackColor = true;
this.buttonStrategyStep.Click += new System.EventHandler(this.buttonStrategyStep_Click);
//
// LocomotiveProject
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonStrategyStep);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.buttonCreateLocomotive);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonLeft);
@ -160,5 +186,7 @@
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreateLocomotive;
private ComboBox comboBox1;
private Button buttonStrategyStep;
}
}

View File

@ -11,6 +11,7 @@ using System.Windows.Forms;
using LocomotiveProject.Entities;
using LocomativeProject.Drawnings;
using LocomotiveProject.Drawnings;
using LocomativeProject.MovementStrategy;
namespace LocomativeProject
{
@ -18,9 +19,12 @@ namespace LocomativeProject
{
private DrawningBaseLocomotive? _drawningLocomotive;
private AbstractStrategy? _strategy;
public LocomotiveProject()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
@ -61,6 +65,8 @@ namespace LocomativeProject
_drawningLocomotive.SetPictureSize(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
_drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBox1.Enabled = true;
Draw();
}
@ -107,5 +113,48 @@ namespace LocomativeProject
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningLocomotive == null)
{
return;
}
if (comboBox1.Enabled)
{
_strategy = comboBox1.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
}
if (_strategy == null)
{
return;
}
comboBox1.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBox1.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,140 @@
namespace LocomativeProject.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,23 @@
namespace LocomativeProject.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,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocomativeProject.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 &&
objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
if (objParams.RightBorder + GetStep() <= FieldWidth)
{
MoveRight();
}
if (objParams.DownBorder + GetStep() <= FieldHeight)
{
MoveDown();
}
}
}

View File

@ -0,0 +1,54 @@
namespace LocomativeProject.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,64 @@
using LocomativeProject.Drawnings;
namespace LocomativeProject.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningLocomotive
/// </summary>
public class MoveableLocomotive : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningBaseLocomotive или его наследника
/// </summary>
private readonly DrawningBaseLocomotive? _locomotive = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="_locomotive">Объект класса DrawningBaseLocomotive</param>
public MoveableLocomotive(DrawningBaseLocomotive locomotive)
{
_locomotive = locomotive;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_locomotive == null || _locomotive._EntityLocomotive == null || !_locomotive.GetPosX.HasValue || !_locomotive.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_locomotive.GetPosX.Value, _locomotive.GetPosY.Value, _locomotive.GetWidth, _locomotive.GetHeight);
}
}
public int GetStep => (int)(_locomotive?._EntityLocomotive?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_locomotive == null || _locomotive._EntityLocomotive == null)
{
return false;
}
return _locomotive.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,26 @@
namespace LocomativeProject.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection : byte
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down,
/// <summary>
/// Влево
/// </summary>
Left,
/// <summary>
/// Вправо
/// </summary>
Right
}

View File

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