From b869ca4747d4896062c51923636c4c58796c769e Mon Sep 17 00:00:00 2001 From: qkrlnt Date: Wed, 27 Mar 2024 01:29:09 +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 --- .../{ => Drawings}/DirectionType.cs | 15 +- ProjectMonorail/Drawings/DrawingMonorail.cs | 101 +++++++++++ .../DrawingTrain.cs} | 158 ++++++++---------- .../{ => Entities}/EntityMonorail.cs | 36 +--- ProjectMonorail/Entities/EntityTrain.cs | 46 +++++ ProjectMonorail/FormMonorail.Designer.cs | 70 ++++++-- ProjectMonorail/FormMonorail.cs | 109 +++++++++--- .../MovementStrategy/AbstractStrategy.cs | 137 +++++++++++++++ .../MovementStrategy/IMovableObjects.cs | 27 +++ .../MovementStrategy/MoveToBorder.cs | 39 +++++ .../MovementStrategy/MoveToCenter.cs | 54 ++++++ .../MovementStrategy/MoveableTrain.cs | 63 +++++++ .../MovementStrategy/MovementDirection.cs | 27 +++ .../MovementStrategy/ObjectParameters.cs | 75 +++++++++ .../MovementStrategy/StrategyStatus.cs | 22 +++ WindowsFormsApp1/App.config | 3 +- 16 files changed, 821 insertions(+), 161 deletions(-) rename ProjectMonorail/{ => Drawings}/DirectionType.cs (72%) create mode 100644 ProjectMonorail/Drawings/DrawingMonorail.cs rename ProjectMonorail/{DrawingMonorail.cs => Drawings/DrawingTrain.cs} (63%) rename ProjectMonorail/{ => Entities}/EntityMonorail.cs (55%) create mode 100644 ProjectMonorail/Entities/EntityTrain.cs create mode 100644 ProjectMonorail/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectMonorail/MovementStrategy/IMovableObjects.cs create mode 100644 ProjectMonorail/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectMonorail/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectMonorail/MovementStrategy/MoveableTrain.cs create mode 100644 ProjectMonorail/MovementStrategy/MovementDirection.cs create mode 100644 ProjectMonorail/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectMonorail/MovementStrategy/StrategyStatus.cs diff --git a/ProjectMonorail/DirectionType.cs b/ProjectMonorail/Drawings/DirectionType.cs similarity index 72% rename from ProjectMonorail/DirectionType.cs rename to ProjectMonorail/Drawings/DirectionType.cs index da38935..1b527c3 100644 --- a/ProjectMonorail/DirectionType.cs +++ b/ProjectMonorail/Drawings/DirectionType.cs @@ -1,21 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectMonorail; +namespace ProjectMonorail.Drawings; /// /// Направление перемещения /// public enum DirectionType { + /// + /// Неизвестное + /// + Unknown = -1, + /// /// Вверх /// Up = 1, - + /// /// Вниз /// diff --git a/ProjectMonorail/Drawings/DrawingMonorail.cs b/ProjectMonorail/Drawings/DrawingMonorail.cs new file mode 100644 index 0000000..4495f37 --- /dev/null +++ b/ProjectMonorail/Drawings/DrawingMonorail.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectMonorail.Entities; + +namespace ProjectMonorail.Drawings; + +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawingMonorail : DrawingTrain +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Количество колёс + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия магнитного рельса + /// Признак наличия второго вагона + public DrawingMonorail(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) : base(40, 150) + { + EntityTrain = new EntityMonorail(speed, (int)weight, wheels, mainColor, additionalColor, rail, secondCarriage); + } + + + /// + /// Прорисовка объекта + /// + /// + public override void DrawTransport(Graphics g) + { + if (EntityTrain == null || EntityTrain is not EntityMonorail monoRail || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + base.DrawTransport(g); + + Brush additionalBrush = new SolidBrush(monoRail.AdditionalColor); + Pen pen = new(Color.Black); + Brush brBlue = new SolidBrush(Color.LightBlue); + Brush brWhite = new SolidBrush(Color.White); + Brush brBlack = new SolidBrush(Color.Black); + + //магнитная рельса + if (monoRail.Rail) + { + if (monoRail.SecondСarriage) + { + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 150, 3); + } + else + { + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3); + } + } + + //Второй вагон + if (monoRail.SecondСarriage) + { + //кузов + g.DrawRectangle(pen, _startPosX.Value + 95, _startPosY.Value, 55, 30); + g.FillRectangle(additionalBrush, _startPosX.Value + 96, _startPosY.Value + 1, 54, 29); + //сцепка + g.FillRectangle(brBlack, _startPosX.Value + 85, _startPosY.Value + 5, 10, 23); + //Окно + g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 35, 10); + g.FillRectangle(brBlue, _startPosX.Value + 106, _startPosY.Value + 6, 34, 9); + //Дверь + g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 10, 23); + g.FillRectangle(brWhite, _startPosX.Value + 106, _startPosY.Value + 16, 9, 12); + //Колёса + g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 30, 10, 10); + g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 30, 10, 10); + g.DrawEllipse(pen, _startPosX.Value + 130, _startPosY.Value + 30, 10, 10); + g.DrawEllipse(pen, _startPosX.Value + 140, _startPosY.Value + 30, 10, 10); + } + + switch (monoRail.Wheels) + { + case 3: + g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); + g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); + break; + case 4: + g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); + g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); + g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10); + g.FillEllipse(brWhite, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10); + break; + } + + + } +} \ No newline at end of file diff --git a/ProjectMonorail/DrawingMonorail.cs b/ProjectMonorail/Drawings/DrawingTrain.cs similarity index 63% rename from ProjectMonorail/DrawingMonorail.cs rename to ProjectMonorail/Drawings/DrawingTrain.cs index f9f31a5..512304e 100644 --- a/ProjectMonorail/DrawingMonorail.cs +++ b/ProjectMonorail/Drawings/DrawingTrain.cs @@ -1,20 +1,21 @@ -using System; +using ProjectMonorail.Entities; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectMonorail; +namespace ProjectMonorail.Drawings; /// -/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности /// -public class DrawingMonorail +public class DrawingTrain { /// /// Класс-сущность "монорельс" /// - public EntityMonorail? EntityMonorail { get; private set; } + public EntityTrain? EntityTrain { get; protected set; } /// /// Высота окна @@ -29,12 +30,12 @@ public class DrawingMonorail /// /// Левая координата прорисовки монорельса /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя координата прорисовки монорельса /// - private int? _startPosY; + protected int? _startPosY; /// /// Высота прорисовки монорельса @@ -44,35 +45,68 @@ public class DrawingMonorail /// /// Ширина прорисовки монорельса /// - private readonly int _drawingMonorailWidth = 100; + private readonly int _drawingMonorailWidth = 95; /// - /// Инициализация свойств + /// Координата X объекта /// - /// Скорость - /// Вес - /// Количество колёс - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия магнитного рельса - /// Признак наличия второго вагона - public void Init(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawingMonorailWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawingMonorailHeight; + + /// + /// Пустой конструктор + /// + private DrawingTrain() { - EntityMonorail = new EntityMonorail(); - EntityMonorail.Init(speed, weight, wheels, mainColor, additionalColor, rail, secondCarriage); _pictureHeight = null; _pictureWidth = null; _startPosX = null; _startPosY = null; } + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawingTrain(int speed, double weight, Color mainColor) : this() + { + EntityTrain = new EntityTrain(speed, weight, mainColor); + } + + /// + /// Конструктор для наследников + /// + /// Высота + /// Ширина + protected DrawingTrain(int drawingMonorailHeight, int drawingMonorailWidth) : this() + { + _drawingMonorailHeight = drawingMonorailHeight; + _drawingMonorailWidth = drawingMonorailWidth; + } + /// /// Установка границ поля /// /// Ширина поля /// Высота поля /// - public bool SetPictureSize(int width, int height) + public bool SetPictureSize(int width, int height) { //TODO! if (_drawingMonorailWidth <= width && _drawingMonorailHeight <= height) @@ -133,50 +167,39 @@ public class DrawingMonorail /// true - перемещение выполнено; false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityMonorail == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } - + switch (direction) { //Перемещение влево case DirectionType.Left: - if (_startPosX.Value - EntityMonorail.Step > 0) + if (_startPosX.Value - EntityTrain.Step > 0) { - _startPosX -= (int)EntityMonorail.Step; + _startPosX -= (int)EntityTrain.Step; } return true; //Перемещение вправо case DirectionType.Right: - if (EntityMonorail.SecondСarriage) + if (_startPosX.Value + _drawingMonorailWidth + EntityTrain.Step < _pictureWidth) { - if (_startPosX.Value + 180 + EntityMonorail.Step < _pictureWidth) - { - _startPosX += (int)EntityMonorail.Step; - } - return true; + _startPosX += (int)EntityTrain.Step; } - else - { - if (_startPosX.Value + _drawingMonorailWidth + EntityMonorail.Step < _pictureWidth) - { - _startPosX += (int)EntityMonorail.Step; - } return true; - } //Перемещение вверх case DirectionType.Up: - if (_startPosY.Value - EntityMonorail.Step > 0) + if (_startPosY.Value - EntityTrain.Step > 0) { - _startPosY -= (int)EntityMonorail.Step; + _startPosY -= (int)EntityTrain.Step; } return true; //Перемещение вниз case DirectionType.Down: - if (_startPosY.Value + _drawingMonorailHeight + EntityMonorail.Step < _pictureHeight) + if (_startPosY.Value + _drawingMonorailHeight + EntityTrain.Step < _pictureHeight) { - _startPosY += (int)EntityMonorail.Step; + _startPosY += (int)EntityTrain.Step; } return true; default: return false; @@ -187,16 +210,15 @@ public class DrawingMonorail /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityMonorail == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush mainBrush = new SolidBrush(EntityMonorail.MainColor); - Brush additionalBrush = new SolidBrush(EntityMonorail.AdditionalColor); + Brush mainBrush = new SolidBrush(EntityTrain.MainColor); Brush brBlue = new SolidBrush(Color.LightBlue); Brush brWhite = new SolidBrush(Color.White); Brush brBlack = new SolidBrush(Color.Black); @@ -269,38 +291,6 @@ public class DrawingMonorail g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 7, 10, 21); g.FillRectangle(brWhite, _startPosX.Value + 41, _startPosY.Value + 8, 9, 20); - //магнитная рельса - if (EntityMonorail.Rail) - { - if (EntityMonorail.SecondСarriage) - { - g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 180, 3); - } - else - { - g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3); - } - } - - //Второй вагон - if (EntityMonorail.SecondСarriage) - { - g.DrawRectangle(pen, _startPosX.Value + 95, _startPosY.Value, 80, 30); - g.FillRectangle(additionalBrush, _startPosX.Value + 96, _startPosY.Value + 1, 79, 29); - g.FillRectangle(brBlack, _startPosX.Value + 85, _startPosY.Value + 5, 10, 23); - //Окно - g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 60, 10); - g.FillRectangle(brBlue, _startPosX.Value + 106, _startPosY.Value + 6, 59, 9); - //Дверь - g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 10, 23); - g.FillRectangle(brWhite, _startPosX.Value + 106, _startPosY.Value + 16, 9, 12); - //Колёса - g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 30, 10, 10); - g.DrawEllipse(pen, _startPosX.Value + 115, _startPosY.Value + 30, 10, 10); - g.DrawEllipse(pen, _startPosX.Value + 145, _startPosY.Value + 30, 10, 10); - g.DrawEllipse(pen, _startPosX.Value + 160, _startPosY.Value + 30, 10, 10); - } - //колёса //1, 4 колесо g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 30, 10, 10); @@ -308,19 +298,5 @@ public class DrawingMonorail g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 30, 10, 10); g.FillEllipse(brWhite, _startPosX.Value + 65, _startPosY.Value + 30, 10, 10); - switch (EntityMonorail.Wheels) - { - case 3: - g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); - g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); - break; - case 4: - g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); - g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10); - g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10); - g.FillEllipse(brWhite, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10); - break; - } - } } diff --git a/ProjectMonorail/EntityMonorail.cs b/ProjectMonorail/Entities/EntityMonorail.cs similarity index 55% rename from ProjectMonorail/EntityMonorail.cs rename to ProjectMonorail/Entities/EntityMonorail.cs index 1eba750..c51edda 100644 --- a/ProjectMonorail/EntityMonorail.cs +++ b/ProjectMonorail/Entities/EntityMonorail.cs @@ -4,33 +4,18 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectMonorail; +namespace ProjectMonorail.Entities; /// /// Класс-сущность "Монорельс" /// -public class EntityMonorail +public class EntityMonorail : EntityTrain { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - /// /// Количество колёс /// public int Wheels { get; private set; } - /// - /// Основной цвет - /// - public Color MainColor { get; private set; } - /// /// Дополнительный цвет /// @@ -39,7 +24,7 @@ public class EntityMonorail /// /// Признак наличия магнитного рельса /// - public bool Rail { get; private set; } + public bool Rail { get; private set; } /// /// Признак наличия второго вагона @@ -47,26 +32,15 @@ public class EntityMonorail public bool SecondСarriage { get; private set; } /// - /// Шаг передвижения + /// Конструктор /// - public double Step => Speed * 100 / Weight; - - /// - /// Инициализация полей объекта-класса монорельса - /// - /// Скорость - /// Вес /// Количество колёс - /// Основной цвет /// Дополнительный цвет /// Признак наличия магнитного рельса /// Признак наличия второго вагона - public void Init(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) + public EntityMonorail(int speed, int weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) : base(speed, weight, mainColor) { - Speed = speed; - Weight = weight; Wheels = wheels; - MainColor = mainColor; AdditionalColor = additionalColor; Rail = rail; SecondСarriage = secondCarriage; diff --git a/ProjectMonorail/Entities/EntityTrain.cs b/ProjectMonorail/Entities/EntityTrain.cs new file mode 100644 index 0000000..9330268 --- /dev/null +++ b/ProjectMonorail/Entities/EntityTrain.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMonorail.Entities; + +/// +/// Класс-сущность "Поезд" +/// +public class EntityTrain +{ + /// + /// Скорость + /// + public int Speed { get; private set; } + + /// + /// Вес + /// + public double Weight { get; private set; } + + /// + /// Основной цвет + /// + public Color MainColor { get; private set; } + + /// + /// Шаг передвижения + /// + public double Step => Speed * 100 / Weight; + + /// + /// Конструктор сущности + /// + /// Скорость + /// Вес + /// Основной цвет + public EntityTrain(int speed, double weight, Color mainColor) + { + Speed = speed; + Weight = weight; + MainColor = mainColor; + } +} diff --git a/ProjectMonorail/FormMonorail.Designer.cs b/ProjectMonorail/FormMonorail.Designer.cs index 6f3bdc4..650fda0 100644 --- a/ProjectMonorail/FormMonorail.Designer.cs +++ b/ProjectMonorail/FormMonorail.Designer.cs @@ -34,6 +34,9 @@ buttonLeft = new Button(); buttonUp = new Button(); CreateMonorailButton = new Button(); + CreateTrainButton = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit(); SuspendLayout(); // @@ -41,8 +44,9 @@ // pictureBoxMonorail.Dock = DockStyle.Fill; pictureBoxMonorail.Location = new Point(0, 0); + pictureBoxMonorail.Margin = new Padding(3, 4, 3, 4); pictureBoxMonorail.Name = "pictureBoxMonorail"; - pictureBoxMonorail.Size = new Size(1200, 647); + pictureBoxMonorail.Size = new Size(1142, 596); pictureBoxMonorail.TabIndex = 5; pictureBoxMonorail.TabStop = false; // @@ -50,7 +54,8 @@ // buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.BackgroundImage = Properties.Resources.icons8_стрелка_50вниз; - buttonDown.Location = new Point(1082, 585); + buttonDown.Location = new Point(1024, 530); + buttonDown.Margin = new Padding(3, 4, 3, 4); buttonDown.Name = "buttonDown"; buttonDown.Size = new Size(50, 50); buttonDown.TabIndex = 10; @@ -61,7 +66,8 @@ // buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.BackgroundImage = Properties.Resources.icons8_стрелка_50__1_; - buttonRight.Location = new Point(1138, 585); + buttonRight.Location = new Point(1080, 530); + buttonRight.Margin = new Padding(3, 4, 3, 4); buttonRight.Name = "buttonRight"; buttonRight.Size = new Size(50, 50); buttonRight.TabIndex = 9; @@ -72,7 +78,8 @@ // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.BackgroundImage = Properties.Resources.icons8_стрелка_50влево; - buttonLeft.Location = new Point(1026, 585); + buttonLeft.Location = new Point(968, 530); + buttonLeft.Margin = new Padding(3, 4, 3, 4); buttonLeft.Name = "buttonLeft"; buttonLeft.Size = new Size(50, 50); buttonLeft.TabIndex = 8; @@ -83,7 +90,8 @@ // buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.BackgroundImage = Properties.Resources.icons8_стрелка_50вверх; - buttonUp.Location = new Point(1082, 529); + buttonUp.Location = new Point(1024, 472); + buttonUp.Margin = new Padding(3, 4, 3, 4); buttonUp.Name = "buttonUp"; buttonUp.Size = new Size(50, 50); buttonUp.TabIndex = 7; @@ -93,25 +101,64 @@ // CreateMonorailButton // CreateMonorailButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - CreateMonorailButton.Location = new Point(12, 606); + CreateMonorailButton.Location = new Point(14, 541); + CreateMonorailButton.Margin = new Padding(3, 4, 3, 4); CreateMonorailButton.Name = "CreateMonorailButton"; - CreateMonorailButton.Size = new Size(76, 29); + CreateMonorailButton.Size = new Size(167, 39); CreateMonorailButton.TabIndex = 6; - CreateMonorailButton.Text = "Создать"; + CreateMonorailButton.Text = "Создать монорельс"; CreateMonorailButton.UseVisualStyleBackColor = true; CreateMonorailButton.Click += CreateButton_Click; // + // CreateTrainButton + // + CreateTrainButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + CreateTrainButton.Location = new Point(205, 541); + CreateTrainButton.Margin = new Padding(3, 4, 3, 4); + CreateTrainButton.Name = "CreateTrainButton"; + CreateTrainButton.Size = new Size(167, 39); + CreateTrainButton.TabIndex = 11; + CreateTrainButton.Text = "Создать поезд"; + CreateTrainButton.UseVisualStyleBackColor = true; + CreateTrainButton.Click += CreateTrainButton_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(979, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(151, 28); + comboBoxStrategy.TabIndex = 12; + // + // buttonStrategyStep + // + buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonStrategyStep.Location = new Point(1036, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 13; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormMonorail // - AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1200, 647); + ClientSize = new Size(1142, 596); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(CreateTrainButton); Controls.Add(buttonDown); Controls.Add(buttonRight); Controls.Add(buttonLeft); Controls.Add(buttonUp); Controls.Add(CreateMonorailButton); Controls.Add(pictureBoxMonorail); + Margin = new Padding(3, 4, 3, 4); Name = "FormMonorail"; Text = "FormMonorail"; ((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).EndInit(); @@ -126,5 +173,8 @@ private Button buttonLeft; private Button buttonUp; private Button CreateMonorailButton; + private Button CreateTrainButton; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectMonorail/FormMonorail.cs b/ProjectMonorail/FormMonorail.cs index 3b241f9..8f2ffd4 100644 --- a/ProjectMonorail/FormMonorail.cs +++ b/ProjectMonorail/FormMonorail.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ProjectMonorail.Drawings; +using ProjectMonorail.MovementStrategy; namespace ProjectMonorail { @@ -18,7 +20,12 @@ namespace ProjectMonorail /// /// Поле-объект для прорисовки объекта /// - private DrawingMonorail? _drawingMonorail; + private DrawingTrain? _drawingTrain; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы @@ -26,6 +33,7 @@ namespace ProjectMonorail public FormMonorail() { InitializeComponent(); + _strategy = null; } /// @@ -33,40 +41,65 @@ namespace ProjectMonorail /// private void Draw() { - if (_drawingMonorail == null) + if (_drawingTrain == null) { return; } Bitmap bmp = new(pictureBoxMonorail.Width, pictureBoxMonorail.Height); Graphics gr = Graphics.FromImage(bmp); - _drawingMonorail.DrawTransport(gr); + _drawingTrain.DrawTransport(gr); pictureBoxMonorail.Image = bmp; } + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawingTrain): + _drawingTrain = new DrawingTrain(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(DrawingMonorail): + _drawingTrain = new DrawingMonorail(random.Next(100, 300), random.Next(1000, 3000), random.Next(2, 5), + 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; + } + + _drawingTrain.SetPictureSize(pictureBoxMonorail.Width, pictureBoxMonorail.Height); + _drawingTrain.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + /// - /// Обработка нажатия кнопки "Создать" + /// Обработка нажатия кнопки "Создать монорельс" /// /// /// - private void CreateButton_Click(object sender, EventArgs e) { - Random random = new(); - _drawingMonorail = new DrawingMonorail(); - _drawingMonorail.Init(random.Next(100, 300), random.Next(1000, 3000), random.Next(2, 5), - 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))); - _drawingMonorail.SetPictureSize(pictureBoxMonorail.Width, pictureBoxMonorail.Height); - _drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100)); + CreateObject(nameof(DrawingMonorail)); + } - Draw(); + /// + /// Обработка нажатия кнопки "Создать поезд" + /// + /// + /// + private void CreateTrainButton_Click(object sender, EventArgs e) + { + CreateObject(nameof(DrawingTrain)); } private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawingMonorail == null) + if (_drawingTrain == null) { return; } @@ -76,16 +109,16 @@ namespace ProjectMonorail switch (name) { case "buttonUp": - result = _drawingMonorail.MoveTransport(DirectionType.Up); + result = _drawingTrain.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawingMonorail.MoveTransport(DirectionType.Down); + result = _drawingTrain.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawingMonorail.MoveTransport(DirectionType.Left); + result = _drawingTrain.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawingMonorail.MoveTransport(DirectionType.Right); + result = _drawingTrain.MoveTransport(DirectionType.Right); break; } if (result) @@ -93,5 +126,43 @@ namespace ProjectMonorail Draw(); } } + + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawingTrain == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTrain(_drawingTrain), pictureBoxMonorail.Width, pictureBoxMonorail.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } } diff --git a/ProjectMonorail/MovementStrategy/AbstractStrategy.cs b/ProjectMonorail/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..992e5df --- /dev/null +++ b/ProjectMonorail/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMonorail.MovementStrategy; + +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMovableObjects? _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(IMovableObjects movableObject, int width, int height) + { + if (movableObject == null) + { + _state = StrategyStatus.NotInit; + return; + } + + _state = StrategyStatus.InProgress; + _moveableObject = movableObject; + FieldHeight = height; + FieldWidth = width; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (IsTargetDestination()) + { + _state = StrategyStatus.Finish; + return; + } + + MoveToTarget(); + } + + /// + /// Шаг влево + /// + /// + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + + /// + /// Шаг вверх + /// + /// + protected bool MoveUp() => MoveTo(MovementDirection.Up); + + /// + /// Шаг вправо + /// + /// + protected bool MoveRight() => MoveTo(MovementDirection.Right); + + /// + /// Шаг вниз + /// + /// + 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 IsTargetDestination(); + + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} diff --git a/ProjectMonorail/MovementStrategy/IMovableObjects.cs b/ProjectMonorail/MovementStrategy/IMovableObjects.cs new file mode 100644 index 0000000..51578d1 --- /dev/null +++ b/ProjectMonorail/MovementStrategy/IMovableObjects.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMonorail.MovementStrategy; + +public interface IMovableObjects +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в заданном направлении + /// + /// Направление + /// + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectMonorail/MovementStrategy/MoveToBorder.cs b/ProjectMonorail/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..cfe9a92 --- /dev/null +++ b/ProjectMonorail/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMonorail.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestination() + { + 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()) + { + MoveRight(); + } + int diffy = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffy) > GetStep()) + { + MoveDown(); + } + } +} diff --git a/ProjectMonorail/MovementStrategy/MoveToCenter.cs b/ProjectMonorail/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..b3ca540 --- /dev/null +++ b/ProjectMonorail/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMonorail.MovementStrategy; + +public class MoveToCenter : AbstractStrategy +{ + protected override bool IsTargetDestination() + { + 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/ProjectMonorail/MovementStrategy/MoveableTrain.cs b/ProjectMonorail/MovementStrategy/MoveableTrain.cs new file mode 100644 index 0000000..54dfce1 --- /dev/null +++ b/ProjectMonorail/MovementStrategy/MoveableTrain.cs @@ -0,0 +1,63 @@ +using ProjectMonorail.Drawings; + +namespace ProjectMonorail.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием DrawingTrain +/// +public class MoveableTrain : IMovableObjects +{ + /// + /// Поле-объект класса DrawingTrain или его наследника + /// + private readonly DrawingTrain? _train = null; + + /// + /// Конструктор + /// + /// Объект класса DrawingTrain + public MoveableTrain(DrawingTrain train) + { + _train = train; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if(_train == null || _train.EntityTrain == null || !_train.GetPosX.HasValue || !_train.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_train.GetPosX.Value, _train.GetPosY.Value, _train.GetWidth, _train.GetHeight); + } + } + + public int GetStep => (int)(_train?.EntityTrain?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_train == null || _train.EntityTrain == null) + { + return false; + } + return _train.MoveTransport(GetDirectionType(direction)); + } + + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + private static DirectionType GetDirectionType(MovementDirection direction) + { + return direction switch + { + MovementDirection.Up => DirectionType.Up, + MovementDirection.Down => DirectionType.Down, + MovementDirection.Left => DirectionType.Left, + MovementDirection.Right => DirectionType.Right, + _ => DirectionType.Unknown, + }; + } +} diff --git a/ProjectMonorail/MovementStrategy/MovementDirection.cs b/ProjectMonorail/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..e9a257f --- /dev/null +++ b/ProjectMonorail/MovementStrategy/MovementDirection.cs @@ -0,0 +1,27 @@ +namespace ProjectMonorail.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4, +} diff --git a/ProjectMonorail/MovementStrategy/ObjectParameters.cs b/ProjectMonorail/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..fd3228c --- /dev/null +++ b/ProjectMonorail/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMonorail.MovementStrategy; + +public class ObjectParameters +{ + /// + /// Координата X + /// + private readonly int _x; + + /// + /// Координата Y + /// + private readonly int _y; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TobBorder => _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; + _height = height; + _width = width; + } +} diff --git a/ProjectMonorail/MovementStrategy/StrategyStatus.cs b/ProjectMonorail/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..28ffaef --- /dev/null +++ b/ProjectMonorail/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace ProjectMonorail.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Всё готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} diff --git a/WindowsFormsApp1/App.config b/WindowsFormsApp1/App.config index 56efbc7..48920e8 100644 --- a/WindowsFormsApp1/App.config +++ b/WindowsFormsApp1/App.config @@ -1,5 +1,4 @@ - - + -- 2.25.1