From b4ac8a93faa9e20d06bb850be654ef9d8e8741c7 Mon Sep 17 00:00:00 2001 From: vasmaae Date: Mon, 25 Mar 2024 19:15:46 +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=20=E2=84=963?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 116 +++++++++ .../AirbusAerodromeService.cs | 55 ++++ .../ICollectionGenericObjects.cs | 47 ++++ .../MassiveGenericObjects.cs | 120 +++++++++ .../ProjectAirbus/Drawnings/DirectionType.cs | 3 + .../ProjectAirbus/Drawnings/DrawningAirbus.cs | 4 +- .../Drawnings/DrawningBigAirbus.cs | 12 + .../ProjectAirbus/Entities/EntityBIgAirbus.cs | 9 + .../ProjectAirbus/FormAirbus.Designer.cs | 28 -- ProjectAirbus/ProjectAirbus/FormAirbus.cs | 239 ++++++++---------- .../FormAirbusCollection.Designer.cs | 170 +++++++++++++ .../ProjectAirbus/FormAirbusCollection.cs | 187 ++++++++++++++ .../ProjectAirbus/FormAirbusCollection.resx | 120 +++++++++ .../MovementStrategy/AbstractStrategy.cs | 67 ++++- .../MovementStrategy/IMoveableObject.cs | 15 ++ .../MovementStrategy/MoveToBorder.cs | 3 + .../MovementStrategy/MoveToCenter.cs | 3 + .../MovementStrategy/MoveableAirbus.cs | 15 ++ .../MovementStrategy/ObjectParameters.cs | 37 +++ .../MovementStrategy/StrategyStatus.cs | 9 + ProjectAirbus/ProjectAirbus/Program.cs | 2 +- 21 files changed, 1101 insertions(+), 160 deletions(-) create mode 100644 ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs create mode 100644 ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AirbusAerodromeService.cs create mode 100644 ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs create mode 100644 ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs create mode 100644 ProjectAirbus/ProjectAirbus/FormAirbusCollection.Designer.cs create mode 100644 ProjectAirbus/ProjectAirbus/FormAirbusCollection.cs create mode 100644 ProjectAirbus/ProjectAirbus/FormAirbusCollection.resx diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs new file mode 100644 index 0000000..ff4a5ef --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs @@ -0,0 +1,116 @@ +using ProjectAirbus.Drawnings; + +namespace ProjectAirbus.CollectionGenericObjects; + +/// +/// Абстракция компании, хранящей коллекцию аэробусов +/// +public abstract class AbstractCompany +{ + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 155; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 60; + + /// + /// Ширина окна + /// + protected readonly int _pictureWidth; + + /// + /// Высота окна + /// + protected readonly int _pictureHeight; + + /// + /// Коллекция аэробусов + /// + protected ICollectionGenericObjects _collection = null; + + /// + /// Вычисление максимального количества элементов, которые можно разместить в окне + /// + private int GetMaxCount => _pictureWidth * _pictureHeight / ((_placeSizeWidth + _placeSizeWidth /2) * _placeSizeHeight) - 1; + + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллекция автомобилей + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + { + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.SetMaxCount = GetMaxCount; + } + + /// + /// Перегрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static int operator +(AbstractCompany company, DrawningAirbus airbus) + { + return company._collection.Insert(airbus); + } + + /// + /// Перегрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static DrawningAirbus operator -(AbstractCompany company, int position) + { + return company._collection.Remove(position); + } + + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawningAirbus? GetRandomObject() + { + Random rnd = new(); + return _collection?.Get(rnd.Next(GetMaxCount)); + } + + /// + /// Вывод всей коллекции + /// + /// + public Bitmap? Show() + { + Bitmap bitmap = new(_pictureWidth, _pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackgroud(graphics); + + SetObjectPosition(); + for (int i = 0; i < (_collection?.Count ?? 0); i++) + { + DrawningAirbus? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + + return bitmap; + } + + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgroud(Graphics g); + + /// + /// Расстановка ообъектов + /// + protected abstract void SetObjectPosition(); +} diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AirbusAerodromeService.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AirbusAerodromeService.cs new file mode 100644 index 0000000..76f45ca --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AirbusAerodromeService.cs @@ -0,0 +1,55 @@ +using ProjectAirbus.Drawnings; + +namespace ProjectAirbus.CollectionGenericObjects; + +/// +/// Реализация абстрактной компании - аэродром +/// +public class AirbusAerodromeService : AbstractCompany +{ + /// + /// Конструктор + /// + /// + /// + /// + public AirbusAerodromeService(int picWidth, int picHeight, ICollectionGenericObjects collection) : + base(picWidth, picHeight, collection) { } + + protected override void DrawBackgroud(Graphics g) + { + int _placeWidth = _placeSizeWidth + _placeSizeWidth / 2; + int _placeHeight = _placeSizeHeight; + for (int x = 2; x < _pictureWidth - _placeSizeWidth; x += _placeWidth) + { + for (int y = 2; y < _pictureHeight - _placeSizeHeight; y += _placeHeight) + { + Pen pen = new Pen(Color.Black, 3); + Point[] points = + { + new Point(x + _placeSizeWidth, y), + new Point(x, y), + new Point(x, y + _placeSizeHeight), + new Point(x + _placeSizeWidth, y + _placeSizeHeight) + }; + g.DrawLines(pen, points); + } + } + } + + protected override void SetObjectPosition() + { + int countOfHorizontal = _pictureWidth / (_placeSizeWidth + _placeSizeWidth / 2); + int countOfVertical = _pictureHeight / _placeSizeHeight; + + for (int i = 0; i < _collection.Count; i++) + { + if (_collection.Get(i) != null) + { + _collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i)?.SetPosition((_placeSizeWidth + _placeSizeWidth / 2) * (countOfHorizontal - i / countOfVertical) + 5, + _placeSizeHeight * (countOfVertical - i % countOfVertical - 1) + 5); + } + } + } +} diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs new file mode 100644 index 0000000..d0e6f13 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -0,0 +1,47 @@ +namespace ProjectAirbus.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/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs new file mode 100644 index 0000000..377f92a --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -0,0 +1,120 @@ +namespace ProjectAirbus.CollectionGenericObjects; + +public class MassiveGenericObjects : ICollectionGenericObjects where T : class +{ + /// + /// Массив хранимых объектов + /// + private T?[] _collection; + + public int Count => _collection.Length; + + public int SetMaxCount + { + set + { + if (value > 0) + { + if (Count > 0) + { + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; + } + } + } + } + + /// + /// Конструктор + /// + public MassiveGenericObjects() + { + _collection = Array.Empty(); + } + + public T? Get(int position) + { + // TODO проверка позиции + if (position < 0 || position > Count) + { + return null; + } + + return _collection[position]; + } + + public int Insert(T obj) + { + // TODO вставка в свободное место набора + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + + return -1; + } + + public int Insert(T obj, int position) + { + // TODO проверка позиции + // TODO проверка, что элемент массима по этой позиции пустой, + // если элемент массима по этой позиции не пустой, + // найти свободное место после этой позиции, если не найдено, + // то искать до + // TODO вставка + if (position < 0 || position >= Count) + { + return -1; + } + + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + } + else + { + for (int i = position + 1; i < Count; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + + for (int i = 0; i < position; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + } + + return -1; + } + + public T Remove(int position) + { + // TODO проверка позиции + // TODO удаление объекта из массива, + // присвоив элементу массива значение null + if (position >= Count || position < 0) + { + return null; + } + + T obj = _collection[position]; + _collection[position] = null; + return obj; + } +} diff --git a/ProjectAirbus/ProjectAirbus/Drawnings/DirectionType.cs b/ProjectAirbus/ProjectAirbus/Drawnings/DirectionType.cs index dcb133f..6419408 100644 --- a/ProjectAirbus/ProjectAirbus/Drawnings/DirectionType.cs +++ b/ProjectAirbus/ProjectAirbus/Drawnings/DirectionType.cs @@ -1,5 +1,8 @@ namespace ProjectAirbus.Drawnings; +/// +/// Направление перемещения +/// public enum DirectionType { /// diff --git a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs index a111595..8aa644b 100644 --- a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningAirbus.cs @@ -69,8 +69,8 @@ public class DrawningAirbus { _pictureWidth = null; _pictureHeight = null; - _startPosX = 0; - _startPosY = 0; + _startPosX = null; + _startPosY = null; } /// diff --git a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningBigAirbus.cs b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningBigAirbus.cs index 18a5182..c73b0df 100644 --- a/ProjectAirbus/ProjectAirbus/Drawnings/DrawningBigAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/Drawnings/DrawningBigAirbus.cs @@ -2,8 +2,20 @@ namespace ProjectAirbus.Drawnings; +/// +/// Класс отрисовки и перемещения объекта-сущности +/// public class DrawningBigAirbus : DrawningAirbus { + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия дополнительного двигателя + /// Признац наличия дополнительного отсека для пассажиров public DrawningBigAirbus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalEngine, bool passengerCompartment) : base(145, 50) { EntityAirbus = new EntityBigAirbus(speed, weight, bodyColor, additionalColor, additionalEngine, passengerCompartment); diff --git a/ProjectAirbus/ProjectAirbus/Entities/EntityBIgAirbus.cs b/ProjectAirbus/ProjectAirbus/Entities/EntityBIgAirbus.cs index 244d208..60b7ffd 100644 --- a/ProjectAirbus/ProjectAirbus/Entities/EntityBIgAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/Entities/EntityBIgAirbus.cs @@ -17,6 +17,15 @@ public class EntityBigAirbus : EntityAirbus /// public bool PassengerCompartment { get; private set; } + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия дополнительного двигателя + /// Признац наличия дополнительного отсека для пассажиров public EntityBigAirbus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalEngine, bool passengerCompartment) : base(speed, weight, bodyColor) { AdditionalColor = additionalColor; diff --git a/ProjectAirbus/ProjectAirbus/FormAirbus.Designer.cs b/ProjectAirbus/ProjectAirbus/FormAirbus.Designer.cs index a22c61f..8738048 100644 --- a/ProjectAirbus/ProjectAirbus/FormAirbus.Designer.cs +++ b/ProjectAirbus/ProjectAirbus/FormAirbus.Designer.cs @@ -29,12 +29,10 @@ private void InitializeComponent() { pictureBoxAirbus = new PictureBox(); - buttonCreateAirbus = new Button(); buttonLeft = new Button(); buttonUp = new Button(); buttonRight = new Button(); buttonDown = new Button(); - buttonCreateBigAirbus = new Button(); comboBoxStrategy = new ComboBox(); buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirbus).BeginInit(); @@ -50,17 +48,6 @@ pictureBoxAirbus.TabIndex = 0; pictureBoxAirbus.TabStop = false; // - // buttonCreateAirbus - // - buttonCreateAirbus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreateAirbus.Location = new Point(182, 529); - buttonCreateAirbus.Name = "buttonCreateAirbus"; - buttonCreateAirbus.Size = new Size(164, 23); - buttonCreateAirbus.TabIndex = 1; - buttonCreateAirbus.Text = "Создать аэробус"; - buttonCreateAirbus.UseVisualStyleBackColor = true; - buttonCreateAirbus.Click += ButtonCreateAirbus_Click; - // // buttonLeft // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; @@ -109,17 +96,6 @@ buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += ButtonMove_Click; // - // buttonCreateBigAirbus - // - buttonCreateBigAirbus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreateBigAirbus.Location = new Point(12, 529); - buttonCreateBigAirbus.Name = "buttonCreateBigAirbus"; - buttonCreateBigAirbus.Size = new Size(164, 23); - buttonCreateBigAirbus.TabIndex = 6; - buttonCreateBigAirbus.Text = "Создать большой аэробус"; - buttonCreateBigAirbus.UseVisualStyleBackColor = true; - buttonCreateBigAirbus.Click += buttonCreateBigAirbus_Click; - // // comboBoxStrategy // comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; @@ -147,12 +123,10 @@ ClientSize = new Size(1042, 564); Controls.Add(buttonStrategyStep); Controls.Add(comboBoxStrategy); - Controls.Add(buttonCreateBigAirbus); Controls.Add(buttonDown); Controls.Add(buttonRight); Controls.Add(buttonUp); Controls.Add(buttonLeft); - Controls.Add(buttonCreateAirbus); Controls.Add(pictureBoxAirbus); Margin = new Padding(3, 2, 3, 2); Name = "FormAirbus"; @@ -165,12 +139,10 @@ #endregion private PictureBox pictureBoxAirbus; - private Button buttonCreateAirbus; private Button buttonLeft; private Button buttonUp; private Button buttonRight; private Button buttonDown; - private Button buttonCreateBigAirbus; private ComboBox comboBoxStrategy; private Button buttonStrategyStep; } diff --git a/ProjectAirbus/ProjectAirbus/FormAirbus.cs b/ProjectAirbus/ProjectAirbus/FormAirbus.cs index 2ba014c..4f01016 100644 --- a/ProjectAirbus/ProjectAirbus/FormAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/FormAirbus.cs @@ -1,156 +1,141 @@ -using System.Diagnostics; -using ProjectAirbus.Drawnings; +using ProjectAirbus.Drawnings; using ProjectAirbus.MovementStrategy; -namespace ProjectAirbus +namespace ProjectAirbus; +/// +/// Форма работающая с обектом "самолёт" +/// +public partial class FormAirbus : Form { /// - /// Форма работающая с обектом "самолёт" + /// Поле-объект для отрисовки объекта /// - public partial class FormAirbus : Form + private DrawningAirbus? _drawningAirbus; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + /// + /// Получение объекта + /// + public DrawningAirbus SetAirbus { - /// - /// Поле-объект для отрисовки объекта - /// - private DrawningAirbus? _drawningAirbus; - - private AbstractStrategy? _strategy; - - /// - /// Конструктор формы - /// - public FormAirbus() + set { - InitializeComponent(); - _strategy = null; - } - - /// - /// метод прорисовки машины - /// - private void Draw() - { - if (_drawningAirbus == null) - { - return; - } - - Bitmap bmp = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height); - Graphics gr = Graphics.FromImage(bmp); - _drawningAirbus.DrawTransport(gr); - pictureBoxAirbus.Image = bmp; - } - - private void CreateObject(string type) - { - Random random = new(); - switch (type) - { - case nameof(DrawningAirbus): - _drawningAirbus = new DrawningAirbus(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(DrawningBigAirbus): - _drawningAirbus = new DrawningBigAirbus(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; - } - + _drawningAirbus = value; _drawningAirbus.SetPictureSize(pictureBoxAirbus.Width, pictureBoxAirbus.Height); - _drawningAirbus.SetPosition(random.Next(10, 100), random.Next(10, 100)); + comboBoxStrategy.Enabled = true; _strategy = null; - //comboBoxStrategy.Enabled = true; Draw(); } + } - /// - /// Обработка кнопки "создать" - /// - /// - /// - private void ButtonCreateAirbus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirbus)); + /// + /// Конструктор формы + /// + public FormAirbus() + { + InitializeComponent(); + _strategy = null; + } - private void buttonCreateBigAirbus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBigAirbus)); - - /// - /// Обработка кнопок перемещения объекта - /// - /// - /// - private void ButtonMove_Click(object sender, EventArgs e) + /// + /// Метод прорисовки машины + /// + private void Draw() + { + if (_drawningAirbus == null) { - if (_drawningAirbus == null) - { - return; - } - - String name = ((Button)sender)?.Name ?? String.Empty; - bool result = false; - switch (name) - { - case "buttonUp": - result = _drawningAirbus.MoveTransport(DirectionType.Up); - break; - case "buttonDown": - result = _drawningAirbus.MoveTransport(DirectionType.Down); - break; - case "buttonLeft": - result = _drawningAirbus.MoveTransport(DirectionType.Left); - break; - case "buttonRight": - result = _drawningAirbus.MoveTransport(DirectionType.Right); - break; - } - - if (result) - { - Draw(); - } + return; } - private void buttonStrategyStep_Click(object sender, EventArgs e) + Bitmap bmp = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawningAirbus.DrawTransport(gr); + pictureBoxAirbus.Image = bmp; + } + + /// + /// Обработка кнопок перемещения объекта + /// + /// + /// + private void ButtonMove_Click(object sender, EventArgs e) + { + if (_drawningAirbus == null) { - if (_drawningAirbus == null) + return; + } + + String name = ((Button)sender)?.Name ?? String.Empty; + bool result = false; + switch (name) + { + case "buttonUp": + result = _drawningAirbus.MoveTransport(DirectionType.Up); + break; + case "buttonDown": + result = _drawningAirbus.MoveTransport(DirectionType.Down); + break; + case "buttonLeft": + result = _drawningAirbus.MoveTransport(DirectionType.Left); + break; + case "buttonRight": + result = _drawningAirbus.MoveTransport(DirectionType.Right); + break; + } + + if (result) + { + Draw(); + } + } + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningAirbus == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch { - return; - } - - if (comboBoxStrategy.Enabled) - { - _strategy = comboBoxStrategy.SelectedIndex switch - { - 0 => new MoveToCenter(), - 1 => new MoveToBorder(), - _ => null, - }; - - if (_strategy == null) - { - return; - } - - _strategy.SetData(new MoveableAirbus(_drawningAirbus), pictureBoxAirbus.Width, pictureBoxAirbus.Height); - } + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; if (_strategy == null) { return; } - comboBoxStrategy.Enabled = false; - _strategy.MakeStep(); - Draw(); + _strategy.SetData(new MoveableAirbus(_drawningAirbus), pictureBoxAirbus.Width, pictureBoxAirbus.Height); + } - if (_strategy.GetStatus() == StrategyStatus.Finish) - { - comboBoxStrategy.Enabled = true; - _strategy = null; - } + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; } } } diff --git a/ProjectAirbus/ProjectAirbus/FormAirbusCollection.Designer.cs b/ProjectAirbus/ProjectAirbus/FormAirbusCollection.Designer.cs new file mode 100644 index 0000000..761286f --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/FormAirbusCollection.Designer.cs @@ -0,0 +1,170 @@ +namespace ProjectAirbus +{ + partial class FormAirbusCollection + { + /// + /// 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() + { + groupBocTools = new GroupBox(); + maskedTextBoxPosition = new MaskedTextBox(); + buttonRefresh = new Button(); + buttonGoToCheck = new Button(); + buttonRemoveAirbus = new Button(); + buttonAddBigAirbus = new Button(); + buttonAddAirbus = new Button(); + comboBoxSelectorCompany = new ComboBox(); + pictureBox = new PictureBox(); + groupBocTools.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + SuspendLayout(); + // + // groupBocTools + // + groupBocTools.Controls.Add(maskedTextBoxPosition); + groupBocTools.Controls.Add(buttonRefresh); + groupBocTools.Controls.Add(buttonGoToCheck); + groupBocTools.Controls.Add(buttonRemoveAirbus); + groupBocTools.Controls.Add(buttonAddBigAirbus); + groupBocTools.Controls.Add(buttonAddAirbus); + groupBocTools.Controls.Add(comboBoxSelectorCompany); + groupBocTools.Dock = DockStyle.Right; + groupBocTools.Location = new Point(867, 0); + groupBocTools.Name = "groupBocTools"; + groupBocTools.Size = new Size(172, 536); + groupBocTools.TabIndex = 0; + groupBocTools.TabStop = false; + groupBocTools.Text = "Инструменты"; + // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + maskedTextBoxPosition.Location = new Point(6, 205); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(160, 23); + maskedTextBoxPosition.TabIndex = 7; + maskedTextBoxPosition.ValidatingType = typeof(int); + // + // buttonRefresh + // + buttonRefresh.Location = new Point(6, 413); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(160, 23); + buttonRefresh.TabIndex = 6; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // buttonGoToCheck + // + buttonGoToCheck.Location = new Point(6, 328); + buttonGoToCheck.Name = "buttonGoToCheck"; + buttonGoToCheck.Size = new Size(160, 23); + buttonGoToCheck.TabIndex = 5; + buttonGoToCheck.Text = "Передать на тесты"; + buttonGoToCheck.UseVisualStyleBackColor = true; + buttonGoToCheck.Click += buttonGoToCheck_Click; + // + // buttonRemoveAirbus + // + buttonRemoveAirbus.Location = new Point(6, 234); + buttonRemoveAirbus.Name = "buttonRemoveAirbus"; + buttonRemoveAirbus.Size = new Size(160, 23); + buttonRemoveAirbus.TabIndex = 4; + buttonRemoveAirbus.Text = "Удалить аэробус"; + buttonRemoveAirbus.UseVisualStyleBackColor = true; + buttonRemoveAirbus.Click += buttonRemoveAirbus_Click; + // + // buttonAddBigAirbus + // + buttonAddBigAirbus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddBigAirbus.Location = new Point(6, 105); + buttonAddBigAirbus.Name = "buttonAddBigAirbus"; + buttonAddBigAirbus.Size = new Size(160, 47); + buttonAddBigAirbus.TabIndex = 2; + buttonAddBigAirbus.Text = "Добавление большого аэробуса"; + buttonAddBigAirbus.UseVisualStyleBackColor = true; + buttonAddBigAirbus.Click += buttonAddBigAirbus_Click; + // + // buttonAddAirbus + // + buttonAddAirbus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddAirbus.Location = new Point(6, 76); + buttonAddAirbus.Name = "buttonAddAirbus"; + buttonAddAirbus.Size = new Size(160, 23); + buttonAddAirbus.TabIndex = 1; + buttonAddAirbus.Text = "Добавление аэробуса"; + buttonAddAirbus.UseVisualStyleBackColor = true; + buttonAddAirbus.Click += buttonAddAirbus_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(6, 22); + comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; + comboBoxSelectorCompany.Size = new Size(160, 23); + 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(867, 536); + pictureBox.TabIndex = 7; + pictureBox.TabStop = false; + // + // FormAirbusCollection + // + AutoScaleMode = AutoScaleMode.None; + ClientSize = new Size(1039, 536); + Controls.Add(pictureBox); + Controls.Add(groupBocTools); + Name = "FormAirbusCollection"; + Text = "Коллекция аэробусов"; + groupBocTools.ResumeLayout(false); + groupBocTools.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private GroupBox groupBocTools; + private ComboBox comboBoxSelectorCompany; + private Button buttonAddBigAirbus; + private Button buttonAddAirbus; + private Button buttonGoToCheck; + private Button buttonRemoveAirbus; + private Button buttonRefresh; + private PictureBox pictureBox; + private MaskedTextBox maskedTextBoxPosition; + } +} \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/FormAirbusCollection.cs b/ProjectAirbus/ProjectAirbus/FormAirbusCollection.cs new file mode 100644 index 0000000..1b40267 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/FormAirbusCollection.cs @@ -0,0 +1,187 @@ +using ProjectAirbus.CollectionGenericObjects; +using ProjectAirbus.Drawnings; + +namespace ProjectAirbus; + +/// +/// Форма работы с компанией и её коллекцией +/// +public partial class FormAirbusCollection : Form +{ + /// + /// Компания + /// + private AbstractCompany? _company = null; + + /// + /// Конструктор + /// + public FormAirbusCollection() + { + InitializeComponent(); + } + + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(Object sender, EventArgs e) + { + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new AirbusAerodromeService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + } + + /// + /// Созданией объейта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + + Random random = new(); + DrawningAirbus drawningAirbus; + + switch (type) + { + case nameof(DrawningAirbus): + drawningAirbus = new DrawningAirbus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); + break; + case nameof(DrawningBigAirbus): + drawningAirbus = new DrawningBigAirbus(random.Next(100, 300), random.Next(1000, 3000), + GetColor(random), GetColor(random), true, true); + break; + default: + return; + } + + if (_company + drawningAirbus != -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 buttonAddAirbus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirbus)); + + /// + /// Добавление большого аэробуса + /// + /// + /// + private void buttonAddBigAirbus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBigAirbus)); + + /// + /// Удаление объекта + /// + /// + /// + private void buttonRemoveAirbus_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; + } + + DrawningAirbus? airbus = null; + int counter = 100; + while (airbus == null) + { + airbus = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (airbus == null) + { + return; + } + + FormAirbus form = new() + { + SetAirbus = airbus + }; + form.ShowDialog(); + } + + /// + /// Перерисовка коллекции + /// + /// + /// + private void buttonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } +} diff --git a/ProjectAirbus/ProjectAirbus/FormAirbusCollection.resx b/ProjectAirbus/ProjectAirbus/FormAirbusCollection.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/FormAirbusCollection.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/ProjectAirbus/ProjectAirbus/MovementStrategy/AbstractStrategy.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/AbstractStrategy.cs index fb67a87..27e50da 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/AbstractStrategy.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/AbstractStrategy.cs @@ -1,17 +1,42 @@ namespace ProjectAirbus.MovementStrategy; +/// +/// Класс-стратегия перемещения объекта +/// public abstract class AbstractStrategy { + /// + /// Перемещаемый объект + /// private IMoveableObject? _moveableObject; + /// + /// Статус перемещения + /// private StrategyStatus _state = StrategyStatus.NotInit; + /// + /// Ширина поля + /// protected int FieldWidth { get; private set; } + /// + /// Высота поля + /// protected int FieldHeight { get; private set; } + /// + /// Статус перемещения + /// + /// public StrategyStatus GetStatus() { return _state; } + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля public void SetData(IMoveableObject moveableObject, int width, int height) { if (moveableObject == null) @@ -26,6 +51,9 @@ public abstract class AbstractStrategy FieldHeight = height; } + /// + /// Шаг перемещения + /// public void MakeStep() { if (_state != StrategyStatus.InProgress) @@ -42,16 +70,39 @@ public abstract class AbstractStrategy MoveToTarget(); } + /// + /// Перемещение влево + /// + /// true - перемещение удалось, false - перемещение не удалось protected bool MoveLeft() => MoveTo(MovementDirection.Left); - + + /// + /// Перемещение вправо + /// + /// true - перемещение удалось, false - перемещение не удалось protected bool MoveRight() => MoveTo(MovementDirection.Right); + /// + /// Перемещение вверх + /// + /// true - перемещение удалось, false - перемещение не удалось protected bool MoveUp() => MoveTo(MovementDirection.Up); - + + /// + /// Перемещение вниз + /// + /// true - перемещение удалось, false - перемещение не удалось protected bool MoveDown() => MoveTo(MovementDirection.Down); + /// + /// Параметры объекта + /// protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + /// + /// Шаг объекта + /// + /// protected int? GetStep() { if (_state != StrategyStatus.InProgress) @@ -62,10 +113,22 @@ public abstract class AbstractStrategy return _moveableObject.GetStep; } + /// + /// Перемещение к цели + /// protected abstract void MoveToTarget(); + /// + /// Достигнута ли цель + /// + /// protected abstract bool IsTargetDestination(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление перемещения + /// true - перемещение удалось, false - перемещение не удалось private bool MoveTo(MovementDirection movementDirection) { if (_state != StrategyStatus.InProgress) diff --git a/ProjectAirbus/ProjectAirbus/MovementStrategy/IMoveableObject.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/IMoveableObject.cs index d9dacfd..e087aa3 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/IMoveableObject.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/IMoveableObject.cs @@ -1,9 +1,24 @@ namespace ProjectAirbus.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// public interface IMoveableObject { + /// + /// Получение координаты объекта + /// ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление перемещения + /// true - объект перемещён, false - перемещение невозможно bool TryMoveObject(MovementDirection direction); } \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToBorder.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToBorder.cs index d5feef9..0a3d324 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToBorder.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToBorder.cs @@ -1,5 +1,8 @@ namespace ProjectAirbus.MovementStrategy; +/// +/// Стратегия перемещения объекта к границе экрана (в угол) +/// public class MoveToBorder : AbstractStrategy { protected override bool IsTargetDestination() diff --git a/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToCenter.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToCenter.cs index b5671c3..0726087 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToCenter.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveToCenter.cs @@ -1,5 +1,8 @@ namespace ProjectAirbus.MovementStrategy; +/// +/// Стратегия перемещения объекта в центр экрана +/// public class MoveToCenter : AbstractStrategy { protected override bool IsTargetDestination() diff --git a/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveableAirbus.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveableAirbus.cs index 39d5f69..bf8414a 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveableAirbus.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/MoveableAirbus.cs @@ -2,10 +2,20 @@ namespace ProjectAirbus.MovementStrategy; +/// +/// Класс-реализация IMoveableObject с использованием DrawningAirbus +/// public class MoveableAirbus : IMoveableObject { + /// + /// Поле-объект класса DrawningCar или его наследника + /// private readonly DrawningAirbus? _airbus = null; + /// + /// Конструктор + /// + /// Объект класса DrawningCar public MoveableAirbus(DrawningAirbus airbus) { _airbus = airbus; @@ -36,6 +46,11 @@ public class MoveableAirbus : IMoveableObject return _airbus.MoveTransport(GetDirectionType(direction)); } + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType private static DirectionType GetDirectionType(MovementDirection direction) { return direction switch diff --git a/ProjectAirbus/ProjectAirbus/MovementStrategy/ObjectParameters.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/ObjectParameters.cs index fe727ab..3673cef 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/ObjectParameters.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/ObjectParameters.cs @@ -5,26 +5,63 @@ /// public class ObjectParameters { + /// + /// Координата X + /// private readonly int _x; + /// + /// Коорината Y + /// 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 BottomBorder => _y + _height; + /// + /// Координата X середины объекта + /// public int ObjectMiddleHorizontal => _x + _width / 2; + /// + /// Координата Y середины объекта + /// public int ObjectMiddleVertical => _y + _height / 2; + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина объекта + /// Высота объекта public ObjectParameters(int x , int y, int width, int height) { _x = x; diff --git a/ProjectAirbus/ProjectAirbus/MovementStrategy/StrategyStatus.cs b/ProjectAirbus/ProjectAirbus/MovementStrategy/StrategyStatus.cs index f9eeb4b..814c4e4 100644 --- a/ProjectAirbus/ProjectAirbus/MovementStrategy/StrategyStatus.cs +++ b/ProjectAirbus/ProjectAirbus/MovementStrategy/StrategyStatus.cs @@ -5,9 +5,18 @@ /// public enum StrategyStatus { + /// + /// Готово к выполнению + /// NotInit, + /// + /// Выполняется + /// InProgress, + /// + /// Завершено + /// Finish } \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/Program.cs b/ProjectAirbus/ProjectAirbus/Program.cs index 9d45ae4..99a94bc 100644 --- a/ProjectAirbus/ProjectAirbus/Program.cs +++ b/ProjectAirbus/ProjectAirbus/Program.cs @@ -11,7 +11,7 @@ namespace ProjectAirbus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormAirbus()); + Application.Run(new FormAirbusCollection()); } } } \ No newline at end of file