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

This commit is contained in:
BoiledMilk123 2024-03-12 00:56:03 +04:00
parent 3348c036dd
commit eacd8071bb
12 changed files with 569 additions and 20 deletions

View File

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

View File

@ -37,13 +37,35 @@ public class DrawningLocomotive
/// <summary> /// <summary>
/// Ширина прорисовки локомотива /// Ширина прорисовки локомотива
/// </summary> /// </summary>
private readonly int _drawningElectricLocomotiveWidth = 83; private readonly int _drawningLocomotiveWidth = 83;
/// <summary> /// <summary>
/// Высота прорисовки локомотива /// Высота прорисовки локомотива
/// </summary> /// </summary>
private readonly int _drawningElectricLocomotiveHeight = 40; private readonly int _drawningLocomotiveHeight = 40;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningLocomotiveWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningLocomotiveHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
@ -70,12 +92,12 @@ public class DrawningLocomotive
/// <summary> /// <summary>
/// Конструктор для наследников /// Конструктор для наследников
/// </summary> /// </summary>
/// <param name="drawningElectricLocomotiveWidth">Ширина прорисовки локомотива</param> /// <param name="drawningLocomotiveWidth">Ширина прорисовки локомотива</param>
/// <param name="drawningElectricLocomotiveHeight">Высота прорисовки локомотива</param> /// <param name="drawningLocomotiveHeight">Высота прорисовки локомотива</param>
protected DrawningLocomotive(int drawningElectricLocomotiveWidth, int drawningElectricLocomotiveHeight) : this() protected DrawningLocomotive(int drawningLocomotiveWidth, int drawningLocomotiveHeight) : this()
{ {
_drawningElectricLocomotiveWidth = drawningElectricLocomotiveWidth; _drawningLocomotiveWidth = drawningLocomotiveWidth;
_drawningElectricLocomotiveHeight = drawningElectricLocomotiveHeight; _drawningLocomotiveHeight = drawningLocomotiveHeight;
} }
/// <summary> /// <summary>
@ -86,19 +108,19 @@ public class DrawningLocomotive
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns> /// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
if (_drawningElectricLocomotiveHeight > height || _drawningElectricLocomotiveWidth > width) if (_drawningLocomotiveHeight > height || _drawningLocomotiveWidth > width)
{ {
return false; return false;
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
if (_startPosY.HasValue && _startPosY + _drawningElectricLocomotiveHeight < _pictureHeight) if (_startPosY.HasValue && _startPosY + _drawningLocomotiveHeight < _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; _startPosY = _pictureHeight - _drawningLocomotiveHeight;
} }
if (_startPosX.HasValue && _startPosX + _drawningElectricLocomotiveWidth < _pictureWidth) if (_startPosX.HasValue && _startPosX + _drawningLocomotiveWidth < _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; _startPosX = _pictureWidth - _drawningLocomotiveWidth;
} }
return true; return true;
} }
@ -121,13 +143,13 @@ public class DrawningLocomotive
if (_drawningElectricLocomotiveHeight + y > _pictureHeight) if (_drawningLocomotiveHeight + y > _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; _startPosY = _pictureHeight - _drawningLocomotiveHeight;
} }
if (_drawningElectricLocomotiveWidth + x > _pictureWidth) if (_drawningLocomotiveWidth + x > _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; _startPosX = _pictureWidth - _drawningLocomotiveWidth;
} }
if (x < 0) if (x < 0)
{ {
@ -172,14 +194,14 @@ public class DrawningLocomotive
return true; return true;
//вправо //вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + _drawningElectricLocomotiveWidth + EntityLocomotive.Step < _pictureWidth) if (_startPosX.Value + _drawningLocomotiveWidth + EntityLocomotive.Step < _pictureWidth)
{ {
_startPosX += (int)EntityLocomotive.Step; _startPosX += (int)EntityLocomotive.Step;
} }
return true; return true;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + _drawningElectricLocomotiveHeight + EntityLocomotive.Step < _pictureHeight) if (_startPosY.Value + _drawningLocomotiveHeight + EntityLocomotive.Step < _pictureHeight)
{ {
_startPosY += (int)EntityLocomotive.Step; _startPosY += (int)EntityLocomotive.Step;
} }

View File

@ -35,6 +35,8 @@
buttonRight = new Button(); buttonRight = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateLocomotive = new Button(); buttonCreateLocomotive = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -121,11 +123,33 @@
buttonCreateLocomotive.UseVisualStyleBackColor = true; buttonCreateLocomotive.UseVisualStyleBackColor = true;
buttonCreateLocomotive.Click += buttonCreateLocomotive_Click; buttonCreateLocomotive.Click += buttonCreateLocomotive_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(733, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(764, 72);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(90, 33);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormElectricLocomotive // FormElectricLocomotive
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(866, 479); ClientSize = new Size(866, 479);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateLocomotive); Controls.Add(buttonCreateLocomotive);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonRight); Controls.Add(buttonRight);
@ -148,5 +172,7 @@
private Button buttonRight; private Button buttonRight;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateLocomotive; private Button buttonCreateLocomotive;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,4 +1,5 @@
using ProjectElectricLocomotive.Drawnings; using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.MovementStrategy;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -13,11 +14,20 @@ namespace ProjectElectricLocomotive;
public partial class FormElectricLocomotive : Form public partial class FormElectricLocomotive : Form
{ {
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningLocomotive? _drawningLocomotive; private DrawningLocomotive? _drawningLocomotive;
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormElectricLocomotive() public FormElectricLocomotive()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
@ -36,6 +46,10 @@ public partial class FormElectricLocomotive : Form
pictureBoxElectricLocomotive.Image = bmp; pictureBoxElectricLocomotive.Image = bmp;
} }
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type"></param>
private void CreateObject(string type) private void CreateObject(string type)
{ {
Random random = new(); Random random = new();
@ -56,6 +70,8 @@ public partial class FormElectricLocomotive : Form
} }
_drawningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); _drawningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
@ -112,6 +128,36 @@ public partial class FormElectricLocomotive : Form
} }
} }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningLocomotive == null) return;
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null) return;
_strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.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 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
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,67 @@
using ProjectElectricLocomotive.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject c использованием DrawningLocomotive
/// </summary>
public class MoveableLocomotive : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningLocomotive или его наследника
/// </summary>
private readonly DrawningLocomotive? _locomotive = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="locomotive">Объект класса DrawningLocomotive</param>
public MoveableLocomotive(DrawningLocomotive 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,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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 = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0) MoveLeft();
else MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0) MoveUp();
else MoveDown();
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вверх
/// </summary>
Down = 2,
/// <summary>
/// Вверх
/// </summary>
Left = 3,
/// <summary>
/// Вверх
/// </summary>
Right = 4,
}

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}