Compare commits

..

2 Commits

15 changed files with 833 additions and 164 deletions

View File

@ -0,0 +1,32 @@
namespace ProjectTrolleybus.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -1,14 +1,18 @@
namespace ProjectTrolleybus; using ProjectTrolleybus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary> namespace ProjectTrolleybus.Drawnings;
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary> public class DrawningTrolleyB
public class DrawningTrolleybus
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityTrolleybus? EntityTrolleybus { get; private set; } public EntityTrolleyB? EntityTrolleyB { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -23,42 +27,77 @@ public class DrawningTrolleybus
/// <summary> /// <summary>
/// Левая координата прорисовки транспорта /// Левая координата прорисовки транспорта
/// </summary> /// </summary>
private int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя координата прорисовки транспорта /// Верхняя координата прорисовки транспорта
/// </summary> /// </summary>
private int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки транспорта /// Ширина прорисовки транспорта
/// </summary> /// </summary>
private readonly int _drawningVehicleWidth = 100; private readonly int _drawningVehicleWidth = 89;
/// <summary> /// <summary>
/// Высота прорисовки транспорта /// Высота прорисовки транспорта
/// </summary> /// </summary>
private readonly int _drawningVehicleHeight = 48; private readonly int _drawningVehicleHeight = 31;
/// <summary> /// <summary>
/// Инициализация свойств /// Координата X объекта
/// </summary> /// </summary>
/// <param name="speed"></param> public int? GetPosX => _startPosX;
/// <param name="weight"></param>
/// <param name="bodyColor"></param> /// <summary>
/// <param name="additionalColor"></param> /// Координата Y объекта
/// <param name="batteryCompartment"></param> /// </summary>
/// <param name="horns"></param> public int? GetPosY => _startPosY;
///
public void Init(EntityTrolleybus _Tr) /// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningVehicleWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHight => _drawningVehicleHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningTrolleyB()
{ {
EntityTrolleybus = _Tr;
_pictureHeight = null; _pictureHeight = null;
_pictureWidth = null; _pictureWidth = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningTrolleyB(int speed, double weight, Color bodyColor) : this()
{
EntityTrolleyB = new EntityTrolleyB(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningVehicleWidth">Ширина прорисовки транспорта</param>
/// <param name="drawningVehicleHeight">Высота прорисовки транспорта</param>
protected DrawningTrolleyB(int drawningVehicleWidth, int drawningVehicleHeight) : this()
{
_drawningVehicleWidth = drawningVehicleWidth;
_drawningVehicleHeight = drawningVehicleHeight;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
@ -102,7 +141,6 @@ public class DrawningTrolleybus
{ {
return; return;
} }
//TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
//то надо изменить координаты, чтобы он оставался в этих границах //то надо изменить координаты, чтобы он оставался в этих границах
if (x + _drawningVehicleWidth > _pictureWidth) if (x + _drawningVehicleWidth > _pictureWidth)
{ {
@ -127,7 +165,7 @@ public class DrawningTrolleybus
/// <returns></returns> /// <returns></returns>
public bool MoveVehicle(DirectionType direction) public bool MoveVehicle(DirectionType direction)
{ {
if (EntityTrolleybus == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityTrolleyB == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
@ -136,33 +174,33 @@ public class DrawningTrolleybus
{ {
// влево // влево
case DirectionType.Left: case DirectionType.Left:
if (_startPosX.Value - EntityTrolleybus.Step > 0) if (_startPosX.Value - EntityTrolleyB.Step > 0)
{ {
_startPosX -= (int)EntityTrolleybus.Step; _startPosX -= (int)EntityTrolleyB.Step;
} }
return true; return true;
// вверх // вверх
case DirectionType.Up: case DirectionType.Up:
if (_startPosY.Value - EntityTrolleybus.Step > 0) if (_startPosY.Value - EntityTrolleyB.Step > 0)
{ {
_startPosY -= (int)EntityTrolleybus.Step; _startPosY -= (int)EntityTrolleyB.Step;
} }
return true; return true;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
{ {
if (_startPosX.Value + _drawningVehicleWidth + EntityTrolleybus.Step < _pictureWidth) if (_startPosX.Value + _drawningVehicleWidth + EntityTrolleyB.Step < _pictureWidth)
{ {
_startPosX += (int)EntityTrolleybus.Step; _startPosX += (int)EntityTrolleyB.Step;
} }
} }
return true; return true;
// вниз // вниз
case DirectionType.Down: case DirectionType.Down:
{ {
if (_startPosY.Value + _drawningVehicleHeight + EntityTrolleybus.Step < _pictureHeight) if (_startPosY.Value + _drawningVehicleHeight + EntityTrolleyB.Step < _pictureHeight)
{ {
_startPosY += (int)EntityTrolleybus.Step; _startPosY += (int)EntityTrolleyB.Step;
} }
} }
return true; return true;
@ -175,9 +213,9 @@ public class DrawningTrolleybus
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityTrolleybus == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityTrolleyB == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
@ -186,68 +224,44 @@ public class DrawningTrolleybus
//Колёса //Колёса
pen.Width = 2; pen.Width = 2;
g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 36, 12, 12); g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 23, 12, 12);
g.DrawEllipse(pen, _startPosX.Value + 80, _startPosY.Value + 36, 12, 12); g.DrawEllipse(pen, _startPosX.Value + 70, _startPosY.Value + 23, 12, 12);
pen.Width = 1; pen.Width = 1;
Brush brBlackWheel = new SolidBrush(Color.Black); Brush brBlackWheel = new SolidBrush(Color.Black);
g.FillEllipse(brBlackWheel, _startPosX.Value + 20, _startPosY.Value + 36, 12, 12); g.FillEllipse(brBlackWheel, _startPosX.Value + 10, _startPosY.Value + 23, 12, 12);
g.FillEllipse(brBlackWheel, _startPosX.Value + 80, _startPosY.Value + 36, 12, 12); g.FillEllipse(brBlackWheel, _startPosX.Value + 70, _startPosY.Value + 23, 12, 12);
Brush brYelWheel = new SolidBrush(Color.Goldenrod); Brush brYelWheel = new SolidBrush(Color.Goldenrod);
g.FillEllipse(brYelWheel, _startPosX.Value + 22, _startPosY.Value + 38, 8, 8); g.FillEllipse(brYelWheel, _startPosX.Value + 12, _startPosY.Value + 25, 8, 8);
g.FillEllipse(brYelWheel, _startPosX.Value + 82, _startPosY.Value + 38, 8, 8); g.FillEllipse(brYelWheel, _startPosX.Value + 72, _startPosY.Value + 25, 8, 8);
//Кузов //Кузов
Brush br = new SolidBrush(EntityTrolleybus.BodyColor); Brush br = new SolidBrush(EntityTrolleyB.BodyColor);
g.FillRectangle(br, _startPosX.Value + 11, _startPosY.Value + 16, 89, 24); g.FillRectangle(br, _startPosX.Value + 1, _startPosY.Value + 3, 89, 24);
//Границы Автомобиля //Границы Автомобиля
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 15, 90, 25); g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 2, 90, 25);
g.DrawRectangle(pen, _startPosX.Value + 36, _startPosY.Value + 25, 10, 15); g.DrawRectangle(pen, _startPosX.Value + 26, _startPosY.Value + 12, 10, 15);
g.DrawRectangle(pen, _startPosX.Value + 88, _startPosY.Value + 19, 12, 12); g.DrawRectangle(pen, _startPosX.Value + 78, _startPosY.Value + 6, 12, 12);
pen.Width = 2; pen.Width = 2;
g.DrawEllipse(pen, _startPosX.Value + 12, _startPosY.Value + 20, 8, 10); g.DrawEllipse(pen, _startPosX.Value + 2, _startPosY.Value + 7, 8, 10);
g.DrawEllipse(pen, _startPosX.Value + 24, _startPosY.Value + 20, 8, 10); g.DrawEllipse(pen, _startPosX.Value + 14, _startPosY.Value + 7, 8, 10);
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 20, 8, 10); g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 7, 8, 10);
g.DrawEllipse(pen, _startPosX.Value + 62, _startPosY.Value + 20, 8, 10); g.DrawEllipse(pen, _startPosX.Value + 52, _startPosY.Value + 7, 8, 10);
g.DrawEllipse(pen, _startPosX.Value + 74, _startPosY.Value + 20, 8, 10); g.DrawEllipse(pen, _startPosX.Value + 64, _startPosY.Value + 7, 8, 10);
pen.Width = 1; pen.Width = 1;
//Стекла и кабина //Стекла и кабина
Brush brBlue = new SolidBrush(Color.LightBlue); Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX.Value + 89, _startPosY.Value + 20, 11, 11); g.FillRectangle(brBlue, _startPosX.Value + 79, _startPosY.Value + 7, 11, 11);
g.FillEllipse(brBlue, _startPosX.Value + 12, _startPosY.Value + 20, 8, 10); g.FillEllipse(brBlue, _startPosX.Value + 2, _startPosY.Value + 7, 8, 10);
g.FillEllipse(brBlue, _startPosX.Value + 24, _startPosY.Value + 20, 8, 10); g.FillEllipse(brBlue, _startPosX.Value + 14, _startPosY.Value + 7, 8, 10);
g.FillEllipse(brBlue, _startPosX.Value + 50, _startPosY.Value + 20, 8, 10); g.FillEllipse(brBlue, _startPosX.Value + 40, _startPosY.Value + 7, 8, 10);
g.FillEllipse(brBlue, _startPosX.Value + 62, _startPosY.Value + 20, 8, 10); g.FillEllipse(brBlue, _startPosX.Value + 52, _startPosY.Value + 7, 8, 10);
g.FillEllipse(brBlue, _startPosX.Value + 74, _startPosY.Value + 20, 8, 10); g.FillEllipse(brBlue, _startPosX.Value + 64, _startPosY.Value + 7, 8, 10);
//Дверь //Дверь
Brush brBlack = new SolidBrush(Color.LightGray); Brush brBlack = new SolidBrush(Color.LightGray);
g.FillRectangle(brBlack, _startPosX.Value + 37, _startPosY.Value + 26, 9, 14); g.FillRectangle(brBlack, _startPosX.Value + 27, _startPosY.Value + 13, 9, 14);
Brush additBrush = new SolidBrush(EntityTrolleybus.AdditionalColor);
// "Рога" для проводов
if (EntityTrolleybus.Horns)
{
pen.Width = 2;
g.DrawLine(pen, _startPosX.Value + 77, _startPosY.Value + 15, _startPosX.Value + 52, _startPosY.Value + 2);
pen.Width = 1;
g.DrawRectangle(pen, _startPosX.Value + 34, _startPosY.Value, 20, 5);
g.FillRectangle(additBrush, _startPosX.Value + 35, _startPosY.Value + 1, 19, 4);
} }
// Отсек под батареи
if (EntityTrolleybus.BatteryCompartment)
{
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 24, 10, 12);
g.FillRectangle(additBrush, _startPosX.Value + 1, _startPosY.Value + 25, 9, 11);
}
}
} }

View File

@ -0,0 +1,64 @@
using ProjectTrolleybus.Entities;
using System.Drawing;
namespace ProjectTrolleybus.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTrolleybus : DrawningTrolleyB
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="batteryCompartment"></param>
/// <param name="horns"></param>
///
public DrawningTrolleybus(int speed, double weight, Color bodyColor, Color additionalColor, bool batteryCompartment, bool horns) : base(100, 48)
{
EntityTrolleyB = new EntityTrolleybus(speed, weight, bodyColor, additionalColor, batteryCompartment, horns);
}
public override void DrawTransport(Graphics g)
{
if (EntityTrolleyB == null || EntityTrolleyB is not EntityTrolleybus trolleybus || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additBrush = new SolidBrush(trolleybus.AdditionalColor);
// "Рога" для проводов
if (trolleybus.Horns)
{
pen.Width = 2;
g.DrawLine(pen, _startPosX.Value + 77, _startPosY.Value + 15, _startPosX.Value + 52, _startPosY.Value + 2);
pen.Width = 1;
g.DrawRectangle(pen, _startPosX.Value + 34, _startPosY.Value, 20, 5);
g.FillRectangle(additBrush, _startPosX.Value + 35, _startPosY.Value + 1, 19, 4);
}
// Отсек под батареи
if (trolleybus .BatteryCompartment)
{
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 24, 10, 12);
g.FillRectangle(additBrush, _startPosX.Value + 1, _startPosY.Value + 25, 9, 11);
}
_startPosX += 10;
_startPosY += 15;
base.DrawTransport(g);
_startPosX -= 10;
_startPosY -= 15;
}
}

View File

@ -0,0 +1,41 @@
namespace ProjectTrolleybus.Entities;
/// <summary>
/// Класс-Сущность "Троллейбус"
/// </summary>
public class EntityTrolleyB
{
/// <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 => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public EntityTrolleyB(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,24 +1,9 @@
namespace ProjectTrolleybus; namespace ProjectTrolleybus.Entities;
/// <summary> /// <summary>
/// Класс-Сущность "Троллейбус" /// Класс-Сущность "Троллейбус"
/// </summary> /// </summary>
public class EntityTrolleybus public class EntityTrolleybus : EntityTrolleyB
{ {
/// <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>
/// Дополнительный цвет /// Дополнительный цвет
/// </summary> /// </summary>
@ -34,8 +19,6 @@ public class EntityTrolleybus
/// </summary> /// </summary>
public bool Horns { get; private set; } public bool Horns { get; private set; }
public double Step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -45,11 +28,8 @@ public class EntityTrolleybus
/// <param name="additionalColor"></param> /// <param name="additionalColor"></param>
/// <param name="batteryCompartment"></param> /// <param name="batteryCompartment"></param>
/// <param name="horns"></param> /// <param name="horns"></param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool batteryCompartment, bool horns) public EntityTrolleybus(int speed, double weight, Color bodyColor, Color additionalColor, bool batteryCompartment, bool horns) : base(speed, weight, bodyColor)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
BatteryCompartment = batteryCompartment; BatteryCompartment = batteryCompartment;
Horns = horns; Horns = horns;

View File

@ -34,6 +34,9 @@
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateTrolleyB = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -51,9 +54,9 @@
buttonCreateTrolleybus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateTrolleybus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTrolleybus.Location = new Point(22, 406); buttonCreateTrolleybus.Location = new Point(22, 406);
buttonCreateTrolleybus.Name = "buttonCreateTrolleybus"; buttonCreateTrolleybus.Name = "buttonCreateTrolleybus";
buttonCreateTrolleybus.Size = new Size(75, 23); buttonCreateTrolleybus.Size = new Size(204, 23);
buttonCreateTrolleybus.TabIndex = 1; buttonCreateTrolleybus.TabIndex = 1;
buttonCreateTrolleybus.Text = "Создать"; buttonCreateTrolleybus.Text = "Создать улучшенный троллейбус";
buttonCreateTrolleybus.UseVisualStyleBackColor = true; buttonCreateTrolleybus.UseVisualStyleBackColor = true;
buttonCreateTrolleybus.Click += ButtonCreateTrolleybus_Click; buttonCreateTrolleybus.Click += ButtonCreateTrolleybus_Click;
// //
@ -105,11 +108,45 @@
buttonUp.UseVisualStyleBackColor = true; buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click; buttonUp.Click += ButtonMove_Click;
// //
// buttonCreateTrolleyB
//
buttonCreateTrolleyB.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTrolleyB.Location = new Point(246, 406);
buttonCreateTrolleyB.Name = "buttonCreateTrolleyB";
buttonCreateTrolleyB.Size = new Size(130, 23);
buttonCreateTrolleyB.TabIndex = 6;
buttonCreateTrolleyB.Text = "Создать троллейбус";
buttonCreateTrolleyB.UseVisualStyleBackColor = true;
buttonCreateTrolleyB.Click += ButtonCreateTrolleyB_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(667, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(713, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormTrolleybus // FormTrolleybus
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTrolleyB);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
@ -130,5 +167,8 @@
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateTrolleyB;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,48 +1,104 @@
namespace ProjectTrolleybus using ProjectTrolleybus.Drawnings;
{ using ProjectTrolleybus.Entities;
using ProjectTrolleybus.MovementStrategy;
namespace ProjectTrolleybus;
/// <summary>
/// Форма работы с объектом "Троллейбус"
/// </summary>
public partial class FormTrolleybus : Form public partial class FormTrolleybus : Form
{ {
private DrawningTrolleybus? _drawningTrolleybus; /// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningTrolleyB? _drawningTrolleyB;
EntityTrolleybus? _Trolleybus; /// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormTrolleybus() public FormTrolleybus()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary>
/// Метод прорисовки транспорта
/// </summary>
private void Draw() private void Draw()
{ {
Bitmap bmp = new(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height); Bitmap bmp = new(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningTrolleybus.DrawTransport(gr); _drawningTrolleyB.DrawTransport(gr);
pictureBoxTrolleybus.Image = bmp; pictureBoxTrolleybus.Image = bmp;
} }
private void ButtonCreateTrolleybus_Click(object sender, EventArgs e)
{
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создания объекта</param>
private void CreateObject(string type)
{
Random random = new(); Random random = new();
_Trolleybus = new EntityTrolleybus(); switch (type)
_Trolleybus.Init(random.Next(100, 300), random.Next(1000, 3000), {
case nameof(DrawningTrolleyB):
_drawningTrolleyB = new DrawningTrolleyB(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(DrawningTrolleybus):
_drawningTrolleyB = new DrawningTrolleybus(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)));
_drawningTrolleybus = new DrawningTrolleybus(); break;
_drawningTrolleybus.Init(_Trolleybus); default:
//_drawningTrolleybus.Init(random.Next(100, 300), random.Next(1000, 3000), return;
// 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)));
_drawningTrolleybus.SetPictureSize(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_drawningTrolleybus.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
Draw();
} }
_drawningTrolleyB.SetPictureSize(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_drawningTrolleyB.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия создать улучшеный троллейбус
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTrolleybus_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningTrolleybus));
}
/// <summary>
/// Обработка нажатия создать троллейбус
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTrolleyB_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningTrolleyB));
}
/// <summary>
/// Перемещение объекта по кнопке (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningTrolleybus == null) if (_drawningTrolleyB == null)
{ {
return; return;
} }
@ -52,16 +108,16 @@
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawningTrolleybus.MoveVehicle(DirectionType.Up); result = _drawningTrolleyB.MoveVehicle(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawningTrolleybus.MoveVehicle(DirectionType.Down); result = _drawningTrolleyB.MoveVehicle(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawningTrolleybus.MoveVehicle(DirectionType.Left); result = _drawningTrolleyB.MoveVehicle(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawningTrolleybus.MoveVehicle(DirectionType.Right); result = _drawningTrolleyB.MoveVehicle(DirectionType.Right);
break; break;
} }
@ -70,7 +126,42 @@
Draw(); Draw();
} }
} }
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningTrolleyB == null)
{
return;
} }
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTrolleyB(_drawningTrolleyB), pictureBoxTrolleybus.Width, pictureBoxTrolleybus.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,123 @@
namespace ProjectTrolleybus.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>
/// <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,24 @@
namespace ProjectTrolleybus.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
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,56 @@
namespace ProjectTrolleybus.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта к границам
/// </summary>
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,54 @@
namespace ProjectTrolleybus.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта к центру
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleVertical + 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,69 @@
using ProjectTrolleybus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningTrolleyB
/// </summary>
public class MoveableTrolleyB : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningTrolleyB или его наследника
/// </summary>
private readonly DrawningTrolleyB? _trolleyB = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="trolleyB">Объект класса DrawningTrolleyB</param>
public MoveableTrolleyB(DrawningTrolleyB trolleyB)
{
_trolleyB = trolleyB;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_trolleyB == null || _trolleyB.EntityTrolleyB == null || !_trolleyB.GetPosX.HasValue || !_trolleyB.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_trolleyB.GetPosX.Value, _trolleyB.GetPosY.Value, _trolleyB.GetWidth, _trolleyB.GetHight);
}
}
public int GetStep => (int)(_trolleyB?.EntityTrolleyB?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_trolleyB == null || _trolleyB.EntityTrolleyB == null)
{
return false;
}
return _trolleyB.MoveVehicle(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

@ -1,9 +1,9 @@
namespace ProjectTrolleybus; namespace ProjectTrolleybus.MovementStrategy;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения
/// </summary> /// </summary>
public enum DirectionType public enum MovementDirection
{ {
/// <summary> /// <summary>
/// Вверх /// Вверх

View File

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