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

This commit is contained in:
insideq 2024-02-18 13:26:32 +04:00
parent 2dc0f239ca
commit a67ac47ff3
13 changed files with 568 additions and 5 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

@ -32,12 +32,32 @@ public class DrawningBulldozer
/// <summary> /// <summary>
/// Ширина прорисовки автомобиля /// Ширина прорисовки автомобиля
/// </summary> /// </summary>
private readonly int _drawingExcWidth = 80; //дописать ширина private readonly int _drawingExcWidth = 65;
/// <summary> /// <summary>
/// Высота прорисовки автомобиля /// Высота прорисовки автомобиля
/// </summary> /// </summary>
private readonly int _drawingExcHeight = 61; //дописать высота private readonly int _drawingExcHeight = 61;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawingExcWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingExcHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
@ -69,7 +89,7 @@ public class DrawningBulldozer
protected DrawningBulldozer(int drawingExcWidth, int drawingExcHeight) : this() protected DrawningBulldozer(int drawingExcWidth, int drawingExcHeight) : this()
{ {
_drawingExcWidth = drawingExcWidth; _drawingExcWidth = drawingExcWidth;
_pictureHeight = drawingExcHeight; _drawingExcHeight = drawingExcHeight;
} }
/// <summary> /// <summary>

View File

@ -1,5 +1,4 @@
using ProjectExcavator.Entities; using ProjectExcavator.Entities;
using System.Net.Sockets;
namespace ProjectExcavator.Drawnings; namespace ProjectExcavator.Drawnings;
@ -20,7 +19,7 @@ public class DrawningExcavator : DrawningBulldozer
public DrawningExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool prop, bool ladle) : base(120, 70) public DrawningExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool prop, bool ladle) : base(120, 70)
{ {
EntityBulldozer = new EntityExcavator(speed, weight, bodyColor, additionalColor, prop, ladle); EntityBulldozer = new EntityExcavator(speed, weight, bodyColor, additionalColor, prop, ladle);
} //ДОПИСАТЬ!!!!!!!!!!!!!!!!!!!!!!!!! }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@ -35,6 +35,8 @@
buttonDown = new Button(); buttonDown = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateBulldozer = new Button(); buttonCreateBulldozer = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -118,11 +120,33 @@
buttonCreateBulldozer.UseVisualStyleBackColor = false; buttonCreateBulldozer.UseVisualStyleBackColor = false;
buttonCreateBulldozer.Click += ButtonCreateBulldozer_Click; buttonCreateBulldozer.Click += ButtonCreateBulldozer_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(798, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(844, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormExcavator // FormExcavator
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(931, 604); ClientSize = new Size(931, 604);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBulldozer); Controls.Add(buttonCreateBulldozer);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonDown); Controls.Add(buttonDown);
@ -145,5 +169,7 @@
private Button buttonDown; private Button buttonDown;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateBulldozer; private Button buttonCreateBulldozer;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,15 +1,32 @@
using ProjectExcavator.Drawnings; using ProjectExcavator.Drawnings;
using ProjectExcavator.MovementStrategy;
namespace ProjectExcavator; namespace ProjectExcavator;
public partial class FormExcavator : Form public partial class FormExcavator : Form
{ {
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningBulldozer? _drawningBulldozer; private DrawningBulldozer? _drawningBulldozer;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormExcavator() public FormExcavator()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary>
/// Метод прорисовки Бульдозера
/// </summary>
private void Draw() private void Draw()
{ {
if (_drawningBulldozer == null) if (_drawningBulldozer == null)
@ -23,6 +40,10 @@ public partial class FormExcavator : Form
pictureBoxExcavator.Image = bmp; pictureBoxExcavator.Image = bmp;
} }
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type) private void CreateObject(string type)
{ {
Random random = new(); Random random = new();
@ -44,6 +65,8 @@ public partial class FormExcavator : Form
_drawningBulldozer.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height); _drawningBulldozer.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height);
_drawningBulldozer.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxExcavator.Width, pictureBoxExcavator.Height); _drawningBulldozer.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxExcavator.Width, pictureBoxExcavator.Height);
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
@ -90,4 +113,46 @@ public partial class FormExcavator : Form
} }
} }
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningBulldozer == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableBulldozer(_drawningBulldozer), pictureBoxExcavator.Width, pictureBoxExcavator.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,137 @@
namespace ProjectExcavator.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="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>Результат перемещения (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 IsTargetDestination();
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,21 @@
namespace ProjectExcavator.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,51 @@
namespace ProjectExcavator.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder - GetStep() <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder - GetStep() <= FieldHeight && 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,54 @@
namespace ProjectExcavator.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
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,64 @@
using ProjectExcavator.Drawnings;
namespace ProjectExcavator.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningBulldozer
/// </summary>
public class MoveableBulldozer : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningBulldozer или его наследника
/// </summary>
private readonly DrawningBulldozer? _bulldozer = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="Bulldozer">Объект класса DrawningBulldozer</param>
public MoveableBulldozer(DrawningBulldozer bulldozer)
{
_bulldozer = bulldozer;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_bulldozer == null || _bulldozer.EntityBulldozer == null || !_bulldozer.GetPosX.HasValue || !_bulldozer.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_bulldozer.GetPosX.Value, _bulldozer.GetPosY.Value, _bulldozer.GetWidth, _bulldozer.GetHeight);
}
}
public int GetStep => (int)(_bulldozer?.EntityBulldozer?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_bulldozer == null || _bulldozer.EntityBulldozer == null)
{
return false;
}
return _bulldozer.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 ProjectExcavator.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 ProjectExcavator.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 ProjectExcavator.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}