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

This commit is contained in:
Мария Котова 2024-02-28 13:28:37 +04:00
parent b6c46f97c2
commit 489f70b80f
12 changed files with 561 additions and 39 deletions

View File

@ -34,41 +34,6 @@ public class DrawingExcavator : DrawingExcavatorEmpty
Brush additionalBrush = new SolidBrush(entityExcavator.AdditionalColor);
Brush bodybrush = new SolidBrush(entityExcavator.BodyColor);
//границы экскаватора
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 20, 100, 30);
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 80, _startPosY.Value, 20, 20);
g.DrawArc(pen, _startPosX.Value, _startPosY.Value + 45, 30, 40, 130, 100);
g.DrawArc(pen, _startPosX.Value + 80, _startPosY.Value + 50, 30, 40, 285, 110);
g.DrawLine(pen, _startPosX.Value + 5, _startPosY.Value + 80, _startPosX.Value + 109, _startPosY.Value + 80);
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 53, 25, 25);
g.DrawEllipse(pen, _startPosX.Value + 80, _startPosY.Value + 53, 25, 25);
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 69, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 48, _startPosY.Value + 69, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 69, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 53, 7, 7);
g.DrawEllipse(pen, _startPosX.Value + 60, _startPosY.Value + 53, 7, 7);
//заливка кабины и основного железа
Brush br = new SolidBrush(Color.Black);
g.FillRectangle(bodybrush, _startPosX.Value, _startPosY.Value + 20, 100, 30);
g.FillRectangle(bodybrush, _startPosX.Value + 30, _startPosY.Value, 10, 20);
g.FillRectangle(bodybrush, _startPosX.Value + 80, _startPosY.Value, 20, 20);
g.FillEllipse(br, _startPosX.Value + 5, _startPosY.Value + 53, 25, 25);
g.FillEllipse(br, _startPosX.Value + 80, _startPosY.Value + 53, 25, 25);
g.FillEllipse(br, _startPosX.Value + 30, _startPosY.Value + 69, 10, 10);
g.FillEllipse(br, _startPosX.Value + 48, _startPosY.Value + 69, 10, 10);
g.FillEllipse(br, _startPosX.Value + 65, _startPosY.Value + 69, 10, 10);
g.FillEllipse(br, _startPosX.Value + 40, _startPosY.Value + 53, 7, 7);
g.FillEllipse(br, _startPosX.Value + 60, _startPosY.Value + 53, 7, 7);
//фары
Brush brfara = new SolidBrush(Color.Blue);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 27, 10, 10);
g.FillRectangle(brfara, _startPosX.Value, _startPosY.Value + 27, 10, 10);
//окно
g.FillRectangle(brfara, _startPosX.Value + 85, _startPosY.Value + 10, 10, 10);
if (entityExcavator.Bucket)
{

View File

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

View File

@ -36,6 +36,8 @@ namespace WinFormsAppExcavator
buttonDown = new Button();
buttonUp = new Button();
CreateExcavatorEmpty = new Button();
buttonStrategyStep = new Button();
comboBoxStrategy = new ComboBox();
((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit();
SuspendLayout();
//
@ -118,11 +120,33 @@ namespace WinFormsAppExcavator
CreateExcavatorEmpty.UseVisualStyleBackColor = true;
CreateExcavatorEmpty.Click += CreateExcavatorEmpty_Click;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(790, 48);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(733, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 9;
//
// FormExcavator
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(898, 329);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStrategyStep);
Controls.Add(CreateExcavatorEmpty);
Controls.Add(buttonUp);
Controls.Add(buttonDown);
@ -145,5 +169,7 @@ namespace WinFormsAppExcavator
private Button buttonUp;
public Button buttonCreat;
public Button CreateExcavatorEmpty;
private Button buttonStrategyStep;
private ComboBox comboBoxStrategy;
}
}

View File

@ -1,5 +1,6 @@
using System;
using WinFormsAppExcavator.Drawings;
using WinFormsAppExcavator.MovementStrategy;
namespace WinFormsAppExcavator
{
@ -13,12 +14,19 @@ namespace WinFormsAppExcavator
/// </summary>
private DrawingExcavatorEmpty? _drawingExcavatorEmpty;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormExcavator()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -42,10 +50,10 @@ namespace WinFormsAppExcavator
///<summary>
///создание объекта класса перемещения
///</summary>
private void CreateObject (String type)
private void CreateObject(String type)
{
Random random= new();
Random random = new();
switch (type)
{
case nameof(DrawingExcavatorEmpty):
@ -65,6 +73,9 @@ namespace WinFormsAppExcavator
_drawingExcavatorEmpty.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height);
_drawingExcavatorEmpty.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
@ -125,6 +136,50 @@ namespace WinFormsAppExcavator
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingExcavatorEmpty == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableExcavator(_drawingExcavatorEmpty), 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,140 @@
namespace WinFormsAppExcavator.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObjectcs? _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(IMoveableObjectcs 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 WinFormsAppExcavator.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObjectcs
{
/// <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,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsAppExcavator.MovementStrategy
{
internal class MoveToBorder : 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;
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,48 @@
namespace WinFormsAppExcavator.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,69 @@

using WinFormsAppExcavator.Drawings;
namespace WinFormsAppExcavator.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningExcavator
/// </summary>
public class MoveableExcavator : IMoveableObjectcs
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawingExcavatorEmpty? _excavator = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="car">Объект класса DrawningCar</param>
public MoveableExcavator(DrawingExcavatorEmpty excavator)
{
_excavator = excavator;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_excavator == null || _excavator.EntityExcavatorEmpty == null || !_excavator.GetPosX.HasValue || !_excavator.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_excavator.GetPosX.Value, _excavator.GetPosY.Value, _excavator.GetWidth, _excavator.GetHeight);
}
}
public int GetStep => (int)(_excavator?.EntityExcavatorEmpty?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_excavator == null || _excavator.EntityExcavatorEmpty == null)
{
return false;
}
return _excavator.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,
};
}
}

View File

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