diff --git a/Monorail/Monorail/DirectionType.cs b/Monorail/Monorail/Drawnings/DirectionType.cs similarity index 78% rename from Monorail/Monorail/DirectionType.cs rename to Monorail/Monorail/Drawnings/DirectionType.cs index 3fb9deb..d8d9e8b 100644 --- a/Monorail/Monorail/DirectionType.cs +++ b/Monorail/Monorail/Drawnings/DirectionType.cs @@ -4,12 +4,17 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace monorail; +namespace Monorail.Drawnings; /// /// Направление перемещения /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/Monorail/Monorail/DrawningMonorail.cs b/Monorail/Monorail/Drawnings/DrawningLocomotive.cs similarity index 77% rename from Monorail/Monorail/DrawningMonorail.cs rename to Monorail/Monorail/Drawnings/DrawningLocomotive.cs index c3bba62..85335db 100644 --- a/Monorail/Monorail/DrawningMonorail.cs +++ b/Monorail/Monorail/Drawnings/DrawningLocomotive.cs @@ -1,15 +1,21 @@ - +using Monorail.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.Drawnings; -namespace monorail; /// -/// Класс отвечающий за прорисовку и перемещение объекта-сущности +/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности /// -public class DrawningMonorail +public class DrawningLocomotive { /// /// Класс-сущность (объект) /// - public EntityMonorail? EntityMonorail { get; private set; } + public EntityLocomotive? EntityLocomotive { get; protected set; } /// /// Ширина окна @@ -24,42 +30,84 @@ public class DrawningMonorail /// /// Левая координата прорисовки монорельса /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя координата прорисовки монорельса /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки монорельса (размер объекта) /// - private readonly int _drawningMonorailWidth = 95; + private readonly int _drawningMonorailWidth = 90; /// /// Высота прорисовки монорельса (размер объекта) /// private readonly int _drawingMonorailHeight = 40; /// - /// Инициализация свойства + /// Координата X объекта /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// магнитный рельс - /// Вторая кабинка в задней части + public int? GetPosX => _startPosX; - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool magneticRail, bool secondCabin) + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningMonorailWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawingMonorailHeight; + + + + + /// + /// Пустой конструктор + /// + private DrawningLocomotive() { - EntityMonorail = new EntityMonorail(); - EntityMonorail.Init(speed, weight, bodyColor, additionalColor, magneticRail, secondCabin); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; + } + + + /// + /// Конструтор + /// + /// Скорость + /// Вес + /// Основной цвет + + + public DrawningLocomotive(int speed, double weight, Color bodyColor) : this() + { + EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor); } + /// + /// Конструтор для наследников + /// + /// Ширина прорисовки монорельса (размер объекта) + /// Высота прорисовки монорельса (размер объекта) + + + protected DrawningLocomotive(int drawningMonorailWidth, int drawingMonorailHeight) : this() + { + _drawningMonorailWidth = drawningMonorailWidth; + _drawingMonorailHeight = drawingMonorailHeight; + } + + /// /// Установка границ поля /// @@ -141,7 +189,7 @@ public class DrawningMonorail /// true - перемещение выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityMonorail == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } @@ -149,33 +197,33 @@ public class DrawningMonorail { //влево case DirectionType.Left: - if (_startPosX.Value - EntityMonorail.Step > 0) + if (_startPosX.Value - EntityLocomotive.Step > 0) { - _startPosX -= (int)EntityMonorail.Step; + _startPosX -= (int)EntityLocomotive.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityMonorail.Step > 0) + if (_startPosY.Value - EntityLocomotive.Step > 0) { - _startPosY -= (int)EntityMonorail.Step; + _startPosY -= (int)EntityLocomotive.Step; } return true; // вправо case DirectionType.Right: // TODO прописать логику сдвига в право - if (_startPosX.Value + EntityMonorail.Step + _drawningMonorailWidth < _pictureWidth) + if (_startPosX.Value + EntityLocomotive.Step + _drawningMonorailWidth < _pictureWidth) { - _startPosX += (int)EntityMonorail.Step; + _startPosX += (int)EntityLocomotive.Step; } return true; //вниз case DirectionType.Down: //TODO прописать логику сдвига в вниз - if (_startPosY.Value + EntityMonorail.Step + _drawingMonorailHeight < _pictureHeight) + if (_startPosY.Value + EntityLocomotive.Step + _drawingMonorailHeight < _pictureHeight) { - _startPosY += (int)EntityMonorail.Step; + _startPosY += (int)EntityLocomotive.Step; } return true; default: @@ -189,43 +237,20 @@ public class DrawningMonorail /// /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityMonorail == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new SolidBrush(EntityMonorail.AdditionalColor); - //магнитная рельса - if (EntityMonorail.MagneticRail) - { - g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3); - } - - //вторая часть монорельса - - if (EntityMonorail.SecondCabin) - { - Point[] points_second_cabin = { - new Point(_startPosX.Value + 85, _startPosY.Value), - new Point(_startPosX.Value + 95, _startPosY.Value + 15), - new Point(_startPosX.Value + 95, _startPosY.Value + 30), - new Point(_startPosX.Value + 85, _startPosY.Value + 30), - new Point(_startPosX.Value + 85, _startPosY.Value + 15), - new Point(_startPosX.Value + 95, _startPosY.Value + 15) - - }; - g.DrawPolygon(pen, points_second_cabin); - g.FillPolygon(additionalBrush, points_second_cabin); - - } + //границы Монорельса - Brush br = new SolidBrush(EntityMonorail.BodyColor); + Brush br = new SolidBrush(EntityLocomotive.BodyColor); g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 15, 80, 15); Point[] points1 = { new Point(_startPosX.Value + 15, _startPosY.Value), @@ -244,7 +269,7 @@ public class DrawningMonorail new Point(_startPosX.Value + 84, _startPosY.Value + 1), new Point(_startPosX.Value + 84, _startPosY.Value + 14), new Point(_startPosX.Value + 6, _startPosY.Value + 14) - }; + }; g.FillPolygon(br, points2); @@ -266,7 +291,7 @@ public class DrawningMonorail //1-ый держатель Point[] points_cart1 = { - new Point(_startPosX.Value, _startPosY.Value + 35), + new Point(_startPosX.Value + 5, _startPosY.Value + 30), new Point(_startPosX.Value + 15, _startPosY.Value + 35), new Point(_startPosX.Value + 15, _startPosY.Value + 30), new Point(_startPosX.Value + 5, _startPosY.Value + 30) @@ -330,4 +355,4 @@ public class DrawningMonorail } -} \ No newline at end of file +} diff --git a/Monorail/Monorail/Drawnings/DrawningMonorail.cs b/Monorail/Monorail/Drawnings/DrawningMonorail.cs new file mode 100644 index 0000000..755ba77 --- /dev/null +++ b/Monorail/Monorail/Drawnings/DrawningMonorail.cs @@ -0,0 +1,62 @@ +using Monorail.Entities; + +namespace Monorail.Drawnings; +/// +/// Класс отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawningMonorail : DrawningLocomotive +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// магнитный рельс + /// Вторая кабинка в задней части + + public DrawningMonorail(int speed, double weight, Color bodyColor, Color additionalColor, bool magneticRail, bool secondCabin) : base(90, 40) + { + EntityLocomotive = new EntityMonorail(speed, weight, bodyColor, additionalColor, magneticRail, secondCabin); + } + + public override void DrawTransport(Graphics g) + { + if (EntityLocomotive == null || EntityLocomotive is not EntityMonorail monorail || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(monorail.AdditionalColor); + + //магнитная рельса + if (monorail.MagneticRail) + { + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3); + } + + //вторая часть монорельса + + if (monorail.SecondCabin) + { + Point[] points_second_cabin = { + new Point(_startPosX.Value + 85, _startPosY.Value), + new Point(_startPosX.Value + 95, _startPosY.Value + 15), + new Point(_startPosX.Value + 95, _startPosY.Value + 30), + new Point(_startPosX.Value + 85, _startPosY.Value + 30), + new Point(_startPosX.Value + 85, _startPosY.Value + 15), + new Point(_startPosX.Value + 95, _startPosY.Value + 15) + + }; + g.DrawPolygon(pen, points_second_cabin); + g.FillPolygon(additionalBrush, points_second_cabin); + + } + + base.DrawTransport(g); + + } +} \ No newline at end of file diff --git a/Monorail/Monorail/Entities/EntityLocomotive.cs b/Monorail/Monorail/Entities/EntityLocomotive.cs new file mode 100644 index 0000000..60d5d08 --- /dev/null +++ b/Monorail/Monorail/Entities/EntityLocomotive.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.Entities; + +/// +/// Класс-сущносить "Локомотив" +/// +public class EntityLocomotive +{ + /// + /// скорость + /// + public int Speed { get; set; } + /// + /// Вес + /// + public double Weight { get; set; } + /// + /// основной цвет + /// + public Color BodyColor { get; set; } + + /// + /// шаг + /// + public double Step => Speed * 100 / Weight; + + + /// + /// Конструктор сущности + /// + /// Скорость + /// Вес + /// Основной цвет + + public EntityLocomotive(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + + } + +} diff --git a/Monorail/Monorail/EntityMonorail.cs b/Monorail/Monorail/Entities/EntityMonorail.cs similarity index 63% rename from Monorail/Monorail/EntityMonorail.cs rename to Monorail/Monorail/Entities/EntityMonorail.cs index 1933d50..70f6377 100644 --- a/Monorail/Monorail/EntityMonorail.cs +++ b/Monorail/Monorail/Entities/EntityMonorail.cs @@ -1,21 +1,9 @@ -namespace monorail; +namespace Monorail.Entities; /// /// Класс-сущность "Монорельс" /// -public class EntityMonorail +public class EntityMonorail : EntityLocomotive { - /// - /// скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// основной цвет - /// - public Color BodyColor { get; private set; } /// /// дополнительный цвет /// @@ -30,11 +18,7 @@ public class EntityMonorail public bool SecondCabin { get; private set; } /// - /// шаг - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса монорельса + /// Конструктор /// /// Скорость /// Вес @@ -42,7 +26,8 @@ public class EntityMonorail /// Дополнительный цвет /// признак наличие рельса /// признак вторая кабинка - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool magneticRail, bool secondCabin) + + public EntityMonorail(int speed, double weight, Color bodyColor, Color additionalColor, bool magneticRail, bool secondCabin) : base(speed, weight, bodyColor) { Speed = speed; Weight = weight; @@ -50,5 +35,6 @@ public class EntityMonorail AdditionalColor = additionalColor; MagneticRail = magneticRail; SecondCabin = secondCabin; + } } \ No newline at end of file diff --git a/Monorail/Monorail/FormMonorail.Designer.cs b/Monorail/Monorail/FormMonorail.Designer.cs index 70f1931..6c90d4f 100644 --- a/Monorail/Monorail/FormMonorail.Designer.cs +++ b/Monorail/Monorail/FormMonorail.Designer.cs @@ -34,6 +34,9 @@ buttonDown = new Button(); buttonRight = new Button(); buttonUp = new Button(); + buttonCreateLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBox1Monorail).BeginInit(); SuspendLayout(); // @@ -51,9 +54,9 @@ buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreate.Location = new Point(10, 358); buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(75, 23); + buttonCreate.Size = new Size(221, 23); buttonCreate.TabIndex = 1; - buttonCreate.Text = "создать"; + buttonCreate.Text = "создать Monorail"; buttonCreate.UseVisualStyleBackColor = true; buttonCreate.Click += buttonCreate_Click; // @@ -105,11 +108,45 @@ buttonUp.UseVisualStyleBackColor = true; buttonUp.Click += buttonMove_Click; // + // buttonCreateLocomotive + // + buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateLocomotive.Location = new Point(247, 358); + buttonCreateLocomotive.Name = "buttonCreateLocomotive"; + buttonCreateLocomotive.Size = new Size(221, 23); + buttonCreateLocomotive.TabIndex = 6; + buttonCreateLocomotive.Text = "создать Locomotive"; + buttonCreateLocomotive.UseVisualStyleBackColor = true; + buttonCreateLocomotive.Click += ButtonCreateLocomotive_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(625, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(685, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(61, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormMonorail // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(755, 393); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateLocomotive); Controls.Add(buttonUp); Controls.Add(buttonRight); Controls.Add(buttonDown); @@ -130,5 +167,8 @@ private Button buttonDown; private Button buttonRight; private Button buttonUp; + private Button buttonCreateLocomotive; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/Monorail/Monorail/FormMonorail.cs b/Monorail/Monorail/FormMonorail.cs index aec1d9e..b0b0614 100644 --- a/Monorail/Monorail/FormMonorail.cs +++ b/Monorail/Monorail/FormMonorail.cs @@ -1,4 +1,6 @@ -using monorail; +using Monorail.Drawnings; +using Monorail.MovementStrategy; + namespace Monorail; /// /// Форма работы с объектом "Монорельс" @@ -8,59 +10,93 @@ public partial class FormMonorail : Form /// /// Поле-объект для прорисовки объекта /// - private DrawningMonorail? _drawningMonorail; + private DrawningLocomotive? _drawningLocomotive; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// /// конструктор формы /// public FormMonorail() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки машины /// private void Draw() { - if (_drawningMonorail == null) + if (_drawningLocomotive == null) { return; } Bitmap bmp = new(pictureBox1Monorail.Width, pictureBox1Monorail.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningMonorail.DrawTransport(gr); + _drawningLocomotive.DrawTransport(gr); pictureBox1Monorail.Image = bmp; } + private void FormMonorail_Load(object sender, EventArgs e) { } + /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningLocomotive): + _drawningLocomotive = new DrawningLocomotive(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); + break; + case nameof(DrawningMonorail): + _drawningLocomotive = new DrawningMonorail(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + + _drawningLocomotive.SetPictureSize(pictureBox1Monorail.Width, pictureBox1Monorail.Height); + _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + + + /// + /// Обработка нажатия кнопки "Создать Монорельс" /// /// /// - private void buttonCreate_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningMonorail = new DrawningMonorail(); - _drawningMonorail.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))); - _drawningMonorail.SetPictureSize(pictureBox1Monorail.Width, pictureBox1Monorail.Height); - _drawningMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100)); + private void buttonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMonorail)); + + + /// + /// Обработка нажатия кнопки "Создать _Монорельс" + /// + /// + /// + private void ButtonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive)); - Bitmap bmp = new(pictureBox1Monorail.Width, pictureBox1Monorail.Height); - Graphics gr = Graphics.FromImage(bmp); - _drawningMonorail.DrawTransport(gr); - pictureBox1Monorail.Image = bmp; - Draw(); - } /// /// Перемещение объекта по форме (нажатие кнопок навигации) @@ -69,7 +105,7 @@ public partial class FormMonorail : Form /// private void buttonMove_Click(object sender, EventArgs e) { - if (_drawningMonorail == null) + if (_drawningLocomotive == null) { return; } @@ -79,16 +115,16 @@ public partial class FormMonorail : Form switch (name) { case "buttonUp": - result = _drawningMonorail.MoveTransport(DirectionType.Up); + result = _drawningLocomotive.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningMonorail.MoveTransport(DirectionType.Down); + result = _drawningLocomotive.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningMonorail.MoveTransport(DirectionType.Left); + result = _drawningLocomotive.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningMonorail.MoveTransport(DirectionType.Right); + result = _drawningLocomotive.MoveTransport(DirectionType.Right); break; } if (result) @@ -97,4 +133,47 @@ public partial class FormMonorail : Form } } + + /// + /// + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningLocomotive == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBox1Monorail.Width, pictureBox1Monorail.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } diff --git a/Monorail/Monorail/MovementStrategy/AbstractStrategy.cs b/Monorail/Monorail/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..7f3b4ce --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.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/Monorail/Monorail/MovementStrategy/IMoveableObject.cs b/Monorail/Monorail/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..0f2fc6c --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// + bool TryMoveObject(MovementDirection direction); +} diff --git a/Monorail/Monorail/MovementStrategy/MoveToBorder.cs b/Monorail/Monorail/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..cac9c6f --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.LeftBorder - GetStep() <= 0 || + objParams.RightBorder + GetStep() >= FieldWidth || + objParams.TopBorder - GetStep() <= 0 + || objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + //реализация в правый нижний угол + int x = objParams.RightBorder; + if (x + GetStep() < FieldWidth) MoveRight(); + int y = objParams.DowBorder; + if (y + GetStep() < FieldHeight) MoveDown(); + } +} diff --git a/Monorail/Monorail/MovementStrategy/MoveToCenter.cs b/Monorail/Monorail/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..6d254d4 --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.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/Monorail/Monorail/MovementStrategy/MoveableLocomotive.cs b/Monorail/Monorail/MovementStrategy/MoveableLocomotive.cs new file mode 100644 index 0000000..9c753cf --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/MoveableLocomotive.cs @@ -0,0 +1,71 @@ +using Monorail.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием Drawning_Monorail +/// +public class MoveableLocomotive : IMoveableObject +{ + /// + /// Поле-объект класса Drawning_Monorail или его наследника + /// + private readonly DrawningLocomotive? Locomotive = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningCar + public MoveableLocomotive(DrawningLocomotive locomotive) + { + Locomotive = locomotive; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if ((Locomotive == null || Locomotive.EntityLocomotive == null || !Locomotive.GetPosX.HasValue || !Locomotive.GetPosY.HasValue)) + { + return null; + } + return new ObjectParameters(Locomotive.GetPosX.Value, Locomotive.GetPosY.Value, Locomotive.GetWidth, Locomotive.GetHeight); + } + } + + public int GetStep => (int)(Locomotive?.EntityLocomotive?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (Locomotive == null || Locomotive.EntityLocomotive == null) + { + return false; + } + + return Locomotive.MoveTransport(GetDirectionType(direction)); + + } + + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + private static DirectionType GetDirectionType(MovementDirection direction) + { + return direction switch + { + MovementDirection.Left => DirectionType.Left, + MovementDirection.Right => DirectionType.Right, + MovementDirection.Up => DirectionType.Up, + MovementDirection.Down => DirectionType.Down, + _ => DirectionType.Unknow, + }; + } + +} diff --git a/Monorail/Monorail/MovementStrategy/MovementDirection.cs b/Monorail/Monorail/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..0bc23ff --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/MovementDirection.cs @@ -0,0 +1,28 @@ + +namespace Monorail.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} diff --git a/Monorail/Monorail/MovementStrategy/ObjectParameters.cs b/Monorail/Monorail/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..f2439cd --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.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 DowBorder => _y + _height; + + /// + /// Серидина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Серидина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// + /// + /// + /// + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/Monorail/Monorail/MovementStrategy/StrategyStatus.cs b/Monorail/Monorail/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..464af51 --- /dev/null +++ b/Monorail/Monorail/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Monorail.MovementStrategy; + +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +}