diff --git a/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs b/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs new file mode 100644 index 0000000..626003b --- /dev/null +++ b/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs @@ -0,0 +1,115 @@ +using Tank.Drowings; +namespace Tank.CollectionGenericObjects; + +/// +/// Абстракция компании, хранящий коллекцию автомобилей +/// +public abstract class AbstractCompany +{ + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 210; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 100; + + /// + /// Ширина окна + /// + 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, DrawningMachine machine) + { + return company._collection.Insert(machine); + } + + /// + /// Перегрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static DrawningMachine operator -(AbstractCompany company, int position) + { + return company._collection?.Remove(position); + } + + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawningMachine? 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) + { + DrawningMachine? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + + return bitmap; + } + + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgound(Graphics g); + + /// + /// Расстановка объектов + /// + protected abstract void SetObjectsPosition(); +} \ No newline at end of file diff --git a/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs b/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs new file mode 100644 index 0000000..6373b8d --- /dev/null +++ b/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tank.Drowings; + +namespace Tank.CollectionGenericObjects; + +public interface ICollectionGenericObjects +where T : class +{ + /// + /// Количество объектов в коллекции + /// + int Count { get; } + /// + /// Установка максимального количества элементов + /// + int SetMaxCount { set; } + /// + /// Добавление объекта в коллекцию + /// + /// Добавляемый объект + /// другое число - вставка прошла удачно, -1 - вставка не удалась + int Insert(T obj); + /// + /// Добавление объекта в коллекцию на конкретную позицию + /// + /// Добавляемый объект + /// Позиция + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj, int position); + /// + /// Удаление объекта из коллекции с конкретной позиции + /// + /// Позиция + /// true - удаление прошло удачно, false - удаление не удалось + T? Remove(int position); + /// + /// Получение объекта по позиции + /// + /// Позиция + /// Объект + T? Get(int position); +} \ No newline at end of file diff --git a/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs b/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs new file mode 100644 index 0000000..83c6b45 --- /dev/null +++ b/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs @@ -0,0 +1,131 @@ +using Tank.CollectionGenericObjects; +namespace Tank.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 < _collection.Length) + { + return _collection[position]; + } + + return null; + } + + public int Insert(T obj) + { + // вставка в свободное место набора + for (int i = 0; i < _collection.Length; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + + return -1; + } + + public int Insert(T obj, int position) + { + // проверка позиции + if (position < 0 || position >= _collection.Length) + { + return -1; + } + + // проверка, что элемент массива по этой позиции пустой, если нет, то + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до + if (_collection[position] != null) + { + bool pushed = false; + for (int index = position + 1; index < _collection.Length; index++) + { + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + + if (!pushed) + { + for (int index = position - 1; index >= 0; index--) + { + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + } + + if (!pushed) + { + return position; + } + } + + // вставка + _collection[position] = obj; + return position; + } + + public T? Remove(int position) + { + // проверка позиции + if (position < 0 || position >= _collection.Length) + { + return null; + } + + if (_collection[position] == null) return null; + + T? temp = _collection[position]; + _collection[position] = null; + return temp; + } +} \ No newline at end of file diff --git a/Tank/Tank/CollectionGenericObjects/TankSharingService.cs b/Tank/Tank/CollectionGenericObjects/TankSharingService.cs new file mode 100644 index 0000000..5ade154 --- /dev/null +++ b/Tank/Tank/CollectionGenericObjects/TankSharingService.cs @@ -0,0 +1,51 @@ +using Tank.Drowings; + +namespace Tank.CollectionGenericObjects; + +public class TankSharingService : AbstractCompany +{ + public TankSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) + { + } + + protected override void DrawBackgound(Graphics g) + { + Pen pen = new(Color.Black, 3); + int posX = 0; + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) + { + int posY = 0; + g.DrawLine(pen, posX, posY, posX, posY + _placeSizeHeight * (_pictureHeight / _placeSizeHeight)); + for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++) + { + g.DrawLine(pen, posX, posY, posX + _placeSizeWidth - 30, posY); + posY += _placeSizeHeight; + } + posX += _placeSizeWidth; + } + } + + protected override void SetObjectsPosition() + { + int posX = 0; + int posY = 0; + for (int i = 0; i < _collection?.Count; i++) + { + if (_collection.Get(i) != null) + { + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(posX * _placeSizeWidth + 5, posY * _placeSizeHeight + 5); + } + if (posX < _pictureWidth/_placeSizeWidth - 1) + { + posX++; + } + else + { + posY++; + posX = 0; + } + if (posY > _pictureHeight/_placeSizeHeight) { return; } + } + } +} diff --git a/Tank/Tank/Drowings/DrawningMachine.cs b/Tank/Tank/Drowings/DrawningMachine.cs index f60e70a..8889412 100644 --- a/Tank/Tank/Drowings/DrawningMachine.cs +++ b/Tank/Tank/Drowings/DrawningMachine.cs @@ -210,4 +210,9 @@ public class DrawningMachine g.FillRectangle(bodyBrush, _startPosX.Value + 5, _startPosY.Value + 40, 140, 25); } + + internal void SetPictureSize(object width, object height) + { + throw new NotImplementedException(); + } } diff --git a/Tank/Tank/FormTank.cs b/Tank/Tank/FormTank.cs index b1b8505..ba4bb4f 100644 --- a/Tank/Tank/FormTank.cs +++ b/Tank/Tank/FormTank.cs @@ -22,6 +22,18 @@ public partial class FormTank : Form /// Стратегия перемещения /// private AbstractStrategy? _strategy; + + public DrawningMachine SetMachine + { + set + { + _drawningMachine = value; + _drawningMachine.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height); + comboBoxStrategy.Enabled = true; + _strategy = null; + Draw(); + } + } /// /// Конструктор формы /// diff --git a/Tank/Tank/FormTankCollection.Designer.cs b/Tank/Tank/FormTankCollection.Designer.cs new file mode 100644 index 0000000..6f67715 --- /dev/null +++ b/Tank/Tank/FormTankCollection.Designer.cs @@ -0,0 +1,173 @@ +namespace Tank +{ + partial class FormTankCollection + { + /// + /// 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(); + buttonDelTank = new Button(); + maskedTextBoxPosition = new MaskedTextBox(); + buttonAddMachine = new Button(); + buttonAddTank = 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(buttonDelTank); + groupBoxTools.Controls.Add(maskedTextBoxPosition); + groupBoxTools.Controls.Add(buttonAddMachine); + groupBoxTools.Controls.Add(buttonAddTank); + groupBoxTools.Controls.Add(comboBoxSelectorCompany); + groupBoxTools.Dock = DockStyle.Right; + groupBoxTools.Location = new Point(1079, 0); + groupBoxTools.Name = "groupBoxTools"; + groupBoxTools.Size = new Size(371, 871); + groupBoxTools.TabIndex = 0; + groupBoxTools.TabStop = false; + groupBoxTools.Text = "Инструменты"; + // + // buttonRefresh + // + buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRefresh.Location = new Point(17, 698); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(342, 77); + 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(17, 554); + buttonGoToCheck.Name = "buttonGoToCheck"; + buttonGoToCheck.Size = new Size(342, 77); + buttonGoToCheck.TabIndex = 5; + buttonGoToCheck.Text = "Передать на тесты"; + buttonGoToCheck.UseVisualStyleBackColor = true; + buttonGoToCheck.Click += ButtonGoToCheck_Click; + // + // buttonDelTank + // + buttonDelTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonDelTank.Location = new Point(17, 403); + buttonDelTank.Name = "buttonDelTank"; + buttonDelTank.Size = new Size(342, 77); + buttonDelTank.TabIndex = 4; + buttonDelTank.Text = "Удалить танк"; + buttonDelTank.UseVisualStyleBackColor = true; + buttonDelTank.Click += ButtonRemoveCar_Click; + // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Location = new Point(17, 308); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(342, 39); + maskedTextBoxPosition.TabIndex = 3; + maskedTextBoxPosition.ValidatingType = typeof(int); + // + // buttonAddMachine + // + buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddMachine.Location = new Point(17, 196); + buttonAddMachine.Name = "buttonAddMachine"; + buttonAddMachine.Size = new Size(342, 77); + buttonAddMachine.TabIndex = 2; + buttonAddMachine.Text = "Добавление машины"; + buttonAddMachine.UseVisualStyleBackColor = true; + buttonAddMachine.Click += ButtonAddMachine_Click; + // + // buttonAddTank + // + buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddTank.Location = new Point(17, 113); + buttonAddTank.Name = "buttonAddTank"; + buttonAddTank.Size = new Size(342, 77); + buttonAddTank.TabIndex = 1; + buttonAddTank.Text = "Добавление танка"; + buttonAddTank.UseVisualStyleBackColor = true; + buttonAddTank.Click += ButtonAddTank_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(17, 53); + comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; + comboBoxSelectorCompany.Size = new Size(342, 40); + 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(1079, 871); + pictureBox.TabIndex = 1; + pictureBox.TabStop = false; + // + // FormTankCollection + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1450, 871); + Controls.Add(pictureBox); + Controls.Add(groupBoxTools); + Name = "FormTankCollection"; + Text = "Коллекция танков"; + groupBoxTools.ResumeLayout(false); + groupBoxTools.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private GroupBox groupBoxTools; + private Button buttonAddMachine; + private Button buttonAddTank; + private PictureBox pictureBox; + private Button buttonGoToCheck; + private Button buttonDelTank; + private MaskedTextBox maskedTextBoxPosition; + private Button buttonRefresh; + private ComboBox comboBoxSelectorCompany; + } +} \ No newline at end of file diff --git a/Tank/Tank/FormTankCollection.cs b/Tank/Tank/FormTankCollection.cs new file mode 100644 index 0000000..01419e5 --- /dev/null +++ b/Tank/Tank/FormTankCollection.cs @@ -0,0 +1,190 @@ +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; +using Tank.CollectionGenericObjects; +using Tank.Drowings; + +namespace Tank; + +/// +/// +/// +public partial class FormTankCollection : Form + +{ + /// + /// + /// + private AbstractCompany? _company = null; + + /// + /// + /// + public FormTankCollection() + { + InitializeComponent(); + } + + /// + /// + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new TankSharingService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + } + /// + /// Добавление обычного автомобиля + /// + /// + /// + private void ButtonAddMachine_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMachine)); + /// + /// Добавление спортивного автомобиля + /// + /// + /// + private void ButtonAddTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank)); + /// + ///Создание объекта класса-перемещения + /// + /// Тип создаваемого объётека + + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + + Random rnd = new Random(); + DrawningMachine drawningMachine; + switch (type) + { + case nameof(DrawningMachine): + drawningMachine = new DrawningMachine(rnd.Next(100, 300), rnd.Next(1000, 3000), GetColor(rnd)); + break; + case nameof(DrawningTank): + drawningMachine = new DrawningTank(rnd.Next(650, 700), rnd.Next(15760, 16130), + GetColor(rnd), + GetColor(rnd), + Convert.ToBoolean(rnd.Next(0, 2)), + Convert.ToBoolean(rnd.Next(0, 2))); + break; + default: + return; + } + + if (_company + drawningMachine != -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; + } + DrawningMachine? tank = null; + int counter = 100; + while (tank == null) + { + tank = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + if (tank == null) + { + return; + } + FormTank form = new() + { + SetMachine = tank + }; + form.ShowDialog(); + } + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + pictureBox.Image = _company.Show(); + } +} \ No newline at end of file diff --git a/Tank/Tank/FormTankCollection.resx b/Tank/Tank/FormTankCollection.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/Tank/Tank/FormTankCollection.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/Tank/Tank/Program.cs b/Tank/Tank/Program.cs index 3fbc0e1..5db0562 100644 --- a/Tank/Tank/Program.cs +++ b/Tank/Tank/Program.cs @@ -11,7 +11,7 @@ namespace Tank // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTank()); + Application.Run(new FormTankCollection()); } } } \ No newline at end of file