From 34308d5707770c98fa1ff7b5107a169ae33fa075 Mon Sep 17 00:00:00 2001 From: aaahsap Date: Wed, 20 Mar 2024 14:26:16 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 117 +++++++++++ .../ICollectionGenericObjects.cs | 50 +++++ .../MassiveGenericObjects.cs | 116 +++++++++++ .../CollectionGenericObjects/TruckPark.cs | 49 +++++ Lab1/Lab1/Drawnings/DrawningRoadTrain.cs | 6 +- Lab1/Lab1/Drawnings/DrawningTruck.cs | 2 +- Lab1/Lab1/FormRoadTrain.Designer.cs | 41 +--- Lab1/Lab1/FormRoadTrain.cs | 61 ++---- Lab1/Lab1/FormTruckCollection.Designer.cs | 173 ++++++++++++++++ Lab1/Lab1/FormTruckCollection.cs | 195 ++++++++++++++++++ Lab1/Lab1/FormTruckCollection.resx | 120 +++++++++++ .../Lab1/MovementStrategy/AbstractStrategy.cs | 4 +- Lab1/Lab1/MovementStrategy/MoveToBorder.cs | 6 + Lab1/Lab1/MovementStrategy/MoveToCenter.cs | 7 +- Lab1/Lab1/MovementStrategy/MoveableTruck.cs | 1 - Lab1/Lab1/Program.cs | 2 +- 16 files changed, 860 insertions(+), 90 deletions(-) create mode 100644 Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs create mode 100644 Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs create mode 100644 Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs create mode 100644 Lab1/Lab1/CollectionGenericObjects/TruckPark.cs create mode 100644 Lab1/Lab1/FormTruckCollection.Designer.cs create mode 100644 Lab1/Lab1/FormTruckCollection.cs create mode 100644 Lab1/Lab1/FormTruckCollection.resx diff --git a/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs b/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs new file mode 100644 index 0000000..5e0a3d7 --- /dev/null +++ b/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Lab1.Drawnings; +namespace Lab1.CollectionGenericObjects; + +public abstract class AbstractCompany +{ + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 180; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 90; + + /// + /// Ширина окна + /// + protected readonly int _pictureWidth; + + /// + /// Высота окна + /// + protected readonly int _pictureHeight; + + /// + /// Коллекция автомобилей + /// + protected ICollectionGenericObjects? _collection = null; + + /// + /// Вычисление максимального количества элементов, который можно разместить в окне + /// + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллекция автомобилей + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + { + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.SetMaxCount = GetMaxCount; + } + + /// + /// Перегрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static int operator +(AbstractCompany company, DrawningTruck truck) + { + return company._collection.Insert(truck); + } + + /// + /// Перегрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static DrawningTruck operator -(AbstractCompany company, int position) + { + return company._collection?.Remove(position); + } + + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawningTruck? GetRandomObject() + { + Random rnd = new(); + return _collection?.Get(rnd.Next(GetMaxCount)); + } + + /// + /// Вывод всей коллекции + /// + /// + public Bitmap? Show() + { + Bitmap bitmap = new(_pictureWidth, _pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackgound(graphics); + + SetObjectsPosition(); + for (int i = 0; i < (_collection?.Count ?? 0); ++i) + { + DrawningTruck? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + + return bitmap; + } + + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgound(Graphics g); + + /// + /// Расстановка объектов + /// + protected abstract void SetObjectsPosition(); +} diff --git a/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs new file mode 100644 index 0000000..d2d68f4 --- /dev/null +++ b/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1.CollectionGenericObjects; + +public interface ICollectionGenericObjects + where T : class +{ + /// + /// колличество объектов в коллекции + /// + int Count { get; } + + /// + /// Установка максимального количества элементов + /// + int SetMaxCount { set; } + + /// + /// Добавление объекта в коллекцию + /// + /// Добавляемый объект + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj); + + /// + /// Добавление объекта в коллекцию на конкретную позицию + /// + /// Добавляемый объект + /// Позиция + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj, int position); + + /// + /// Удаление объекта из коллекции с конкретной позиции + /// + /// Позиция + /// true - удаление прошло удачно, false - удаление не удалось + T Remove(int position); + + /// + /// Получение объекта по позиции + /// + /// Позиция + /// Объект + T? Get(int position); +} diff --git a/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs new file mode 100644 index 0000000..7c442b1 --- /dev/null +++ b/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1.CollectionGenericObjects; + +public class MassiveGenericObjects : ICollectionGenericObjects + where T : class +{ + /// + /// массив объектов, которые храним + /// + private T?[] _collection; + public int Count => _collection.Length; + + public int SetMaxCount + { + set + { + if (value > 0) + { + if (_collection.Length > 0) + { + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; + } + } + } + } + + /// + /// Конструктор + /// + public MassiveGenericObjects() + { + _collection = Array.Empty(); + } + + public T? Get(int position) + { + // TODO проверка позиции + if (position >= _collection.Length || position < 0) + { return null; } + return _collection[position]; + } + + public int Insert(T obj) + { + // TODO вставка в свободное место набора + int index = 0; + while (index < _collection.Length) + { + if (_collection[index] == null) + { + _collection[index] = obj; + return index; + } + + index++; + } + return -1; + } + + public int Insert(T obj, int position) + { + // TODO проверка позиции + // TODO проверка, что элемент массива по этой позиции пустой, если нет, то + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до + // TODO вставка + if (position >= _collection.Length || position < 0) + { return -1; } + + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + } + int index; + + for (index = position + 1; index < _collection.Length; ++index) + { + if (_collection[index] == null) + { + _collection[position] = obj; + return position; + } + } + + for (index = position - 1; index >= 0; --index) + { + if (_collection[index] == null) + { + _collection[position] = obj; + return position; + } + } + return -1; + } + + public T Remove(int position) + { + // TODO проверка позиции + // TODO удаление объекта из массива, присвоив элементу массива значение null + if (position >= _collection.Length || position < 0) + { return null; } + T obj = _collection[position]; + _collection[position] = null; + return obj; + } +} diff --git a/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs b/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs new file mode 100644 index 0000000..3d1e54a --- /dev/null +++ b/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Lab1.Drawnings; +namespace Lab1.CollectionGenericObjects; + +public class TruckPark : AbstractCompany +{ + /// + /// Конструктор + /// + /// + /// + /// + public TruckPark(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) + { + } + //TO DO + protected override void DrawBackgound(Graphics g) + { + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; + Pen pen = new(Color.Black, 3); + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height + 1; ++j) + { + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth - 15, j * _placeSizeHeight); + } + } + } + + //TO DO + protected override void SetObjectsPosition() + { + int count = 0; + for (int y = 5; y + 50 < _pictureHeight; y += 90) + { + for (int x = 5; x + 200 < _pictureWidth; x += _placeSizeHeight + 90) + { + _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(count)?.SetPosition(x, y); + count++; + } + } + } +} diff --git a/Lab1/Lab1/Drawnings/DrawningRoadTrain.cs b/Lab1/Lab1/Drawnings/DrawningRoadTrain.cs index 466193b..308a191 100644 --- a/Lab1/Lab1/Drawnings/DrawningRoadTrain.cs +++ b/Lab1/Lab1/Drawnings/DrawningRoadTrain.cs @@ -28,8 +28,10 @@ public class DrawningRoadTrain : DrawningTruck } - - public override void DrawTransport(Graphics g) + /// + /// переопределение метода DrawTransport + /// + public override void DrawTransport(Graphics g) { if (EntityTruck == null || EntityTruck is not EntityRoadTrain roadTrain || !_startPosX.HasValue || !_startPosY.HasValue) { diff --git a/Lab1/Lab1/Drawnings/DrawningTruck.cs b/Lab1/Lab1/Drawnings/DrawningTruck.cs index 92ff299..690872d 100644 --- a/Lab1/Lab1/Drawnings/DrawningTruck.cs +++ b/Lab1/Lab1/Drawnings/DrawningTruck.cs @@ -66,7 +66,7 @@ public class DrawningTruck public int GetHeight => _drawningCarHeight; - private DrawningTruck() + public DrawningTruck() { _pictureWidth = null; _pictureHeight = null; diff --git a/Lab1/Lab1/FormRoadTrain.Designer.cs b/Lab1/Lab1/FormRoadTrain.Designer.cs index f383397..d7052e3 100644 --- a/Lab1/Lab1/FormRoadTrain.Designer.cs +++ b/Lab1/Lab1/FormRoadTrain.Designer.cs @@ -8,7 +8,7 @@ private System.ComponentModel.IContainer components = null; /// - /// Clean up any resources being used. + /// Переопределение метода Dispose.Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) @@ -28,29 +28,16 @@ /// private void InitializeComponent() { - buttonCreate = new Button(); buttonLeft = new Button(); buttonUp = new Button(); buttonRight = new Button(); buttonDown = new Button(); pictureBoxYborshik = new PictureBox(); - buttonCreateTruck = new Button(); comboBoxStrategy = new ComboBox(); buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxYborshik).BeginInit(); SuspendLayout(); // - // buttonCreate - // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(2, 428); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(327, 29); - buttonCreate.TabIndex = 0; - buttonCreate.Text = "Создать подметально-уборочную машину\r\n"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; - // // buttonLeft // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; @@ -61,7 +48,7 @@ buttonLeft.Size = new Size(35, 35); buttonLeft.TabIndex = 1; buttonLeft.UseVisualStyleBackColor = true; - buttonLeft.Click += buttonMove_Click; + buttonLeft.Click += ButtonMove_Click; // // buttonUp // @@ -73,7 +60,7 @@ buttonUp.Size = new Size(35, 35); buttonUp.TabIndex = 2; buttonUp.UseVisualStyleBackColor = true; - buttonUp.Click += buttonMove_Click; + buttonUp.Click += ButtonMove_Click; // // buttonRight // @@ -85,7 +72,7 @@ buttonRight.Size = new Size(35, 35); buttonRight.TabIndex = 3; buttonRight.UseVisualStyleBackColor = true; - buttonRight.Click += buttonMove_Click; + buttonRight.Click += ButtonMove_Click; // // buttonDown // @@ -97,7 +84,7 @@ buttonDown.Size = new Size(35, 35); buttonDown.TabIndex = 4; buttonDown.UseVisualStyleBackColor = true; - buttonDown.Click += buttonMove_Click; + buttonDown.Click += ButtonMove_Click; // // pictureBoxYborshik // @@ -108,17 +95,6 @@ pictureBoxYborshik.TabIndex = 5; pictureBoxYborshik.TabStop = false; // - // buttonCreateTruck - // - buttonCreateTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreateTruck.Location = new Point(335, 425); - buttonCreateTruck.Name = "buttonCreateTruck"; - buttonCreateTruck.Size = new Size(141, 29); - buttonCreateTruck.TabIndex = 6; - buttonCreateTruck.Text = "Создать грузовик"; - buttonCreateTruck.UseVisualStyleBackColor = true; - buttonCreateTruck.Click += buttonCreateTruck_Click; - // // comboBoxStrategy // comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; @@ -137,7 +113,7 @@ buttonStrategyStep.TabIndex = 8; buttonStrategyStep.Text = "Шаг"; buttonStrategyStep.UseVisualStyleBackColor = true; - buttonStrategyStep.Click += buttonStrategyStep_Click; + buttonStrategyStep.Click += ButtonStrategyStep_Click; // // FormRoadTrain // @@ -146,12 +122,10 @@ ClientSize = new Size(851, 456); Controls.Add(buttonStrategyStep); Controls.Add(comboBoxStrategy); - Controls.Add(buttonCreateTruck); Controls.Add(buttonDown); Controls.Add(buttonRight); Controls.Add(buttonUp); Controls.Add(buttonLeft); - Controls.Add(buttonCreate); Controls.Add(pictureBoxYborshik); Name = "FormRoadTrain"; Text = "FormYborshik"; @@ -160,14 +134,11 @@ } #endregion - - private Button buttonCreate; private Button buttonLeft; private Button buttonUp; private Button buttonRight; private Button buttonDown; private PictureBox pictureBoxYborshik; - private Button buttonCreateTruck; private ComboBox comboBoxStrategy; private Button buttonStrategyStep; } diff --git a/Lab1/Lab1/FormRoadTrain.cs b/Lab1/Lab1/FormRoadTrain.cs index 557f837..e72d02b 100644 --- a/Lab1/Lab1/FormRoadTrain.cs +++ b/Lab1/Lab1/FormRoadTrain.cs @@ -28,6 +28,18 @@ namespace Lab1 /// private AbstractStrategy? _strategy; + public DrawningTruck SetTruck + { + set + { + _drawningTruck = value; + _drawningTruck.SetPictureSize(pictureBoxYborshik.Width, pictureBoxYborshik.Height); + comboBoxStrategy.Enabled = true; + _strategy = null; + Draw(); + } + } + /// /// Конструктор формы /// @@ -50,53 +62,8 @@ namespace Lab1 pictureBoxYborshik.Image = bmp; } - /// - /// Создание объекта класса-перемещения - /// - /// Тип создаваемого объекта - private void CreateObject(string type) - { - Random random = new(); - switch (type) - { - case nameof(DrawningTruck): - _drawningTruck = new DrawningTruck(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); - break; - case nameof(DrawningRoadTrain): - _drawningTruck = new DrawningRoadTrain(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - break; - default: - return; - } - _drawningTruck.SetPictureSize(pictureBoxYborshik.Width, pictureBoxYborshik.Height); - _drawningTruck.SetPosition(random.Next(10, 100), random.Next(10, 100)); - _strategy = null; - comboBoxStrategy.Enabled = true; - Draw(); - } - - - /// - /// Обработка нажатия кнопки "Создать" - /// - /// - /// - - private void buttonCreate_Click(object sender, EventArgs e) - { - CreateObject(nameof(DrawningRoadTrain)); - } - private void buttonCreateTruck_Click(object sender, EventArgs e) - { - CreateObject(nameof(DrawningTruck)); - } - - private void buttonMove_Click(object sender, EventArgs e) + private void ButtonMove_Click(object sender, EventArgs e) { if (_drawningTruck == null) { @@ -127,7 +94,7 @@ namespace Lab1 } } - private void buttonStrategyStep_Click(object sender, EventArgs e) + private void ButtonStrategyStep_Click(object sender, EventArgs e) { if (_drawningTruck == null) { diff --git a/Lab1/Lab1/FormTruckCollection.Designer.cs b/Lab1/Lab1/FormTruckCollection.Designer.cs new file mode 100644 index 0000000..cb7e01f --- /dev/null +++ b/Lab1/Lab1/FormTruckCollection.Designer.cs @@ -0,0 +1,173 @@ +namespace Lab1 +{ + partial class FormTruckCollection + { + /// + /// 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() + { + groupBoxTools = new GroupBox(); + buttonRefresh = new Button(); + buttonGoToCheck = new Button(); + buttonRemoveTruck = new Button(); + maskedTextBoxPosition = new MaskedTextBox(); + buttonAddRoadTrain = new Button(); + buttonAddTruck = new Button(); + comboBoxSelectorCompany = new ComboBox(); + pictureBox = new PictureBox(); + groupBoxTools.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + SuspendLayout(); + // + // groupBoxTools + // + groupBoxTools.Controls.Add(buttonRefresh); + groupBoxTools.Controls.Add(buttonGoToCheck); + groupBoxTools.Controls.Add(buttonRemoveTruck); + groupBoxTools.Controls.Add(maskedTextBoxPosition); + groupBoxTools.Controls.Add(buttonAddRoadTrain); + groupBoxTools.Controls.Add(buttonAddTruck); + groupBoxTools.Controls.Add(comboBoxSelectorCompany); + groupBoxTools.Dock = DockStyle.Right; + groupBoxTools.Location = new Point(807, 0); + groupBoxTools.Name = "groupBoxTools"; + groupBoxTools.Size = new Size(242, 628); + groupBoxTools.TabIndex = 0; + groupBoxTools.TabStop = false; + groupBoxTools.Text = "Инструменты"; + // + // buttonRefresh + // + buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRefresh.Location = new Point(16, 423); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(214, 58); + buttonRefresh.TabIndex = 6; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonGoToCheck + // + buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonGoToCheck.Location = new Point(16, 333); + buttonGoToCheck.Name = "buttonGoToCheck"; + buttonGoToCheck.Size = new Size(214, 58); + buttonGoToCheck.TabIndex = 5; + buttonGoToCheck.Text = "Передать на тесты"; + buttonGoToCheck.UseVisualStyleBackColor = true; + buttonGoToCheck.Click += ButtonGoToCheck_Click; + // + // buttonRemoveTruck + // + buttonRemoveTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRemoveTruck.Location = new Point(16, 248); + buttonRemoveTruck.Name = "buttonRemoveTruck"; + buttonRemoveTruck.Size = new Size(214, 58); + buttonRemoveTruck.TabIndex = 4; + buttonRemoveTruck.Text = "Удалить грузовик"; + buttonRemoveTruck.UseVisualStyleBackColor = true; + buttonRemoveTruck.Click += ButtonRemoveCar_Click; + // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Location = new Point(16, 215); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(214, 27); + maskedTextBoxPosition.TabIndex = 3; + maskedTextBoxPosition.ValidatingType = typeof(int); + // + // buttonAddRoadTrain + // + buttonAddRoadTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddRoadTrain.Location = new Point(16, 133); + buttonAddRoadTrain.Name = "buttonAddRoadTrain"; + buttonAddRoadTrain.Size = new Size(214, 58); + buttonAddRoadTrain.TabIndex = 2; + buttonAddRoadTrain.Text = "Добавление грузовика с дополнениями"; + buttonAddRoadTrain.UseVisualStyleBackColor = true; + buttonAddRoadTrain.Click += ButtonAddRoadTrain_Click; + // + // buttonAddTruck + // + buttonAddTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddTruck.Location = new Point(16, 98); + buttonAddTruck.Name = "buttonAddTruck"; + buttonAddTruck.Size = new Size(214, 29); + buttonAddTruck.TabIndex = 1; + buttonAddTruck.Text = "Добавление грузовика"; + buttonAddTruck.UseVisualStyleBackColor = true; + buttonAddTruck.Click += ButtonAddTruck_Click; + // + // comboBoxSelectorCompany + // + comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxSelectorCompany.FormattingEnabled = true; + comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); + comboBoxSelectorCompany.Location = new Point(16, 26); + comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; + comboBoxSelectorCompany.Size = new Size(214, 28); + comboBoxSelectorCompany.TabIndex = 0; + comboBoxSelectorCompany.Click += ComboBoxSelectorCompany_SelectedIndexChanged; + // + // pictureBox + // + pictureBox.Dock = DockStyle.Fill; + pictureBox.Location = new Point(0, 0); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(807, 628); + pictureBox.TabIndex = 1; + pictureBox.TabStop = false; + // + // FormTruckCollection + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1049, 628); + Controls.Add(pictureBox); + Controls.Add(groupBoxTools); + Name = "FormTruckCollection"; + Text = "Коллекция грузовиков"; + groupBoxTools.ResumeLayout(false); + groupBoxTools.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private GroupBox groupBoxTools; + private Button buttonAddTruck; + private ComboBox comboBoxSelectorCompany; + private MaskedTextBox maskedTextBoxPosition; + private Button buttonAddRoadTrain; + private PictureBox pictureBox; + private Button buttonRemoveTruck; + private Button buttonGoToCheck; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/Lab1/Lab1/FormTruckCollection.cs b/Lab1/Lab1/FormTruckCollection.cs new file mode 100644 index 0000000..ce6d3cd --- /dev/null +++ b/Lab1/Lab1/FormTruckCollection.cs @@ -0,0 +1,195 @@ +using Lab1.CollectionGenericObjects; +using Lab1.Drawnings; +using Lab1.MovementStrategy; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Lab1; + +public partial class FormTruckCollection : Form +{ + /// + /// Компания + /// + AbstractCompany? _company = null; + + /// + /// Конструктор + /// + public FormTruckCollection() + { + InitializeComponent(); + } + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new TruckPark(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + } + + /// + /// Добавление обычного автомобиля + /// + /// + /// + private void ButtonAddTruck_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTruck)); + + /// + /// Добавление спортивного автомобиля + /// + /// + /// + private void ButtonAddRoadTrain_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningRoadTrain)); + + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + + Random random = new(); + DrawningTruck drawningTruck; + switch (type) + { + case nameof(DrawningTruck): + drawningTruck = new DrawningTruck(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); + break; + case nameof(DrawningRoadTrain): + // TODO вызов диалогового окна для выбора цвета + drawningTruck = new DrawningRoadTrain(random.Next(100, 300), random.Next(1000, 3000), + GetColor(random), + GetColor(random), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + + if (_company + drawningTruck != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + + /// + /// Получение цвета + /// + /// Генератор случайных чисел + /// + private static Color GetColor(Random random) + { + 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; + } + + return color; + } + + /// + /// Удаление объекта + /// + /// + /// + private void ButtonRemoveCar_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + return; + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + } + + /// + /// Передача объекта в другую форму + /// + /// + /// + private void ButtonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawningTruck? truck = null; + int counter = 100; + while (truck == null) + { + truck = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (truck == null) + { + return; + } + + FormRoadTrain form = new() + { + SetTruck = truck + }; + form.ShowDialog(); + } + + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } +} diff --git a/Lab1/Lab1/FormTruckCollection.resx b/Lab1/Lab1/FormTruckCollection.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/Lab1/Lab1/FormTruckCollection.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/Lab1/Lab1/MovementStrategy/AbstractStrategy.cs b/Lab1/Lab1/MovementStrategy/AbstractStrategy.cs index c900f9b..bcbdf5d 100644 --- a/Lab1/Lab1/MovementStrategy/AbstractStrategy.cs +++ b/Lab1/Lab1/MovementStrategy/AbstractStrategy.cs @@ -34,7 +34,7 @@ public abstract class AbstractStrategy public StrategyStatus GetStatus() { return _state; } /// - /// Установка данных + /// Установка данных c полиморфизмом подтипов /// /// Перемещаемый объект /// Ширина поля @@ -126,7 +126,7 @@ public abstract class AbstractStrategy protected abstract bool IsTargetDestinaion(); /// - /// Попытка перемещения в требуемом направлении + /// Попытка перемещения в требуемом направлении c полиморфизмом подтипов /// /// Направление /// Результат попытки (true - удалось переместиться, false - неудача) diff --git a/Lab1/Lab1/MovementStrategy/MoveToBorder.cs b/Lab1/Lab1/MovementStrategy/MoveToBorder.cs index c09df3c..4f278bd 100644 --- a/Lab1/Lab1/MovementStrategy/MoveToBorder.cs +++ b/Lab1/Lab1/MovementStrategy/MoveToBorder.cs @@ -8,6 +8,9 @@ namespace Lab1.MovementStrategy; public class MoveToBorder : AbstractStrategy { + /// + /// Переопределение метода IsTargetDestinaion + /// protected override bool IsTargetDestinaion() { var objectparams = GetObjectParameters; @@ -21,6 +24,9 @@ public class MoveToBorder : AbstractStrategy return false; } + /// + /// Переопределение метода MoveToTarget + /// protected override void MoveToTarget() { var objectparams = GetObjectParameters; diff --git a/Lab1/Lab1/MovementStrategy/MoveToCenter.cs b/Lab1/Lab1/MovementStrategy/MoveToCenter.cs index 667bd6b..c9a7e45 100644 --- a/Lab1/Lab1/MovementStrategy/MoveToCenter.cs +++ b/Lab1/Lab1/MovementStrategy/MoveToCenter.cs @@ -8,6 +8,9 @@ namespace Lab1.MovementStrategy; public class MoveToCenter : AbstractStrategy { + /// + /// Переопределение метода IsTargetDestinaion + /// protected override bool IsTargetDestinaion() { ObjectParameters? objParams = GetObjectParameters; @@ -19,7 +22,9 @@ public class MoveToCenter : AbstractStrategy return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; } - + /// + /// Переопределение метода MoveToTarget + /// protected override void MoveToTarget() { ObjectParameters? objParams = GetObjectParameters; diff --git a/Lab1/Lab1/MovementStrategy/MoveableTruck.cs b/Lab1/Lab1/MovementStrategy/MoveableTruck.cs index fae960c..ac17c26 100644 --- a/Lab1/Lab1/MovementStrategy/MoveableTruck.cs +++ b/Lab1/Lab1/MovementStrategy/MoveableTruck.cs @@ -62,7 +62,6 @@ public class MoveableTruck : IMoveableObjectcs MovementDirection.Right => DirectionType.Right, MovementDirection.Up => DirectionType.Up, MovementDirection.Down => DirectionType.Down, - _ => DirectionType.Unknow, }; } } diff --git a/Lab1/Lab1/Program.cs b/Lab1/Lab1/Program.cs index a3fedfa..1fc53b0 100644 --- a/Lab1/Lab1/Program.cs +++ b/Lab1/Lab1/Program.cs @@ -11,7 +11,7 @@ namespace Lab1 // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormRoadTrain()); + Application.Run(new FormTruckCollection()); } } } \ No newline at end of file