PIbd_13 Klykov_N.V.Lab02 Simple #2

Closed
nikos77781 wants to merge 2 commits from Lab02 into Lab01
12 changed files with 542 additions and 2 deletions
Showing only changes of commit 255b862e89 - Show all commits

View File

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

View File

@ -45,6 +45,26 @@ public class DrawningSimpleExcavator
/// </summary>
private readonly int _drawningExcavatorHeight = 80;
/// <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

@ -35,6 +35,8 @@
buttonDown = new Button();
buttonRight = new Button();
buttonCreateSimpleExcavator = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit();
SuspendLayout();
//
@ -117,11 +119,34 @@
buttonCreateSimpleExcavator.UseVisualStyleBackColor = true;
buttonCreateSimpleExcavator.Click += ButtonCreateSimpleExcavator_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю " });
comboBoxStrategy.Location = new Point(790, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(790, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(121, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormExcavator
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 597);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateSimpleExcavator);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
@ -144,5 +169,7 @@
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateSimpleExcavator;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,6 @@
using Excavator.Drawnings;
using Excavator.Entities;
using Excavator.MovementSrtategy;
namespace Excavator;
@ -12,12 +14,15 @@ public partial class FormExcavator : Form
/// </summary>
private DrawningSimpleExcavator? _drawningSimpleExcavator;
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormExcavator()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -61,7 +66,7 @@ public partial class FormExcavator : Form
_drawningSimpleExcavator.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height);
_drawningSimpleExcavator.SetPosition(random.Next(10, 100), random.Next(10, 100));
//_strategy = null;
_strategy = null;
//comboBoxStrategy.Enabled = true;
Draw();
@ -122,4 +127,47 @@ public partial class FormExcavator : Form
Draw();
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningSimpleExcavator == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableSimpleExcavator(_drawningSimpleExcavator), 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,139 @@
using Excavator.MovementStrategy;
namespace Excavator.MovementSrtategy;
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?.GetObjectParameters;
/// <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 @@
using Excavator.MovementStrategy;
namespace Excavator.MovementSrtategy;
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectParameters { get; }
/// <summary>
/// Шаг
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка перемстить объект
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,39 @@
namespace Excavator.MovementSrtategy;
public class MoveToBorder : AbstractStrategy
{
/// <summary>
/// Стратегия перемещения объекта к Краю экрана
/// </summary>
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())
{
MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,55 @@
namespace Excavator.MovementSrtategy;
/// <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,65 @@
using Excavator.Drawnings;
using Excavator.MovementStrategy;
namespace Excavator.MovementSrtategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием Drawningexcavator
/// </summary>
public class MoveableSimpleExcavator : IMoveableObject
{
/// <summary>
/// Поле-объект класса Drawningexcavator или его наследника
/// </summary>
private readonly DrawningSimpleExcavator? _excavator = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="excavator">Объект класса Drawningexcavator</param>
public MoveableSimpleExcavator(DrawningSimpleExcavator excavator)
{
_excavator = excavator;
}
public ObjectParameters? GetObjectParameters
{
get
{
if (_excavator == null || _excavator.EntitySimpleExcavator == 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?.EntitySimpleExcavator?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_excavator == null || _excavator.EntitySimpleExcavator == 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,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,27 @@
namespace Excavator.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,70 @@

namespace Excavator.MovementSrtategy;
public class ObjectParameters
{
/// <summary>
/// Координата Х
/// </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"></param>
/// <param name="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 Excavator.MovementSrtategy;
public enum StrategyStatus
{
/// <summary>
/// Всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}