Лабораторная работа 2

This commit is contained in:
Samecoins 2024-04-01 15:06:18 +04:00
parent 33d663adfe
commit a18f6a4410
13 changed files with 587 additions and 20 deletions

View File

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

View File

@ -44,11 +44,11 @@ public class DrawningDumpTruck : DrawningTruck
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value, 90, 35);
}
_startPosX += 10;
_startPosY += 20;
_startPosX += 0;
_startPosY += 0;
base.DrawTransport(g);
_startPosX -= 10;
_startPosY -= 20;
_startPosX -= 0;
_startPosY -= 0;
//Отрисовка тента

View File

@ -37,19 +37,32 @@ public class DrawningTruck
/// <summary>
/// Ширина прорисовки самосвала
/// </summary>
private readonly int _drawningDumpTruckWidth = 90;
private readonly int _drawningDumpTruckWidth = 130;
/// <summary>
/// Высота прорисовки самосвала
/// </summary>
private readonly int _drawningDumpTruckHeight = 50;
private readonly int _drawningDumpTruckHeight = 90;
// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Конструктор
/// Координата Y объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningDumpTruckWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningDumpTruckHeight;
/// <summary>
/// Пустой конструктор
@ -63,6 +76,13 @@ public class DrawningTruck
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningTruck(int speed, double weight, Color bodyColor) : this()
{
EntityTruck = new EntityTruck(speed, weight, bodyColor);
@ -208,22 +228,22 @@ public class DrawningTruck
//Отрисовка основы (кабины водителя и днища)
Brush body = new SolidBrush(EntityTruck.BodyColor);
g.FillRectangle(body, _startPosX.Value + 60, _startPosY.Value + 5, 20, 20); // Уменьшенная кабина
g.FillRectangle(body, _startPosX.Value, _startPosY.Value + 25, 90, 15); // Уменьшенное днище
g.FillRectangle(body, _startPosX.Value + 100, _startPosY.Value, 30, 35);
g.FillRectangle(body, _startPosX.Value, _startPosY.Value + 40, 130, 20);
//Отрисовка колёс
Brush wheels = new SolidBrush(Color.Gray);
g.FillEllipse(wheels, _startPosX.Value + 5, _startPosY.Value + 35, 20, 20); // Уменьшенные колеса
g.FillEllipse(wheels, _startPosX.Value + 35, _startPosY.Value + 35, 20, 20);
g.FillEllipse(wheels, _startPosX.Value + 65, _startPosY.Value + 35, 20, 20);
g.FillEllipse(wheels, _startPosX.Value, _startPosY.Value + 60, 30, 30);
g.FillEllipse(wheels, _startPosX.Value + 30, _startPosY.Value + 60, 30, 30);
g.FillEllipse(wheels, _startPosX.Value + 100, _startPosY.Value + 60, 30, 30);
//Отрисовка границ
Brush border = new SolidBrush(Color.Black);
g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value + 5, 20, 20); // Граница кабины
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 25, 90, 15); // Граница днища
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 35, 20, 20); // Границы колёс
g.DrawEllipse(pen, _startPosX.Value + 35, _startPosY.Value + 35, 20, 20);
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 35, 20, 20);
g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value, 30, 35);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 40, 130, 20);
g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 60, 30, 30);
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 60, 30, 30);
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 60, 30, 30);
}
}

View File

@ -35,6 +35,8 @@
buttonRight = new Button();
buttonCreateDumpTruck = new Button();
buttonCreateTruck = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).BeginInit();
SuspendLayout();
//
@ -117,11 +119,33 @@
buttonCreateTruck.UseVisualStyleBackColor = true;
buttonCreateTruck.Click += ButtonCreateTruck_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К границе поля" });
comboBoxStrategy.Location = new Point(884, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(930, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormTransport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1017, 533);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTruck);
Controls.Add(buttonCreateDumpTruck);
Controls.Add(buttonRight);
@ -144,5 +168,7 @@
private Button buttonRight;
private Button buttonCreateDumpTruck;
private Button buttonCreateTruck;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -8,6 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Форма работы с объектом "Самосвал"
@ -21,12 +22,18 @@ namespace ProjectDumpTruck
/// </summary>
private DrawningTruck? _drawningTruck;
/// <summary>
///
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormTransport()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -70,6 +77,8 @@ namespace ProjectDumpTruck
_drawningTruck.SetPictureSize(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
_drawningTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
@ -124,5 +133,47 @@ namespace ProjectDumpTruck
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningTruck == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTruck(_drawningTruck), pictureBoxDumpTruck.Width, pictureBoxDumpTruck.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 ProjectDumpTruck.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>
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,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </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,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
if (GetObjectParameters == null)
{
return false;
}
return GetObjectParameters.RightBorder <= FieldWidth &&
GetObjectParameters.RightBorder + GetStep() >= FieldWidth &&
GetObjectParameters.DownBorder <= FieldHeight &&
GetObjectParameters.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
if (GetObjectParameters == null)
{
return;
}
if (Math.Abs(GetObjectParameters.ObjectMiddleHorizontal - FieldWidth) > GetStep())
{
if (GetObjectParameters.ObjectMiddleHorizontal - FieldWidth > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
if (Math.Abs(GetObjectParameters.ObjectMiddleVertical - FieldHeight) > GetStep())
{
if (GetObjectParameters.ObjectMiddleVertical - FieldHeight > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= 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,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Drawnings;
namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningTruck
/// </summary>
public class MoveableTruck : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningShip или его наследника
/// </summary>
private readonly DrawningTruck? _truck = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="truck"></param>
public MoveableTruck(DrawningTruck truck)
{
_truck = truck;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_truck == null || _truck.EntityTruck == null || !_truck.GetPosX.HasValue || !_truck.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_truck.GetPosX.Value, _truck.GetPosY.Value, _truck.GetWidth, _truck.GetHeight);
}
}
public int GetStep => (int)(_truck?.EntityTruck?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_truck == null || _truck.EntityTruck == null)
{
return false;
}
return _truck.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 ProjectDumpTruck.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 ProjectDumpTruck.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,19 @@
namespace ProjectDumpTruck.MovementStrategy;
public enum StrategyStatus
{
/// <summary
/// Все готово к началу
/// </summary
NotInit,
/// <summary
/// Выполняется
/// </summary
InProgress,
/// <summary
/// Завершено
/// </summary
Finish
}