diff --git a/lab_0/Drawnings/DirectionType.cs b/lab_0/Drawnings/DirectionType.cs index bcea611..8214c58 100644 --- a/lab_0/Drawnings/DirectionType.cs +++ b/lab_0/Drawnings/DirectionType.cs @@ -1,4 +1,4 @@ -namespace ProjectBus. Drawings; +namespace ProjectBus. Drawnings; /// /// Направление перемещения @@ -6,6 +6,11 @@ public enum DirectionType { + /// + /// Вверх + /// + Unknow = -1, + /// /// Вверх /// diff --git a/lab_0/Drawnings/DrawningBus.cs b/lab_0/Drawnings/DrawningBus.cs index b98a55b..e391f59 100644 --- a/lab_0/Drawnings/DrawningBus.cs +++ b/lab_0/Drawnings/DrawningBus.cs @@ -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); diff --git a/lab_0/Drawnings/DrawningSimpleBus.cs b/lab_0/Drawnings/DrawningSimpleBus.cs index 31fa21a..873435a 100644 --- a/lab_0/Drawnings/DrawningSimpleBus.cs +++ b/lab_0/Drawnings/DrawningSimpleBus.cs @@ -1,4 +1,4 @@ -using ProjectBus.Drawings; +using ProjectBus.Drawnings; using ProjectBus.Entities; namespace ProjectBus.Drawnings; @@ -29,7 +29,6 @@ public class DrawningSimpleBus /// Верхняя кооридната прорисовки автобуса /// protected int? _startPosY; - /// /// Ширина прорисовки автобуса @@ -41,6 +40,23 @@ public class DrawningSimpleBus /// private readonly int _drawningBusHeight = 52; + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningBusWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningBusHeight; + /// /// Пустой конструктор /// diff --git a/lab_0/FormBus.Designer.cs b/lab_0/FormBus.Designer.cs index 885c720..cdcb98c 100644 --- a/lab_0/FormBus.Designer.cs +++ b/lab_0/FormBus.Designer.cs @@ -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; } } \ No newline at end of file diff --git a/lab_0/FormBus.cs b/lab_0/FormBus.cs index e91af74..f63567b 100644 --- a/lab_0/FormBus.cs +++ b/lab_0/FormBus.cs @@ -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; +/// +/// форма работы с объектом "Автобус" +/// +public partial class FormBus : Form { - public partial class FormBus : Form + /// + /// поле-объект для прорисовки объекта + /// + private DrawningSimpleBus? _drawningSimpleBus; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + + /// + /// конструктор формы + /// + public FormBus() { - private DrawningSimpleBus? _drawningSimpleBus; + InitializeComponent(); + _strategy = null; + } - public FormBus() + /// + /// метод прорисовки машины + /// + 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; + } + + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + 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; } - /// - /// Создание объекта класса-перемещения - /// - /// Тип создаваемого объекта - 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(); + } + + /// + /// Обработка нажатия кнопки "Создать автобус с доп отсеком" + /// + /// + /// + private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBus)); + + /// + /// Обработка нажатия кнопки "Создать обычный автобус" + /// + /// + /// + 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(); } + } - /// - /// Обработка нажатия кнопки "Создать автобус с доп отсеком" - /// - /// - /// - private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBus)); - - /// - /// Обработка нажатия кнопки "Создать обычный автобус" - /// - /// - /// - private void buttonCreateSimpleBus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSimpleBus)); - - - - private void ButtonMove_Click(object sender, EventArgs e) + /// + /// + /// + /// + /// + 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; } } } + diff --git a/lab_0/MovementStrategy/AbstractStrategy.cs b/lab_0/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..aeb8914 --- /dev/null +++ b/lab_0/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,139 @@ +namespace ProjectBus.MovementStrategy; + +/// +/// Класс-стратегия перемещения объекта +/// +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotInit; + + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + + /// + /// Статус перемещения + /// + public StrategyStatus GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + 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; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (IsTargetDestinaion()) + { + _state = StrategyStatus.Finish; + return; + } + + MoveToTarget(); + } + + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(MovementDirection.Right); + + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(MovementDirection.Up); + + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveDown() => MoveTo(MovementDirection.Down); + + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} \ No newline at end of file diff --git a/lab_0/MovementStrategy/IMoveableObject.cs b/lab_0/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..6b7c9e4 --- /dev/null +++ b/lab_0/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace ProjectBus.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/lab_0/MovementStrategy/MoveToBorder.cs b/lab_0/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..1a70a48 --- /dev/null +++ b/lab_0/MovementStrategy/MoveToBorder.cs @@ -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(); + } + } + } +} \ No newline at end of file diff --git a/lab_0/MovementStrategy/MoveToCenter.cs b/lab_0/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..59df3bb --- /dev/null +++ b/lab_0/MovementStrategy/MoveToCenter.cs @@ -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(); + } + } + } +} \ No newline at end of file diff --git a/lab_0/MovementStrategy/MoveableSimpleBus.cs b/lab_0/MovementStrategy/MoveableSimpleBus.cs new file mode 100644 index 0000000..3c83c2c --- /dev/null +++ b/lab_0/MovementStrategy/MoveableSimpleBus.cs @@ -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; + +/// +/// Класс-реализация IMoveableObject с использованием DrawingSimpleBus +/// + +public class MoveableSimpleBus : IMoveableObject +{ + // + /// Поле-объект класса DrawningTrans или его наследника + /// + private readonly DrawningSimpleBus? _simplebus = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningSimpleBus + 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)); + } + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + 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, + }; + } +} diff --git a/lab_0/MovementStrategy/MovementDirection.cs b/lab_0/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..593381a --- /dev/null +++ b/lab_0/MovementStrategy/MovementDirection.cs @@ -0,0 +1,28 @@ +namespace ProjectBus.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Неизвестное направление + /// + Unknow = -1, + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/lab_0/MovementStrategy/ObjectParameters.cs b/lab_0/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..5d99dbb --- /dev/null +++ b/lab_0/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,72 @@ +namespace ProjectBus.MovementStrategy; + +/// +/// Параметры-координаты объекта +/// +public class ObjectParameters +{ + /// + /// Координата X + /// + private readonly int _x; + + /// + /// Координата Y + /// + private readonly int _y; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/lab_0/MovementStrategy/StrategyStatus.cs b/lab_0/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..42abe03 --- /dev/null +++ b/lab_0/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace ProjectBus.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} \ No newline at end of file