From ea0d1b3981be309d9c0859fd72eea204b85f14a1 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Tue, 24 Oct 2023 15:02:37 +0400 Subject: [PATCH] PIbd-21_MasenkinMS_LabWork03 --- AccordionBus/AccordionBus/AbstractStrategy.cs | 149 +++++++++++ .../AccordionBus/AccordionBusForm.Designer.cs | 84 +++++- AccordionBus/AccordionBus/AccordionBusForm.cs | 151 +++++++++-- .../AccordionBus/AccordionBusForm.resx | 6 +- .../BusCollectionForm.Designer.cs | 133 ++++++++++ .../AccordionBus/BusCollectionForm.cs | 92 +++++++ .../AccordionBus/BusCollectionForm.resx | 120 +++++++++ .../AccordionBus/BusGenericCollection.cs | 153 +++++++++++ .../AccordionBus/DrawingAccordionBus.cs | 160 ++---------- AccordionBus/AccordionBus/DrawingBus.cs | 246 ++++++++++++++++++ AccordionBus/AccordionBus/DrawingObjectBus.cs | 40 +++ .../AccordionBus/EntityAccordionBus.cs | 34 +-- AccordionBus/AccordionBus/EntityBus.cs | 47 ++++ AccordionBus/AccordionBus/IMoveableObject.cs | 39 +++ AccordionBus/AccordionBus/MoveToBorder.cs | 48 ++++ AccordionBus/AccordionBus/MoveToCenter.cs | 61 +++++ AccordionBus/AccordionBus/ObjectParameters.cs | 64 +++++ AccordionBus/AccordionBus/Program.cs | 2 +- AccordionBus/AccordionBus/SetGeneric.cs | 126 +++++++++ AccordionBus/AccordionBus/Status.cs | 20 ++ 20 files changed, 1571 insertions(+), 204 deletions(-) create mode 100644 AccordionBus/AccordionBus/AbstractStrategy.cs create mode 100644 AccordionBus/AccordionBus/BusCollectionForm.Designer.cs create mode 100644 AccordionBus/AccordionBus/BusCollectionForm.cs create mode 100644 AccordionBus/AccordionBus/BusCollectionForm.resx create mode 100644 AccordionBus/AccordionBus/BusGenericCollection.cs create mode 100644 AccordionBus/AccordionBus/DrawingBus.cs create mode 100644 AccordionBus/AccordionBus/DrawingObjectBus.cs create mode 100644 AccordionBus/AccordionBus/EntityBus.cs create mode 100644 AccordionBus/AccordionBus/IMoveableObject.cs create mode 100644 AccordionBus/AccordionBus/MoveToBorder.cs create mode 100644 AccordionBus/AccordionBus/MoveToCenter.cs create mode 100644 AccordionBus/AccordionBus/ObjectParameters.cs create mode 100644 AccordionBus/AccordionBus/SetGeneric.cs create mode 100644 AccordionBus/AccordionBus/Status.cs 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..acada71 100644 --- a/AccordionBus/AccordionBus/AccordionBusForm.Designer.cs +++ b/AccordionBus/AccordionBus/AccordionBusForm.Designer.cs @@ -29,25 +29,31 @@ 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(); + buttonSelectBus = 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 +112,66 @@ 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; + // + // buttonSelectBus + // + buttonSelectBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonSelectBus.AutoSizeMode = AutoSizeMode.GrowAndShrink; + buttonSelectBus.Location = new Point(275, 409); + buttonSelectBus.Name = "buttonSelectBus"; + buttonSelectBus.RightToLeft = RightToLeft.No; + buttonSelectBus.Size = new Size(124, 41); + buttonSelectBus.TabIndex = 9; + buttonSelectBus.Text = "Выбрать автобус"; + buttonSelectBus.UseVisualStyleBackColor = true; + buttonSelectBus.Click += buttonSelectBus_Click; + // // AccordionBusForm // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(884, 461); + Controls.Add(buttonSelectBus); + 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 +180,15 @@ #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; + private Button buttonSelectBus; } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/AccordionBusForm.cs b/AccordionBus/AccordionBus/AccordionBusForm.cs index 3dea021..b039681 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,17 @@ namespace AccordionBus /// /// - /// - private DrawingAccordionBus? _drawingAccordionBus; + private DrawingBus? _drawingBus; + + /// + /// + /// + private AbstractStrategy? _abstractStrategy; + + /// + /// + /// + public DrawingBus? SelectedBus { get; private set; } /// /// @@ -16,6 +31,8 @@ namespace AccordionBus public AccordionBusForm() { InitializeComponent(); + _abstractStrategy = null; + SelectedBus = null; } /// @@ -23,7 +40,7 @@ namespace AccordionBus /// private void Draw() { - if (_drawingAccordionBus == null) + if (_drawingBus == null) { return; } @@ -31,33 +48,76 @@ 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), + Random random = new(); + + // + Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + bodyColor = dialog.Color; + } + + // + Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + additionalColor = dialog.Color; + } + + _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)), + bodyColor, + additionalColor, Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), 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(); + + // + Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + bodyColor = dialog.Color; + } + + _drawingBus = new DrawingBus(random.Next(100, 300), + random.Next(1000, 3000), + bodyColor, + pictureBoxAccordionBus.Width, + pictureBoxAccordionBus.Height); + + _drawingBus.SetPosition(random.Next(10, 100), + random.Next(10, 100)); + Draw(); + } /// /// @@ -66,7 +126,7 @@ namespace AccordionBus /// private void buttonMove_Click(object sender, EventArgs e) { - if (_drawingAccordionBus == null) + if (_drawingBus == null) { return; } @@ -75,19 +135,76 @@ 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; + } + } + + /// + /// + /// + /// + /// + private void buttonSelectBus_Click(object sender, EventArgs e) + { + SelectedBus = _drawingBus; + DialogResult = DialogResult.OK; + } } } \ 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/BusCollectionForm.Designer.cs b/AccordionBus/AccordionBus/BusCollectionForm.Designer.cs new file mode 100644 index 0000000..37deb1a --- /dev/null +++ b/AccordionBus/AccordionBus/BusCollectionForm.Designer.cs @@ -0,0 +1,133 @@ +namespace AccordionBus +{ + partial class BusCollectionForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + pictureBoxCollection = new PictureBox(); + panelTools = new Panel(); + maskedTextBox = new MaskedTextBox(); + buttonRefreshCollection = new Button(); + buttonRemoveBus = new Button(); + buttonAddBus = new Button(); + labelTools = new Label(); + ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); + panelTools.SuspendLayout(); + SuspendLayout(); + // + // pictureBoxCollection + // + pictureBoxCollection.Location = new Point(0, 0); + pictureBoxCollection.Name = "pictureBoxCollection"; + pictureBoxCollection.Size = new Size(700, 461); + pictureBoxCollection.TabIndex = 0; + pictureBoxCollection.TabStop = false; + // + // panelTools + // + panelTools.Controls.Add(maskedTextBox); + panelTools.Controls.Add(buttonRefreshCollection); + panelTools.Controls.Add(buttonRemoveBus); + panelTools.Controls.Add(buttonAddBus); + panelTools.Controls.Add(labelTools); + panelTools.Location = new Point(706, 0); + panelTools.Name = "panelTools"; + panelTools.Size = new Size(174, 461); + panelTools.TabIndex = 1; + // + // maskedTextBox + // + maskedTextBox.Location = new Point(30, 160); + maskedTextBox.Name = "maskedTextBox"; + maskedTextBox.Size = new Size(120, 23); + maskedTextBox.TabIndex = 4; + // + // buttonRefreshCollection + // + buttonRefreshCollection.Location = new Point(30, 290); + buttonRefreshCollection.Name = "buttonRefreshCollection"; + buttonRefreshCollection.Size = new Size(120, 40); + buttonRefreshCollection.TabIndex = 3; + buttonRefreshCollection.Text = "Обновить коллекцию"; + buttonRefreshCollection.UseVisualStyleBackColor = true; + buttonRefreshCollection.Click += buttonRefreshCollection_Click; + // + // buttonRemoveBus + // + buttonRemoveBus.Location = new Point(30, 190); + buttonRemoveBus.Name = "buttonRemoveBus"; + buttonRemoveBus.Size = new Size(120, 40); + buttonRemoveBus.TabIndex = 2; + buttonRemoveBus.Text = "Удалить автобус"; + buttonRemoveBus.UseVisualStyleBackColor = true; + buttonRemoveBus.Click += buttonRemoveBus_Click; + // + // buttonAddBus + // + buttonAddBus.Location = new Point(30, 60); + buttonAddBus.Name = "buttonAddBus"; + buttonAddBus.Size = new Size(120, 40); + buttonAddBus.TabIndex = 1; + buttonAddBus.Text = "Добавить автобус"; + buttonAddBus.UseVisualStyleBackColor = true; + buttonAddBus.Click += buttonAddBus_Click; + // + // labelTools + // + labelTools.AutoSize = true; + labelTools.Location = new Point(0, 0); + labelTools.Name = "labelTools"; + labelTools.Size = new Size(83, 15); + labelTools.TabIndex = 0; + labelTools.Text = "Инструменты"; + // + // BusCollectionForm + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(884, 461); + Controls.Add(panelTools); + Controls.Add(pictureBoxCollection); + Name = "BusCollectionForm"; + Text = "BusCollectionForm"; + ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); + panelTools.ResumeLayout(false); + panelTools.PerformLayout(); + ResumeLayout(false); + } + + #endregion + + private PictureBox pictureBoxCollection; + private Panel panelTools; + private Label labelTools; + private MaskedTextBox maskedTextBox; + private Button buttonRefreshCollection; + private Button buttonRemoveBus; + private Button buttonAddBus; + } +} \ No newline at end of file diff --git a/AccordionBus/AccordionBus/BusCollectionForm.cs b/AccordionBus/AccordionBus/BusCollectionForm.cs new file mode 100644 index 0000000..19d3cc5 --- /dev/null +++ b/AccordionBus/AccordionBus/BusCollectionForm.cs @@ -0,0 +1,92 @@ +using AccordionBus.Drawings; +using AccordionBus.Generics; +using AccordionBus.MovementStrategy; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Numerics; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AccordionBus +{ + /// + /// Форма для работы с набором объектов класса DrawingBus + /// + public partial class BusCollectionForm : Form + { + /// + /// Набор объектов + /// + private readonly BusGenericCollection _buses; + + /// + /// Конструктор + /// + public BusCollectionForm() + { + InitializeComponent(); + _buses = new BusGenericCollection(pictureBoxCollection.Width, pictureBoxCollection.Height); + } + + /// + /// Добавление объекта в набор + /// + /// + /// + private void buttonAddBus_Click(object sender, EventArgs e) + { + AccordionBusForm form = new(); + if (form.ShowDialog() == DialogResult.OK) + { + if (_buses + form.SelectedBus > -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = _buses.ShowBuses(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + } + + /// + /// Удаление объекта из набора + /// + /// + /// + private void buttonRemoveBus_Click(object sender, EventArgs e) + { + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBox.Text); + if (_buses - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = _buses.ShowBuses(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + } + + /// + /// Обновление рисунка по набору + /// + /// + /// + private void buttonRefreshCollection_Click(object sender, EventArgs e) + { + pictureBoxCollection.Image = _buses.ShowBuses(); + } + } +} diff --git a/AccordionBus/AccordionBus/BusCollectionForm.resx b/AccordionBus/AccordionBus/BusCollectionForm.resx new file mode 100644 index 0000000..a395bff --- /dev/null +++ b/AccordionBus/AccordionBus/BusCollectionForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/AccordionBus/AccordionBus/BusGenericCollection.cs b/AccordionBus/AccordionBus/BusGenericCollection.cs new file mode 100644 index 0000000..7ce53ad --- /dev/null +++ b/AccordionBus/AccordionBus/BusGenericCollection.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AccordionBus.Drawings; +using AccordionBus.MovementStrategy; + +namespace AccordionBus.Generics +{ + /// + /// Параметризованный класс для набора объектов DrawingBus + /// + /// + /// + internal class BusGenericCollection + where T : DrawingBus + where U : IMoveableObject + { + /// + /// Ширина окна прорисовки + /// + private readonly int _pictureWidth; + + /// + /// Высота окна прорисовки + /// + private readonly int _pictureHeight; + + /// + /// Размер занимаемого объектом места (ширина) + /// + private readonly int _placeSizeWidth = 215; + + /// + /// Размер занимаемого объектом места (высота) + /// + private readonly int _placeSizeHeight = 50; + + /// + /// Набор объектов + /// + private readonly SetGeneric _collection; + + /// + /// Конструктор + /// + /// Ширина картинки + /// Высота картинки + public BusGenericCollection(int picWidth, int picHeight) + { + int width = picWidth / _placeSizeWidth; + int height = picHeight / _placeSizeHeight; + _pictureWidth = picWidth; + _pictureHeight = picHeight; + + _collection = new SetGeneric(width * height); + } + + /// + /// Перегрузка оператора сложения + /// + /// + /// + /// + public static int operator +(BusGenericCollection collect, T? obj) + { + if (obj == null) + { + return -1; + } + + return collect?._collection.Insert(obj) ?? -1; + } + + /// + /// Перегрузка оператора вычитания + /// + /// + /// + /// + public static bool operator -(BusGenericCollection collect, int pos) + { + T? obj = collect._collection.Get(pos); + + if (obj != null) + { + return collect._collection.Remove(pos); + } + + return false; + } + + /// + /// Получение объекта IMoveableObject + /// + /// Позиция + /// + public U? GetU(int pos) + { + return (U?)_collection.Get(pos)?.GetMoveableObject; + } + + /// + /// Вывод всего набора объектов + /// + /// + public Bitmap ShowBuses() + { + Bitmap bmp = new(_pictureWidth, _pictureHeight); + Graphics g = Graphics.FromImage(bmp); + DrawBackground(g); + DrawObjects(g); + return bmp; + } + + /// + /// Метод отрисовки фона + /// + /// + private void DrawBackground(Graphics g) + { + Pen pen = new(Color.Black, 3); + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) + { + for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; j++) + { + // Линия разметки места + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight); + } + g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight); + } + } + + private void DrawObjects(Graphics g) + { + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; + for (int i = 0; i < _collection.Count; i++) + { + // Получение объекта + var obj = _collection.Get(i); + // Установка позиции + obj?.SetPosition( + (int)((width - 1) * _placeSizeWidth - (i % width * _placeSizeWidth)), + (int)((height - 1) * _placeSizeHeight - (i / width * _placeSizeHeight)) + ); + // Прорисовка объекта + obj?.DrawTransport(g); + } + } + } +} \ No newline at end of file diff --git a/AccordionBus/AccordionBus/DrawingAccordionBus.cs b/AccordionBus/AccordionBus/DrawingAccordionBus.cs index ae52685..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 readonly int _busWidth = 200; - - /// - /// Высота прорисовки автобуса - /// - private readonly int _busHeight = 50; - - /// - /// Инициализация свойств + /// Конструктор /// /// Скорость /// Вес @@ -55,81 +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(); - EntityAccordionBus.Init(speed, weight, - bodyColor, additionalColor, - additionalBody, additionalDoor); - - // Проверка на вместимость объекта в размеры картинки - if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight)) + if (EntityBus != null) { - 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) - { - _startPosX += (int)EntityAccordionBus.Step; - } - break; - case DirectionType.Down: - if (_startPosY + EntityAccordionBus.Step < _pictureHeight) - { - _startPosY += (int)EntityAccordionBus.Step; - } - break; + EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, additionalBody, additionalDoor); } } @@ -137,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); @@ -192,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); @@ -215,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..d17cf17 --- /dev/null +++ b/AccordionBus/AccordionBus/DrawingBus.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AccordionBus.Entities; +using AccordionBus.MovementStrategy; + +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 GetHeight => _busHeight; + + /// + /// Получение объекта IMoveableObject из объекта DrawningCar + /// + public IMoveableObject GetMoveableObject => new DrawingObjectBus(this); + + /// + /// Проверка, что объект может перемещаться по указанному направлению + /// + /// направление + /// 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) + { + // Проверка на вместимость объекта в размеры картинки + if ((_busWidth >= width) || (_busHeight >= height)) + { + return; + } + + _pictureWidth = width; + _pictureHeight = height; + EntityBus = new EntityBus(speed, weight, bodyColor); + } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Ширина картинки + /// Высота картинки + /// Ширинка прорисовки автобуса + /// Выоста прорисовки автобуса + protected DrawingBus(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight) + { + // Проверка на вместимость объекта в размеры картинки + if ((_busWidth >= width) || (_busHeight >= height)) + { + return; + } + + _pictureWidth = width; + _pictureHeight = height; + _busWidth = busWidth; + _busHeight = busHeight; + EntityBus = new EntityBus(speed, weight, bodyColor); + } + + /// + /// Установка позиции + /// + /// Координата X + /// Координата Y + public void SetPosition(int x, int y) + { + if (x < 0 || y < 0) + { + _startPosX = 0; + _startPosY = 0; + } + else 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..60e9a17 --- /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.GetHeight); + } + } + + 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..109c222 --- /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 +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + public 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..30bcc2b --- /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 +{ + /// + /// Параметры-координаты объекта + /// + public 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/Program.cs b/AccordionBus/AccordionBus/Program.cs index 7a864f0..39e4d5e 100644 --- a/AccordionBus/AccordionBus/Program.cs +++ b/AccordionBus/AccordionBus/Program.cs @@ -11,7 +11,7 @@ namespace AccordionBus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new AccordionBusForm()); + Application.Run(new BusCollectionForm()); } } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/SetGeneric.cs b/AccordionBus/AccordionBus/SetGeneric.cs new file mode 100644 index 0000000..504d31c --- /dev/null +++ b/AccordionBus/AccordionBus/SetGeneric.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Generics +{ + /// + /// Параметризованный набор объектов + /// + /// + internal class SetGeneric where T : class + { + /// + /// Массив объектов, которые храним + /// + private readonly T?[] _places; + + /// + /// Количество объектов в массиве + /// + public int Count => _places.Length; + + /// + /// Конструктор + /// + /// + public SetGeneric(int count) + { + _places = new T?[count]; + } + + /// + /// Добавление объекта в набор + /// + /// Добавляемый автобус + /// + public int Insert(T bus) + { + return Insert(bus, 0); + } + + /// + /// Добавление объекта в набор на конкретную позицию + /// + /// Добавляемый автобус + /// Позиция + /// + public int Insert(T bus, int position) + { + // Проверка позиции + if (position < 0 || position >= Count) + { + return -1; + } + + // Проверка, что элемент массива по этой позиции пустой + if (_places[position] != null) + { + // Проверка, что после вставляемого элемента в массиве есть пустой элемент + int index = -1; + for (int i = position + 1; i < Count; i++) + { + if (_places[i] == null) + { + index = i; + break; + } + } + + // Проверка, если пустого элемента нет + if (index == -1) + { + return -1; + } + + // Сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента + int j = index - 1; + while (j >= position) + { + _places[j + 1] = _places[j]; + j--; + } + } + + // Вставка по позиции + _places[position] = bus; + return position; + } + + /// + /// Удаление объекта из набора с конкретной позиции + /// + /// Позициия + /// + public bool Remove(int position) + { + // Проверка позиции + if (position < 0 || position >= Count) + { + return false; + } + + // Удаление объекта из массива, присвоив элементу массива значение null + _places[position] = null; + return true; + } + + /// + /// Получение объекта из набора по позиции + /// + /// Позиция + /// + public T? Get(int position) + { + // Проверка позиции + if (position < 0 || position >= Count) + { + return null; + } + + return _places[position]; + } + } +} 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 + } +}