diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/DirectionType.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs similarity index 73% rename from ProjectElectricLocomotive/ProjectElectricLocomotive/DirectionType.cs rename to ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs index 17ab51c..28e2f32 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/DirectionType.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DirectionType.cs @@ -4,10 +4,15 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectElectricLocomotive; +namespace ProjectElectricLocomotive.Drawnings; public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs new file mode 100644 index 0000000..c9283c8 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs @@ -0,0 +1,74 @@ + +using ProjectElectricLocomotive.Entities; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Класс, отвечающий за прорисовку и перемещение объекта - сущности +/// +public class DrawningElectricLocomotive : DrawningLocomotive +{ + /// + /// Конструктор + /// + /// + /// + /// + /// + /// + /// + public DrawningElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) : base(83,45) + { + EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement); + } + + public override void DrawTransport(Graphics g) + { + if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + //Создание перьев и кистей для прорисовки электровоза + Brush blackBrush = new SolidBrush(Color.Black); + Pen penSolid = new(electricLocomotive.AdditionalColor, 2); + Pen penSolidYellow = new(Color.Yellow, 0.5f); + Brush additionalBrush = new SolidBrush(electricLocomotive.AdditionalColor); + + //Прорисовка дополнительного элемента (рогов) + if (electricLocomotive.ElectricHorns) + { + + //Инициализация опорных точек для прорисовки "рогов" + Point pointHorns1 = new Point(_startPosX.Value + 13, _startPosY.Value + 5); + Point pointHorns2 = new Point(_startPosX.Value + 16, _startPosY.Value + 2); + Point pointHorns3 = new Point(_startPosX.Value + 11, _startPosY.Value); + + //Прорисовка "рогов" электровоза + g.DrawLine(penSolid, pointHorns1, pointHorns2); + g.DrawLine(penSolid, pointHorns2, pointHorns3); + } + //Прорисовка дополнительного элемента (места под батарею) + if (electricLocomotive.BatteryPlacement) + { + //Инициализация опорных точек для прорисовки молнии на хранилище батарей + Point pointLightning1 = new Point(_startPosX.Value + 39, _startPosY.Value + 37); + Point pointLightning2 = new Point(_startPosX.Value + 37, _startPosY.Value + 39); + Point pointLightning3 = new Point(_startPosX.Value + 39, _startPosY.Value + 40); + Point pointLightning4 = new Point(_startPosX.Value + 37, _startPosY.Value + 41); + + //Прорисовка "хранилища батарей" электровоза + g.FillRectangle(additionalBrush, _startPosX.Value + 36, _startPosY.Value + 37, 8, 4.5f); + g.DrawLine(penSolidYellow, pointLightning1, pointLightning2); + g.DrawLine(penSolidYellow, pointLightning2, pointLightning3); + g.DrawLine(penSolidYellow, pointLightning3, pointLightning4); + + } + + _startPosY += 5; + base.DrawTransport(g); + _startPosY -= 5; + + } + +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs similarity index 54% rename from ProjectElectricLocomotive/ProjectElectricLocomotive/DrawningElectricLocomotive.cs rename to ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs index b3298c0..b5c64de 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/DrawningElectricLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -1,15 +1,18 @@ - -namespace ProjectElectricLocomotive; +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -/// -/// Класс, отвечающий за прорисовку и перемещение объекта - сущности -/// -public class DrawningElectricLocomotive +namespace ProjectElectricLocomotive.Drawnings; + +public class DrawningLocomotive { /// /// Класс-сущность /// - public EntityElectricLocomotive? EntityElectricLocomotive { get; private set; } + public EntityLocomotive? EntityLocomotive { get; protected set; } /// /// Ширина окна @@ -22,47 +25,79 @@ public class DrawningElectricLocomotive private int? _pictureHeight; /// - /// Левая координата прорисовки электровоза + /// Левая координата прорисовки локомотива /// - private int? _startPosX; + protected int? _startPosX; /// - /// Верхняя координата прорисовки электровоза + /// Верхняя координата прорисовки локомотива /// - private int? _startPosY; + protected int? _startPosY; /// - /// Ширина прорисовки электровоза + /// Ширина прорисовки локомотива /// - private readonly int _drawningElectricLocomotiveWidth = 83; + private readonly int _drawningLocomotiveWidth = 83; /// - /// Высота прорисовки электровоза + /// Высота прорисовки локомотива /// - private readonly int _drawningElectricLocomotiveHeight = 45; + private readonly int _drawningLocomotiveHeight = 40; /// - /// Инициализация свойств + /// Координата X объекта /// - /// - /// - /// - /// - /// - /// - /// - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLocomotiveWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningLocomotiveHeight; + + /// + /// Пустой конструктор + /// + private DrawningLocomotive() { - EntityElectricLocomotive = new EntityElectricLocomotive(); - - EntityElectricLocomotive.Init(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + /// + /// Конструктор + /// + /// + /// + /// + public DrawningLocomotive(int speed, double weight, Color bodyColor) : this() + { + EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor); + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки локомотива + /// Высота прорисовки локомотива + protected DrawningLocomotive(int drawningLocomotiveWidth, int drawningLocomotiveHeight) : this() + { + _drawningLocomotiveWidth = drawningLocomotiveWidth; + _drawningLocomotiveHeight = drawningLocomotiveHeight; + } + /// /// Установка границ поля /// @@ -71,19 +106,19 @@ public class DrawningElectricLocomotive /// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах public bool SetPictureSize(int width, int height) { - if(_drawningElectricLocomotiveHeight > height || _drawningElectricLocomotiveWidth > width) + if (_drawningLocomotiveHeight > height || _drawningLocomotiveWidth > width) { return false; } _pictureWidth = width; _pictureHeight = height; - if (_startPosY.HasValue && _startPosY + _drawningElectricLocomotiveHeight < _pictureHeight ) + if (_startPosY.HasValue && _startPosY + _drawningLocomotiveHeight < _pictureHeight) { - _startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; + _startPosY = _pictureHeight - _drawningLocomotiveHeight; } - if (_startPosX.HasValue && _startPosX + _drawningElectricLocomotiveWidth < _pictureWidth ) + if (_startPosX.HasValue && _startPosX + _drawningLocomotiveWidth < _pictureWidth) { - _startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; + _startPosX = _pictureWidth - _drawningLocomotiveWidth; } return true; } @@ -95,23 +130,21 @@ public class DrawningElectricLocomotive /// Координата Y public void SetPosition(int x, int y) { - if(!_pictureHeight.HasValue || !_pictureWidth.HasValue) { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { return; } - _startPosX = x; _startPosY = y; - - - if ( _drawningElectricLocomotiveHeight + y > _pictureHeight) + if (_drawningLocomotiveHeight + y > _pictureHeight) { - _startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; + _startPosY = _pictureHeight - _drawningLocomotiveHeight; } - if ( _drawningElectricLocomotiveWidth + x > _pictureWidth) + if (_drawningLocomotiveWidth + x > _pictureWidth) { - _startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; + _startPosX = _pictureWidth - _drawningLocomotiveWidth; } if (x < 0) { @@ -133,39 +166,39 @@ public class DrawningElectricLocomotive /// true - перемещение выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if(EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } - switch(direction) + switch (direction) { //влево case DirectionType.Left: - if(_startPosX.Value - EntityElectricLocomotive.Step > 0) + if (_startPosX.Value - EntityLocomotive.Step > 0) { - _startPosX -= (int)EntityElectricLocomotive.Step; + _startPosX -= (int)EntityLocomotive.Step; } return true; //вверх case DirectionType.Up: - if(_startPosY.Value - EntityElectricLocomotive.Step > 0) + if (_startPosY.Value - EntityLocomotive.Step > 0) { - _startPosY -= (int)EntityElectricLocomotive.Step; - } + _startPosY -= (int)EntityLocomotive.Step; + } return true; //вправо case DirectionType.Right: - if (_startPosX.Value + _drawningElectricLocomotiveWidth + EntityElectricLocomotive.Step < _pictureWidth) + if (_startPosX.Value + _drawningLocomotiveWidth + EntityLocomotive.Step < _pictureWidth) { - _startPosX += (int)EntityElectricLocomotive.Step; + _startPosX += (int)EntityLocomotive.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + _drawningElectricLocomotiveHeight + EntityElectricLocomotive.Step < _pictureHeight) + if (_startPosY.Value + _drawningLocomotiveHeight + EntityLocomotive.Step < _pictureHeight) { - _startPosY += (int)EntityElectricLocomotive.Step; + _startPosY += (int)EntityLocomotive.Step; } return true; default: @@ -177,9 +210,9 @@ public class DrawningElectricLocomotive /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } @@ -189,34 +222,34 @@ public class DrawningElectricLocomotive Pen penSolid = new(Color.Black, 2); Pen penSolidYellow = new(Color.Yellow, 0.5f); Pen windowPen = new(Color.DeepSkyBlue); - Brush additionalBrush = new SolidBrush(EntityElectricLocomotive.AdditionalColor); Brush blackBrush = new SolidBrush(Color.Black); Brush whiteBrush = new SolidBrush(Color.White); + Brush additionalBrush = new SolidBrush(EntityLocomotive.BodyColor); //Инициализация опорных точек для прорисовки корпуса - Point pointStart = new Point(_startPosX.Value + 75, _startPosY.Value + 20); - Point point1 = new Point(_startPosX.Value + 75, _startPosY.Value + 5); - Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value + 5); - Point pointFinish = new Point(_startPosX.Value + 5, _startPosY.Value + 20); + Point pointStart = new Point(_startPosX.Value + 75, _startPosY.Value + 15); + Point point1 = new Point(_startPosX.Value + 75, _startPosY.Value); + Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value); + Point pointFinish = new Point(_startPosX.Value + 5, _startPosY.Value + 15); //Инициализация опорных точек для прорисовки первой "юбки" - Point point3 = new Point(_startPosX.Value + 7, _startPosY.Value + 37); - Point point4 = new Point(_startPosX.Value + 0, _startPosY.Value + 37 +6 ); - Point point5 = new Point(_startPosX.Value + 7, _startPosY.Value + 37 + 6 ); + Point point3 = new Point(_startPosX.Value + 7, _startPosY.Value + 32); + Point point4 = new Point(_startPosX.Value, _startPosY.Value + 32 + 6); + Point point5 = new Point(_startPosX.Value + 7, _startPosY.Value + 32 + 6); //Инициализация опорных точек для прорисовки второй "юбки" - Point point6 = new Point(_startPosX.Value + 69, _startPosY.Value + 37); - Point point7 = new Point(_startPosX.Value + 75 + 7, _startPosY.Value + 37 + 6); - Point point8 = new Point(_startPosX.Value + 69, _startPosY.Value + 37 + 6); - + Point point6 = new Point(_startPosX.Value + 69, _startPosY.Value + 32); + Point point7 = new Point(_startPosX.Value + 75 + 7, _startPosY.Value + 32 + 6); + Point point8 = new Point(_startPosX.Value + 69, _startPosY.Value + 32 + 6); + //Совокупность точек полигона уголка первой "юбки" Point[] firstTrianglePoints = { - + point3, point4, point5, - + }; //Совокупность точек полигона уголка второй "юбки" Point[] secondTrianglePoints = @@ -233,77 +266,49 @@ public class DrawningElectricLocomotive g.FillPolygon(blackBrush, secondTrianglePoints); //Прорисовка корпуса - g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 20, 70, 17); + g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 15, 70, 17); g.DrawLine(pen, point3, point4); - + g.DrawLine(pen, pointStart, point1); g.DrawLine(pen, point1, point2); g.DrawLine(pen, point2, pointFinish); Brush brWhite = new SolidBrush(Color.White); - g.DrawRectangle(windowPen, _startPosX.Value + 24.3f, _startPosY.Value + 9, 8, 8); + g.DrawRectangle(windowPen, _startPosX.Value + 24.3f, _startPosY.Value + 4, 8, 8); - g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 14, 8, 12); - - g.FillRectangle(brWhite, _startPosX.Value + 36, _startPosY.Value + 16, 7, 10); + g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 9, 8, 12); + g.FillRectangle(brWhite, _startPosX.Value + 36, _startPosY.Value + 11, 7, 10); //Прорисовка передней и задней "юбки" - g.FillRectangle(blackBrush, _startPosX.Value + 7, _startPosY.Value + 37, 25, 5.3f); - g.FillRectangle(blackBrush, _startPosX.Value + 47, _startPosY.Value + 37, 22, 5.3f); + g.FillRectangle(blackBrush, _startPosX.Value + 7, _startPosY.Value + 32, 25, 5.3f); + g.FillRectangle(blackBrush, _startPosX.Value + 47, _startPosY.Value + 32, 22, 5.3f); //Прорисовка двух передних колёс - g.FillEllipse(whiteBrush, _startPosX.Value + 6.3f, _startPosY.Value + 37, 10, 10); - g.DrawEllipse(penSolid, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8); - g.FillEllipse(additionalBrush, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8); - g.DrawEllipse(penSolid, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8); - g.FillEllipse(additionalBrush, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8); + g.FillEllipse(whiteBrush, _startPosX.Value + 6.3f, _startPosY.Value + 32, 10, 10); + g.DrawEllipse(penSolid, _startPosX.Value + 9, _startPosY.Value + 32, 8, 8); + g.DrawEllipse(penSolid, _startPosX.Value + 24, _startPosY.Value + 32, 8, 8); + //Прорисовка двух задних колёс - g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 38, _startPosY.Value + 37, 10, 10); - g.DrawEllipse(penSolid, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8); - g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8); - g.DrawEllipse(penSolid, _startPosX.Value+ 25 + 37, _startPosY.Value + 37, 8, 8); - g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 37, 8, 8); + g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 38, _startPosY.Value + 32, 10, 10); + g.DrawEllipse(penSolid, _startPosX.Value + 25 + 26, _startPosY.Value + 32, 8, 8); + g.DrawEllipse(penSolid, _startPosX.Value + 25 + 37, _startPosY.Value + 32, 8, 8); //Прорисовка заднего "шлюза" - g.FillRectangle(blackBrush, _startPosX.Value + 75, _startPosY.Value + 9, 5.7f, 27.4f); + g.FillRectangle(blackBrush, _startPosX.Value + 75, _startPosY.Value + 4, 5.7f, 27.4f); //Прорисовка первого и третьего окна - g.DrawRectangle(windowPen, _startPosX.Value + 12, _startPosY.Value + 9, 8, 8); - g.DrawRectangle(windowPen, _startPosX.Value + 63, _startPosY.Value + 9, 8, 8); + g.DrawRectangle(windowPen, _startPosX.Value + 12, _startPosY.Value + 4, 8, 8); + g.DrawRectangle(windowPen, _startPosX.Value + 63, _startPosY.Value + 4, 8, 8); + //Опциональная прорисовка цвета передних колёс + g.FillEllipse(additionalBrush, _startPosX.Value + 9, _startPosY.Value + 32, 8, 8); + g.FillEllipse(additionalBrush, _startPosX.Value + 24, _startPosY.Value + 32, 8, 8); - - if (EntityElectricLocomotive.ElectricHorns) - { - - - //Инициализация опорных точек для прорисовки "рогов" - Point pointHorns1 = new Point(_startPosX.Value + 13, _startPosY.Value + 5); - Point pointHorns2 = new Point(_startPosX.Value + 16, _startPosY.Value + 2); - Point pointHorns3 = new Point(_startPosX.Value + 11, _startPosY.Value); - - //Прорисовка "рогов" электровоза - g.DrawLine(penSolid, pointHorns1, pointHorns2); - g.DrawLine(penSolid, pointHorns2, pointHorns3); - } - if(EntityElectricLocomotive.BatteryPlacement) - { - //Инициализация опорных точек для прорисовки молнии на хранилище батарей - Point pointLightning1 = new Point(_startPosX.Value + 39, _startPosY.Value + 37); - Point pointLightning2 = new Point(_startPosX.Value + 37, _startPosY.Value + 39); - Point pointLightning3 = new Point(_startPosX.Value + 39, _startPosY.Value + 40); - Point pointLightning4 = new Point(_startPosX.Value + 37, _startPosY.Value + 41); - - //Прорисовка "хранилища батарей" электровоза - g.FillRectangle(blackBrush, _startPosX.Value + 36, _startPosY.Value + 37, 8, 4.5f); - g.DrawLine(penSolidYellow, pointLightning1, pointLightning2); - g.DrawLine(penSolidYellow, pointLightning2, pointLightning3); - g.DrawLine(penSolidYellow, pointLightning3, pointLightning4); - - } - + //Опциональная прорисовка цвета задних колёс + g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 32, 8, 8); + g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 32, 8, 8); } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/EntityElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs similarity index 57% rename from ProjectElectricLocomotive/ProjectElectricLocomotive/EntityElectricLocomotive.cs rename to ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs index 0a3040f..18602b6 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/EntityElectricLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs @@ -1,26 +1,11 @@  -namespace ProjectElectricLocomotive; +namespace ProjectElectricLocomotive.Entities; /// -/// Класс-сущность "Тепловоз" +/// Класс-сущность "Электровоз" /// -public class EntityElectricLocomotive +public class EntityElectricLocomotive : EntityLocomotive { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// /// Дополнительный цвет (для дополнительных элементов) /// @@ -36,11 +21,6 @@ public class EntityElectricLocomotive /// public bool BatteryPlacement { get; private set; } - /// - /// Шаг перемещения объекта - /// - public double Step => Speed * 100 / Weight; - /// /// Инициализация полей объекта-класса тепловоза /// @@ -50,15 +30,10 @@ public class EntityElectricLocomotive /// /// /// - - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) + public EntityElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; ElectricHorns = electricHorns; BatteryPlacement = batteryPlacement; - } } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs new file mode 100644 index 0000000..52007b7 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Entities/EntityLocomotive.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Entities; +/// +/// Класс-сущность "Локомотив" +/// +public class EntityLocomotive +{ + /// + /// Скорость + /// + public int Speed { get; private set; } + + /// + /// Вес + /// + public double Weight { get; private set; } + + /// + /// Основной цвет + /// + public Color BodyColor { get; private set; } + + /// + /// Шаг перемещения объекта + /// + public double Step => Speed * 100 / Weight; + + /// + /// Конструктор сущности + /// + /// + /// + /// + public EntityLocomotive(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs index 577dbcc..b758749 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.Designer.cs @@ -34,6 +34,9 @@ buttonDown = new Button(); buttonRight = new Button(); buttonUp = new Button(); + buttonCreateLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); SuspendLayout(); // @@ -49,11 +52,11 @@ // buttonCreate // buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 430); + buttonCreate.Location = new Point(12, 436); buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(104, 37); + buttonCreate.Size = new Size(150, 31); buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; + buttonCreate.Text = "Создать электровоз"; buttonCreate.UseVisualStyleBackColor = true; buttonCreate.Click += ButtonCreate_Click; // @@ -109,11 +112,45 @@ buttonUp.UseVisualStyleBackColor = false; buttonUp.Click += ButtonMove_Click; // + // buttonCreateLocomotive + // + buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateLocomotive.Location = new Point(187, 436); + buttonCreateLocomotive.Name = "buttonCreateLocomotive"; + buttonCreateLocomotive.Size = new Size(150, 31); + buttonCreateLocomotive.TabIndex = 6; + buttonCreateLocomotive.Text = "Создать локомотив"; + buttonCreateLocomotive.UseVisualStyleBackColor = true; + buttonCreateLocomotive.Click += buttonCreateLocomotive_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(733, 24); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(764, 72); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(90, 33); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormElectricLocomotive // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(866, 479); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateLocomotive); Controls.Add(buttonUp); Controls.Add(buttonRight); Controls.Add(buttonDown); @@ -134,5 +171,8 @@ private Button buttonDown; private Button buttonRight; private Button buttonUp; + private Button buttonCreateLocomotive; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs index d788b47..305f806 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormElectricLocomotive.cs @@ -1,4 +1,6 @@ -using System; +using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.MovementStrategy; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,11 +14,20 @@ namespace ProjectElectricLocomotive; public partial class FormElectricLocomotive : Form { - private DrawningElectricLocomotive? _drawningElectricLocomotive; + /// + /// Поле-объект для прорисовки объекта + /// + private DrawningLocomotive? _drawningLocomotive; + private AbstractStrategy? _strategy; + + /// + /// Конструктор формы + /// public FormElectricLocomotive() { InitializeComponent(); + _strategy = null; } /// @@ -24,34 +35,61 @@ public partial class FormElectricLocomotive : Form /// private void Draw() { - if (_drawningElectricLocomotive == null) + if (_drawningLocomotive == null) { return; } Bitmap bmp = new(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningElectricLocomotive.DrawTransport(gr); + _drawningLocomotive.DrawTransport(gr); pictureBoxElectricLocomotive.Image = bmp; } - private void ButtonCreate_Click(object sender, EventArgs e) + /// + /// Создание объекта класса-перемещения + /// + /// + private void CreateObject(string type) { Random random = new(); - _drawningElectricLocomotive = new DrawningElectricLocomotive(); - _drawningElectricLocomotive.Init(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))); - _drawningElectricLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); - _drawningElectricLocomotive.SetPosition(random.Next(0,pictureBoxElectricLocomotive.Width), random.Next(0,pictureBoxElectricLocomotive.Height)); - - Bitmap bmp = new(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); - Graphics gr = Graphics.FromImage(bmp); - _drawningElectricLocomotive.DrawTransport(gr); - pictureBoxElectricLocomotive.Image = bmp; + switch (type) + { + case nameof(DrawningLocomotive): + _drawningLocomotive = new DrawningLocomotive(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(DrawningElectricLocomotive): + _drawningLocomotive = new DrawningElectricLocomotive(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; + } + _drawningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + _drawningLocomotive.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(DrawningElectricLocomotive)); + + /// + /// Обработка нажатия кнопки "Создать локомотив" + /// + /// + /// + private void buttonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive)); + + /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -59,7 +97,7 @@ public partial class FormElectricLocomotive : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningElectricLocomotive == null) + if (_drawningLocomotive == null) { return; } @@ -69,19 +107,19 @@ public partial class FormElectricLocomotive : Form { case "buttonUp": result = - _drawningElectricLocomotive.MoveTransport(DirectionType.Up); + _drawningLocomotive.MoveTransport(DirectionType.Up); break; case "buttonDown": result = - _drawningElectricLocomotive.MoveTransport(DirectionType.Down); + _drawningLocomotive.MoveTransport(DirectionType.Down); break; case "buttonLeft": result = - _drawningElectricLocomotive.MoveTransport(DirectionType.Left); + _drawningLocomotive.MoveTransport(DirectionType.Left); break; case "buttonRight": result = - _drawningElectricLocomotive.MoveTransport(DirectionType.Right); + _drawningLocomotive.MoveTransport(DirectionType.Right); break; } if (result) @@ -89,6 +127,38 @@ public partial class FormElectricLocomotive : Form Draw(); } } + + /// + /// + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningLocomotive == null) return; + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) return; + _strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + } + if (_strategy == null) return; + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..3b2a3d2 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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; + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/IMoveableObject.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..209f702 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public interface IMoveableObject +{ + /// + /// Получение координат объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// True - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovableLocomotive.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovableLocomotive.cs new file mode 100644 index 0000000..88dbbc8 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovableLocomotive.cs @@ -0,0 +1,69 @@ +using ProjectElectricLocomotive.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject c использованием DrawningLocomotive +/// +public class MoveableLocomotive : IMoveableObject +{ + /// + /// Поле-объект класса DrawningLocomotive или его наследника + /// + private readonly DrawningLocomotive? _locomotive = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningLocomotive + public MoveableLocomotive(DrawningLocomotive locomotive) + { + _locomotive = locomotive; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_locomotive == null || _locomotive.EntityLocomotive == null || !_locomotive.GetPosX.HasValue || !_locomotive.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_locomotive.GetPosX.Value, _locomotive.GetPosY.Value, _locomotive.GetWidth, _locomotive.GetHeight); + } + } + + public int GetStep => (int)(_locomotive?.EntityLocomotive?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_locomotive == null || _locomotive.EntityLocomotive == null) + { + return false; + } + return _locomotive.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/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..d4f70a9 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder + GetStep() >= FieldWidth && 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(); + } + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..30374fc --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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(); + } + } + +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..1d38253 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вверх + /// + Down = 2, + + /// + /// Вверх + /// + Left = 3, + + /// + /// Вверх + /// + Right = 4, + +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..5b3cc06 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..90d9a61 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public enum StrategyStatus +{ + /// + /// Всё готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +}