From 3e84994000fde2f96577127f9a930805248eb8a8 Mon Sep 17 00:00:00 2001 From: ujijrujijr Date: Wed, 25 Oct 2023 20:28:25 +0300 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=BB=D0=B8=D0=BB=20=D0=BB=D0=B0?= =?UTF-8?q?=D0=B13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Trolleybus/BusesGenericCollection.cs | 156 +++++++++++++++ Trolleybus/Trolleybus/DrawingBus.cs | 5 + Trolleybus/Trolleybus/FormBusesCollection.cs | 181 ++++++++++++++++++ .../Trolleybus/FormBusesCollection.resx | 120 ++++++++++++ .../Trolleybus/FormTrolleybus.Designer.cs | 14 ++ Trolleybus/Trolleybus/FormTrolleybus.cs | 48 ++++- Trolleybus/Trolleybus/Program.cs | 2 +- Trolleybus/Trolleybus/SetGeneric.cs | 140 ++++++++++++++ 8 files changed, 661 insertions(+), 5 deletions(-) create mode 100644 Trolleybus/Trolleybus/BusesGenericCollection.cs create mode 100644 Trolleybus/Trolleybus/FormBusesCollection.cs create mode 100644 Trolleybus/Trolleybus/FormBusesCollection.resx create mode 100644 Trolleybus/Trolleybus/SetGeneric.cs diff --git a/Trolleybus/Trolleybus/BusesGenericCollection.cs b/Trolleybus/Trolleybus/BusesGenericCollection.cs new file mode 100644 index 0000000..9bc3b84 --- /dev/null +++ b/Trolleybus/Trolleybus/BusesGenericCollection.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using Trolleybus.DrawingObjects; +using Trolleybus.MovementStrategy; +namespace Trolleybus.Generics +{ + /// + /// Параметризованный класс для набора объектов DrawingBus + /// + /// + /// + internal class BusesGenericCollection + where T : DrawingBus + where U : IMoveableObject + { + /// + /// Ширина окна прорисовки + /// + private readonly int _pictureWidth; + /// + /// Высота окна прорисовки + /// + private readonly int _pictureHeight; + /// + /// Размер занимаемого объектом места (ширина) + /// + private readonly int _placeSizeWidth = 150; + /// + /// Размер занимаемого объектом места (высота) + /// + private readonly int _placeSizeHeight = 95; + /// + /// Набор объектов + /// + private readonly SetGeneric _collection; + /// + /// Конструктор + /// + /// + /// + public BusesGenericCollection(int picWidth, int picHeight) + { + int width = picWidth / _placeSizeWidth; //width - кол-во помещаемых на PictureBox автобусов по горизонтали + int height = picHeight / _placeSizeHeight; //height - кол-во помещаемых на PictureBox автобусов по вертикали + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = new SetGeneric(width * height); //width*height - кол-во мест на PictureBox для автобусов; размер массива + } + /// + /// Перегрузка оператора сложения + /// + /// + /// + /// + //Возвращается место в коллекции, в которое добавлено + public static int operator +(BusesGenericCollection collect, T? obj) + { + if (obj == null) + { + return -1; + } + return collect._collection.Insert(obj); + } + /// + /// Перегрузка оператора вычитания + /// + /// + /// + /// + public static bool operator -(BusesGenericCollection collect, int pos) + { + T? obj = collect._collection.Get(pos); + if (obj != null) + { + collect._collection.Remove(pos); + return true; + + } + return false; + } + + /// + /// Получение объекта IMoveableObject + /// + /// + /// + public U? GetU(int pos) + { + return (U?)_collection.Get(pos)?.GetMoveableObject; + } + /// + /// Вывод всего набора объектов + /// + /// + public Bitmap ShowBuses() + { + Bitmap bmp = new(_pictureWidth, _pictureHeight); + Graphics gr = Graphics.FromImage(bmp); + DrawBackground(gr); + DrawObjects(gr); + return bmp; + } + /// + /// Метод отрисовки фона + /// + /// + private void DrawBackground(Graphics g) + { + Pen pen = new(Color.Black, 3); + //вертикальные линии + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) + { + g.DrawLine(pen, i * (_placeSizeWidth + 10), 0, i * (_placeSizeWidth + 10), (_pictureHeight / _placeSizeHeight) * (_placeSizeHeight + 10)); + } + //горизонтальные линии + for (int i = 0; i <= _pictureHeight / _placeSizeHeight; i++) + { + for (int j = 0; j < _pictureWidth / _placeSizeWidth; j++) + { + g.DrawLine(pen, j * (_placeSizeWidth + 10), i * (_placeSizeHeight + 10), j * (_placeSizeWidth + 10) + _placeSizeWidth / 2, i * (_placeSizeHeight + 10)); + } + } + } + + /// + /// Метод прорисовки объектов + /// + /// + private void DrawObjects(Graphics g) + { + int i = 0; + int j = _pictureWidth / _placeSizeWidth - 1; + for (int k = 0; k < _collection.Count; k++) + { + DrawingBus bus = _collection.Get(k); + if (bus != null) + { + bus.SetPosition(j * (_placeSizeWidth + 10) + 5, i * (_placeSizeHeight) + 10); + bus.DrawTransport(g); + } + j--; + //переход на новую строчку + if (j < 0) + { + j = _pictureWidth / _placeSizeWidth - 1; + i++; + } + + } + } + } +} diff --git a/Trolleybus/Trolleybus/DrawingBus.cs b/Trolleybus/Trolleybus/DrawingBus.cs index a89bc36..114ecb1 100644 --- a/Trolleybus/Trolleybus/DrawingBus.cs +++ b/Trolleybus/Trolleybus/DrawingBus.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Trolleybus.Entities; +using Trolleybus.MovementStrategy; namespace Trolleybus.DrawingObjects { @@ -56,6 +57,10 @@ namespace Trolleybus.DrawingObjects /// Высота объекта /// public int GetHeight => _busHeight; + /// + /// Получение объекта IMoveableObject из объекта DrawningBus + /// + public IMoveableObject GetMoveableObject => new DrawingObjectBus(this); /// /// Конструктор diff --git a/Trolleybus/Trolleybus/FormBusesCollection.cs b/Trolleybus/Trolleybus/FormBusesCollection.cs new file mode 100644 index 0000000..9b53501 --- /dev/null +++ b/Trolleybus/Trolleybus/FormBusesCollection.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using Trolleybus.DrawingObjects; +using Trolleybus.Generics; +using Trolleybus.MovementStrategy; + +namespace Trolleybus +{ + /// + /// Форма для работы с набором объектов класса DrawingBus + /// + public partial class FormBusesCollection : Form + { + /// + /// Набор объектов + /// + private readonly BusesGenericCollection _buses; + /// + /// Конструктор + /// + public FormBusesCollection() + { + InitializeComponent(); + _buses = new BusesGenericCollection(pictureBoxCollection.Width, pictureBoxCollection.Height); + } + /// + /// Добавление объекта в набор + /// + /// + /// + private void ButtonAddBus_Click(object sender, EventArgs e) + { + FormTrolleybus form = new FormTrolleybus(); + 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; + } + String pos_string = maskedTextBoxNumber.Text; + if (pos_string == "") + { + pos_string = "0"; + } + int pos = Convert.ToInt32(pos_string); + if (_buses - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = _buses.ShowBuses(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + } + /// + /// Обновление рисунка по набору + /// + /// + /// + private void ButtonRefreshCollection_Click(object sender, EventArgs e) + { + pictureBoxCollection.Image = _buses.ShowBuses(); + } + + private void InitializeComponent() + { + pictureBoxCollection = new PictureBox(); + panelTools = new Panel(); + buttonRefreshCollection = new Button(); + maskedTextBoxNumber = new MaskedTextBox(); + buttonRemoveBus = new Button(); + buttonAddBus = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); + panelTools.SuspendLayout(); + SuspendLayout(); + // + // pictureBoxCollection + // + pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + pictureBoxCollection.Location = new Point(0, 0); + pictureBoxCollection.Name = "pictureBoxCollection"; + pictureBoxCollection.Size = new Size(670, 453); + pictureBoxCollection.TabIndex = 0; + pictureBoxCollection.TabStop = false; + // + // panelTools + // + panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; + panelTools.Controls.Add(buttonRefreshCollection); + panelTools.Controls.Add(maskedTextBoxNumber); + panelTools.Controls.Add(buttonRemoveBus); + panelTools.Controls.Add(buttonAddBus); + panelTools.Location = new Point(682, 0); + panelTools.Name = "panelTools"; + panelTools.Size = new Size(200, 453); + panelTools.TabIndex = 1; + // + // buttonRefreshCollection + // + buttonRefreshCollection.Location = new Point(17, 190); + buttonRefreshCollection.Name = "buttonRefreshCollection"; + buttonRefreshCollection.Size = new Size(170, 40); + buttonRefreshCollection.TabIndex = 3; + buttonRefreshCollection.Text = "Обновить коллекцию"; + buttonRefreshCollection.UseVisualStyleBackColor = true; + buttonRefreshCollection.Click += ButtonRefreshCollection_Click; + // + // maskedTextBoxNumber + // + maskedTextBoxNumber.Location = new Point(39, 76); + maskedTextBoxNumber.Mask = "00"; + maskedTextBoxNumber.Name = "maskedTextBoxNumber"; + maskedTextBoxNumber.Size = new Size(125, 27); + maskedTextBoxNumber.TabIndex = 2; + maskedTextBoxNumber.ValidatingType = typeof(int); + // + // buttonRemoveBus + // + buttonRemoveBus.Location = new Point(17, 125); + buttonRemoveBus.Name = "buttonRemoveBus"; + buttonRemoveBus.Size = new Size(170, 40); + buttonRemoveBus.TabIndex = 1; + buttonRemoveBus.Text = "Удалить автобус"; + buttonRemoveBus.UseVisualStyleBackColor = true; + buttonRemoveBus.Click += ButtonRemoveBus_Click; + // + // buttonAddBus + // + buttonAddBus.Location = new Point(17, 12); + buttonAddBus.Name = "buttonAddBus"; + buttonAddBus.Size = new Size(170, 40); + buttonAddBus.TabIndex = 0; + buttonAddBus.Text = "Добавить автобус"; + buttonAddBus.UseVisualStyleBackColor = true; + buttonAddBus.Click += ButtonAddBus_Click; + // + // FormBusCollection + // + ClientSize = new Size(882, 453); + Controls.Add(panelTools); + Controls.Add(pictureBoxCollection); + Name = "FormBusCollection"; + Text = "Набор автобусов"; + ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); + panelTools.ResumeLayout(false); + panelTools.PerformLayout(); + ResumeLayout(false); + } + + private PictureBox pictureBoxCollection; + private Panel panelTools; + private Button buttonRefreshCollection; + private MaskedTextBox maskedTextBoxNumber; + private Button buttonRemoveBus; + private Button buttonAddBus; + } +} diff --git a/Trolleybus/Trolleybus/FormBusesCollection.resx b/Trolleybus/Trolleybus/FormBusesCollection.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Trolleybus/Trolleybus/FormBusesCollection.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/Trolleybus/Trolleybus/FormTrolleybus.Designer.cs b/Trolleybus/Trolleybus/FormTrolleybus.Designer.cs index 610fd6e..d5ab5e2 100644 --- a/Trolleybus/Trolleybus/FormTrolleybus.Designer.cs +++ b/Trolleybus/Trolleybus/FormTrolleybus.Designer.cs @@ -37,6 +37,7 @@ buttonCreateBus = new Button(); comboBoxStrategy = new ComboBox(); buttonStep = new Button(); + buttonSelectBus = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit(); SuspendLayout(); // @@ -141,11 +142,23 @@ buttonStep.UseVisualStyleBackColor = true; buttonStep.Click += ButtonStep_Click; // + // buttonSelectBus + // + buttonSelectBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonSelectBus.Location = new Point(264, 388); + buttonSelectBus.Name = "buttonSelectBus"; + buttonSelectBus.Size = new Size(120, 50); + buttonSelectBus.TabIndex = 14; + buttonSelectBus.Text = "Выбрать"; + buttonSelectBus.UseVisualStyleBackColor = true; + buttonSelectBus.Click += ButtonSelectBus_Click; + // // FormTrolleybus // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(882, 453); + Controls.Add(buttonSelectBus); Controls.Add(buttonStep); Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateBus); @@ -172,5 +185,6 @@ private Button buttonCreateBus; private ComboBox comboBoxStrategy; private Button buttonStep; + private Button buttonSelectBus; } } \ No newline at end of file diff --git a/Trolleybus/Trolleybus/FormTrolleybus.cs b/Trolleybus/Trolleybus/FormTrolleybus.cs index 3ad371a..3e31af8 100644 --- a/Trolleybus/Trolleybus/FormTrolleybus.cs +++ b/Trolleybus/Trolleybus/FormTrolleybus.cs @@ -16,9 +16,16 @@ namespace Trolleybus /// /// private AbstractStrategy? _abstractStrategy; + /// + /// + /// + public DrawingBus? SelectedBus { get; private set; } + public FormTrolleybus() { InitializeComponent(); + _abstractStrategy = null; + SelectedBus = null; } /// /// @@ -42,10 +49,26 @@ namespace Trolleybus private void ButtonCreateTrolleybus_Click(object sender, EventArgs e) { Random random = new(); + Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + + // + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + color = dialog.Color; + } + Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + + // + ColorDialog dopDialog = new(); + if (dopDialog.ShowDialog() == DialogResult.OK) + { + dopColor = dopDialog.Color; + } _drawingBus = new DrawingTrolleybus(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)), + color, + dopColor, Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height); @@ -61,10 +84,16 @@ namespace Trolleybus private void ButtonCreateBus_Click(object sender, EventArgs e) { Random random = new(); + // + Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + color = dialog.Color; + } _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)), + color, pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height); _drawingBus.SetPosition(random.Next(10, 100), random.Next(10, 100)); Draw(); @@ -138,5 +167,16 @@ namespace Trolleybus _abstractStrategy = null; } } + + /// + /// + /// + /// + /// + private void ButtonSelectBus_Click(object sender, EventArgs e) + { + SelectedBus = _drawingBus; + DialogResult = DialogResult.OK; + } } } \ No newline at end of file diff --git a/Trolleybus/Trolleybus/Program.cs b/Trolleybus/Trolleybus/Program.cs index 1e98dfe..728fe68 100644 --- a/Trolleybus/Trolleybus/Program.cs +++ b/Trolleybus/Trolleybus/Program.cs @@ -11,7 +11,7 @@ namespace Trolleybus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTrolleybus()); + Application.Run(new FormBusesCollection()); } } } \ No newline at end of file diff --git a/Trolleybus/Trolleybus/SetGeneric.cs b/Trolleybus/Trolleybus/SetGeneric.cs new file mode 100644 index 0000000..6c615cb --- /dev/null +++ b/Trolleybus/Trolleybus/SetGeneric.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Trolleybus.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) + { + if (_places[0] == null) + { + _places[0] = bus; + //0 в данном случае - индекс в массиве, вставка прошла успешно + return 0; + } + else + { + int index = 0; + while (_places[index] != null) + { + index++; + if (index >= Count) + { + //места в массиве нет, ни по какому индексу вставить нельзя + return -1; + } + } + //cдвиг элементов + for (int i = index; i > 0; i--) + { + _places[i] = _places[i - 1]; + + } + _places[0] = bus; + //0 в данном случае - индекс в массиве, вставка прошла успешно + return 0; + } + + } + /// + /// Добавление объекта в набор на конкретную позицию + /// + /// Добавляемый автобус + /// Позиция + /// + public int Insert(T bus, int position) + { + if (position >= Count || position < 0) + { + //индекс неверный, значит вставить по индексу нельзя + return -1; + } + if (_places[position] == null) + { + _places[position] = bus; + } + else + { + //проверка, что в массиве после вставляемого эл-а есть место + int index = position; + while (_places[index] != null) + { + index++; + if (index >= Count) + { + //места в массиве нет, ни по какому индексу вставить нельзя + return -1; + } + } + //сдвиг элементов + for (int i = index; i > position; i--) + { + _places[i] = _places[i - 1]; + + } + //вставка по позиции + _places[position] = bus; + + } + //индекс в массиве, по которому вставили, вставка прошла успешно + return position; + } + /// + /// Удаление объекта из набора с конкретной позиции + /// + /// + /// + public bool Remove(int position) + { + if (position >= Count || position < 0) + { + return false; + } + _places[position] = null; + return true; + } + /// + /// Получение объекта из набора по позиции + /// + /// + /// + public T? Get(int position) + { + if (position >= Count || position < 0) + { + return null; + } + return _places[position]; + } + } +}