From 7b607d826ff7bc827ae65fc0382949a5c4143c46 Mon Sep 17 00:00:00 2001 From: vkobi Date: Tue, 12 Mar 2024 19:32:46 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=80=D0=BE=D0=B4=D0=B8=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9=20=D0=B8=20=D0=B2=D0=B2=D0=BE=D0=B4=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ => Drawnings}/DirectionType.cs | 2 +- .../DrawningLocomotive.cs} | 190 +++++++++--------- .../Drawnings/DrawningWarmlyLocomotive.cs | 63 ++++++ .../Entities/EntityLocomotive.cs | 40 ++++ .../{ => Entities}/EntityWarmlyLocomotive.cs | 33 +-- .../FormWarmlyLocomotive.Designer.cs | 18 +- .../WarmlyLocomotive/FormWarmlyLocomotive.cs | 70 +++++-- lab_1/lab_1.sln | 31 --- lab_1/lab_1/Lab_1.c | 50 ----- lab_1/lab_1/lab_1.vcxproj | 135 ------------- lab_1/lab_1/lab_1.vcxproj.filters | 22 -- 11 files changed, 267 insertions(+), 387 deletions(-) rename WarmlyLocomotive/WarmlyLocomotive/{ => Drawnings}/DirectionType.cs (90%) rename WarmlyLocomotive/WarmlyLocomotive/{DrawningWarmlyLocomotive.cs => Drawnings/DrawningLocomotive.cs} (59%) create mode 100644 WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningWarmlyLocomotive.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/Entities/EntityLocomotive.cs rename WarmlyLocomotive/WarmlyLocomotive/{ => Entities}/EntityWarmlyLocomotive.cs (64%) delete mode 100644 lab_1/lab_1.sln delete mode 100644 lab_1/lab_1/Lab_1.c delete mode 100644 lab_1/lab_1/lab_1.vcxproj delete mode 100644 lab_1/lab_1/lab_1.vcxproj.filters diff --git a/WarmlyLocomotive/WarmlyLocomotive/DirectionType.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs similarity index 90% rename from WarmlyLocomotive/WarmlyLocomotive/DirectionType.cs rename to WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs index c935f15..2e9b21f 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/DirectionType.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs @@ -1,4 +1,4 @@ -namespace WarmlyLocomotive; +namespace WarmlyLocomotive.Drawnings; /// /// Направление перемещения /// diff --git a/WarmlyLocomotive/WarmlyLocomotive/DrawningWarmlyLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs similarity index 59% rename from WarmlyLocomotive/WarmlyLocomotive/DrawningWarmlyLocomotive.cs rename to WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs index 6fd15f3..af79ad4 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/DrawningWarmlyLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs @@ -1,14 +1,13 @@ -namespace WarmlyLocomotive; +using WarmlyLocomotive.Entities; -/// -/// Класс, отвечающий за прорисовку и перемещение объекта-сущности -/// -public class DrawningWarmlyLocomotive +namespace WarmlyLocomotive.Drawnings; + +public class DrawningLocomotive { /// /// Класс-сущность /// - public EntityWarmlyLocomotive? EntityWarmlyLocomotive { get; private set; } + public EntityLocomotive? EntityLocomotive { get; protected set; } /// /// Ширина окна /// @@ -20,38 +19,53 @@ public class DrawningWarmlyLocomotive /// /// Левая координата прорисовки паровоза /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки паровоза /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки паровоза /// - private readonly int _drawningWarmlyLocomotiveWidth = 130; + private readonly int _drawningLocomotiveWidth = 130; /// /// Высота прорисовки паровоза /// - private readonly int _drawningWarmlyLocomotiveHeight = 50; + private readonly int _drawningLocomotiveHeight = 40; + /// - /// Инициализация свойств + /// Пустой конструктор /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия дымохода - /// Признак наличия отсека - /// Признак наличия обозначающей полосы - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool chimney, bool compartment, bool indicatingLine) + private DrawningLocomotive() { - EntityWarmlyLocomotive = new EntityWarmlyLocomotive(); - EntityWarmlyLocomotive.Init(speed, weight, bodyColor, additionalColor, chimney, compartment, indicatingLine); _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; + _pictureHeight = drawningLocomotiveHeight; + } + /// /// Установка границ поля /// @@ -63,7 +77,7 @@ public class DrawningWarmlyLocomotive // TODO проверка, что объект "влезает" в размеры поля // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена - if (width > _drawningWarmlyLocomotiveWidth && height > _drawningWarmlyLocomotiveHeight) + if (width > _drawningLocomotiveWidth && height > _drawningLocomotiveHeight) { _pictureWidth = width; _pictureHeight = height; @@ -75,14 +89,14 @@ public class DrawningWarmlyLocomotive if (_startPosY.Value < 0) { _startPosY = 0; } - if (_startPosX.Value + _drawningWarmlyLocomotiveWidth > _pictureWidth) + if (_startPosX.Value + _drawningLocomotiveWidth > _pictureWidth) { - _startPosX = _pictureWidth - _drawningWarmlyLocomotiveWidth; + _startPosX = _pictureWidth - _drawningLocomotiveWidth; } - if (_startPosY.Value + _drawningWarmlyLocomotiveHeight > _pictureHeight) + if (_startPosY.Value + _drawningLocomotiveHeight > _pictureHeight) { - _startPosY = _pictureHeight - _drawningWarmlyLocomotiveHeight; + _startPosY = _pictureHeight - _drawningLocomotiveHeight; } } return true; @@ -110,18 +124,18 @@ public class DrawningWarmlyLocomotive if (_startPosY.Value < 0) { _startPosY = 0; } if (_startPosX.Value < 0) { _startPosX = 0; } - if (_startPosX.Value + _drawningWarmlyLocomotiveWidth > _pictureWidth) + if (_startPosX.Value + _drawningLocomotiveWidth > _pictureWidth) { - _startPosX = _pictureWidth - _drawningWarmlyLocomotiveWidth; + _startPosX = _pictureWidth - _drawningLocomotiveWidth; } - if (_startPosY.Value + _drawningWarmlyLocomotiveHeight > _pictureHeight) + if (_startPosY.Value + _drawningLocomotiveHeight > _pictureHeight) { - _startPosY = _pictureHeight - _drawningWarmlyLocomotiveHeight; + _startPosY = _pictureHeight - _drawningLocomotiveHeight; } - } + } } - + /// /// Изменение направления перемещения /// @@ -129,7 +143,7 @@ public class DrawningWarmlyLocomotive /// true - перемещене выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityWarmlyLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } @@ -137,30 +151,30 @@ public class DrawningWarmlyLocomotive { //влево case DirectionType.Left: - if (_startPosX.Value - EntityWarmlyLocomotive.Step > 0) + if (_startPosX.Value - EntityLocomotive.Step > 0) { - _startPosX -= (int)EntityWarmlyLocomotive.Step; + _startPosX -= (int)EntityLocomotive.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityWarmlyLocomotive.Step > 0) + if (_startPosY.Value - EntityLocomotive.Step > 0) { - _startPosY -= (int)EntityWarmlyLocomotive.Step; + _startPosY -= (int)EntityLocomotive.Step; } return true; // вправо case DirectionType.Right: - if (_startPosX.Value + EntityWarmlyLocomotive.Step + _drawningWarmlyLocomotiveWidth < _pictureWidth) + if (_startPosX.Value + EntityLocomotive.Step + _drawningLocomotiveWidth < _pictureWidth) { - _startPosX += (int)EntityWarmlyLocomotive.Step; + _startPosX += (int)EntityLocomotive.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + EntityWarmlyLocomotive.Step + _drawningWarmlyLocomotiveHeight < _pictureHeight) + if (_startPosY.Value + EntityLocomotive.Step + _drawningLocomotiveHeight < _pictureHeight) { - _startPosY += (int)EntityWarmlyLocomotive.Step; + _startPosY += (int)EntityLocomotive.Step; } return true; default: @@ -172,88 +186,66 @@ public class DrawningWarmlyLocomotive /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityWarmlyLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new SolidBrush(EntityWarmlyLocomotive.AdditionalColor); - // обвесы - if (EntityWarmlyLocomotive.Chimney) - { - //труба - g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 0, 10, 10); - g.FillRectangle(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 0, 10, 5); - } - - if (EntityWarmlyLocomotive.Compartment) - { - //топливо отсек - g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 35, 20, 5); - g.FillRectangle(additionalBrush, _startPosX.Value + 40, _startPosY.Value + 35, 20, 5); - } //границы паровоза - g.DrawRectangle(pen, _startPosX.Value + 0, _startPosY.Value + 20, 120, 15); - g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 5, 110, 15); + g.DrawRectangle(pen, _startPosX.Value + 0, _startPosY.Value + 15, 120, 15); + g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 0, 110, 15); //кузов - Brush bk = new SolidBrush(EntityWarmlyLocomotive.BodyColor); - g.FillRectangle(bk, _startPosX.Value + 0, _startPosY.Value + 20, 120, 15); - g.FillRectangle(bk, _startPosX.Value + 10, _startPosY.Value + 5, 110, 15); + Brush bk = new SolidBrush(EntityLocomotive.BodyColor); + g.FillRectangle(bk, _startPosX.Value + 0, _startPosY.Value + 15, 120, 15); + g.FillRectangle(bk, _startPosX.Value + 10, _startPosY.Value + 0, 110, 15); //дверь - g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 10, 10, 22); - + g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 5, 10, 22); + //нос - g.DrawLine(pen, _startPosX.Value + 0, _startPosY.Value + 20, _startPosX.Value + 10, _startPosY.Value + 5); + g.DrawLine(pen, _startPosX.Value + 0, _startPosY.Value + 15, _startPosX.Value + 10, _startPosY.Value + 0); //стекла Pen penBlue = new(Color.LightBlue); Brush wt = new SolidBrush(Color.White); - g.FillRectangle(wt, _startPosX.Value + 15, _startPosY.Value + 7, 10, 10); - g.DrawRectangle(penBlue, _startPosX.Value + 15, _startPosY.Value + 7, 10, 10); - g.FillRectangle(wt, _startPosX.Value + 30, _startPosY.Value + 7, 10, 10); - g.DrawRectangle(penBlue, _startPosX.Value + 30, _startPosY.Value + 7, 10, 10); - g.FillRectangle(wt, _startPosX.Value + 107, _startPosY.Value + 7, 10, 10); - g.DrawRectangle(penBlue, _startPosX.Value + 107, _startPosY.Value + 7, 10, 10); + g.FillRectangle(wt, _startPosX.Value + 15, _startPosY.Value + 2, 10, 10); + g.DrawRectangle(penBlue, _startPosX.Value + 15, _startPosY.Value + 2, 10, 10); + g.FillRectangle(wt, _startPosX.Value + 30, _startPosY.Value + 2, 10, 10); + g.DrawRectangle(penBlue, _startPosX.Value + 30, _startPosY.Value + 2, 10, 10); + g.FillRectangle(wt, _startPosX.Value + 107, _startPosY.Value + 2, 10, 10); + g.DrawRectangle(penBlue, _startPosX.Value + 107, _startPosY.Value + 2, 10, 10); //треугольники низ Brush br = new SolidBrush(Color.Black); - g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 35, 30, 5); - g.DrawLine(pen, _startPosX.Value + 10, _startPosY.Value + 35, _startPosX.Value + 0, _startPosY.Value + 40); - g.DrawLine(pen, _startPosX.Value + 0, _startPosY.Value + 40, _startPosX.Value + 10, _startPosY.Value + 40); - g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 35, 30, 5); + g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 30, 30, 5); + g.DrawLine(pen, _startPosX.Value + 10, _startPosY.Value + 30, _startPosX.Value + 0, _startPosY.Value + 35); + g.DrawLine(pen, _startPosX.Value + 0, _startPosY.Value + 35, _startPosX.Value + 10, _startPosY.Value + 35); + g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 30, 30, 5); + + g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 30, 30, 5); + g.DrawLine(pen, _startPosX.Value + 110, _startPosY.Value + 30, _startPosX.Value + 130, _startPosY.Value + 35); + g.DrawLine(pen, _startPosX.Value + 130, _startPosY.Value + 35, _startPosX.Value + 110, _startPosY.Value + 35); + g.FillRectangle(br, _startPosX.Value + 85, _startPosY.Value + 30, 30, 5); - g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 35, 30, 5); - g.DrawLine(pen, _startPosX.Value + 110, _startPosY.Value + 35, _startPosX.Value + 130, _startPosY.Value + 40); - g.DrawLine(pen, _startPosX.Value + 130, _startPosY.Value + 40, _startPosX.Value + 110, _startPosY.Value + 40); - g.FillRectangle(br, _startPosX.Value + 85, _startPosY.Value + 35, 30, 5); - //зад.часть - g.DrawRectangle(pen, _startPosX.Value + 120, _startPosY.Value + 7, 5, 25); - g.FillRectangle(br, _startPosX.Value + 120, _startPosY.Value + 7, 5, 25); + g.DrawRectangle(pen, _startPosX.Value + 120, _startPosY.Value + 2, 5, 25); + g.FillRectangle(br, _startPosX.Value + 120, _startPosY.Value + 2, 5, 25); //колеса - g.FillEllipse(wt, _startPosX.Value + 10, _startPosY.Value + 35, 12, 11); - g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 35, 12, 11); + g.FillEllipse(wt, _startPosX.Value + 10, _startPosY.Value + 30, 12, 11); + g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 30, 12, 11); - g.FillEllipse(wt, _startPosX.Value + 30, _startPosY.Value + 35, 12, 11); - g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 35, 12, 11); + g.FillEllipse(wt, _startPosX.Value + 30, _startPosY.Value + 30, 12, 11); + g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 12, 11); - g.FillEllipse(wt, _startPosX.Value + 80, _startPosY.Value + 35, 12, 11); - g.DrawEllipse(pen, _startPosX.Value + 80, _startPosY.Value + 35, 12, 11); + g.FillEllipse(wt, _startPosX.Value + 80, _startPosY.Value + 30, 12, 11); + g.DrawEllipse(pen, _startPosX.Value + 80, _startPosY.Value + 30, 12, 11); - g.FillEllipse(wt, _startPosX.Value + 100, _startPosY.Value + 35, 12, 11); - g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 35, 12, 11); - - //линия - if (EntityWarmlyLocomotive.IndicatingLine) - { - g.FillRectangle(additionalBrush, _startPosX.Value + 0, _startPosY.Value + 20, 120, 2); - - } + g.FillEllipse(wt, _startPosX.Value + 100, _startPosY.Value + 30, 12, 11); + g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 30, 12, 11); } -} +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningWarmlyLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningWarmlyLocomotive.cs new file mode 100644 index 0000000..1065b4a --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningWarmlyLocomotive.cs @@ -0,0 +1,63 @@ +using WarmlyLocomotive.Entities; + +namespace WarmlyLocomotive.Drawnings; + +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawningWarmlyLocomotive : DrawningLocomotive +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия дымохода + /// Признак наличия отсека + /// Признак наличия обозначающей полосы + public DrawningWarmlyLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool chimney, bool compartment, bool indicatingLine) : base(130, 50) + { + EntityLocomotive = new EntityWarmlyLocomotive(speed, weight, bodyColor, additionalColor, chimney, compartment, indicatingLine); + } + + public override void DrawTransport(Graphics g) + { + if (EntityLocomotive == null || EntityLocomotive is not EntityWarmlyLocomotive warmlyLocmotive || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(warmlyLocmotive.AdditionalColor); + + // обвесы + if (warmlyLocmotive.Chimney) + { + //труба + g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 0, 10, 10); + g.FillRectangle(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 0, 10, 5); + } + + if (warmlyLocmotive.Compartment) + { + //топливо отсек + g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 35, 20, 5); + g.FillRectangle(additionalBrush, _startPosX.Value + 40, _startPosY.Value + 35, 20, 5); + } + + _startPosX += 0; + _startPosY += 5; + base.DrawTransport(g); + _startPosX -= 0; + _startPosY -= 5; + + //линия + if (warmlyLocmotive.IndicatingLine) + { + g.FillRectangle(additionalBrush, _startPosX.Value + 0, _startPosY.Value + 20, 120, 2); + + } + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/Entities/EntityLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/Entities/EntityLocomotive.cs new file mode 100644 index 0000000..d45e800 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/Entities/EntityLocomotive.cs @@ -0,0 +1,40 @@ +namespace WarmlyLocomotive.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; + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/EntityWarmlyLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/Entities/EntityWarmlyLocomotive.cs similarity index 64% rename from WarmlyLocomotive/WarmlyLocomotive/EntityWarmlyLocomotive.cs rename to WarmlyLocomotive/WarmlyLocomotive/Entities/EntityWarmlyLocomotive.cs index cb6983f..717f153 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/EntityWarmlyLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Entities/EntityWarmlyLocomotive.cs @@ -1,21 +1,11 @@ -namespace WarmlyLocomotive; +namespace WarmlyLocomotive.Entities; + /// /// Класс-сущность "тепловоз" /// -public class EntityWarmlyLocomotive +public class EntityWarmlyLocomotive : EntityLocomotive { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } + /// /// Дополнительный цвет (для опциональных элементов) /// @@ -32,12 +22,9 @@ public class EntityWarmlyLocomotive /// Признак (опция) наличия гоночной полосы /// public bool IndicatingLine { get; private set; } + /// - /// Шаг перемещения автомобиля - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса тепловоза + /// Конструктор /// /// Скорость /// Вес тепловоза @@ -46,15 +33,11 @@ public class EntityWarmlyLocomotive /// Признак наличия трубы /// Признак наличия топливного отсека /// Признак наличия обозначающей полосы - - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool chimney, bool compartment, bool indicatingLine) + public EntityWarmlyLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool chimney, bool compartment, bool indicatingLine) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Chimney = chimney; Compartment = compartment; IndicatingLine = indicatingLine; } -} +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs index aad507f..c9c6f40 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs @@ -34,6 +34,7 @@ buttonDown = new Button(); buttonRight = new Button(); buttonUp = new Button(); + buttonCreateLocomotive = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyLocomotive).BeginInit(); SuspendLayout(); // @@ -51,9 +52,9 @@ buttonCreateWarmlyLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateWarmlyLocomotive.Location = new Point(12, 409); buttonCreateWarmlyLocomotive.Name = "buttonCreateWarmlyLocomotive"; - buttonCreateWarmlyLocomotive.Size = new Size(94, 29); + buttonCreateWarmlyLocomotive.Size = new Size(156, 29); buttonCreateWarmlyLocomotive.TabIndex = 1; - buttonCreateWarmlyLocomotive.Text = "создать"; + buttonCreateWarmlyLocomotive.Text = "создать локомотив"; buttonCreateWarmlyLocomotive.UseVisualStyleBackColor = true; buttonCreateWarmlyLocomotive.Click += ButtonCreateWarmlyLocomotive_Click; // @@ -105,11 +106,23 @@ buttonUp.UseVisualStyleBackColor = true; buttonUp.Click += ButtonMove_Click; // + // buttonCreateLocomotive + // + buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateLocomotive.Location = new Point(174, 409); + buttonCreateLocomotive.Name = "buttonCreateLocomotive"; + buttonCreateLocomotive.Size = new Size(156, 29); + buttonCreateLocomotive.TabIndex = 6; + buttonCreateLocomotive.Text = "создать паровоз"; + buttonCreateLocomotive.UseVisualStyleBackColor = true; + buttonCreateLocomotive.Click += ButtonCreateLocomotive_Click; + // // FormWarmlyLocomotive // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonCreateLocomotive); Controls.Add(buttonUp); Controls.Add(buttonRight); Controls.Add(buttonDown); @@ -130,5 +143,6 @@ private Button buttonDown; private Button buttonRight; private Button buttonUp; + private Button buttonCreateLocomotive; } } \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs index d506d2e..31aa6f3 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs @@ -1,4 +1,6 @@ -namespace WarmlyLocomotive; +using WarmlyLocomotive.Drawnings; + +namespace WarmlyLocomotive; /// /// Форма работы с объектом "тепловоз" @@ -8,7 +10,7 @@ public partial class FormWarmlyLocomotive : Form /// /// Поле-объект для прорисовки объекта /// - private DrawningWarmlyLocomotive? _drawningWarmlyLocomotive; + private DrawningLocomotive? _drawningLocomotive; /// /// Конструктор формы @@ -23,35 +25,57 @@ public partial class FormWarmlyLocomotive : Form /// private void Draw() { - if (_drawningWarmlyLocomotive == null) + if (_drawningLocomotive == null) { return; } Bitmap bmp = new(pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningWarmlyLocomotive.DrawTransport(gr); + _drawningLocomotive.DrawTransport(gr); pictureBoxWarmlyLocomotive.Image = bmp; } /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + 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(DrawningWarmlyLocomotive): + _drawningLocomotive = new DrawningWarmlyLocomotive(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)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + _drawningLocomotive.SetPictureSize(pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); + _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать локомотив" /// /// /// - private void ButtonCreateWarmlyLocomotive_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningWarmlyLocomotive = new DrawningWarmlyLocomotive(); - _drawningWarmlyLocomotive.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)), Convert.ToBoolean(random.Next(0, 2))); - _drawningWarmlyLocomotive.SetPictureSize(pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); - _drawningWarmlyLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + private void ButtonCreateWarmlyLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningWarmlyLocomotive)); - Draw(); + /// + /// Обработка нажатия кнопки "Создать паровоз" + /// + /// + /// + private void ButtonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive)); - } /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -59,27 +83,29 @@ public partial class FormWarmlyLocomotive : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningWarmlyLocomotive == null) + if (_drawningLocomotive == null) { return; } string name = ((Button)sender)?.Name ?? string.Empty; bool result = false; + switch (name) { case "buttonUp": - result = _drawningWarmlyLocomotive.MoveTransport(DirectionType.Up); + result = _drawningLocomotive.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningWarmlyLocomotive.MoveTransport(DirectionType.Down); + result = _drawningLocomotive.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningWarmlyLocomotive.MoveTransport(DirectionType.Left); + result = _drawningLocomotive.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningWarmlyLocomotive.MoveTransport(DirectionType.Right); + result = _drawningLocomotive.MoveTransport(DirectionType.Right); break; } + if (result) { Draw(); diff --git a/lab_1/lab_1.sln b/lab_1/lab_1.sln deleted file mode 100644 index 55518f5..0000000 --- a/lab_1/lab_1.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.7.34024.191 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lab_1", "lab_1\lab_1.vcxproj", "{88F6E495-8313-457C-8B37-34F8848D95C3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {88F6E495-8313-457C-8B37-34F8848D95C3}.Debug|x64.ActiveCfg = Debug|x64 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Debug|x64.Build.0 = Debug|x64 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Debug|x86.ActiveCfg = Debug|Win32 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Debug|x86.Build.0 = Debug|Win32 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Release|x64.ActiveCfg = Release|x64 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Release|x64.Build.0 = Release|x64 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Release|x86.ActiveCfg = Release|Win32 - {88F6E495-8313-457C-8B37-34F8848D95C3}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {AFE935BC-7614-4661-8922-8FCC085EA88C} - EndGlobalSection -EndGlobal diff --git a/lab_1/lab_1/Lab_1.c b/lab_1/lab_1/Lab_1.c deleted file mode 100644 index 89d85e3..0000000 --- a/lab_1/lab_1/Lab_1.c +++ /dev/null @@ -1,50 +0,0 @@ -#define _CRT_SECURE_NO_WARNINGS -#include -#include -#include -#include - -// -struct medicine { - char name[10]; - int index; - struct medicine* next; -}; - -struct medicine* first = NULL; - -void sortMedicine(struct medicine* list); - -struct medicine* create(struct medicine* end, int n, char* p) { - struct medicine* tmp; - - tmp = (struct medicine*)malloc(sizeof(struct medicine)); - - tmp->index = n; - strcpy(tmp->name, p); - - if (end == NULL) { - tmp->next = NULL; - } - else { - tmp->next = end; - } - - return tmp; -} - - -void print(struct medicine *p) { - do { - printf("%10s (%d) -> ", p->name, p->index); - } while ((p = p->next) != NULL); - - printf("\n"); -} - -void main() { - first = NULL; - printList(); - addElement("bimbim", 2); - printList(); -} \ No newline at end of file diff --git a/lab_1/lab_1/lab_1.vcxproj b/lab_1/lab_1/lab_1.vcxproj deleted file mode 100644 index 2b896e3..0000000 --- a/lab_1/lab_1/lab_1.vcxproj +++ /dev/null @@ -1,135 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 17.0 - Win32Proj - {88f6e495-8313-457c-8b37-34f8848d95c3} - lab1 - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - - Level3 - true - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - Level3 - true - _DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - - - \ No newline at end of file diff --git a/lab_1/lab_1/lab_1.vcxproj.filters b/lab_1/lab_1/lab_1.vcxproj.filters deleted file mode 100644 index dd529d6..0000000 --- a/lab_1/lab_1/lab_1.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Исходные файлы - - - \ No newline at end of file -- 2.25.1 From 6711705a957194623922340865ca46464fbeb1ad Mon Sep 17 00:00:00 2001 From: vkobi Date: Tue, 12 Mar 2024 20:06:30 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=D1=82=D1=80=D0=B0=D1=82=D0=B5=D0=B3?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Drawnings/DirectionType.cs | 8 + .../Drawnings/DrawningLocomotive.cs | 21 +++ .../FormWarmlyLocomotive.Designer.cs | 26 ++++ .../WarmlyLocomotive/FormWarmlyLocomotive.cs | 51 ++++++- .../MovementStrategy/AbstractStrategy.cs | 140 ++++++++++++++++++ .../MovementStrategy/IMoveableObject.cs | 24 +++ .../MovementStrategy/MoveToBorder.cs | 58 ++++++++ .../MovementStrategy/MoveToCenter.cs | 58 ++++++++ .../MovementStrategy/MoveableLocomotive.cs | 64 ++++++++ .../MovementStrategy/MovementDirection.cs | 27 ++++ .../MovementStrategy/ObjectParameters.cs | 73 +++++++++ .../MovementStrategy/StrategyStatus.cs | 22 +++ 12 files changed, 571 insertions(+), 1 deletion(-) create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs create mode 100644 WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs index 2e9b21f..789f590 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DirectionType.cs @@ -4,18 +4,26 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// Up = 1, + /// /// Вниз /// Down = 2, + /// /// Влево /// Left = 3, + /// /// Вправо /// diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs index af79ad4..cda06db 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotive.cs @@ -33,6 +33,27 @@ public class DrawningLocomotive /// private readonly int _drawningLocomotiveHeight = 40; + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLocomotiveWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningLocomotiveHeight; + + /// /// Пустой конструктор /// diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs index c9c6f40..831d23a 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.Designer.cs @@ -35,6 +35,8 @@ buttonRight = new Button(); buttonUp = new Button(); buttonCreateLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyLocomotive).BeginInit(); SuspendLayout(); // @@ -117,11 +119,33 @@ buttonCreateLocomotive.UseVisualStyleBackColor = true; buttonCreateLocomotive.Click += ButtonCreateLocomotive_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" }); + comboBoxStrategy.Location = new Point(637, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(151, 28); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(694, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormWarmlyLocomotive // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateLocomotive); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -144,5 +168,7 @@ private Button buttonRight; private Button buttonUp; private Button buttonCreateLocomotive; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs index 31aa6f3..9065f4e 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormWarmlyLocomotive.cs @@ -1,4 +1,5 @@ using WarmlyLocomotive.Drawnings; +using WarmlyLocomotive.MovementStrategy; namespace WarmlyLocomotive; @@ -12,12 +13,18 @@ public partial class FormWarmlyLocomotive : Form /// private DrawningLocomotive? _drawningLocomotive; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// /// Конструктор формы /// public FormWarmlyLocomotive() { InitializeComponent(); + _strategy = null; } /// @@ -59,6 +66,8 @@ public partial class FormWarmlyLocomotive : Form } _drawningLocomotive.SetPictureSize(pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } @@ -111,4 +120,44 @@ public partial class FormWarmlyLocomotive : 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), + pictureBoxWarmlyLocomotive.Width, pictureBoxWarmlyLocomotive.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..b70cfd2 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,140 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Класс-стратегия перемещения объекта +/// +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotInit; + + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + + /// + /// Статус перемещения + /// + public StrategyStatus GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = StrategyStatus.NotInit; + return; + } + + _state = StrategyStatus.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (IsTargetDestinaion()) + { + _state = StrategyStatus.Finish; + return; + } + + MoveToTarget(); + } + + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false -неудача) + protected bool MoveRight() => MoveTo(MovementDirection.Right); + + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(MovementDirection.Up); + + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveDown() => MoveTo(MovementDirection.Down); + + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + + return _moveableObject?.GetStep; + } + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..1d2a1cd --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..473df0f --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,58 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Стратегия перемещения объекта в правый кран экрана +/// +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; + + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + + if (objParams == null) + { + return; + } + + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth; + + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + int diffY = objParams.ObjectMiddleVertical - FieldHeight; + + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..7c38ef0 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,58 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Стратегия перемещения объекта в центр экрана +/// +public class MoveToCenter : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + + if (objParams == null) + { + return false; + } + + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + + if (objParams == null) + { + return; + } + + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs new file mode 100644 index 0000000..c3522ba --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MoveableLocomotive.cs @@ -0,0 +1,64 @@ +using WarmlyLocomotive.Drawnings; + +namespace WarmlyLocomotive.MovementStrategy; + +// +/// Класс-реализация IMoveableObject с использованием 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, + }; + } +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..02d2563 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/MovementDirection.cs @@ -0,0 +1,27 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..e29a2d6 --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,73 @@ +namespace WarmlyLocomotive.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; + } + +} \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..26ed74c --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace WarmlyLocomotive.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} \ No newline at end of file -- 2.25.1