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

This commit is contained in:
Anya 2024-04-18 14:03:03 +04:00
parent b956941018
commit 6323fb7bc8
13 changed files with 658 additions and 87 deletions

View File

@ -1,4 +1,4 @@
namespace ProjectBus. Drawings;
namespace ProjectBus. Drawnings;
/// <summary>
/// Направление перемещения
@ -6,6 +6,11 @@
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -57,8 +57,6 @@ public class DrawningBus : DrawningSimpleBus
g.DrawEllipse(pen, _startPosX.Value + 250, _startPosY.Value + 40, 20, 20);
}
_startPosX += 0;
_startPosY += 0;
base.DrawTransport(g);

View File

@ -1,4 +1,4 @@
using ProjectBus.Drawings;
using ProjectBus.Drawnings;
using ProjectBus.Entities;
namespace ProjectBus.Drawnings;
@ -29,7 +29,6 @@ public class DrawningSimpleBus
/// Верхняя кооридната прорисовки автобуса
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки автобуса
@ -41,6 +40,23 @@ public class DrawningSimpleBus
/// </summary>
private readonly int _drawningBusHeight = 52;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBusWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningBusHeight;
/// <summary>
/// Пустой конструктор
/// </summary>

View File

@ -35,6 +35,8 @@
buttonUp = new Button();
buttonDown = new Button();
buttonCreateSimpleBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBus).BeginInit();
SuspendLayout();
//
@ -117,11 +119,33 @@
buttonCreateSimpleBus.UseVisualStyleBackColor = true;
buttonCreateSimpleBus.Click += buttonCreateSimpleBus_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(901, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(242, 40);
comboBoxStrategy.TabIndex = 9;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(993, 58);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(150, 46);
buttonStrategyStep.TabIndex = 10;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormBus
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1155, 557);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateSimpleBus);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
@ -143,5 +167,7 @@
private Button buttonUp;
private Button buttonDown;
private Button buttonCreateSimpleBus;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,5 +1,5 @@
using ProjectBus.Drawings;
using ProjectBus.Drawnings;
using ProjectBus.Drawnings;
using ProjectBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,109 +10,172 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectBus
namespace ProjectBus;
/// <summary>
/// форма работы с объектом "Автобус"
/// </summary>
public partial class FormBus : Form
{
public partial class FormBus : Form
/// <summary>
/// поле-объект для прорисовки объекта
/// </summary>
private DrawningSimpleBus? _drawningSimpleBus;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// конструктор формы
/// </summary>
public FormBus()
{
private DrawningSimpleBus? _drawningSimpleBus;
InitializeComponent();
_strategy = null;
}
public FormBus()
/// <summary>
/// метод прорисовки машины
/// </summary>
private void Draw()
{
if (_drawningSimpleBus == null)
{
InitializeComponent();
return;
}
private void Draw()
Bitmap bmp = new(pictureBoxBus.Width, pictureBoxBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningSimpleBus.DrawTransport(gr);
pictureBoxBus.Image = bmp;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
if (_drawningSimpleBus == null)
{
case nameof(DrawningSimpleBus):
_drawningSimpleBus = new DrawningSimpleBus(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningBus):
_drawningSimpleBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
Bitmap bmp = new(pictureBoxBus.Width, pictureBoxBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningSimpleBus.DrawTransport(gr);
pictureBoxBus.Image = bmp;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
_drawningSimpleBus.SetPictureSize(pictureBoxBus.Width, pictureBoxBus.Height);
_drawningSimpleBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать автобус с доп отсеком"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBus));
/// <summary>
/// Обработка нажатия кнопки "Создать обычный автобус"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateSimpleBus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSimpleBus));
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningSimpleBus == null)
{
Random random = new();
switch (type)
{
case nameof(DrawningSimpleBus):
_drawningSimpleBus = new DrawningSimpleBus(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningBus):
_drawningSimpleBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
return;
}
_drawningSimpleBus.SetPictureSize(pictureBoxBus.Width, pictureBoxBus.Height);
_drawningSimpleBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
/// <summary>
/// Обработка нажатия кнопки "Создать автобус с доп отсеком"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBus));
/// <summary>
/// Обработка нажатия кнопки "Создать обычный автобус"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateSimpleBus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSimpleBus));
private void ButtonMove_Click(object sender, EventArgs e)
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningSimpleBus == null)
{
if (_drawningSimpleBus == null)
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableSimpleBus(_drawningSimpleBus), pictureBoxBus.Width, pictureBoxBus.Height);
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningSimpleBus.MoveTransport(DirectionType.Right);
break;
}
if (_strategy == null)
{
return;
}
if (result)
{
Draw();
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

@ -0,0 +1,139 @@
namespace ProjectBus.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,24 @@
namespace ProjectBus.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
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,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBus.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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.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,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBus.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,66 @@
using ProjectBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBus.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawingSimpleBus
/// </summary>
public class MoveableSimpleBus : IMoveableObject
{
// <summary>
/// Поле-объект класса DrawningTrans или его наследника
/// </summary>
private readonly DrawningSimpleBus? _simplebus = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="simplebus">Объект класса DrawningSimpleBus</param>
public MoveableSimpleBus(DrawningSimpleBus simplebus)
{
_simplebus = simplebus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_simplebus == null || _simplebus.EntitySimpleBus == null || !_simplebus.GetPosX.HasValue || !_simplebus.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_simplebus.GetPosX.Value, _simplebus.GetPosY.Value, _simplebus.GetWidth, _simplebus.GetHeight);
}
}
public int GetStep => (int)(_simplebus?.EntitySimpleBus ?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_simplebus == null || _simplebus.EntitySimpleBus == null)
{
return false;
}
return _simplebus.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,28 @@
namespace ProjectBus.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

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