diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs new file mode 100644 index 0000000..cf6e208 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs @@ -0,0 +1,116 @@ +using ProjectExcavator.Drawnings; + +namespace ProjectExcavator.CollectionGenericObjects; + +/// +/// Абстракция компании, хранящий коллекцию экскаваторов/Гусеничных машин +/// +public abstract class AbstractCompany +{ + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 180; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 60; + + /// + /// Ширина окна + /// + 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, DrawningTrackedVehicle excavator) + { + return company._collection.Insert(excavator); + } + + /// + /// Перегрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) + { + return company._collection.Remove(position); + } + + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawningTrackedVehicle? 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) + { + DrawningTrackedVehicle? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + + return bitmap; + } + + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgound(Graphics g); + + /// + /// Расстановка объектов + /// + protected abstract void SetObjectsPosition(); +} diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs new file mode 100644 index 0000000..370da23 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs @@ -0,0 +1,68 @@ +using ProjectExcavator.Drawnings; + +namespace ProjectExcavator.CollectionGenericObjects; + +/// +/// Реализация абстрактной компании - Гараж +/// +internal class GarageService : AbstractCompany +{ + /// + /// Конструктор + /// + /// + /// + /// + public GarageService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) + { + } + + protected override void DrawBackgound(Graphics g) + { + Pen pen = new Pen(Color.Black, 3f); + + + int PlaceWidth = _pictureWidth / _placeSizeWidth; + int PlaceHeight = _pictureHeight / _placeSizeHeight; + int Indent = 20; + + + for (int i = 0; i < PlaceHeight / 2; i++) + { + g.DrawLine(pen, Indent , i * _placeSizeHeight * 2, PlaceWidth * _placeSizeWidth + Indent, i * _placeSizeHeight * 2); + for (int j = 0; j < PlaceWidth + 1; ++j) + { + g.DrawLine(pen, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2 + _placeSizeHeight); + } + } + } + + protected override void SetObjectsPosition() + { + + int col = _collection?.Count ?? 0; + + int LevelWidth = 0; + int LevelHeight = 0; + + for (int i = 0; i < col; i++) + { + if (LevelHeight + 1 > _pictureHeight/ (_placeSizeHeight + 60)) + { + return; + } + + _collection?.Get(i)?.SetPosition((_pictureWidth - 190) - _placeSizeWidth * LevelWidth, 20 + (_placeSizeHeight + 60) * LevelHeight ); + + if (LevelWidth + 1 < _pictureWidth / _placeSizeWidth) + { + LevelWidth++; + } + else + { + LevelWidth = 0; + LevelHeight++; + } + } + } +} diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs new file mode 100644 index 0000000..e0f246d --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -0,0 +1,48 @@ +namespace ProjectExcavator.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/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs new file mode 100644 index 0000000..c953890 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -0,0 +1,133 @@ +namespace ProjectExcavator.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) + { + //Проверка позиции + + if (position < 0 || position > Count-1) + { + return null; + } + else + { + return _collection[position]; + } + } + + public int Insert(T obj) + { + //Вставка в свободное место набора + + for (int i = 0; i < Count -1; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + return -1; + } + + public int Insert(T obj, int position) + { + //Проверка позиции + //Проверка, что элемент массива по этой позиции пустой, если нет, то + //Ищется свободное место после этой позиции и идет вставка туда + //если нет после, ищем до вставка + + if (position >= Count || position < 0) return -1; + + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + } + else + { + int after_position = position + 1; + while (after_position < Count) + { + if (_collection[after_position] == null) + { + _collection[after_position] = obj; + return after_position; + } + after_position ++; + } + + int behind_position = position - 1; + while (behind_position >= 0) + { + if (_collection[behind_position] == null) + { + _collection[behind_position] = obj; + return behind_position; + } + behind_position --; + } + + return -1; + + } + } + + public T? Remove(int position) + { + // Проверка позиции + // Удаление объекта из массива, присвоив элементу массива значение null + + T? obj = _collection[position]; + if (position < 0 || _collection[position] == null || position > Count -1) + { + return null; + } + + else + { + _collection[position] = null; + return obj; + } + } + +} diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs index 951b599..fef274d 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs @@ -5,7 +5,7 @@ namespace ProjectExcavator.Drawnings; /// /// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// -public class DrawningExcavator : DrawningBaseExcavator +public class DrawningExcavator : DrawningTrackedVehicle { /// /// Конструктор @@ -18,12 +18,12 @@ public class DrawningExcavator : DrawningBaseExcavator /// Признак наличия поддержки public DrawningExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool bucket, bool supports) : base(135, 82) { - EntityBaseExcavator = new EntityExcavator(speed, weight, bodyColor, additionalColor, bucket, supports); + EntityTrackedVehicle = new EntityExcavator(speed, weight, bodyColor, additionalColor, bucket, supports); } public override void DrawTransport(Graphics g) { - if (EntityBaseExcavator == null|| EntityBaseExcavator is not EntityExcavator excavator || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTrackedVehicle == null|| EntityTrackedVehicle is not EntityExcavator excavator || !_startPosX.HasValue || !_startPosY.HasValue) { return; } diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBaseExcavator.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicle.cs similarity index 83% rename from ProjectExcavator/ProjectExcavator/Drawnings/DrawningBaseExcavator.cs rename to ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicle.cs index b0838c6..1cf7de9 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBaseExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicle.cs @@ -5,12 +5,12 @@ namespace ProjectExcavator.Drawnings; /// /// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// -public class DrawningBaseExcavator +public class DrawningTrackedVehicle { /// /// Класс-сущность /// - public EntityBaseExcavator? EntityBaseExcavator { get; protected set; } + public TrackedVehicle? EntityTrackedVehicle { get; protected set; } /// /// Ширина окна @@ -23,22 +23,22 @@ public class DrawningBaseExcavator private int? _pictureHeight; /// - /// Левая координата прорисовки Экскаватора + /// Левая координата прорисовки Гусеничной машины /// protected int? _startPosX; /// - /// Верхняя кооридната прорисовки Экскаватора + /// Верхняя кооридната прорисовки гусеничной машины /// protected int? _startPosY; /// - /// Ширина прорисовки Экскаватора + /// Ширина прорисовки гусеничной машины /// private readonly int _drawningExcavatorWidth = 78; /// - /// Высота прорисовки Экскаватора + /// Высота прорисовки гусеничной машины /// private readonly int _drawningExcavatorHeight = 63; @@ -65,7 +65,7 @@ public class DrawningBaseExcavator /// /// Пустой конструктор /// - private DrawningBaseExcavator() + private DrawningTrackedVehicle() { _pictureWidth = null; _pictureHeight = null; @@ -79,17 +79,17 @@ public class DrawningBaseExcavator /// Скорость /// Вес /// Основной цвет - public DrawningBaseExcavator(int speed, double weight, Color bodyColor) : this() + public DrawningTrackedVehicle(int speed, double weight, Color bodyColor) : this() { - EntityBaseExcavator = new EntityBaseExcavator(speed, weight, bodyColor); + EntityTrackedVehicle = new TrackedVehicle(speed, weight, bodyColor); } /// /// Конструктор для наследников /// - /// Ширина прорисовки Экскаватора - /// Высота прорисовки Экскаватора - protected DrawningBaseExcavator(int drawningExcavatorWidth, int drawningExcavatorHeight) : this() + /// Ширина прорисовки гусеничной машины + /// Высота прорисовки гусеничной машины + protected DrawningTrackedVehicle(int drawningExcavatorWidth, int drawningExcavatorHeight) : this() { _drawningExcavatorWidth = drawningExcavatorWidth; _drawningExcavatorHeight = drawningExcavatorHeight; @@ -106,7 +106,7 @@ public class DrawningBaseExcavator //проверка, что объект "влезает" в размеры поля if (_drawningExcavatorWidth > width || _drawningExcavatorHeight > height) { - EntityBaseExcavator = null; + EntityTrackedVehicle = null; return false; } @@ -169,7 +169,7 @@ public class DrawningBaseExcavator /// true - перемещене выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityBaseExcavator == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } @@ -178,30 +178,30 @@ public class DrawningBaseExcavator { //влево case DirectionType.Left: - if (_startPosX.Value - EntityBaseExcavator.Step > 0) + if (_startPosX.Value - EntityTrackedVehicle.Step > 0) { - _startPosX -= (int)EntityBaseExcavator.Step; + _startPosX -= (int)EntityTrackedVehicle.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityBaseExcavator.Step > 0) + if (_startPosY.Value - EntityTrackedVehicle.Step > 0) { - _startPosY -= (int)EntityBaseExcavator.Step; + _startPosY -= (int)EntityTrackedVehicle.Step; } return true; // вправо case DirectionType.Right: - if (_startPosX.Value + EntityBaseExcavator.Step < _pictureWidth - _drawningExcavatorWidth) + if (_startPosX.Value + EntityTrackedVehicle.Step < _pictureWidth - _drawningExcavatorWidth) { - _startPosX += (int)EntityBaseExcavator.Step; + _startPosX += (int)EntityTrackedVehicle.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + EntityBaseExcavator.Step < _pictureHeight - _drawningExcavatorHeight) + if (_startPosY.Value + EntityTrackedVehicle.Step < _pictureHeight - _drawningExcavatorHeight) { - _startPosY += (int)EntityBaseExcavator.Step; + _startPosY += (int)EntityTrackedVehicle.Step; } return true; default: @@ -215,7 +215,7 @@ public class DrawningBaseExcavator /// public virtual void DrawTransport(Graphics g) { - if (EntityBaseExcavator == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } @@ -225,7 +225,7 @@ public class DrawningBaseExcavator Brush brBrown = new SolidBrush(Color.DarkSlateGray); //контур и заливка основы - Brush br = new SolidBrush(EntityBaseExcavator.BodyColor); + Brush br = new SolidBrush(EntityTrackedVehicle.BodyColor); g.FillRectangle(br, _startPosX.Value + 51, _startPosY.Value, 25, 25);//кабина g.DrawRectangle(pen, _startPosX.Value + 51, _startPosY.Value, 25, 25); diff --git a/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs b/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs index 3bb5508..c47796c 100644 --- a/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs @@ -3,7 +3,7 @@ /// /// Класс-сущность "Экскаватор" /// -public class EntityExcavator : EntityBaseExcavator +public class EntityExcavator : TrackedVehicle { /// /// Дополнительный цвет (для опциональных элементов) diff --git a/ProjectExcavator/ProjectExcavator/Entities/EntityBaseExcavator.cs b/ProjectExcavator/ProjectExcavator/Entities/TrackedVehicle.cs similarity index 71% rename from ProjectExcavator/ProjectExcavator/Entities/EntityBaseExcavator.cs rename to ProjectExcavator/ProjectExcavator/Entities/TrackedVehicle.cs index c0fd356..c577bde 100644 --- a/ProjectExcavator/ProjectExcavator/Entities/EntityBaseExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Entities/TrackedVehicle.cs @@ -1,9 +1,9 @@ namespace ProjectExcavator.Entities; /// -/// Класс-сущность "Базовый Экскаватор" +/// Класс-сущность "Гусеничная Машина" /// -public class EntityBaseExcavator +public class TrackedVehicle { /// /// Скорость @@ -21,7 +21,7 @@ public class EntityBaseExcavator public Color BodyColor { get; private set; } /// - /// Шаг перемещения Экскаватора + /// Шаг перемещения Экскаватора/Гусеничной машины /// public double Step => Speed * 100 / Weight; @@ -29,10 +29,10 @@ public class EntityBaseExcavator /// Конструктор сущности /// /// Скорость - /// Вес Экскаватора + /// Вес /// Основной цвет - public EntityBaseExcavator(int speed, double weight, Color bodyColor) + public TrackedVehicle(int speed, double weight, Color bodyColor) { Speed = speed; Weight = weight; diff --git a/ProjectExcavator/ProjectExcavator/FormExcavator.Designer.cs b/ProjectExcavator/ProjectExcavator/FormExcavator.Designer.cs index 25b4602..5458504 100644 --- a/ProjectExcavator/ProjectExcavator/FormExcavator.Designer.cs +++ b/ProjectExcavator/ProjectExcavator/FormExcavator.Designer.cs @@ -29,12 +29,10 @@ private void InitializeComponent() { pictureBoxExcavator = new PictureBox(); - buttonCreateExcavator = new Button(); buttonLeft = new Button(); buttonDown = new Button(); buttonUp = new Button(); buttonRight = new Button(); - ButtonCreateBaseExcavator = new Button(); comboBoxStrategy = new ComboBox(); buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit(); @@ -49,16 +47,6 @@ pictureBoxExcavator.TabIndex = 0; pictureBoxExcavator.TabStop = false; // - // buttonCreateExcavator - // - buttonCreateExcavator.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreateExcavator.Location = new Point(12, 540); - buttonCreateExcavator.Name = "buttonCreateExcavator"; - buttonCreateExcavator.Size = new Size(250, 45); - buttonCreateExcavator.TabIndex = 0; - buttonCreateExcavator.Text = "Создать усиленный экскаватор"; - buttonCreateExcavator.Click += ButtonCreateExcavator_Click; - // // buttonLeft // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; @@ -107,16 +95,6 @@ buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += ButtonMove_Click; // - // ButtonCreateBaseExcavator - // - ButtonCreateBaseExcavator.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - ButtonCreateBaseExcavator.Location = new Point(265, 540); - ButtonCreateBaseExcavator.Name = "ButtonCreateBaseExcavator"; - ButtonCreateBaseExcavator.Size = new Size(250, 45); - ButtonCreateBaseExcavator.TabIndex = 5; - ButtonCreateBaseExcavator.Text = "Создать обычный экскаватор"; - ButtonCreateBaseExcavator.Click += ButtonCreateBaseExcavator_Click; - // // comboBoxStrategy // comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -146,12 +124,10 @@ ClientSize = new Size(905, 597); Controls.Add(buttonStrategyStep); Controls.Add(comboBoxStrategy); - Controls.Add(ButtonCreateBaseExcavator); Controls.Add(buttonRight); Controls.Add(buttonUp); Controls.Add(buttonDown); Controls.Add(buttonLeft); - Controls.Add(buttonCreateExcavator); Controls.Add(pictureBoxExcavator); Name = "FormExcavator"; Text = "Экскаватор"; @@ -162,12 +138,10 @@ #endregion private PictureBox pictureBoxExcavator; - private Button buttonCreateExcavator; private Button buttonLeft; private Button buttonDown; private Button buttonUp; private Button buttonRight; - private Button ButtonCreateBaseExcavator; private ComboBox comboBoxStrategy; private Button buttonStrategyStep; } diff --git a/ProjectExcavator/ProjectExcavator/FormExcavator.cs b/ProjectExcavator/ProjectExcavator/FormExcavator.cs index 56a58f4..c00b931 100644 --- a/ProjectExcavator/ProjectExcavator/FormExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/FormExcavator.cs @@ -5,20 +5,35 @@ namespace ProjectExcavator; /// -/// Форма работы с объектом "Усиленный экскаватор" +/// Форма работы с объектом "Экскаватор" /// public partial class FormExcavator : Form { /// /// Поле-объект для прорисовки объекта /// - private DrawningBaseExcavator? _drawningBaseExcavator; + private DrawningTrackedVehicle? _drawningTrackedVehicle; /// /// Стратегия перемещения /// private AbstractStrategy? _strategy; + /// + /// Получение объекта + /// + public DrawningTrackedVehicle SetTrackedVehicle + { + set + { + _drawningTrackedVehicle = value; + _drawningTrackedVehicle.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height); + comboBoxStrategy.Enabled = true; + _strategy = null; + Draw(); + } + } + /// /// Конструктор формы /// @@ -33,61 +48,17 @@ public partial class FormExcavator : Form /// private void Draw() { - if (_drawningBaseExcavator == null) + if (_drawningTrackedVehicle == null) { return; } Bitmap bmp = new(pictureBoxExcavator.Width, pictureBoxExcavator.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningBaseExcavator.DrawTransport(gr); + _drawningTrackedVehicle.DrawTransport(gr); pictureBoxExcavator.Image = bmp; } - /// - /// Создание объекта класса-перемещения - /// - /// Тип создаваемого объекта - private void CreateObject(string type) - { - Random random = new(); - switch (type) - { - case nameof(DrawningBaseExcavator): - _drawningBaseExcavator = new DrawningBaseExcavator(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(DrawningExcavator): - _drawningBaseExcavator = new DrawningExcavator(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; - } - - _drawningBaseExcavator.SetPictureSize(pictureBoxExcavator.Width, pictureBoxExcavator.Height); - _drawningBaseExcavator.SetPosition(random.Next(10, 100), random.Next(10, 100)); - _strategy = null; - comboBoxStrategy.Enabled = true; - Draw(); - } - - /// - /// Обработка нажатия кнопки "Создать усиленный экскаватор" - /// - /// - /// - private void ButtonCreateExcavator_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningExcavator)); - - /// - /// Обработка нажатия "Создать обычный экскаватор" - /// - /// - /// - private void ButtonCreateBaseExcavator_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBaseExcavator)); - /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -95,7 +66,7 @@ public partial class FormExcavator : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningBaseExcavator == null) + if (_drawningTrackedVehicle == null) { return; } @@ -105,16 +76,16 @@ public partial class FormExcavator : Form switch (name) { case "buttonUp": - result = _drawningBaseExcavator.MoveTransport(DirectionType.Up); + result = _drawningTrackedVehicle.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningBaseExcavator.MoveTransport(DirectionType.Down); + result = _drawningTrackedVehicle.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningBaseExcavator.MoveTransport(DirectionType.Left); + result = _drawningTrackedVehicle.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningBaseExcavator.MoveTransport(DirectionType.Right); + result = _drawningTrackedVehicle.MoveTransport(DirectionType.Right); break; } @@ -132,7 +103,7 @@ public partial class FormExcavator : Form /// private void ButtonStrategyStep_Click(object sender, EventArgs e) { - if (_drawningBaseExcavator == null) + if (_drawningTrackedVehicle == null) { return; } @@ -149,7 +120,7 @@ public partial class FormExcavator : Form { return; } - _strategy.SetData(new MoveableBaseExcavator(_drawningBaseExcavator), pictureBoxExcavator.Width, pictureBoxExcavator.Height); + _strategy.SetData(new MoveableTrackedVehicle(_drawningTrackedVehicle), pictureBoxExcavator.Width, pictureBoxExcavator.Height); } if (_strategy == null) diff --git a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.Designer.cs b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.Designer.cs new file mode 100644 index 0000000..dbbe438 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.Designer.cs @@ -0,0 +1,168 @@ +namespace ProjectExcavator +{ + partial class FormExcavatorCollection + { + /// + /// 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(); + ButtonRemoveExcavator = new Button(); + maskedTextBoxPosition = new MaskedTextBox(); + buttonAddExcavator = new Button(); + buttonAddTrackedVehicle = 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(ButtonRemoveExcavator); + groupBoxTools.Controls.Add(maskedTextBoxPosition); + groupBoxTools.Controls.Add(buttonAddExcavator); + groupBoxTools.Controls.Add(buttonAddTrackedVehicle); + groupBoxTools.Controls.Add(comboBoxSelectorCompany); + groupBoxTools.Dock = DockStyle.Right; + groupBoxTools.Location = new Point(777, 0); + groupBoxTools.Name = "groupBoxTools"; + groupBoxTools.Size = new Size(225, 639); + groupBoxTools.TabIndex = 0; + groupBoxTools.TabStop = false; + groupBoxTools.Text = "Инструменты"; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(13, 554); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(200, 60); + buttonRefresh.TabIndex = 6; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonGoToCheck + // + buttonGoToCheck.Location = new Point(13, 469); + buttonGoToCheck.Name = "buttonGoToCheck"; + buttonGoToCheck.Size = new Size(200, 60); + buttonGoToCheck.TabIndex = 5; + buttonGoToCheck.Text = "Передать на тесты"; + buttonGoToCheck.UseVisualStyleBackColor = true; + buttonGoToCheck.Click += ButtonGoToCheck_Click; + // + // ButtonRemoveExcavator + // + ButtonRemoveExcavator.Location = new Point(10, 386); + ButtonRemoveExcavator.Name = "ButtonRemoveExcavator"; + ButtonRemoveExcavator.Size = new Size(200, 60); + ButtonRemoveExcavator.TabIndex = 4; + ButtonRemoveExcavator.Text = "Удаление транспорта"; + ButtonRemoveExcavator.UseVisualStyleBackColor = true; + ButtonRemoveExcavator.Click += ButtonRemoveExcavator_Click; + // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Location = new Point(13, 281); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(200, 27); + maskedTextBoxPosition.TabIndex = 3; + maskedTextBoxPosition.ValidatingType = typeof(int); + // + // buttonAddExcavator + // + buttonAddExcavator.Location = new Point(13, 164); + buttonAddExcavator.Name = "buttonAddExcavator"; + buttonAddExcavator.Size = new Size(200, 65); + buttonAddExcavator.TabIndex = 2; + buttonAddExcavator.Text = "Добавление экскаватора"; + buttonAddExcavator.UseVisualStyleBackColor = true; + buttonAddExcavator.Click += ButtonAddExcavator_Click; + // + // buttonAddTrackedVehicle + // + buttonAddTrackedVehicle.Location = new Point(10, 93); + buttonAddTrackedVehicle.Name = "buttonAddTrackedVehicle"; + buttonAddTrackedVehicle.Size = new Size(200, 65); + buttonAddTrackedVehicle.TabIndex = 1; + buttonAddTrackedVehicle.Text = "Добавление гусеничной машины"; + buttonAddTrackedVehicle.UseVisualStyleBackColor = true; + buttonAddTrackedVehicle.Click += ButtonAddTrackedVehicle_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(10, 26); + comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; + comboBoxSelectorCompany.Size = new Size(200, 28); + comboBoxSelectorCompany.TabIndex = 0; + comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; + // + // pictureBox + // + pictureBox.Dock = DockStyle.Fill; + pictureBox.Location = new Point(0, 0); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(777, 639); + pictureBox.TabIndex = 1; + pictureBox.TabStop = false; + // + // FormExcavatorCollection + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1002, 639); + Controls.Add(pictureBox); + Controls.Add(groupBoxTools); + Name = "FormExcavatorCollection"; + Text = "Коллекция экскаваторов"; + groupBoxTools.ResumeLayout(false); + groupBoxTools.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private GroupBox groupBoxTools; + private ComboBox comboBoxSelectorCompany; + private Button buttonAddExcavator; + private Button buttonAddTrackedVehicle; + private PictureBox pictureBox; + private Button ButtonRemoveExcavator; + private MaskedTextBox maskedTextBoxPosition; + private Button buttonGoToCheck; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs new file mode 100644 index 0000000..1fc62c0 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs @@ -0,0 +1,184 @@ +using ProjectExcavator.CollectionGenericObjects; +using ProjectExcavator.Drawnings; + +namespace ProjectExcavator; +/// +/// Форма работы с компанией и ее коллекцией +/// +public partial class FormExcavatorCollection : Form +{ + /// + /// Компания + /// + private AbstractCompany? _company = null; + + /// + /// Конструктор + /// + public FormExcavatorCollection() + { + InitializeComponent(); + } + + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new GarageService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + } + + /// + /// Добавление гусеничной машины + /// + /// + /// + private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrackedVehicle)); + + + /// + /// Добавление экскаватора + /// + /// + /// + private void ButtonAddExcavator_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningExcavator)); + + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + + Random random = new(); + DrawningTrackedVehicle drawningTrackedVehicle; + switch (type) + { + case nameof(DrawningTrackedVehicle): + drawningTrackedVehicle = new DrawningTrackedVehicle(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); + break; + case nameof(DrawningExcavator): + drawningTrackedVehicle = new DrawningExcavator(random.Next(100, 300), random.Next(1000, 3000), GetColor(random), GetColor(random), true, true); + break; + default: + return; + } + + if (_company + drawningTrackedVehicle != -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 ButtonRemoveExcavator_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + return; + } + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + 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; + } + + DrawningTrackedVehicle? TrackedVehicle = null; + int counter = 100; + while (TrackedVehicle == null) + { + TrackedVehicle = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (TrackedVehicle == null) + { + return; + } + + FormExcavator form = new() + { + SetTrackedVehicle = TrackedVehicle + }; + form.ShowDialog(); + } + + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } +} diff --git a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.resx b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.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/ProjectExcavator/ProjectExcavator/MovementStrategy/MoveableBaseExcavator.cs b/ProjectExcavator/ProjectExcavator/MovementStrategy/MoveableTrackedVehicle.cs similarity index 53% rename from ProjectExcavator/ProjectExcavator/MovementStrategy/MoveableBaseExcavator.cs rename to ProjectExcavator/ProjectExcavator/MovementStrategy/MoveableTrackedVehicle.cs index 8d92e83..a846ae8 100644 --- a/ProjectExcavator/ProjectExcavator/MovementStrategy/MoveableBaseExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/MovementStrategy/MoveableTrackedVehicle.cs @@ -3,46 +3,46 @@ namespace ProjectExcavator.MovementStrategy; /// -/// Класс-реализация IMoveableObject с использованием DrawningBaseExcavator +/// Класс-реализация IMoveableObject с использованием DrawningTrackedVehicle /// -public class MoveableBaseExcavator : IMoveableObject +public class MoveableTrackedVehicle : IMoveableObject { /// - /// Поле-объект класса DrawningBaseExcavator или его наследника + /// Поле-объект класса DrawningTrackedVehicle или его наследника /// - private readonly DrawningBaseExcavator? _baseExcavator = null; + private readonly DrawningTrackedVehicle? _TrackedVehicle = null; /// /// Конструктор /// - /// Объект класса DrawningBaseExcavator - public MoveableBaseExcavator(DrawningBaseExcavator baseExcavator) + /// Объект класса DrawningTrackedVehicle + public MoveableTrackedVehicle(DrawningTrackedVehicle TrackedVehicle) { - _baseExcavator = baseExcavator; + _TrackedVehicle = TrackedVehicle; } public ObjectParameters? GetObjectPosition { get { - if (_baseExcavator == null || _baseExcavator.EntityBaseExcavator == null || !_baseExcavator.GetPosX.HasValue || !_baseExcavator.GetPosY.HasValue) + if (_TrackedVehicle == null || _TrackedVehicle.EntityTrackedVehicle == null || !_TrackedVehicle.GetPosX.HasValue || !_TrackedVehicle.GetPosY.HasValue) { return null; } - return new ObjectParameters(_baseExcavator.GetPosX.Value, _baseExcavator.GetPosY.Value, _baseExcavator.GetWidth, _baseExcavator.GetHeight); + return new ObjectParameters(_TrackedVehicle.GetPosX.Value, _TrackedVehicle.GetPosY.Value, _TrackedVehicle.GetWidth, _TrackedVehicle.GetHeight); } } - public int GetStep => (int)(_baseExcavator?.EntityBaseExcavator?.Step ?? 0); + public int GetStep => (int)(_TrackedVehicle?.EntityTrackedVehicle?.Step ?? 0); public bool TryMoveObject(MovementDirection direction) { - if (_baseExcavator == null || _baseExcavator.EntityBaseExcavator == null) + if (_TrackedVehicle == null || _TrackedVehicle.EntityTrackedVehicle == null) { return false; } - return _baseExcavator.MoveTransport(GetDirectionType(direction)); + return _TrackedVehicle.MoveTransport(GetDirectionType(direction)); } /// diff --git a/ProjectExcavator/ProjectExcavator/Program.cs b/ProjectExcavator/ProjectExcavator/Program.cs index 59b8c54..8be0f08 100644 --- a/ProjectExcavator/ProjectExcavator/Program.cs +++ b/ProjectExcavator/ProjectExcavator/Program.cs @@ -11,7 +11,7 @@ namespace ProjectExcavator // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormExcavator()); + Application.Run(new FormExcavatorCollection()); } } } \ No newline at end of file