pibd-12_Tangatarov.I.A._Base LabWork02 #2

Closed
sqdselo wants to merge 4 commits from LabWork02 into LabWork01
13 changed files with 540 additions and 20 deletions
Showing only changes of commit a1dab73b6d - Show all commits

View File

@ -1,10 +1,14 @@
namespace HoistingCrane.Drawning;
public enum DirectionType : byte //Создали не класс(class), а перечисление (enum)
public enum DirectionType //Создали не класс(class), а перечисление (enum)
{
//Перечислим основные траектории движния нашего автомобиля. Сразу же зададим значения.
/// <summary>
/// Вверх1
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>

View File

@ -5,10 +5,6 @@ namespace HoistingCrane.Drawning;
//В данном классе мы будем думать над полем игры, размерами персонажа, размерами объектов и т.д.
public class DrawningHoistingCrane : DrawningTrackedVehicle
{
/// <summary>
/// Класс - сущность
/// </summary>
public EntityHoistingCrane? EntityHoistingCrane { get; private set; }
/// <summary>
/// Ширина окна
@ -24,6 +20,7 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawingCarWidth = 115;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
@ -42,10 +39,16 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle
}
//Метод изменения траектории движения из дочернего класса
public void CreateMovement()
{
if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
EntityTrackedVehicle.MoveTransport(direction);
}
/// <summary>
/// Метод отрисовки объекта

View File

@ -7,10 +7,6 @@ namespace HoistingCrane.Drawning
{
/// <summary>
/// Класс - сущность
/// </summary>
@ -44,6 +40,11 @@ namespace HoistingCrane.Drawning
/// </summary>
private readonly int _drawingCarHeight = 63;
public int? GetPosX => _startPosX;
public int? GetPosY => _startPosY;
public int GetWidth => _drawingCarWidth;
public int GetHeight => _drawingCarHeight;
/// <summary>
@ -164,7 +165,7 @@ namespace HoistingCrane.Drawning
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public bool MoveTransport(DirectionType direction)
protected bool MoveTransport(DirectionType direction)
{
if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue)
{

View File

@ -31,6 +31,8 @@ namespace HoistingCrane
ButtonUp = new Button();
ButtonDown = new Button();
buttonCreateTrackedVehicle = new Button();
comboStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxHoistingCrane).BeginInit();
SuspendLayout();
//
@ -109,15 +111,37 @@ namespace HoistingCrane
buttonCreateTrackedVehicle.Name = "buttonCreateTrackedVehicle";
buttonCreateTrackedVehicle.Size = new Size(194, 23);
buttonCreateTrackedVehicle.TabIndex = 6;
buttonCreateTrackedVehicle.Text = "Создать бронебойную машину";
buttonCreateTrackedVehicle.Text = "Создать гусеничную машину";
buttonCreateTrackedVehicle.UseVisualStyleBackColor = true;
buttonCreateTrackedVehicle.Click += buttonCreateTrackedVehicle_Click;
//
// comboStrategy
//
comboStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboStrategy.FormattingEnabled = true;
comboStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboStrategy.Location = new Point(697, 42);
comboStrategy.Name = "comboStrategy";
comboStrategy.Size = new Size(121, 23);
comboStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(743, 71);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormHoistingCrane
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(818, 515);
Controls.Add(buttonStrategyStep);
Controls.Add(comboStrategy);
Controls.Add(buttonCreateTrackedVehicle);
Controls.Add(ButtonDown);
Controls.Add(ButtonUp);
@ -140,5 +164,7 @@ namespace HoistingCrane
private Button ButtonUp;
private Button ButtonDown;
private Button buttonCreateTrackedVehicle;
private ComboBox comboStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,5 @@
using HoistingCrane.Drawning;
using HoistingCrane.MovementStrategy;
namespace HoistingCrane
{
@ -6,10 +7,11 @@ namespace HoistingCrane
{
private DrawningTrackedVehicle? _drawning;
private AbstractStrategy? _abstractStrategy;
public FormHoistingCrane()
{
InitializeComponent();
_abstractStrategy = null;
}
private void Draw()
@ -50,19 +52,21 @@ namespace HoistingCrane
{
case nameof(DrawningHoistingCrane):
_drawning = new DrawningHoistingCrane(rand.Next(100, 300),rand.Next(1000, 3000),Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)),
_drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)),
Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)), true, true);
break;
break;
case nameof(DrawningTrackedVehicle):
_drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256)));
break;
break;
default:
return;
}
_drawning.SetPictureSize(pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
_drawning.SetPosition(rand.Next(0, 100), rand.Next(0, 100));
comboStrategy.Enabled = true;
Draw();
}
@ -98,6 +102,42 @@ namespace HoistingCrane
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawning == null)
{
return;
}
if (comboStrategy.Enabled)
{
_abstractStrategy = comboStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new MoveableCar(_drawning), pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == StrategyStatus.Finish)
{
comboStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,139 @@
namespace HoistingCrane.MovementStrategy
{
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObjects? _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(IMoveableObjects 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();
/// <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 HoistingCrane.MovementStrategy
{
public interface IMoveableObjects
{
/// <summary>
/// Получение позиции объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Получение шага объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">направление</param>
/// <returns></returns>
bool TryMoveObject(MovementDirection direction);
}
}

View File

@ -0,0 +1,51 @@
namespace HoistingCrane.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
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,52 @@
namespace HoistingCrane.MovementStrategy
{
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,63 @@
using HoistingCrane.Drawning;
namespace HoistingCrane.MovementStrategy
{
public class MoveableCar : IMoveableObjects
{
/// <summary>
/// Поле-объект класса DrawningAirplane или его наследника
/// </summary>
private readonly DrawningTrackedVehicle? drawningTrackedVehicle = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="airplane">Объект класса DrawningAirplane</param>
public MoveableCar(DrawningTrackedVehicle drawningTrackedVehicle)
{
this.drawningTrackedVehicle = drawningTrackedVehicle;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (drawningTrackedVehicle == null || drawningTrackedVehicle.EntityTrackedVehicle == null || !drawningTrackedVehicle.GetPosX.HasValue || !drawningTrackedVehicle.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(drawningTrackedVehicle.GetPosX.Value, drawningTrackedVehicle.GetPosY.Value, drawningTrackedVehicle.GetWidth, drawningTrackedVehicle.GetHeight);
}
}
public int GetStep => (int)(drawningTrackedVehicle?.EntityTrackedVehicle?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (drawningTrackedVehicle == null || drawningTrackedVehicle.EntityTrackedVehicle == null)
{
return false;
}
return drawningTrackedVehicle.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,25 @@
namespace HoistingCrane.MovementStrategy
{
public enum MovementDirection
{
//Перечислим основные траектории движния нашего автомобиля. Сразу же зададим значения.
/// <summary>
/// Вверх1
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,70 @@
namespace HoistingCrane.MovementStrategy
{
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 RightBorder => _x + _width;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <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)
{
this._x = _x;
this._y = _y;
this._width = _width;
this._height = _height;
}
}
}

View File

@ -0,0 +1,22 @@
namespace HoistingCrane.MovementStrategy
{
public enum StrategyStatus
{
/// <summary>
/// Всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}
}