diff --git a/AccordionBus/AccordionBus/AbstractStrategy.cs b/AccordionBus/AccordionBus/AbstractStrategy.cs new file mode 100644 index 0000000..7500776 --- /dev/null +++ b/AccordionBus/AccordionBus/AbstractStrategy.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AccordionBus.Drawings; + +namespace AccordionBus.MovementStrategy +{ + /// + /// Класс-стратегия перемещения объекта + /// + internal abstract class AbstractStrategy + { + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + + /// + /// Статус перемещения + /// + private Status _state = Status.NotInit; + + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + + /// + /// Статус перемещения + /// + /// + public Status GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = Status.NotInit; + return; + } + + _state = Status.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != Status.InProgress) + { + return; + } + if (IsTargetDestination()) + { + _state = Status.Finish; + return; + } + MoveToTarget(); + } + + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалость переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(DirectionType.Left); + + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалость переместиться, false - неудача) + protected bool MoveRight() => MoveTo(DirectionType.Right); + + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалость переместиться, false - неудача) + protected bool MoveUp() => MoveTo(DirectionType.Up); + + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалость переместиться, false - неудача) + protected bool MoveDown() => MoveTo(DirectionType.Down); + + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != Status.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + protected abstract bool IsTargetDestination(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат перемещения (true - удалость переместиться, false - неудача) + private bool MoveTo(DirectionType directionType) + { + if (_state != Status.InProgress) + { + return false; + } + if (_moveableObject?.CheckCanMove(directionType) ?? false) + { + _moveableObject.MoveObject(directionType); + return true; + } + return false; + } + } +} diff --git a/AccordionBus/AccordionBus/AccordionBusForm.Designer.cs b/AccordionBus/AccordionBus/AccordionBusForm.Designer.cs index 9af3924..86a7300 100644 --- a/AccordionBus/AccordionBus/AccordionBusForm.Designer.cs +++ b/AccordionBus/AccordionBus/AccordionBusForm.Designer.cs @@ -29,25 +29,30 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AccordionBusForm)); - buttonCreate = new Button(); + buttonCreateAccordionBus = new Button(); buttonRight = new Button(); buttonDown = new Button(); buttonLeft = new Button(); buttonUp = new Button(); pictureBoxAccordionBus = new PictureBox(); + comboBoxStrategy = new ComboBox(); + buttonCreateBus = new Button(); + buttonStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit(); SuspendLayout(); // - // buttonCreate + // buttonCreateAccordionBus // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(10, 420); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(75, 30); - buttonCreate.TabIndex = 0; - buttonCreate.Text = "Создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; + buttonCreateAccordionBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateAccordionBus.AutoSizeMode = AutoSizeMode.GrowAndShrink; + buttonCreateAccordionBus.Location = new Point(15, 409); + buttonCreateAccordionBus.Name = "buttonCreateAccordionBus"; + buttonCreateAccordionBus.RightToLeft = RightToLeft.No; + buttonCreateAccordionBus.Size = new Size(124, 41); + buttonCreateAccordionBus.TabIndex = 0; + buttonCreateAccordionBus.Text = "Создать автобус-гармошку"; + buttonCreateAccordionBus.UseVisualStyleBackColor = true; + buttonCreateAccordionBus.Click += buttonCreateAccordionBus_Click; // // buttonRight // @@ -106,16 +111,52 @@ pictureBoxAccordionBus.TabIndex = 5; pictureBoxAccordionBus.TabStop = false; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" }); + comboBoxStrategy.Location = new Point(768, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(102, 23); + comboBoxStrategy.TabIndex = 6; + // + // buttonCreateBus + // + buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateBus.AutoSizeMode = AutoSizeMode.GrowAndShrink; + buttonCreateBus.Location = new Point(145, 409); + buttonCreateBus.Name = "buttonCreateBus"; + buttonCreateBus.RightToLeft = RightToLeft.No; + buttonCreateBus.Size = new Size(124, 41); + buttonCreateBus.TabIndex = 7; + buttonCreateBus.Text = "Создать автобус"; + buttonCreateBus.UseVisualStyleBackColor = true; + buttonCreateBus.Click += buttonCreateBus_Click; + // + // buttonStep + // + buttonStep.Location = new Point(795, 41); + buttonStep.Name = "buttonStep"; + buttonStep.Size = new Size(75, 30); + buttonStep.TabIndex = 8; + buttonStep.Text = "Шаг"; + buttonStep.UseVisualStyleBackColor = true; + buttonStep.Click += buttonStep_Click; + // // AccordionBusForm // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(884, 461); + Controls.Add(buttonStep); + Controls.Add(buttonCreateBus); + Controls.Add(comboBoxStrategy); Controls.Add(buttonUp); Controls.Add(buttonLeft); Controls.Add(buttonDown); Controls.Add(buttonRight); - Controls.Add(buttonCreate); + Controls.Add(buttonCreateAccordionBus); Controls.Add(pictureBoxAccordionBus); Name = "AccordionBusForm"; ((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).EndInit(); @@ -124,11 +165,14 @@ #endregion - private Button buttonCreate; + private Button buttonCreateAccordionBus; private Button buttonRight; private Button buttonDown; private Button buttonLeft; private Button buttonUp; private PictureBox pictureBoxAccordionBus; + private ComboBox comboBoxStrategy; + private Button buttonCreateBus; + private Button buttonStep; } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/AccordionBusForm.cs b/AccordionBus/AccordionBus/AccordionBusForm.cs index 3dea021..66387a9 100644 --- a/AccordionBus/AccordionBus/AccordionBusForm.cs +++ b/AccordionBus/AccordionBus/AccordionBusForm.cs @@ -1,3 +1,8 @@ +using AccordionBus.Drawings; +using AccordionBus.MovementStrategy; +using System; +using System.Diagnostics.PerformanceData; + namespace AccordionBus { /// @@ -8,7 +13,12 @@ namespace AccordionBus /// /// - /// - private DrawingAccordionBus? _drawingAccordionBus; + private DrawingBus? _drawingBus; + + /// + /// + /// + private AbstractStrategy? _abstractStrategy; /// /// @@ -23,7 +33,7 @@ namespace AccordionBus /// private void Draw() { - if (_drawingAccordionBus == null) + if (_drawingBus == null) { return; } @@ -31,20 +41,19 @@ namespace AccordionBus Bitmap bmp = new(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height); Graphics gr = Graphics.FromImage(bmp); - _drawingAccordionBus.DrawTransport(gr); + _drawingBus.DrawTransport(gr); pictureBoxAccordionBus.Image = bmp; } /// - /// "" + /// " -" /// /// /// - private void buttonCreate_Click(object sender, EventArgs e) + private void buttonCreateAccordionBus_Click(object sender, EventArgs e) { Random random = new Random(); - _drawingAccordionBus = new DrawingAccordionBus(); - _drawingAccordionBus.Init(random.Next(100, 300), + _drawingBus = new DrawingAccordionBus(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)), @@ -53,11 +62,29 @@ namespace AccordionBus pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height); - _drawingAccordionBus.SetPosition(random.Next(10, 100), - random.Next(10, 100)); + _drawingBus.SetPosition(random.Next(10, 100), + random.Next(10, 100)); Draw(); } + /// + /// " " + /// + /// + /// + private void buttonCreateBus_Click(object sender, EventArgs e) + { + Random random = new Random(); + _drawingBus = new DrawingBus(random.Next(100, 300), + random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + pictureBoxAccordionBus.Width, + pictureBoxAccordionBus.Height); + + _drawingBus.SetPosition(random.Next(10, 100), + random.Next(10, 100)); + Draw(); + } /// /// @@ -66,7 +93,7 @@ namespace AccordionBus /// private void buttonMove_Click(object sender, EventArgs e) { - if (_drawingAccordionBus == null) + if (_drawingBus == null) { return; } @@ -75,19 +102,65 @@ namespace AccordionBus switch (name) { case "buttonUp": - _drawingAccordionBus.MoveTransport(DirectionType.Up); + _drawingBus.MoveTransport(DirectionType.Up); break; case "buttonDown": - _drawingAccordionBus.MoveTransport(DirectionType.Down); + _drawingBus.MoveTransport(DirectionType.Down); break; case "buttonLeft": - _drawingAccordionBus.MoveTransport(DirectionType.Left); + _drawingBus.MoveTransport(DirectionType.Left); break; case "buttonRight": - _drawingAccordionBus.MoveTransport(DirectionType.Right); + _drawingBus.MoveTransport(DirectionType.Right); break; } Draw(); } + + /// + /// "" + /// + /// + /// + private void buttonStep_Click(object sender, EventArgs e) + { + if (_drawingBus == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _abstractStrategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_abstractStrategy == null) + { + return; + } + + _abstractStrategy.SetData(new DrawingObjectBus(_drawingBus), + pictureBoxAccordionBus.Width, + pictureBoxAccordionBus.Height); + comboBoxStrategy.Enabled = false; + } + + if (_abstractStrategy == null) + { + return; + } + + _abstractStrategy.MakeStep(); + Draw(); + if (_abstractStrategy.GetStatus() == Status.Finish) + { + comboBoxStrategy.Enabled = true; + _abstractStrategy = null; + } + } } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/AccordionBusForm.resx b/AccordionBus/AccordionBus/AccordionBusForm.resx index 862b6cf..f8ed555 100644 --- a/AccordionBus/AccordionBus/AccordionBusForm.resx +++ b/AccordionBus/AccordionBus/AccordionBusForm.resx @@ -121,7 +121,7 @@ iVBORw0KGgoAAAANSUhEUgAAA4QAAAOECAYAAAD5Tv87AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS - cgAAEnIBXmVb4wAAxL5JREFUeF7s/VHO3Ii6Xdke97+fuxuuCvuwKkwPUTMilZkSuRYwcIC7M+bTL/Ij + cQAAEnEB89x6jgAAxL5JREFUeF7s/VHO3Ii6Xdke97+fuxuuCvuwKkwPUTMilZkSuRYwcIC7M+bTL/Ij XMD9r/+5bdv24P3Xf/3X//wf/+N/XHr9N99Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr7rq bNu23WV7om3b9uidjz45H4KfUK9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq+66mzbtt1le6Jt 2/bonY8+OR+Cn1CvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1Kvumps27bdZXuibdv26L0Ou/fj @@ -966,7 +966,7 @@ iVBORw0KGgoAAAANSUhEUgAAA4QAAAOECAYAAAD5Tv87AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS - cgAAEnIBXmVb4wAAtdhJREFUeF7s3QFyG4mVbdvu8b4R9oQ8jf8bFaADnV6SNkgkRTLPiVjh91zgdkkE + cQAAEnEB89x6jgAAtdhJREFUeF7s3QFyG4mVbdvu8b4R9oQ8jf8bFaADnV6SNkgkRTLPiVjh91zgdkkE wnmD7tJ//X/btm3btm3btm3bJbeDcNu2bdu2bdu27aLbQbht27Zt27Zt23bR7SDctm3btm3btm276HYQ btu2bdu2bdu2XXQ7CLdt27Zt27Zt2y66HYTbtm3btm3btm0X3Q7Cbdu2bdu2bdu2i24H4bZt27Zt27Zt 20W3g3Dbtm3btm3btu2i20G4bdu2bdu2bdt20e0g3LZt27Zt27Ztu+h2EG7btm3btm3btl10Owi3bdu2 @@ -1748,7 +1748,7 @@ iVBORw0KGgoAAAANSUhEUgAAA4QAAAOECAYAAAD5Tv87AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS - cgAAEnIBXmVb4wAAw+5JREFUeF7s3VFyI9liZdmq8WqEb0I5je5yVbmEBy0itoOMCBI4x2zZMxOA3f1B + cQAAEnEB89x6jgAAw+5JREFUeF7s3VFyI9liZdmq8WqEb0I5je5yVbmEBy0itoOMCBI4x2zZMxOA3f1B Xly3ZGX+r/9v27Zt27Zt27Zte8vtgXDbtm3btm3btu1NtwfCbdu2bdu2bdu2N90eCLdt27Zt27Zt2950 eyDctm3btm3btm170+2BcNu2bdu2bdu27U23B8Jt27Zt27Zt27Y33R4It23btm3btm3b3nR7INy2bdu2 bdu2bXvT7YFw27Zt27Zt27btTbcHwm3btm3btm3btjfdHgi3bdu2bdu2bdvedHsg3LZt27Zt27Zte9Pt diff --git a/AccordionBus/AccordionBus/DrawingAccordionBus.cs b/AccordionBus/AccordionBus/DrawingAccordionBus.cs index 900b169..21a59a4 100644 --- a/AccordionBus/AccordionBus/DrawingAccordionBus.cs +++ b/AccordionBus/AccordionBus/DrawingAccordionBus.cs @@ -1,53 +1,20 @@ using System; using System.Collections.Generic; +using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; +using AccordionBus.Entities; -namespace AccordionBus +namespace AccordionBus.Drawings { /// /// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// - public class DrawingAccordionBus + internal class DrawingAccordionBus : DrawingBus { /// - /// Класс-сущность - /// - public EntityAccordionBus? EntityAccordionBus { get; private set; } - - /// - /// Ширина окна - /// - private int _pictureWidth; - - /// - /// Высота окна - /// - private int _pictureHeight; - - /// - /// Левая координата прорисовки автобуса - /// - private int _startPosX; - - /// - /// Верхняя координата прорисовки автобуса - /// - private int _startPosY; - - /// - /// Ширина прорисовки автобуса - /// - private int _busWidth = 100; - - /// - /// Высота прорисовки автобуса - /// - private readonly int _busHeight = 50; - - /// - /// Инициализация свойств + /// Конструктор /// /// Скорость /// Вес @@ -55,85 +22,13 @@ namespace AccordionBus /// Дополнительный цвет /// Дополнительный отсек /// Дополнительная дверь - /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах< - public bool Init(int speed, int weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor, int width, int height) + /// Ширина картинки + /// Высота картинки + public DrawingAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor, int width, int height) : base(speed, weight, bodyColor, width, height, 215, 50) { - _pictureWidth = width; - _pictureHeight = height; - EntityAccordionBus = new EntityAccordionBus(); - if (additionalBody) + if (EntityBus != null) { - _busWidth = 215; - } - EntityAccordionBus.Init(speed, weight, - bodyColor, additionalColor, - additionalBody, additionalDoor); - - // Проверка на вместимость объекта в размеры картинки - if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight)) - { - Console.WriteLine("Ошибка! Нельзя создать рбъект такого размера"); - } - - return true; - } - - /// - /// Установка позиции - /// - /// Координата X - /// Координата Y - public void SetPosition(int x, int y) - { - if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight)) - { - _startPosX = _pictureWidth - _busWidth; - _startPosY = _pictureHeight - _busHeight; - } - else - { - _startPosX = x; - _startPosY = y; - } - } - - /// - /// Изменение направления перемещения - /// - /// Направление - public void MoveTransport(DirectionType direction) - { - if (EntityAccordionBus == null) - { - return; - } - - switch (direction) - { - case DirectionType.Left: - if (_startPosX - EntityAccordionBus.Step > 0) - { - _startPosX -= (int)EntityAccordionBus.Step; - } - break; - case DirectionType.Up: - if (_startPosY - EntityAccordionBus.Step > 0) - { - _startPosY -= (int)EntityAccordionBus.Step; - } - break; - case DirectionType.Right: - if (_startPosX + EntityAccordionBus.Step < _pictureWidth - _busWidth) - { - _startPosX += (int)EntityAccordionBus.Step; - } - break; - case DirectionType.Down: - if (_startPosY + EntityAccordionBus.Step < _pictureHeight - _busHeight) - { - _startPosY += (int)EntityAccordionBus.Step; - } - break; + EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, additionalBody, additionalDoor); } } @@ -141,46 +36,20 @@ namespace AccordionBus /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public override void DrawTransport(Graphics g) { - if (EntityAccordionBus == null) + if (EntityBus is not EntityAccordionBus accordionBus) { return; } + base.DrawTransport(g); Pen pen = new Pen(Color.Black, 3); - Brush bodyBrush = new SolidBrush(EntityAccordionBus.BodyColor); - Brush additionalBrush = new SolidBrush(EntityAccordionBus.AdditionalColor); - - // Граница главного отсека - g.DrawRectangle(pen, _startPosX, _startPosY, 100, 40); - - // Кузов главного отсека - g.FillRectangle(bodyBrush, _startPosX + 1, _startPosY + 1, 99, 39); - - // Колеса главного отсека Brush brush = new SolidBrush(Color.White); - g.DrawEllipse(pen, _startPosX + 15, _startPosY + 33, 15, 15); - g.FillEllipse(brush, _startPosX + 16, _startPosY + 34, 14, 14); - g.DrawEllipse(pen, _startPosX + 70, _startPosY + 33, 15, 15); - g.FillEllipse(brush, _startPosX + 71, _startPosY + 34, 14, 14); - - // Дверь главного отсека - pen = new Pen(Color.Black, 2); - g.DrawRectangle(pen, _startPosX + 35, _startPosY + 10, 15, 30); - g.FillRectangle(brush, _startPosX + 36, _startPosY + 11, 14, 29); - - // Окна главного отсека - pen = new Pen(Color.DodgerBlue, 2); - g.DrawEllipse(pen, _startPosX + 10, _startPosY + 5, 15, 20); - g.FillEllipse(brush, _startPosX + 11, _startPosY + 6, 14, 19); - g.DrawEllipse(pen, _startPosX + 55, _startPosY + 5, 15, 20); - g.FillEllipse(brush, _startPosX + 56, _startPosY + 6, 14, 19); - g.DrawEllipse(pen, _startPosX + 75, _startPosY + 5, 15, 20); - g.FillEllipse(brush, _startPosX + 76, _startPosY + 6, 14, 19); + Brush additionalBrush = new SolidBrush(accordionBus.AdditionalColor); // Дополнительный отсек - if (EntityAccordionBus.AdditionalBody) + if (accordionBus.AdditionalBody) { // Граница дополнительного отсека pen = new Pen(Color.Black, 3); @@ -196,7 +65,7 @@ namespace AccordionBus g.FillEllipse(brush, _startPosX + 186, _startPosY + 34, 14, 14); // Дверь дополнительного отсека - if (EntityAccordionBus.AdditionalDoor) + if (accordionBus.AdditionalDoor) { pen = new Pen(Color.Black, 2); g.DrawRectangle(pen, _startPosX + 160, _startPosY + 10, 15, 30); @@ -219,7 +88,6 @@ namespace AccordionBus g.DrawLine(pen, _startPosX + 100 + i * 3, _startPosY, _startPosX + 100 + i * 3, _startPosY + 40); } } - } } } diff --git a/AccordionBus/AccordionBus/DrawingBus.cs b/AccordionBus/AccordionBus/DrawingBus.cs new file mode 100644 index 0000000..aa655c9 --- /dev/null +++ b/AccordionBus/AccordionBus/DrawingBus.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AccordionBus.Entities; + +namespace AccordionBus.Drawings +{ + /// + /// Класс, отвечающий за прорисовку и перемещение объекта-сущности + /// + public class DrawingBus + { + /// + /// Класс-сущность + /// + public EntityBus? EntityBus { get; protected set; } + + /// + /// Ширина окна + /// + private int _pictureWidth; + + /// + /// Высота окна + /// + private int _pictureHeight; + + /// + /// Левая координата прорисовки автобуса + /// + protected int _startPosX; + + /// + /// Координата X объекта + /// + public int GetPosX => _startPosX; + + /// + /// Верхняя координата прорисовки автобуса + /// + protected int _startPosY; + + /// + /// Координата Y объекта + /// + public int GetPosY => _startPosY; + + /// + /// Ширина прорисовки автобуса + /// + private readonly int _busWidth = 100; + + /// + /// Ширина объекта + /// + public int GetWidth => _busWidth; + + /// + /// Высота прорисовки автобуса + /// + private readonly int _busHeight = 50; + + /// + /// Высота объекта + /// + public int GetHeigth => _busHeight; + + /// + /// Проверка, что объект может перемещаться по указанному направлению + /// + /// направление + /// true - может переместиться по указанному направлению + public bool CanMove(DirectionType direction) + { + if (EntityBus == null) + { + return false; + } + + return direction switch + { + // Влево + DirectionType.Left => _startPosX - EntityBus.Step > 0, + // Вверх + DirectionType.Up => _startPosY - EntityBus.Step > 0, + // Вправо + DirectionType.Right => _startPosX + EntityBus.Step < _pictureWidth - _busWidth, + // Вниз + DirectionType.Down => _startPosY + EntityBus.Step < _pictureHeight - _busHeight, + _ => false + }; + } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Ширина картинки + /// Высота картинки + public DrawingBus(int speed, int weight, Color bodyColor, int width, int height) + { + _pictureWidth = width; + _pictureHeight = height; + EntityBus = new EntityBus(speed, weight, bodyColor); + + // Проверка на вместимость объекта в размеры картинки + if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight)) + { + Console.WriteLine("Ошибка! Нельзя создать рбъект такого размера!"); + return; + } + } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Ширина картинки + /// Высота картинки + /// Ширинка прорисовки автобуса + /// Выоста прорисовки автобуса + protected DrawingBus(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight) + { + _pictureWidth = width; + _pictureHeight = height; + _busWidth = busWidth; + _busHeight = busHeight; + EntityBus = new EntityBus(speed, weight, bodyColor); + + // Проверка на вместимость объекта в размеры картинки + if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight)) + { + Console.WriteLine("Ошибка! Нельзя создать рбъект такого размера!"); + return; + } + } + + /// + /// Установка позиции + /// + /// Координата X + /// Координата Y + public void SetPosition(int x, int y) + { + if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight)) + { + _startPosX = _pictureWidth - _busWidth; + _startPosY = _pictureHeight - _busHeight; + } + else + { + _startPosX = x; + _startPosY = y; + } + } + + /// + /// Изменение направления перемещения + /// + /// Направление + public void MoveTransport(DirectionType direction) + { + if (!CanMove(direction) || EntityBus == null) + { + return; + } + + switch (direction) + { + // Влево + case DirectionType.Left: + _startPosX -= (int)EntityBus.Step; + break; + // Вверх + case DirectionType.Up: + _startPosY -= (int)EntityBus.Step; + break; + // Вправо + case DirectionType.Right: + _startPosX += (int)EntityBus.Step; + break; + // Вниз + case DirectionType.Down: + _startPosY += (int)EntityBus.Step; + break; + } + } + + /// + /// Прорисовка объекта + /// + /// + public virtual void DrawTransport(Graphics g) + { + if (EntityBus == null) + { + return; + } + + Pen pen = new Pen(Color.Black, 3); + Brush brush = new SolidBrush(Color.White); + Brush bodyBrush = new SolidBrush(EntityBus.BodyColor); + + // Граница главного отсека + g.DrawRectangle(pen, _startPosX, _startPosY, 100, 40); + + // Кузов главного отсека + g.FillRectangle(bodyBrush, _startPosX + 1, _startPosY + 1, 99, 39); + + // Колеса главного отсека + g.DrawEllipse(pen, _startPosX + 15, _startPosY + 33, 15, 15); + g.FillEllipse(brush, _startPosX + 16, _startPosY + 34, 14, 14); + g.DrawEllipse(pen, _startPosX + 70, _startPosY + 33, 15, 15); + g.FillEllipse(brush, _startPosX + 71, _startPosY + 34, 14, 14); + + // Дверь главного отсека + pen = new Pen(Color.Black, 2); + g.DrawRectangle(pen, _startPosX + 35, _startPosY + 10, 15, 30); + g.FillRectangle(brush, _startPosX + 36, _startPosY + 11, 14, 29); + + // Окна главного отсека + pen = new Pen(Color.DodgerBlue, 2); + g.DrawEllipse(pen, _startPosX + 10, _startPosY + 5, 15, 20); + g.FillEllipse(brush, _startPosX + 11, _startPosY + 6, 14, 19); + g.DrawEllipse(pen, _startPosX + 55, _startPosY + 5, 15, 20); + g.FillEllipse(brush, _startPosX + 56, _startPosY + 6, 14, 19); + g.DrawEllipse(pen, _startPosX + 75, _startPosY + 5, 15, 20); + g.FillEllipse(brush, _startPosX + 76, _startPosY + 6, 14, 19); + } + } +} diff --git a/AccordionBus/AccordionBus/DrawingObjectBus.cs b/AccordionBus/AccordionBus/DrawingObjectBus.cs new file mode 100644 index 0000000..00a26f9 --- /dev/null +++ b/AccordionBus/AccordionBus/DrawingObjectBus.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AccordionBus.Drawings; + +namespace AccordionBus.MovementStrategy +{ + /// + /// Реализация интерфейса IMoveableObject для работы с объектом DrawingBus (паттерн Adapter) + /// + internal class DrawingObjectBus : IMoveableObject + { + private readonly DrawingBus? _drawingBus = null; + + public DrawingObjectBus(DrawingBus drawingBus) + { + _drawingBus = drawingBus; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_drawingBus == null || _drawingBus.EntityBus == null) + { + return null; + } + return new ObjectParameters(_drawingBus.GetPosX, _drawingBus.GetPosY, _drawingBus.GetWidth, _drawingBus.GetHeigth); + } + } + + public int GetStep => (int)(_drawingBus?.EntityBus?.Step ?? 0); + + public bool CheckCanMove(DirectionType direction) => _drawingBus?.CanMove(direction) ?? false; + + public void MoveObject(DirectionType direction) => _drawingBus?.MoveTransport(direction); + } +} diff --git a/AccordionBus/AccordionBus/EntityAccordionBus.cs b/AccordionBus/AccordionBus/EntityAccordionBus.cs index 00b7be1..f6b83af 100644 --- a/AccordionBus/AccordionBus/EntityAccordionBus.cs +++ b/AccordionBus/AccordionBus/EntityAccordionBus.cs @@ -4,25 +4,13 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace AccordionBus +namespace AccordionBus.Entities { - public class EntityAccordionBus + /// + /// Класс-сущность "Автобус-гармошка" + /// + internal class EntityAccordionBus : EntityBus { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// /// Дополнительный цвет /// @@ -39,12 +27,7 @@ namespace AccordionBus public bool AdditionalDoor { get; private set; } /// - /// Шаг перемещения автобуса - /// - public double Step => (double)Speed * 100 / Weight; - - /// - /// Инициализация полей обЪекта-класса автобуса + /// Конструктор с параметрами /// /// Скорость /// Вес @@ -52,11 +35,8 @@ namespace AccordionBus /// Дополнительный цвет /// Дополнительный отсек /// Дополнительная дверь - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor) + public EntityAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; AdditionalBody = additionalBody; AdditionalDoor = additionalDoor; diff --git a/AccordionBus/AccordionBus/EntityBus.cs b/AccordionBus/AccordionBus/EntityBus.cs new file mode 100644 index 0000000..7c68641 --- /dev/null +++ b/AccordionBus/AccordionBus/EntityBus.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Entities +{ + /// + /// Класс-сущность "Автобус" + /// + public class EntityBus + { + /// + /// Скорость + /// + public int Speed { get; private set; } + + /// + /// Вес + /// + public double Weight { get; private set; } + + /// + /// Основной цвет + /// + public Color BodyColor { get; private set; } + + /// + /// Шаг перемещения автобуса + /// + public double Step => (double)Speed * 100 / Weight; + + /// + /// Конструктор с параметрами + /// + /// Скорость + /// Вес + /// Основной цвет + public EntityBus(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } + } +} diff --git a/AccordionBus/AccordionBus/IMoveableObject.cs b/AccordionBus/AccordionBus/IMoveableObject.cs new file mode 100644 index 0000000..af444c1 --- /dev/null +++ b/AccordionBus/AccordionBus/IMoveableObject.cs @@ -0,0 +1,39 @@ +using AccordionBus.MovementStrategy; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AccordionBus.Drawings; + +namespace AccordionBus.MovementStrategy +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + internal interface IMoveableObject + { + /// + /// Получение координаты X объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Проверка, можно ли переместиться по нужному направлению + /// + /// Направление + /// + bool CheckCanMove(DirectionType direction); + + /// + /// Изменение направления перемещения объекта + /// + /// Направление + void MoveObject(DirectionType direction); + } +} diff --git a/AccordionBus/AccordionBus/MoveToBorder.cs b/AccordionBus/AccordionBus/MoveToBorder.cs new file mode 100644 index 0000000..d340fa6 --- /dev/null +++ b/AccordionBus/AccordionBus/MoveToBorder.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.MovementStrategy +{ + // Стратегия перемещения объекта в правый нижний угол экрана + internal class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestination() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.RightBorder <= FieldWidth && + objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder <= FieldHeight && + objParams.DownBorder + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + var diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + MoveRight(); + } + + var diffY = objParams.ObjectMiddleVertical - FieldWidth; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } + } +} + diff --git a/AccordionBus/AccordionBus/MoveToCenter.cs b/AccordionBus/AccordionBus/MoveToCenter.cs new file mode 100644 index 0000000..d6d3036 --- /dev/null +++ b/AccordionBus/AccordionBus/MoveToCenter.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.MovementStrategy +{ + // Стратегия перемещения объекта в центр экрана + internal class MoveToCenter : AbstractStrategy + { + protected override bool IsTargetDestination() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 && + objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical <= FieldHeight / 2 && + objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + + protected override void MoveToTarget() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } + } +} diff --git a/AccordionBus/AccordionBus/ObjectParameters.cs b/AccordionBus/AccordionBus/ObjectParameters.cs new file mode 100644 index 0000000..5ce0cf9 --- /dev/null +++ b/AccordionBus/AccordionBus/ObjectParameters.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.MovementStrategy +{ + /// + /// Параметры-координаты рбъекта + /// + internal class ObjectParameters + { + private readonly int _x; + private readonly int _y; + private readonly int _width; + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина + /// Высота + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } + } +} diff --git a/AccordionBus/AccordionBus/Status.cs b/AccordionBus/AccordionBus/Status.cs new file mode 100644 index 0000000..918ab1a --- /dev/null +++ b/AccordionBus/AccordionBus/Status.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.MovementStrategy +{ + /// + /// Статус выполнения операции перемещения + /// + internal enum Status + { + NotInit, + + InProgress, + + Finish + } +}