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

This commit is contained in:
mar-va 2024-03-20 15:22:04 +04:00
parent 9c1f576994
commit c9e4d0b039
14 changed files with 577 additions and 16 deletions

View File

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

View File

@ -4,14 +4,15 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectAccordionBus.Drawnings; namespace ProjectAccordionBus.Drawnings;
public class DrawningAccordionBus : DrawningBus public class DrawningAccordionBus : DrawningBus
{ {
public DrawningAccordionBus(EntityAccordionBus entity) : base(110, 40) public DrawningAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool compartment, bool entrance, bool windows) : base(110, 40)
{ {
EntityBus = entity; EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, compartment, entrance, windows);
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)

View File

@ -8,19 +8,60 @@ using System.Threading.Tasks;
namespace ProjectAccordionBus.Drawnings; namespace ProjectAccordionBus.Drawnings;
public class DrawningBus public class DrawningBus
{ {
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; } public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth; private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight; private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки транспорта
/// </summary>
protected int? _startPosX; protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки транспорта
/// </summary>
protected int? _startPosY; protected int? _startPosY;
private int _drawningBusWidth = 50; /// <summary>
/// Ширина прорисовки транспорта
/// </summary>
private readonly int _drawningBusWidth = 50;
private readonly int _drawningBusHeight = 40; /// <summary>
/// Высота прорисовки транспорта
/// </summary>
private readonly int _drawningBusHeight = 35;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBusWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHight => _drawningBusHeight;
// Пустой конструктор // Пустой конструктор
private DrawningBus() private DrawningBus()
@ -32,9 +73,9 @@ public class DrawningBus
} }
// Конструктор // Конструктор
public DrawningBus(EntityBus entity) : this() public DrawningBus(int speed, double weight, Color bodyColor) : this()
{ {
EntityBus = entity; EntityBus = new EntityBus(speed, weight, bodyColor);
} }
// Конструктор // Конструктор

View File

@ -28,7 +28,7 @@ public class EntityAccordionBus : EntityBus
{ {
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Compartment = compartment; // отсек Compartment = compartment; // отсек
Entrance = entrance; // крылья Entrance = entrance;
Windows = windows; Windows = windows;
} }

View File

@ -36,6 +36,8 @@
buttonUp = new Button(); buttonUp = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateBus = new Button(); buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -119,11 +121,34 @@
buttonCreateBus.UseVisualStyleBackColor = true; buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += buttonCreateBus_Click; buttonCreateBus.Click += buttonCreateBus_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(595, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
comboBoxStrategy.SelectedIndexChanged += comboBoxStrategy_SelectedIndexChanged;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(641, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormAccordionBus // FormAccordionBus
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(728, 386); ClientSize = new Size(728, 386);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus); Controls.Add(buttonCreateBus);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonUp); Controls.Add(buttonUp);
@ -151,5 +176,7 @@
private Button buttonUp; private Button buttonUp;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateBus; private Button buttonCreateBus;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,5 +1,6 @@
using ProjectAccordionBus.Drawnings; using ProjectAccordionBus.Drawnings;
using ProjectAccordionBus.Entities; using ProjectAccordionBus.Entities;
using ProjectAccordionBus.MovementStrategy;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -16,14 +17,13 @@ public partial class FormAccordionBus : Form
private DrawningBus? _drawningBus; private DrawningBus? _drawningBus;
private EntityBus? _entity; private AbstractStrategy? _strategy;
private EntityAccordionBus? _entityAccordionBus;
public FormAccordionBus() public FormAccordionBus()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
private void Draw() private void Draw()
@ -45,16 +45,14 @@ public partial class FormAccordionBus : Form
switch (type) switch (type)
{ {
case nameof(DrawningBus): case nameof(DrawningBus):
_entity = new EntityBus(random.Next(100, 300), random.Next(1000, 3000), _drawningBus = 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)));
_drawningBus = new DrawningBus(_entity);
break; break;
case nameof(DrawningAccordionBus): case nameof(DrawningAccordionBus):
_entityAccordionBus = new EntityAccordionBus(random.Next(100, 300), random.Next(1000, 3000), _drawningBus = new DrawningAccordionBus(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)),
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)), Convert.ToBoolean(random.Next(0, 2))); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningBus = new DrawningAccordionBus(_entityAccordionBus);
break; break;
default: default:
return; return;
@ -62,7 +60,8 @@ public partial class FormAccordionBus : Form
_drawningBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height); _drawningBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
_drawningBus.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawningBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
@ -107,7 +106,48 @@ public partial class FormAccordionBus : Form
} }
} }
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableBus(_drawningBus), pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void comboBoxStrategy_SelectedIndexChanged(object sender, EventArgs e)
{
}
} }

View File

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
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>
/// <returns></returns>
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;
}
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;
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestination();
protected bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public interface IMoveableObject
{
/// <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,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
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,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.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,61 @@
using ProjectAccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public class MoveableBus : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningBus или его наследника
/// </summary>
private readonly DrawningBus? _bus = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="bus">Объект класса DrawningBus</param>
public MoveableBus(DrawningBus bus)
{
_bus = bus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_bus == null || _bus.EntityBus == null || !_bus.GetPosX.HasValue || !_bus.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_bus.GetPosX.Value, _bus.GetPosY.Value, _bus.GetWidth, _bus.GetHight);
}
}
public int GetStep => (int)(_bus?.EntityBus?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_bus == null || _bus.EntityBus == null)
{
return false;
}
return _bus.MoveTransport(GetDirectionType(direction));
}
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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
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;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}