From f0c31b34b30b17829bb8ecb59fdf6a4203077b0f Mon Sep 17 00:00:00 2001 From: Anitonchik Date: Wed, 13 Mar 2024 23:41:35 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=962?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ => Drawnings}/DirectionType.cs | 6 +- .../Drawnings/DrawningDumpTruck.cs | 73 ++++++++ .../DrawningTruck.cs} | 170 +++++++++--------- .../Entities/EntityDumpTruck.cs | 42 +++++ .../ProjectDumpTruck/Entities/EntityTruck.cs | 46 +++++ .../ProjectDumpTruck/EntityDumpTruck.cs | 58 ------ .../FormDumpTruck.Designer.cs | 47 ++++- .../ProjectDumpTruck/FormDumpTruck.cs | 110 +++++++++--- .../MovementStrategy/AbstractStrategy.cs | 124 +++++++++++++ .../MovementStrategy/IMoveableObject.cs | 25 +++ .../MovementStrategy/MoveToBorder.cs | 42 +++++ .../MovementStrategy/MoveToCenter.cs | 55 ++++++ .../MovementStrategy/MoveableTruck.cs | 66 +++++++ .../MovementStrategy/MovementDirection.cs | 30 ++++ .../MovementStrategy/ObjectParameters.cs | 65 +++++++ .../MovementStrategy/StrategyStatus.cs | 26 +++ 16 files changed, 817 insertions(+), 168 deletions(-) rename ProjectDumpTruck/ProjectDumpTruck/{ => Drawnings}/DirectionType.cs (77%) create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs rename ProjectDumpTruck/ProjectDumpTruck/{DrawningDumpTruck.cs => Drawnings/DrawningTruck.cs} (52%) create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs delete mode 100644 ProjectDumpTruck/ProjectDumpTruck/EntityDumpTruck.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObject.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTruck.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs diff --git a/ProjectDumpTruck/ProjectDumpTruck/DirectionType.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DirectionType.cs similarity index 77% rename from ProjectDumpTruck/ProjectDumpTruck/DirectionType.cs rename to ProjectDumpTruck/ProjectDumpTruck/Drawnings/DirectionType.cs index 82478f9..be9b66a 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/DirectionType.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DirectionType.cs @@ -4,13 +4,17 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectDumpTruck; +namespace ProjectDumpTruck.Drawnings; /// /// Напривление перемещения /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs new file mode 100644 index 0000000..66c37c7 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectDumpTruck.Entities; + +namespace ProjectDumpTruck.Drawnings; + +/// +/// Класс, отвечающий за прорисовку и перемещение +/// +public class DrawningDumpTruck : DrawningTruck +{ + /// + /// + /// Конструктор + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия кузова + /// Признак наличия тента + public DrawningDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool body, bool tent) : base(110, 100) + { + EntityTruck = new EntityDumpTruck(speed, weight, bodyColor, additionalColor, body, tent); + + } + + public override void DrawTransport(Graphics g) + { + if (EntityTruck == null || EntityTruck is not EntityDumpTruck entityTruck || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + _startPosX += 10; + base.DrawTransport(g); + _startPosX -= 10; + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(entityTruck.AdditionalColor); + + Brush brBody = new SolidBrush(entityTruck.AdditionalColor); + + if (entityTruck.Body) + { + Point[] body = + { + new Point (_startPosX.Value, _startPosY.Value + 15), + new Point (_startPosX.Value + 77, _startPosY.Value + 15), + new Point (_startPosX.Value + 77, _startPosY.Value + 50), + new Point (_startPosX.Value + 20, _startPosY.Value + 50) + }; + g.DrawPolygon(pen, points: body); + + g.FillPolygon(brBody, body); + } + + if (entityTruck.Tent && entityTruck.Body) + { + Point[] tent = + { + new Point (_startPosX.Value, _startPosY.Value + 13), + new Point (_startPosX.Value + 39, _startPosY.Value), + new Point (_startPosX.Value + 77, _startPosY.Value + 13) + }; + g.DrawPolygon(pen, points: tent); + + g.FillPolygon(brBody, tent); + } + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/DrawningDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs similarity index 52% rename from ProjectDumpTruck/ProjectDumpTruck/DrawningDumpTruck.cs rename to ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs index fd2513c..9c772ac 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/DrawningDumpTruck.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs @@ -1,20 +1,18 @@ -using System; +using ProjectDumpTruck.Entities; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectDumpTruck; +namespace ProjectDumpTruck.Drawnings; -/// -/// Класс, отвечающий за прорисовку и перемещение -/// -public class DrawningDumpTruck +public class DrawningTruck { /// /// Класс-сущность /// - public EntityDumpTruck? EntityDumpTruck { get; private set; } + public EntityTruck? EntityTruck { get; protected set; } /// /// Ширина окна /// @@ -26,41 +24,71 @@ public class DrawningDumpTruck /// /// Левая координата прорисовки автомобиля /// - private int? _startPosX; + protected private int? _startPosX; /// /// Верхняя кооридната прорисовки автомобиля /// - private int? _startPosY; + protected private int? _startPosY; /// /// Ширина прорисовки самосвала /// - private readonly int _drawningDumpTruckWidth = 116; + private readonly int _drawningTruckWidth = 100; /// /// Высота прорисовки самосвала /// - private readonly int _drawingDumpTruckHeight = 100; + private readonly int _drawningTruckHeight = 92; + /// + /// Координата Х объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата У объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningTruckWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningTruckHeight; + /// + /// Пустой конструктор /// - /// Инициализация свойств - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия кузова - /// Признак наличия тента - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool body, bool tent) + private DrawningTruck() { - EntityDumpTruck = new EntityDumpTruck(); - EntityDumpTruck.Init(speed, weight, bodyColor, additionalColor, - body, tent); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + /// + /// + /// Конструктор + /// Скорость + /// Вес + /// Основной цвет + public DrawningTruck(int speed, double weight, Color bodyColor) : this() + { + EntityTruck = new EntityTruck(speed, weight, bodyColor); + + } + + /// + /// + /// Конструктор для наследников + /// Ширина прорисовки самосвала + /// Высота прорисовки самосвала + protected DrawningTruck(int drawningTruckWidth, int drawningTruckHeight) : this() + { + _drawningTruckWidth = drawningTruckWidth; + _drawningTruckHeight = drawningTruckHeight; + } + /// /// Установка границ поля @@ -72,21 +100,21 @@ public class DrawningDumpTruck { // TODO проверка, что объект "влезает" в размеры поля // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена - if (_drawningDumpTruckWidth > width || _drawingDumpTruckHeight > height) + if (_drawningTruckWidth > width || _drawningTruckHeight > height) { return false; } if (_pictureWidth.HasValue && width != _pictureWidth || _pictureHeight.HasValue && height != _pictureHeight) { - if (_startPosX + _drawningDumpTruckWidth > width) + if (_startPosX + _drawningTruckWidth > width) { - _startPosX -= _drawningDumpTruckWidth; + _startPosX -= _drawningTruckWidth; } - if (_startPosY + _drawingDumpTruckHeight > height) + if (_startPosY + _drawningTruckHeight > height) { - _startPosY -= _drawingDumpTruckHeight; + _startPosY -= _drawningTruckHeight; } } @@ -111,17 +139,17 @@ public class DrawningDumpTruck { x = 0; } - if (x + _drawningDumpTruckWidth > _pictureWidth) + if (x + _drawningTruckWidth > _pictureWidth) { - x = (int)_pictureWidth - _drawningDumpTruckWidth; + x = (int)_pictureWidth - _drawningTruckWidth; } if (y < 0) { y = 0; } - if (y + _drawingDumpTruckHeight > _pictureHeight) + if (y + _drawningTruckHeight > _pictureHeight) { - y = (int)_pictureHeight - _drawingDumpTruckHeight; + y = (int)_pictureHeight - _drawningTruckHeight; } @@ -139,7 +167,7 @@ public class DrawningDumpTruck /// true - перемещене выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityDumpTruck == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTruck == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } @@ -148,30 +176,30 @@ public class DrawningDumpTruck { //влево case DirectionType.Left: - if (_startPosX.Value - EntityDumpTruck.Step > 0) + if (_startPosX.Value - EntityTruck.Step > 0) { - _startPosX -= (int)EntityDumpTruck.Step; + _startPosX -= (int)EntityTruck.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityDumpTruck.Step > 0) + if (_startPosY.Value - EntityTruck.Step > 0) { - _startPosY -= (int)EntityDumpTruck.Step; + _startPosY -= (int)EntityTruck.Step; } return true; // вправо case DirectionType.Right: - if (_startPosX.Value + _drawningDumpTruckWidth < _pictureWidth) + if (_startPosX.Value + _drawningTruckWidth < _pictureWidth) { - _startPosX += (int)EntityDumpTruck.Step; + _startPosX += (int)EntityTruck.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + _drawingDumpTruckHeight < _pictureHeight) + if (_startPosY.Value + _drawningTruckHeight < _pictureHeight) { - _startPosY += (int)EntityDumpTruck.Step; + _startPosY += (int)EntityTruck.Step; } return true; default: @@ -183,70 +211,40 @@ public class DrawningDumpTruck /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityDumpTruck == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTruck == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new SolidBrush(EntityDumpTruck.AdditionalColor); - Brush brBody = new SolidBrush(EntityDumpTruck.AdditionalColor); - - if (EntityDumpTruck.Body) - { - Point[] body = - { - new Point (_startPosX.Value, _startPosY.Value + 15), - new Point (_startPosX.Value + 77, _startPosY.Value + 15), - new Point (_startPosX.Value + 77, _startPosY.Value + 50), - new Point (_startPosX.Value + 20, _startPosY.Value + 50) - }; - g.DrawPolygon(pen, points: body); - - g.FillPolygon(brBody, body); - } - - if (EntityDumpTruck.Tent && EntityDumpTruck.Body) - { - Point[] tent = - { - new Point (_startPosX.Value, _startPosY.Value + 13), - new Point (_startPosX.Value + 39, _startPosY.Value), - new Point (_startPosX.Value + 77, _startPosY.Value + 13) - }; - g.DrawPolygon(pen, points: tent); - - g.FillPolygon(brBody, tent); - } //Границы самосвала - g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 53, 100, 13); - g.DrawRectangle(pen, _startPosX.Value + 80, _startPosY.Value + 15, 30, 36); - g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 20, 20, 20); + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 53, 100, 13); + g.DrawRectangle(pen, _startPosX.Value + 70, _startPosY.Value + 15, 30, 36); + g.DrawRectangle(pen, _startPosX.Value + 75, _startPosY.Value + 20, 20, 20); // Колеса - g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 67, 25, 25); - g.DrawEllipse(pen, _startPosX.Value + 38, _startPosY.Value + 67, 25, 25); - g.DrawEllipse(pen, _startPosX.Value + 83, _startPosY.Value + 67, 25, 25); + g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 67, 25, 25); + g.DrawEllipse(pen, _startPosX.Value + 28, _startPosY.Value + 67, 25, 25); + g.DrawEllipse(pen, _startPosX.Value + 73, _startPosY.Value + 67, 25, 25); // Кузов - Brush br = new SolidBrush(EntityDumpTruck.BodyColor); - g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 53, 100, 13); - g.FillRectangle(br, _startPosX.Value + 80, _startPosY.Value + 15, 30, 36); + Brush br = new SolidBrush(EntityTruck.BodyColor); + g.FillRectangle(br, _startPosX.Value, _startPosY.Value + 53, 100, 13); + g.FillRectangle(br, _startPosX.Value + 70, _startPosY.Value + 15, 30, 36); // Колеса Brush brBlack = new SolidBrush(Color.Black); - g.FillEllipse(brBlack, _startPosX.Value + 10, _startPosY.Value + 67, 25, 25); - g.FillEllipse(brBlack, _startPosX.Value + 38, _startPosY.Value + 67, 25, 25); - g.FillEllipse(brBlack, _startPosX.Value + 83, _startPosY.Value + 67, 25, 25); + g.FillEllipse(brBlack, _startPosX.Value, _startPosY.Value + 67, 25, 25); + g.FillEllipse(brBlack, _startPosX.Value + 28, _startPosY.Value + 67, 25, 25); + g.FillEllipse(brBlack, _startPosX.Value + 73, _startPosY.Value + 67, 25, 25); //Окно Brush brBlue = new SolidBrush(Color.LightBlue); - g.FillRectangle(brBlue, _startPosX.Value + 85, _startPosY.Value + 20, 20, 20); - + g.FillRectangle(brBlue, _startPosX.Value + 75, _startPosY.Value + 20, 20, 20); } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs new file mode 100644 index 0000000..0e3cdae --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.Entities; + +/// +/// Класс-сущность Самосвала +/// +public class EntityDumpTruck : EntityTruck +{ + /// + /// Дополнительный цвет (для опциональных элементов) + /// + public Color AdditionalColor { get; private set; } + /// + /// Наличие кузова + /// + public bool Body { get; private set; } + /// + /// Наличие тента + /// + public bool Tent { get; private set; } + + /// + /// Конструктор + /// + /// Скорость + /// Вес самосвала + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия кузова + /// Признак наличия тента + public EntityDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool body, bool tent) : base(speed, weight, bodyColor: bodyColor) + { + AdditionalColor = additionalColor; + Body = body; + Tent = tent; + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs new file mode 100644 index 0000000..1fa467b --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.Entities; + +/// +/// Класс-сущность "Грузовик" +/// +public class EntityTruck +{ + /// + /// Скорость + /// + 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 EntityTruck(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/EntityDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/EntityDumpTruck.cs deleted file mode 100644 index 28045bc..0000000 --- a/ProjectDumpTruck/ProjectDumpTruck/EntityDumpTruck.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectDumpTruck; - -public class EntityDumpTruck -{ - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// - /// Дополнительный цвет (для опциональных элементов) - /// - public Color AdditionalColor { get; private set; } - /// - /// Наличие кузова - /// - public bool Body { get; private set; } - /// - /// Наличие тента - /// - public bool Tent { get; private set; } - /// - /// Шаг перемещения автомобиля - /// - public double Step => Speed * 100 / Weight; - - /// - /// Инициализация полей объекта-класса спортивного автомобиля - /// - /// Скорость - /// Вес автомобиля - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия обвеса - /// Признак наличия антикрыла - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool body, bool tent) - { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; - Body = body; - Tent = tent; - } -} diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.Designer.cs b/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.Designer.cs index c36ffcc..ebe2b0c 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.Designer.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.Designer.cs @@ -34,6 +34,9 @@ buttonUp = new Button(); buttonDown = new Button(); buttonRight = new Button(); + buttonCreateTruck = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).BeginInit(); SuspendLayout(); // @@ -51,9 +54,9 @@ buttonCreateDumpTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateDumpTruck.Location = new Point(14, 505); buttonCreateDumpTruck.Name = "buttonCreateDumpTruck"; - buttonCreateDumpTruck.Size = new Size(94, 29); + buttonCreateDumpTruck.Size = new Size(237, 29); buttonCreateDumpTruck.TabIndex = 1; - buttonCreateDumpTruck.Text = "Создать"; + buttonCreateDumpTruck.Text = "Создать самосвал"; buttonCreateDumpTruck.UseVisualStyleBackColor = true; buttonCreateDumpTruck.Click += ButtonCreateDumpTruck_Click; // @@ -105,11 +108,46 @@ buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += ButtonMove_Click; // + // buttonCreateTruck + // + buttonCreateTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateTruck.Location = new Point(269, 504); + buttonCreateTruck.Name = "buttonCreateTruck"; + buttonCreateTruck.Size = new Size(237, 29); + buttonCreateTruck.TabIndex = 6; + buttonCreateTruck.Text = "Создать грузовик"; + buttonCreateTruck.UseVisualStyleBackColor = true; + buttonCreateTruck.Click += ButtonCreateTruck_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(731, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(151, 28); + comboBoxStrategy.TabIndex = 7; + //comboBoxStrategy.SelectedIndexChanged += comboBoxStrategy_SelectedIndexChanged; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(785, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ВuttonStrategyStep_Click; + // // FormDumpTruck // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(894, 545); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateTruck); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonUp); @@ -122,6 +160,8 @@ ResumeLayout(false); } + + #endregion private PictureBox pictureBoxDumpTruck; @@ -130,5 +170,8 @@ private Button buttonUp; private Button buttonDown; private Button buttonRight; + private Button buttonCreateTruck; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.cs index abeb332..3ec4f85 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormDumpTruck.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ProjectDumpTruck.Drawnings; +using ProjectDumpTruck.MovementStrategy; namespace ProjectDumpTruck { @@ -15,49 +17,79 @@ namespace ProjectDumpTruck /// /// Поле-объект для прорисовки объекта /// - private DrawningDumpTruck? _drawningDumpTruck; + private DrawningTruck? _drawningTruck; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы /// public FormDumpTruck() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки машины /// private void Draw() { - if (_drawningDumpTruck == null) + if (_drawningTruck == null) { return; } Bitmap bmp = new(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningDumpTruck.DrawTransport(gr); + _drawningTruck.DrawTransport(gr); pictureBoxDumpTruck.Image = bmp; } + /// - /// Обработка нажатия кнопки "Создать" + /// Сосздание объекста класса-перемещения /// - /// - /// - private void ButtonCreateDumpTruck_Click(object sender, EventArgs e) + /// + private void CreateObject(string type) { - Random random = new(); - _drawningDumpTruck = new DrawningDumpTruck(); - _drawningDumpTruck.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))); - _drawningDumpTruck.SetPictureSize(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height); + Random random = new Random(); + switch (type) + { + case nameof(DrawningTruck): + _drawningTruck = new DrawningTruck(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(DrawningDumpTruck): + _drawningTruck = new DrawningDumpTruck(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; + } - - _drawningDumpTruck.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _drawningTruck.SetPictureSize(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height); + _drawningTruck.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } + + /// + /// Обработка нажатия кнопки "Создать самосвал" + /// + /// + /// + private void ButtonCreateDumpTruck_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningDumpTruck)); + + /// + /// Обработка нажатия кнопки "Создать грузовик" + /// + /// + /// + private void ButtonCreateTruck_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTruck)); /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -65,7 +97,7 @@ namespace ProjectDumpTruck /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningDumpTruck == null) + if (_drawningTruck == null) { return; } @@ -75,19 +107,19 @@ namespace ProjectDumpTruck { case "buttonUp": result = - _drawningDumpTruck.MoveTransport(DirectionType.Up); + _drawningTruck.MoveTransport(DirectionType.Up); break; case "buttonDown": result = - _drawningDumpTruck.MoveTransport(DirectionType.Down); + _drawningTruck.MoveTransport(DirectionType.Down); break; case "buttonLeft": result = - _drawningDumpTruck.MoveTransport(DirectionType.Left); + _drawningTruck.MoveTransport(DirectionType.Left); break; case "buttonRight": result = - _drawningDumpTruck.MoveTransport(DirectionType.Right); + _drawningTruck.MoveTransport(DirectionType.Right); break; } if (result) @@ -95,6 +127,42 @@ namespace ProjectDumpTruck Draw(); } } + + private void ВuttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningTruck == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTruck(_drawningTruck), pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } } + diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..bbd8e36 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.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/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObject.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..831aef0 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.MovementStrategy; + +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..ee314e6 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.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 = FieldWidth - objParams.RightBorder; + if (Math.Abs(diffX) > GetStep()) + { + MoveRight(); + } + + int diffY = FieldHeight - objParams.DownBorder; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..ab9d12e --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.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/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTruck.cs new file mode 100644 index 0000000..b68c741 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTruck.cs @@ -0,0 +1,66 @@ +using ProjectDumpTruck.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectDumpTruck.MovementStrategy; + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием DrawningCar +/// +public class MoveableTruck : IMoveableObject +{ + /// + /// Поле-объект класса DrawningCar или его наследника + /// + private readonly DrawningTruck? _truck = null; + /// + /// Конструктор + /// + /// Объект класса DrawningCar + public MoveableTruck(DrawningTruck truck) + { + _truck = truck; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_truck == null || _truck.EntityTruck == null || + !_truck.GetPosX.HasValue || !_truck.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_truck.GetPosX.Value, _truck.GetPosY.Value, _truck.GetWidth, _truck.GetHeight); + } + } + + public int GetStep => (int)(_truck?.EntityTruck?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_truck == null || _truck.EntityTruck == null) + { + return false; + } + return _truck.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/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..74eac7b --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..6ed40e7 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.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/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..e49e07e --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +} -- 2.25.1