From d1cc8a693a9618980ca38b7b7e4abe53b8cb5766 Mon Sep 17 00:00:00 2001 From: Aidar Date: Fri, 5 Apr 2024 18:55:05 +0400 Subject: [PATCH] =?UTF-8?q?=20=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 | 10 +- .../ProjectLiner/Drawnings/DrawningLiner.cs | 69 +++++++ .../DrawningSmallLiner.cs} | 182 +++++++++--------- .../{ => Entities}/EntityLiner.cs | 33 +--- .../ProjectLiner/Entities/EntitySmallLiner.cs | 40 ++++ .../ProjectLiner/FormLiner.Designer.cs | 64 ++++-- ProjectLiner/ProjectLiner/FormLiner.cs | 126 +++++++++--- .../MovementStrategy/AbstractStrategy.cs | 136 +++++++++++++ .../MovementStrategy/IMoveableObject.cs | 24 +++ .../MovementStrategy/MoveToBorder.cs | 38 ++++ .../MovementStrategy/MoveToCenter.cs | 53 +++++ .../MovementStrategy/MoveableLiner.cs | 79 ++++++++ .../MovementStrategy/MovementDirection.cs | 24 +++ .../MovementStrategy/ObjectParameters.cs | 69 +++++++ .../MovementStrategy/StrategyStatus.cs | 20 ++ 15 files changed, 813 insertions(+), 154 deletions(-) rename ProjectLiner/ProjectLiner/{ => Drawnings}/DirectionType.cs (72%) create mode 100644 ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs rename ProjectLiner/ProjectLiner/{DrawningLiner.cs => Drawnings/DrawningSmallLiner.cs} (57%) rename ProjectLiner/ProjectLiner/{ => Entities}/EntityLiner.cs (55%) create mode 100644 ProjectLiner/ProjectLiner/Entities/EntitySmallLiner.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/IMoveableObject.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/MoveableLiner.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/MovementDirection.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectLiner/ProjectLiner/MovementStrategy/StrategyStatus.cs diff --git a/ProjectLiner/ProjectLiner/DirectionType.cs b/ProjectLiner/ProjectLiner/Drawnings/DirectionType.cs similarity index 72% rename from ProjectLiner/ProjectLiner/DirectionType.cs rename to ProjectLiner/ProjectLiner/Drawnings/DirectionType.cs index 17b4361..dc64678 100644 --- a/ProjectLiner/ProjectLiner/DirectionType.cs +++ b/ProjectLiner/ProjectLiner/Drawnings/DirectionType.cs @@ -1,22 +1,30 @@ -namespace ProjectLiner; +namespace ProjectLiner.Drawnings; /// /// Направление передвижения /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// Up = 1, + /// /// Вниз /// Down = 2, + /// /// Влево /// Left = 3, + /// /// Вправо /// diff --git a/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs new file mode 100644 index 0000000..26b123c --- /dev/null +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs @@ -0,0 +1,69 @@ +using ProjectLiner.Entities; + +namespace ProjectLiner.Drawnings; + +/// +/// Класс-прорисовка сущности "Лайнер" +/// +public class DrawningLiner : DrawningSmallLiner +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Наличие второй палубы + /// Наличие басейна + public DrawningLiner(int speed, double weight, Color bodyColor, Color additionalColor, bool secondDeck, bool pool) : base(150, 65) + { + EntitySmallLiner = new EntityLiner(speed, weight, bodyColor, additionalColor, secondDeck, pool); + } + + public override void DrawTransport(Graphics g) + { + if (EntitySmallLiner == null || EntitySmallLiner is not EntityLiner Liner || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black, 2); + Brush br = new SolidBrush(Liner.BodyColor); + Brush additionalBrush = new SolidBrush(Liner.AdditionalColor); + + // Вторая палуба + if (Liner.SecondDeck) + { + g.FillPolygon(additionalBrush, new[] + { + new Point(_startPosX.Value + 20, _startPosY.Value + 15), + new Point(_startPosX.Value + 30, _startPosY.Value + 0), + new Point(_startPosX.Value + 95, _startPosY.Value + 0), + new Point(_startPosX.Value + 100, _startPosY.Value + 15) + }); + g.DrawPolygon(pen, new[] + { + new Point(_startPosX.Value + 20, _startPosY.Value + 15), + new Point(_startPosX.Value + 30, _startPosY.Value + 0), + new Point(_startPosX.Value + 95, _startPosY.Value + 0), + new Point(_startPosX.Value + 100, _startPosY.Value + 15) + }); + + } + + // Бассейн + if (Liner.Pool) + { + g.FillRectangle(additionalBrush, _startPosX.Value + 110, _startPosY.Value + 25, 30, 5); + g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + 25, 30, 5); + g.DrawArc(pen, _startPosX.Value + 135, _startPosY.Value + 20, 8, 8, 180, 180); + g.DrawLine(pen, _startPosX.Value + 143, _startPosY.Value + 25, _startPosX.Value + 143, _startPosY.Value + 30); + } + + // Основные элементы + _startPosY += 15; + base.DrawTransport(g); + _startPosY -= 15; + } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/DrawningLiner.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningSmallLiner.cs similarity index 57% rename from ProjectLiner/ProjectLiner/DrawningLiner.cs rename to ProjectLiner/ProjectLiner/Drawnings/DrawningSmallLiner.cs index 3171ad2..27d63a9 100644 --- a/ProjectLiner/ProjectLiner/DrawningLiner.cs +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningSmallLiner.cs @@ -1,14 +1,13 @@ -namespace ProjectLiner; +using ProjectLiner.Entities; -/// -/// Класс-прорисовка сущности "Лайнер" -/// -public class DrawningLiner +namespace ProjectLiner.Drawnings; + +public class DrawningSmallLiner { /// - /// Класс-сущность "Лайнер" + /// Класс-сущность "Маленький Лайнер" /// - public EntityLiner? EntityLiner { get; private set; } + public EntitySmallLiner? EntitySmallLiner { get; protected set; } /// /// Ширина окна @@ -23,12 +22,12 @@ public class DrawningLiner /// /// Левая координата прорисовки сущности "Лайнер" /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхнаяя координата прорисовки сущности "Лайнер" /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки сущности "Лайнер" @@ -36,29 +35,64 @@ public class DrawningLiner private readonly int _drawningLinerWidth = 150; /// - /// Высота сущности "Лайнер" + /// Высота прорисовки сущности "Лайнер" /// - private readonly int _drawningLinerHeight = 65; + private readonly int _drawningLinerHeight = 50; /// - /// Инициализация свойств + /// Координата X объекта /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Наличие второй палубы - /// Наличие басейна - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool secondDeck, bool pool) + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLinerWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningLinerHeight; + + /// + /// Пустой конструктор + /// + private DrawningSmallLiner() { - EntityLiner = new EntityLiner(); - EntityLiner.Init(speed, weight, bodyColor, additionalColor, secondDeck, pool); + _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningSmallLiner(int speed, double weight, Color bodyColor) : this() + { + EntitySmallLiner = new EntitySmallLiner(speed, weight, bodyColor); + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки сущности "Маленький Лайнер" + /// Высота прорисовки сущности "Маленький Лайнер" + protected DrawningSmallLiner(int drawningLinerWidth, int drawningLinerHeight) : this() + { + _drawningLinerWidth = drawningLinerWidth; + _drawningLinerHeight = drawningLinerHeight; + } + /// /// Установка границ поля /// @@ -73,8 +107,6 @@ public class DrawningLiner } _pictureWidth = width; _pictureHeight = height; - if (_startPosX.HasValue && _startPosX + _drawningLinerWidth > width) _startPosX = _pictureWidth - _drawningLinerWidth; - if (_startPosY.HasValue && _startPosY + _drawningLinerHeight > height) _startPosY = _pictureHeight - _drawningLinerHeight; return true; } @@ -116,7 +148,7 @@ public class DrawningLiner /// true - перемещение выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityLiner == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntitySmallLiner == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } @@ -124,34 +156,31 @@ public class DrawningLiner { // Влево case DirectionType.Left: - if (_startPosX.Value - EntityLiner.Step > 0) + if (_startPosX.Value - EntitySmallLiner.Step > 0) { - _startPosX -= (int)EntityLiner.Step; + _startPosX -= (int)EntitySmallLiner.Step; } return true; - // Вверх case DirectionType.Up: - if (_startPosY.Value - EntityLiner.Step > 0) + if (_startPosY.Value - EntitySmallLiner.Step > 0) { - _startPosY -= (int)EntityLiner.Step; + _startPosY -= (int)EntitySmallLiner.Step; } return true; - // Вправо case DirectionType.Right: - if (_startPosX.Value + _drawningLinerWidth + EntityLiner.Step < _pictureWidth.Value) + if (_startPosX.Value + _drawningLinerWidth + EntitySmallLiner.Step < _pictureWidth.Value) { - _startPosX += (int)EntityLiner.Step; + _startPosX += (int)EntitySmallLiner.Step; } return true; - // Вниз case DirectionType.Down: - if (_startPosY.Value + _drawningLinerHeight + EntityLiner.Step < _pictureHeight.Value) + if (_startPosY.Value + _drawningLinerHeight + EntitySmallLiner.Step < _pictureHeight.Value) { - _startPosY += (int)EntityLiner.Step; + _startPosY += (int)EntitySmallLiner.Step; } return true; default: @@ -163,79 +192,50 @@ public class DrawningLiner /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityLiner == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntitySmallLiner == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black, 2); - Brush br = new SolidBrush(EntityLiner.BodyColor); - Brush additionalBrush = new SolidBrush(EntityLiner.AdditionalColor); - - // Вторая палуба - if (EntityLiner.SecondDeck) - { - g.FillPolygon(additionalBrush, new[] - { - new Point(_startPosX.Value + 20, _startPosY.Value + 15), - new Point(_startPosX.Value + 30, _startPosY.Value + 0), - new Point(_startPosX.Value + 95, _startPosY.Value + 0), - new Point(_startPosX.Value + 100, _startPosY.Value + 15) - }); - g.DrawPolygon(pen, new[] - { - new Point(_startPosX.Value + 20, _startPosY.Value + 15), - new Point(_startPosX.Value + 30, _startPosY.Value + 0), - new Point(_startPosX.Value + 95, _startPosY.Value + 0), - new Point(_startPosX.Value + 100, _startPosY.Value + 15) - }); - - } - - // Бассейн - if (EntityLiner.Pool) - { - g.FillRectangle(additionalBrush, _startPosX.Value + 110, _startPosY.Value + 25, 30, 5); - g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + 25, 30, 5); - g.DrawArc(pen, _startPosX.Value + 135, _startPosY.Value + 20, 8, 8, 180, 180); - g.DrawLine(pen, _startPosX.Value + 143, _startPosY.Value + 25, _startPosX.Value + 143, _startPosY.Value + 30); - } + Brush br = new SolidBrush(EntitySmallLiner.BodyColor); // Корпус и палуба Лайнера g.FillPolygon(br, new[] { - new Point(_startPosX.Value + 0, _startPosY.Value + 30), - new Point(_startPosX.Value + 150, _startPosY.Value + 30), - new Point(_startPosX.Value + 120, _startPosY.Value + 65), - new Point(_startPosX.Value + 30, _startPosY.Value + 65) + new Point(_startPosX.Value + 0, _startPosY.Value + 15), + new Point(_startPosX.Value + 150, _startPosY.Value + 15), + new Point(_startPosX.Value + 120, _startPosY.Value + 50), + new Point(_startPosX.Value + 30, _startPosY.Value + 50) }); g.FillPolygon(br, new[] { - new Point(_startPosX.Value + 5, _startPosY.Value + 30), - new Point(_startPosX.Value + 15, _startPosY.Value + 15), - new Point(_startPosX.Value + 100, _startPosY.Value + 15), - new Point(_startPosX.Value + 105, _startPosY.Value + 30) + new Point(_startPosX.Value + 5, _startPosY.Value + 15), + new Point(_startPosX.Value + 15, _startPosY.Value + 0), + new Point(_startPosX.Value + 100, _startPosY.Value + 0), + new Point(_startPosX.Value + 105, _startPosY.Value + 15) + }); + + g.DrawPolygon(pen, new[] + { + new Point(_startPosX.Value + 0, _startPosY.Value + 15), + new Point(_startPosX.Value + 150, _startPosY.Value + 15), + new Point(_startPosX.Value + 120, _startPosY.Value + 50), + new Point(_startPosX.Value + 30, _startPosY.Value + 50) }); g.DrawPolygon(pen, new[] { - new Point(_startPosX.Value + 0, _startPosY.Value + 30), - new Point(_startPosX.Value + 150, _startPosY.Value + 30), - new Point(_startPosX.Value + 120, _startPosY.Value + 65), - new Point(_startPosX.Value + 30, _startPosY.Value + 65) - }); - g.DrawPolygon(pen, new[] - { - new Point(_startPosX.Value + 5, _startPosY.Value + 30), - new Point(_startPosX.Value + 15, _startPosY.Value + 15), - new Point(_startPosX.Value + 100, _startPosY.Value + 15), - new Point(_startPosX.Value + 105, _startPosY.Value + 30) + new Point(_startPosX.Value + 5, _startPosY.Value + 15), + new Point(_startPosX.Value + 15, _startPosY.Value + 0), + new Point(_startPosX.Value + 100, _startPosY.Value + 0), + new Point(_startPosX.Value + 105, _startPosY.Value + 15) }); // Якорь - g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 33, _startPosX.Value + 30, _startPosY.Value + 45); - g.DrawLine(pen, _startPosX.Value + 27, _startPosY.Value + 36, _startPosX.Value + 33, _startPosY.Value + 36); - g.DrawLine(pen, _startPosX.Value + 25, _startPosY.Value + 40, _startPosX.Value + 30, _startPosY.Value + 45); - g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 45, _startPosX.Value + 35, _startPosY.Value + 40); + g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 18, _startPosX.Value + 30, _startPosY.Value + 30); + g.DrawLine(pen, _startPosX.Value + 27, _startPosY.Value + 21, _startPosX.Value + 33, _startPosY.Value + 21); + g.DrawLine(pen, _startPosX.Value + 25, _startPosY.Value + 25, _startPosX.Value + 30, _startPosY.Value + 30); + g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 30, _startPosX.Value + 35, _startPosY.Value + 25); } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/EntityLiner.cs b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs similarity index 55% rename from ProjectLiner/ProjectLiner/EntityLiner.cs rename to ProjectLiner/ProjectLiner/Entities/EntityLiner.cs index 444ed7b..35426c8 100644 --- a/ProjectLiner/ProjectLiner/EntityLiner.cs +++ b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs @@ -1,25 +1,10 @@ -namespace ProjectLiner; +namespace ProjectLiner.Entities; /// /// Класс-сущность "Лайнер" /// -public class EntityLiner +public class EntityLiner : EntitySmallLiner { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// /// Дополнительный цвет /// @@ -36,24 +21,16 @@ public class EntityLiner public bool Pool { get; private set; } /// - /// Шаг перемещения сущности "Лайнер" - /// - public double Step => Speed * 100 / Weight; - - /// - /// Инициализация полей объекта класса "Лайнер" + /// Конструктор /// /// Скорость /// Вес /// Основой цвет /// Дополнительный цвет /// Наличие второй палубы - /// Наличие бассейна - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool secondDeck, bool pool) + /// Наличие бассейна + public EntityLiner(int speed, double weight, Color bodyColor, Color additionalColor, bool secondDeck, bool pool) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; SecondDeck = secondDeck; Pool = pool; diff --git a/ProjectLiner/ProjectLiner/Entities/EntitySmallLiner.cs b/ProjectLiner/ProjectLiner/Entities/EntitySmallLiner.cs new file mode 100644 index 0000000..e98142e --- /dev/null +++ b/ProjectLiner/ProjectLiner/Entities/EntitySmallLiner.cs @@ -0,0 +1,40 @@ +namespace ProjectLiner.Entities; + +/// +/// Класс-сущность "Маленький Лайнер" +/// +public class EntitySmallLiner +{ + /// + /// Скорость + /// + 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 EntitySmallLiner(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLiner.Designer.cs b/ProjectLiner/ProjectLiner/FormLiner.Designer.cs index bb87f5d..0d6ebfc 100644 --- a/ProjectLiner/ProjectLiner/FormLiner.Designer.cs +++ b/ProjectLiner/ProjectLiner/FormLiner.Designer.cs @@ -29,11 +29,14 @@ private void InitializeComponent() { pictureBoxLiner = new PictureBox(); - buttonCreate = new Button(); + buttonCreateSmallLiner = new Button(); buttonRight = new Button(); buttonDown = new Button(); buttonLeft = new Button(); buttonUp = new Button(); + buttonCreateLiner = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxLiner).BeginInit(); SuspendLayout(); // @@ -46,16 +49,16 @@ pictureBoxLiner.TabIndex = 0; pictureBoxLiner.TabStop = false; // - // buttonCreate + // buttonCreateSmallLiner // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 426); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(75, 23); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += ButtonCreate_Click; + buttonCreateSmallLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateSmallLiner.Location = new Point(12, 426); + buttonCreateSmallLiner.Name = "buttonCreateSmallLiner"; + buttonCreateSmallLiner.Size = new Size(154, 23); + buttonCreateSmallLiner.TabIndex = 1; + buttonCreateSmallLiner.Text = "Создать малый лайнер"; + buttonCreateSmallLiner.UseVisualStyleBackColor = true; + buttonCreateSmallLiner.Click += ButtonCreateSmallLiner_Click; // // buttonRight // @@ -105,16 +108,50 @@ buttonUp.UseVisualStyleBackColor = true; buttonUp.Click += ButtonMove_Click; // + // buttonCreateLiner + // + buttonCreateLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateLiner.Location = new Point(172, 426); + buttonCreateLiner.Name = "buttonCreateLiner"; + buttonCreateLiner.Size = new Size(154, 23); + buttonCreateLiner.TabIndex = 6; + buttonCreateLiner.Text = "Создать лайнер"; + buttonCreateLiner.UseVisualStyleBackColor = true; + buttonCreateLiner.Click += ButtonCreateLiner_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(751, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(797, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormLiner // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(884, 461); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateLiner); Controls.Add(buttonUp); Controls.Add(buttonLeft); Controls.Add(buttonDown); Controls.Add(buttonRight); - Controls.Add(buttonCreate); + Controls.Add(buttonCreateSmallLiner); Controls.Add(pictureBoxLiner); Name = "FormLiner"; StartPosition = FormStartPosition.CenterScreen; @@ -126,10 +163,13 @@ #endregion private PictureBox pictureBoxLiner; - private Button buttonCreate; + private Button buttonCreateSmallLiner; private Button buttonRight; private Button buttonDown; private Button buttonLeft; private Button buttonUp; + private Button buttonCreateLiner; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLiner.cs b/ProjectLiner/ProjectLiner/FormLiner.cs index 248a90e..ac0ee1b 100644 --- a/ProjectLiner/ProjectLiner/FormLiner.cs +++ b/ProjectLiner/ProjectLiner/FormLiner.cs @@ -1,4 +1,7 @@ -namespace ProjectLiner; +using ProjectLiner.Drawnings; +using ProjectLiner.MovementStrategy; + +namespace ProjectLiner; /// /// Форма работы с объектом "Лайнер" @@ -8,7 +11,12 @@ public partial class FormLiner : Form /// /// Поле-объект для прорисовки объекта /// - private DrawningLiner? _drawningLiner; + private DrawningSmallLiner? _drawningSmallLiner; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы @@ -16,6 +24,7 @@ public partial class FormLiner : Form public FormLiner() { InitializeComponent(); + _strategy = null; } /// @@ -23,35 +32,62 @@ public partial class FormLiner : Form /// private void Draw() { - if (_drawningLiner == null) + if (_drawningSmallLiner == null) { return; } Bitmap bmp = new(pictureBoxLiner.Width, pictureBoxLiner.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningLiner.DrawTransport(gr); + _drawningSmallLiner.DrawTransport(gr); pictureBoxLiner.Image = bmp; } /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningSmallLiner): + _drawningSmallLiner = new DrawningSmallLiner( + 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(DrawningLiner): + _drawningSmallLiner = new DrawningLiner( + 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; + } + _drawningSmallLiner.SetPictureSize(pictureBoxLiner.Width, pictureBoxLiner.Height); + _drawningSmallLiner.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать лайнер" /// /// /// - private void ButtonCreate_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningLiner = new DrawningLiner(); - _drawningLiner.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))); - _drawningLiner.SetPictureSize(pictureBoxLiner.Width, pictureBoxLiner.Height); - _drawningLiner.SetPosition(random.Next(10, 100), random.Next(10, 100)); + private void ButtonCreateLiner_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLiner)); - Draw(); - } + /// + /// Обработка нажатия кнопки "Создать малый лайнер" + /// + /// + /// + private void ButtonCreateSmallLiner_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSmallLiner)); /// /// Обработка нажатия кнопок навигации движения @@ -60,7 +96,7 @@ public partial class FormLiner : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningLiner == null) + if (_drawningSmallLiner == null) { return; } @@ -69,16 +105,16 @@ public partial class FormLiner : Form switch (name) { case "buttonUp": - result = _drawningLiner.MoveTransport(DirectionType.Up); + result = _drawningSmallLiner.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningLiner.MoveTransport(DirectionType.Down); + result = _drawningSmallLiner.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningLiner.MoveTransport(DirectionType.Left); + result = _drawningSmallLiner.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningLiner.MoveTransport(DirectionType.Right); + result = _drawningSmallLiner.MoveTransport(DirectionType.Right); break; } if (result) @@ -86,4 +122,50 @@ public partial class FormLiner : Form Draw(); } } + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningSmallLiner == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) + { + return; + } + + _strategy.SetData(new MoveableLiner(_drawningSmallLiner), + pictureBoxLiner.Width, pictureBoxLiner.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/ProjectLiner/ProjectLiner/MovementStrategy/AbstractStrategy.cs b/ProjectLiner/ProjectLiner/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..1a69f7e --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,136 @@ +namespace ProjectLiner.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/ProjectLiner/ProjectLiner/MovementStrategy/IMoveableObject.cs b/ProjectLiner/ProjectLiner/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..cef1345 --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace ProjectLiner.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/ProjectLiner/ProjectLiner/MovementStrategy/MoveToBorder.cs b/ProjectLiner/ProjectLiner/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..9f2507a --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,38 @@ +namespace ProjectLiner.MovementStrategy; + +/// +/// Стратегия перемещения объекта в угол экрана +/// +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + int diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) MoveLeft(); + else MoveRight(); + } + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) MoveUp(); + else MoveDown(); + } + } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/MovementStrategy/MoveToCenter.cs b/ProjectLiner/ProjectLiner/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..fe0bee7 --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,53 @@ +namespace ProjectLiner.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/ProjectLiner/ProjectLiner/MovementStrategy/MoveableLiner.cs b/ProjectLiner/ProjectLiner/MovementStrategy/MoveableLiner.cs new file mode 100644 index 0000000..b3e7f58 --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/MoveableLiner.cs @@ -0,0 +1,79 @@ +using ProjectLiner.Drawnings; + +namespace ProjectLiner.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием drawningSmallLiner +/// +public class MoveableLiner : IMoveableObject +{ + /// + /// Поле-объект класса DrawningSmallLiner или его наследника + /// + private readonly DrawningSmallLiner? _liner = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningSmallLiner + public MoveableLiner(DrawningSmallLiner liner) + { + _liner = liner; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_liner == null || _liner.EntitySmallLiner == null || + !_liner.GetPosX.HasValue || !_liner.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_liner.GetPosX.Value, + _liner.GetPosY.Value, _liner.GetWidth, _liner.GetHeight); + } + } + + public int GetStep => (int)(_liner?.EntitySmallLiner?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_liner == null || _liner.EntitySmallLiner == null) + { + return false; + } + return _liner.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, + }; + } + + /*public MoveableLiner(DrawningSmallLiner drawningSmallLiner) + { + _drawningSmallLiner = drawningSmallLiner; + } + + public ObjectParameters? GetObjectPosition => throw new NotImplementedException(); + + public int GetStep => throw new NotImplementedException(); + + public bool TryMoveObject(MovementDirection direction) + { + throw new NotImplementedException(); + }*/ +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/MovementStrategy/MovementDirection.cs b/ProjectLiner/ProjectLiner/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..fa5cb99 --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/MovementDirection.cs @@ -0,0 +1,24 @@ +namespace ProjectLiner.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/MovementStrategy/ObjectParameters.cs b/ProjectLiner/ProjectLiner/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..601600f --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,69 @@ +namespace ProjectLiner.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/ProjectLiner/ProjectLiner/MovementStrategy/StrategyStatus.cs b/ProjectLiner/ProjectLiner/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..d9ef09c --- /dev/null +++ b/ProjectLiner/ProjectLiner/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,20 @@ +namespace ProjectLiner.MovementStrategy; + +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish + +} \ No newline at end of file