Залил лаб2

This commit is contained in:
ujijrujijr 2023-10-21 21:27:46 +03:00
parent e8a24da5cd
commit 77ea779c6b
13 changed files with 798 additions and 181 deletions

View File

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status 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 = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,215 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.Entities;
namespace Trolleybus.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автобуса
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автобуса
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автобуса
/// </summary>
protected readonly int _busWidth = 150;
/// <summary>
/// Высота прорисовки автобуса
/// </summary>
protected readonly int _busHeight = 95;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _busWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _busHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingBus(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _busWidth || height < _busHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityBus = new EntityBus(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="busWidth">Ширина прорисовки автобуса</param>
/// <param name="busHeight">Высота прорисовки автобус</param>
protected DrawingBus(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight)
{
if (width < _busWidth || height < _busHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_busWidth = busWidth;
_busHeight = busHeight;
EntityBus = new EntityBus(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
_startPosX = Math.Min(Math.Max(x, 0), _pictureWidth - _busWidth);
_startPosY = Math.Min(Math.Max(y, 0), _pictureHeight - _busHeight);
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityBus == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityBus.Step > 0)
{
_startPosX -= (int)EntityBus.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityBus.Step > 0)
{
_startPosY -= (int)EntityBus.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _busWidth + EntityBus.Step < _pictureWidth)
{
_startPosX += (int)EntityBus.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _busHeight + EntityBus.Step < _pictureHeight)
{
_startPosY += (int)EntityBus.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
Pen pen = new(Color.Black); //чёрный цвет для колёс
Pen bodyPen = new(EntityBus.BodyColor);
Pen windowPen = new(Color.Cyan); //цвет окон
//РИСОВАНИЕ САМОГО АВТОБУСА
//корпус
g.DrawLine(bodyPen, _startPosX, _startPosY + 30, _startPosX, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX, _startPosY + 80, _startPosX + 20, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 45, _startPosY + 80, _startPosX + 105, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 130, _startPosY + 80, _startPosX + 150, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 150, _startPosY + 80, _startPosX + 150, _startPosY + 30);
g.DrawLine(bodyPen, _startPosX + 150, _startPosY + 30, _startPosX, _startPosY + 30);
//колёса
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 70, 25, 25);
g.DrawEllipse(pen, _startPosX + 105, _startPosY + 70, 25, 25);
//дверь
g.DrawRectangle(bodyPen, _startPosX + 55, _startPosY + 50, 15, 30);
//окна
//окна до двери
for (int i = 0; i < 2; i++)
{
g.DrawEllipse(windowPen, _startPosX + 5 + 25 * i, _startPosY + 35, 16, 24);
}
//окна после двери
for (int i = 0; i < 3; i++)
{
g.DrawEllipse(windowPen, _startPosX + 75 + 25 * i, _startPosY + 35, 16, 24);
}
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityBus == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityBus.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityBus.Step > 0,
// вправо
DirectionType.Right => _startPosX + _busWidth + EntityBus.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _busHeight + EntityBus.Step < _pictureHeight,
_ => false,
};
}
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
namespace Trolleybus.MovementStrategy
{
public class DrawingObjectBus : IMoveableObject
{
private readonly DrawingBus? _drawingBus = null;
public DrawingObjectBus(DrawingBus drawingBus)
{
_drawingBus = drawingBus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingBus == null || _drawingBus.EntityBus == null)
{
return null;
}
return new ObjectParameters(_drawingBus.GetPosX, _drawingBus.GetPosY, _drawingBus.GetWidth, _drawingBus.GetHeight);
}
}
public int GetStep => (int)(_drawingBus?.EntityBus?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingBus?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingBus?.MoveTransport(direction);
}
}

View File

@ -4,41 +4,14 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Trolleybus.Entities;
namespace Trolleybus namespace Trolleybus.DrawingObjects
{ {
public class DrawingTrolleybus public class DrawingTrolleybus : DrawingBus
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Конструктор
/// </summary>
public EntityTrolleybus? EntityTrolleybus { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки троллейбуса
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки троллейбуса
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки троллейбуса
/// </summary>
private readonly int _trolleybusWidth = 150;
/// <summary>
/// Высота прорисовки троллейбуса
/// </summary>
private readonly int _trolleybusHeight = 95;
/// <summary>
/// Инициализация свойств
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
@ -49,122 +22,32 @@ namespace Trolleybus
/// <param name="width">Ширина картинки</param> /// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param> /// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns> /// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool batteries, int width, int height) public DrawingTrolleybus(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool batteries, int width, int height) : base(speed, weight, bodyColor, width, height, 150, 95)
{ {
if (width < _trolleybusWidth || height < _trolleybusHeight) if (EntityBus != null)
{ {
return false; EntityBus = new EntityTrolleybus(speed, weight, bodyColor, additionalColor, horns, batteries);
} }
_pictureWidth = width;
_pictureHeight = height;
EntityTrolleybus = new EntityTrolleybus();
EntityTrolleybus.Init(speed, weight, bodyColor, additionalColor, horns, batteries);
return true;
} }
/// <summary> public override void DrawTransport(Graphics g)
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{ {
_startPosX = Math.Min(Math.Max(x, 0), _pictureWidth - _trolleybusWidth); if (EntityBus is not EntityTrolleybus trolleyBus)
_startPosY = Math.Min(Math.Max(y, 0), _pictureHeight - _trolleybusHeight);
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityTrolleybus == null)
{ {
return; return;
} }
switch (direction) Pen additionalPen = new(trolleyBus.AdditionalColor);
{ Brush additionalBrush = new SolidBrush(trolleyBus.AdditionalColor);
//влево base.DrawTransport(g);
case DirectionType.Left:
if (_startPosX - EntityTrolleybus.Step > 0)
{
_startPosX -= (int)EntityTrolleybus.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityTrolleybus.Step > 0)
{
_startPosY -= (int)EntityTrolleybus.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _trolleybusWidth + EntityTrolleybus.Step < _pictureWidth)
{
_startPosX += (int)EntityTrolleybus.Step;
}
break;
// вниз
case DirectionType.Down:
if (_startPosY + _trolleybusHeight + EntityTrolleybus.Step < _pictureHeight)
{
_startPosY += (int)EntityTrolleybus.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityTrolleybus == null)
{
return;
}
Pen pen = new(Color.Black);
Pen bodyPen = new(EntityTrolleybus.BodyColor);
Pen additionalPen = new(EntityTrolleybus.AdditionalColor);
Brush additionalBrush = new SolidBrush(EntityTrolleybus.AdditionalColor);
Pen windowPen = new(Color.Cyan);
//РИСОВАНИЕ САМОГО ТРРОЛЛЕЙБУСА
//корпус
g.DrawLine(bodyPen, _startPosX, _startPosY + 30, _startPosX, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX, _startPosY + 80, _startPosX + 20, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 45, _startPosY + 80, _startPosX + 105, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 130, _startPosY + 80, _startPosX + 150, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 150, _startPosY + 80, _startPosX + 150, _startPosY + 30);
g.DrawLine(bodyPen, _startPosX + 150, _startPosY + 30, _startPosX, _startPosY + 30);
//колёса
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 70, 25, 25);
g.DrawEllipse(pen, _startPosX + 105, _startPosY + 70, 25, 25);
//дверь
g.DrawRectangle(bodyPen, _startPosX + 55, _startPosY + 50, 16, 30);
//окна
//окна до двери
for (int i = 0; i < 2; i++)
{
g.DrawEllipse(windowPen, _startPosX + 5 + 25 * i, _startPosY + 35, 16, 24);
}
//окна после двери
for (int i = 0; i < 3; i++)
{
g.DrawEllipse(windowPen, _startPosX + 75 + 25 * i, _startPosY + 35, 16, 24);
}
//опциональные "рога" //опциональные "рога"
if (EntityTrolleybus.Horns) if (trolleyBus.Horns)
{ {
g.DrawLine(additionalPen, _startPosX + 70, _startPosY + 30, _startPosX + 40, _startPosY); g.DrawLine(additionalPen, _startPosX + 70, _startPosY + 30, _startPosX + 40, _startPosY);
g.DrawLine(additionalPen, _startPosX + 70, _startPosY + 30, _startPosX + 60, _startPosY); g.DrawLine(additionalPen, _startPosX + 70, _startPosY + 30, _startPosX + 60, _startPosY);
} }
//опциональный отсек для батареи //опциональный отсек для батареи
if (EntityTrolleybus.Batteries) if (trolleyBus.Batteries)
{ {
Point[] pointsOfBatteries = { new Point(_startPosX + 70, _startPosY + 30), new Point(_startPosX + 70, _startPosY + 25), new Point(_startPosX + 100, _startPosY + 25), new Point(_startPosX + 110, _startPosY + 30)}; Point[] pointsOfBatteries = { new Point(_startPosX + 70, _startPosY + 30), new Point(_startPosX + 70, _startPosY + 25), new Point(_startPosX + 100, _startPosY + 25), new Point(_startPosX + 110, _startPosY + 30)};
g.FillPolygon(additionalBrush, pointsOfBatteries); g.FillPolygon(additionalBrush, pointsOfBatteries);

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.Entities
{
/// <summary>
/// Класс-сущность "Автобус"
/// </summary>
public class EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения автобуса
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автобуса</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -4,22 +4,13 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Trolleybus namespace Trolleybus.Entities
{
public class EntityTrolleybus
{ {
/// <summary> /// <summary>
/// Скорость /// Класс-сущность "Троллейбус"
/// </summary> /// </summary>
public int Speed { get; private set; } public class EntityTrolleybus : EntityBus
/// <summary> {
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary> /// <summary>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
@ -33,10 +24,6 @@ namespace Trolleybus
/// </summary> /// </summary>
public bool Batteries { get; private set; } public bool Batteries { get; private set; }
/// <summary> /// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса троллейбуса /// Инициализация полей объекта-класса троллейбуса
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
@ -45,11 +32,8 @@ namespace Trolleybus
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="horns">Признак наличия "рогов"</param> /// <param name="horns">Признак наличия "рогов"</param>
/// <param name="batteries">Признак наличия отсека под электрические батареи</param> /// <param name="batteries">Признак наличия отсека под электрические батареи</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool batteries) public EntityTrolleybus(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool batteries) : base(speed, weight, bodyColor)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Horns = horns; Horns = horns;
Batteries = batteries; Batteries = batteries;

View File

@ -29,11 +29,14 @@
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxTrolleybus = new PictureBox(); pictureBoxTrolleybus = new PictureBox();
buttonCreate = new Button(); buttonCreateTrolleybus = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -46,16 +49,16 @@
pictureBoxTrolleybus.TabIndex = 5; pictureBoxTrolleybus.TabIndex = 5;
pictureBoxTrolleybus.TabStop = false; pictureBoxTrolleybus.TabStop = false;
// //
// buttonCreate // buttonCreateTrolleybus
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateTrolleybus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 409); buttonCreateTrolleybus.Location = new Point(12, 389);
buttonCreate.Name = "buttonCreate"; buttonCreateTrolleybus.Name = "buttonCreateTrolleybus";
buttonCreate.Size = new Size(90, 30); buttonCreateTrolleybus.Size = new Size(120, 50);
buttonCreate.TabIndex = 6; buttonCreateTrolleybus.TabIndex = 6;
buttonCreate.Text = "Создать"; buttonCreateTrolleybus.Text = "Создать троллейбус";
buttonCreate.UseVisualStyleBackColor = true; buttonCreateTrolleybus.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click; buttonCreateTrolleybus.Click += ButtonCreateTrolleybus_Click;
// //
// buttonUp // buttonUp
// //
@ -105,16 +108,52 @@
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.Location = new Point(138, 389);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.Size = new Size(120, 50);
buttonCreateBus.TabIndex = 11;
buttonCreateBus.Text = "Создать автобус";
buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += ButtonCreateBus_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "В центр", "В правый нижний угол" });
comboBoxStrategy.Location = new Point(719, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 12;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(748, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 13;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// FormTrolleybus // FormTrolleybus
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453); ClientSize = new Size(882, 453);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonCreate); Controls.Add(buttonCreateTrolleybus);
Controls.Add(pictureBoxTrolleybus); Controls.Add(pictureBoxTrolleybus);
Name = "FormTrolleybus"; Name = "FormTrolleybus";
Text = "Троллейбус"; Text = "Троллейбус";
@ -125,10 +164,13 @@
#endregion #endregion
private PictureBox pictureBoxTrolleybus; private PictureBox pictureBoxTrolleybus;
private Button buttonCreate; private Button buttonCreateTrolleybus;
private Button buttonUp; private Button buttonUp;
private Button buttonLeft; private Button buttonLeft;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateBus;
private ComboBox comboBoxStrategy;
private Button buttonStep;
} }
} }

View File

@ -1,3 +1,6 @@
using Trolleybus.DrawingObjects;
using Trolleybus.MovementStrategy;
namespace Trolleybus namespace Trolleybus
{ {
/// <summary> /// <summary>
@ -8,7 +11,11 @@ namespace Trolleybus
/// <summary> /// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà /// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary> /// </summary>
private DrawingTrolleybus? _drawingTrolleybus; private DrawingBus? _drawingBus;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
public FormTrolleybus() public FormTrolleybus()
{ {
InitializeComponent(); InitializeComponent();
@ -18,26 +25,24 @@ namespace Trolleybus
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawingTrolleybus == null) if (_drawingBus == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height); Bitmap bmp = new(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawingTrolleybus.DrawTransport(gr); _drawingBus.DrawTransport(gr);
pictureBoxTrolleybus.Image = bmp; pictureBoxTrolleybus.Image = bmp;
} }
/// <summary> /// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü" /// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü òðîëëåéáóñ"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e) private void ButtonCreateTrolleybus_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawingTrolleybus = new DrawingTrolleybus(); _drawingBus = new DrawingTrolleybus(random.Next(100, 300),
//èíèöèàëèçàöèÿ ïîëåé
_drawingTrolleybus.Init(random.Next(100, 300),
random.Next(1000, 3000), 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)),
@ -45,17 +50,34 @@ namespace Trolleybus
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height); pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
//çàäà¸ì íà÷àëüíûå êîîðäèíàòû ïðîðèñîâêè //çàäà¸ì íà÷àëüíûå êîîðäèíàòû ïðîðèñîâêè
_drawingTrolleybus.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
/// <summary> /// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîáóñ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateBus_Click(object sender, EventArgs e)
{
Random random = new();
_drawingBus = new DrawingBus(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_drawingBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïîê äâèæåíèÿ /// Îáðàáîòêà íàæàòèÿ êíîïîê äâèæåíèÿ
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawingTrolleybus == null) if (_drawingBus == null)
{ {
return; return;
} }
@ -63,19 +85,58 @@ namespace Trolleybus
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
_drawingTrolleybus.MoveTransport(DirectionType.Up); _drawingBus.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
_drawingTrolleybus.MoveTransport(DirectionType.Down); _drawingBus.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
_drawingTrolleybus.MoveTransport(DirectionType.Left); _drawingBus.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
_drawingTrolleybus.MoveTransport(DirectionType.Right); _drawingBus.MoveTransport(DirectionType.Right);
break; break;
} }
Draw(); Draw();
} }
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBus(_drawingBus), pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
} }
} }

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
namespace Trolleybus.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var 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()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var 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()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}