diff --git a/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs b/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs index 35c32ef..0e4c774 100644 --- a/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs +++ b/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs @@ -29,31 +29,87 @@ private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.groupBoxSet = new System.Windows.Forms.GroupBox(); + this.ButtonDelObject = new System.Windows.Forms.Button(); + this.ListBoxStorages = new System.Windows.Forms.ListBox(); + this.ButtonAddObject = new System.Windows.Forms.Button(); + this.textBoxStorageName = new System.Windows.Forms.TextBox(); this.ButtonRefreshCollection = new System.Windows.Forms.Button(); this.ButtonRemovePlane = new System.Windows.Forms.Button(); this.maskedTextBoxNumber = new System.Windows.Forms.TextBox(); this.ButtonAddPlane = new System.Windows.Forms.Button(); this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); this.groupBox1.SuspendLayout(); + this.groupBoxSet.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); this.SuspendLayout(); // // groupBox1 // + this.groupBox1.Controls.Add(this.groupBoxSet); this.groupBox1.Controls.Add(this.ButtonRefreshCollection); this.groupBox1.Controls.Add(this.ButtonRemovePlane); this.groupBox1.Controls.Add(this.maskedTextBoxNumber); this.groupBox1.Controls.Add(this.ButtonAddPlane); this.groupBox1.Location = new System.Drawing.Point(586, 2); this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(216, 453); + this.groupBox1.Size = new System.Drawing.Size(216, 563); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Инструменты"; // + // groupBoxSet + // + this.groupBoxSet.Controls.Add(this.ButtonDelObject); + this.groupBoxSet.Controls.Add(this.ListBoxStorages); + this.groupBoxSet.Controls.Add(this.ButtonAddObject); + this.groupBoxSet.Controls.Add(this.textBoxStorageName); + this.groupBoxSet.Location = new System.Drawing.Point(21, 25); + this.groupBoxSet.Name = "groupBoxSet"; + this.groupBoxSet.Size = new System.Drawing.Size(180, 274); + this.groupBoxSet.TabIndex = 4; + this.groupBoxSet.TabStop = false; + this.groupBoxSet.Text = "Наборы"; + // + // ButtonDelObject + // + this.ButtonDelObject.Location = new System.Drawing.Point(7, 226); + this.ButtonDelObject.Name = "ButtonDelObject"; + this.ButtonDelObject.Size = new System.Drawing.Size(161, 37); + this.ButtonDelObject.TabIndex = 3; + this.ButtonDelObject.Text = "Удалить набор"; + this.ButtonDelObject.UseVisualStyleBackColor = true; + this.ButtonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click); + // + // ListBoxStorages + // + this.ListBoxStorages.FormattingEnabled = true; + this.ListBoxStorages.Location = new System.Drawing.Point(9, 112); + this.ListBoxStorages.Name = "ListBoxStorages"; + this.ListBoxStorages.Size = new System.Drawing.Size(162, 95); + this.ListBoxStorages.TabIndex = 2; + this.ListBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxStorages_SelectedIndexChanged); + // + // ButtonAddObject + // + this.ButtonAddObject.Location = new System.Drawing.Point(8, 61); + this.ButtonAddObject.Name = "ButtonAddObject"; + this.ButtonAddObject.Size = new System.Drawing.Size(164, 34); + this.ButtonAddObject.TabIndex = 1; + this.ButtonAddObject.Text = "Добавить набор"; + this.ButtonAddObject.UseVisualStyleBackColor = true; + this.ButtonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click); + // + // textBoxStorageName + // + this.textBoxStorageName.Location = new System.Drawing.Point(7, 21); + this.textBoxStorageName.Name = "textBoxStorageName"; + this.textBoxStorageName.Size = new System.Drawing.Size(166, 20); + this.textBoxStorageName.TabIndex = 0; + // // ButtonRefreshCollection // - this.ButtonRefreshCollection.Location = new System.Drawing.Point(17, 237); + this.ButtonRefreshCollection.Location = new System.Drawing.Point(18, 509); this.ButtonRefreshCollection.Name = "ButtonRefreshCollection"; this.ButtonRefreshCollection.Size = new System.Drawing.Size(178, 41); this.ButtonRefreshCollection.TabIndex = 3; @@ -63,24 +119,24 @@ // // ButtonRemovePlane // - this.ButtonRemovePlane.Location = new System.Drawing.Point(17, 136); + this.ButtonRemovePlane.Location = new System.Drawing.Point(18, 430); this.ButtonRemovePlane.Name = "ButtonRemovePlane"; this.ButtonRemovePlane.Size = new System.Drawing.Size(179, 41); this.ButtonRemovePlane.TabIndex = 2; - this.ButtonRemovePlane.Text = "Удалить автомобиль"; + this.ButtonRemovePlane.Text = "Удалить самолет"; this.ButtonRemovePlane.UseVisualStyleBackColor = true; this.ButtonRemovePlane.Click += new System.EventHandler(this.ButtonRemovePlane_Click); // // maskedTextBoxNumber // - this.maskedTextBoxNumber.Location = new System.Drawing.Point(17, 99); + this.maskedTextBoxNumber.Location = new System.Drawing.Point(18, 388); this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; this.maskedTextBoxNumber.Size = new System.Drawing.Size(180, 20); this.maskedTextBoxNumber.TabIndex = 1; // // ButtonAddPlane // - this.ButtonAddPlane.Location = new System.Drawing.Point(17, 36); + this.ButtonAddPlane.Location = new System.Drawing.Point(18, 327); this.ButtonAddPlane.Name = "ButtonAddPlane"; this.ButtonAddPlane.Size = new System.Drawing.Size(185, 40); this.ButtonAddPlane.TabIndex = 0; @@ -92,7 +148,7 @@ // this.pictureBoxCollection.Location = new System.Drawing.Point(-2, 2); this.pictureBoxCollection.Name = "pictureBoxCollection"; - this.pictureBoxCollection.Size = new System.Drawing.Size(600, 452); + this.pictureBoxCollection.Size = new System.Drawing.Size(600, 563); this.pictureBoxCollection.TabIndex = 1; this.pictureBoxCollection.TabStop = false; // @@ -100,13 +156,15 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 450); + this.ClientSize = new System.Drawing.Size(800, 564); this.Controls.Add(this.pictureBoxCollection); this.Controls.Add(this.groupBox1); this.Name = "FormPlaneCollection"; this.Text = "Набор самолетов"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); + this.groupBoxSet.ResumeLayout(false); + this.groupBoxSet.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); this.ResumeLayout(false); @@ -120,5 +178,10 @@ private System.Windows.Forms.TextBox maskedTextBoxNumber; private System.Windows.Forms.Button ButtonAddPlane; private System.Windows.Forms.PictureBox pictureBoxCollection; + private System.Windows.Forms.GroupBox groupBoxSet; + private System.Windows.Forms.Button ButtonDelObject; + private System.Windows.Forms.ListBox ListBoxStorages; + private System.Windows.Forms.Button ButtonAddObject; + private System.Windows.Forms.TextBox textBoxStorageName; } } \ No newline at end of file diff --git a/ProjectBomber/ProjectBomber/FormPlaneCollection.cs b/ProjectBomber/ProjectBomber/FormPlaneCollection.cs index f10fafc..ddd9444 100644 --- a/ProjectBomber/ProjectBomber/FormPlaneCollection.cs +++ b/ProjectBomber/ProjectBomber/FormPlaneCollection.cs @@ -14,23 +14,87 @@ using ProjectBomber.DrawningObjects; namespace ProjectBomber { /// - /// Форма для работы с набором объектов класса DrawningCar + /// Форма для работы с набором объектов класса DrawningBomber /// public partial class FormPlaneCollection : Form { /// /// Набор объектов /// - private readonly PlanesGenericCollection _planes; + private readonly PlanesGenericStorage _storage; /// /// Конструктор /// public FormPlaneCollection() { InitializeComponent(); - _planes = new PlanesGenericCollection(pictureBoxCollection.Width, pictureBoxCollection.Height); + _storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + } + /// + /// Заполнение listBoxObjects + /// + private void ReloadObjects() + { + int index = ListBoxStorages.SelectedIndex; + ListBoxStorages.Items.Clear(); + for (int i = 0; i < _storage.Keys.Count; i++) + { + ListBoxStorages.Items.Add(_storage.Keys[i]); + } + if (ListBoxStorages.Items.Count > 0 && (index == -1 || index + >= ListBoxStorages.Items.Count)) + { + ListBoxStorages.SelectedIndex = 0; + } + else if (ListBoxStorages.Items.Count > 0 && index > -1 && + index < ListBoxStorages.Items.Count) + { + ListBoxStorages.SelectedIndex = index; + } + } + /// + /// Добавление набора в коллекцию + /// + /// + /// + private void ButtonAddObject_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxStorageName.Text)) + { + MessageBox.Show("Не все данные заполнены", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _storage.AddSet(textBoxStorageName.Text); + ReloadObjects(); + } + /// + /// Выбор набора + /// + /// + /// + private void ListBoxStorages_SelectedIndexChanged(object sender, EventArgs e) + { + pictureBoxCollection.Image = +_storage[ListBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowPlanes(); + } + /// + /// Удаление набора + /// + /// + /// + private void ButtonDelObject_Click(object sender, EventArgs e) + { + if (ListBoxStorages.SelectedIndex == -1) + { + return; + } + if (MessageBox.Show($"Удалить объект {ListBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, +MessageBoxIcon.Question) == DialogResult.Yes) + { + _storage.DelSet(ListBoxStorages.SelectedItem.ToString()?? string.Empty); + ReloadObjects(); + } } /// /// Добавление объекта в набор @@ -39,13 +103,23 @@ namespace ProjectBomber /// private void ButtonAddPlane_Click(object sender, EventArgs e) { + if (ListBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[ListBoxStorages.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } FormBomber form = new FormBomber(); if (form.ShowDialog() == DialogResult.OK) { - if (_planes + form.SelectedBomber != 1) + if (obj + form.SelectedBomber) { MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = _planes.ShowPlanes(); + pictureBoxCollection.Image = obj.ShowPlanes(); } else { @@ -60,16 +134,25 @@ namespace ProjectBomber /// private void ButtonRemovePlane_Click(object sender, EventArgs e) { + if (ListBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[ListBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + return; + } if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (_planes - pos != null) + if (obj - pos != null) { MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = _planes.ShowPlanes(); + pictureBoxCollection.Image = obj.ShowPlanes(); } else { @@ -83,7 +166,17 @@ namespace ProjectBomber /// private void ButtonRefreshCollection_Click(object sender, EventArgs e) { - pictureBoxCollection.Image = _planes.ShowPlanes(); + if (ListBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[ListBoxStorages.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + pictureBoxCollection.Image = obj.ShowPlanes(); } } } diff --git a/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs b/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs index a86241d..9042780 100644 --- a/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs +++ b/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs @@ -57,14 +57,15 @@ namespace ProjectBomber.Generics /// /// /// - public static int? operator +(PlanesGenericCollection collect, T + public static bool operator +(PlanesGenericCollection collect, T obj) { if (obj == null) { - return -1; + return false; } - return collect?._collection.Insert(obj); + collect?._collection.Insert(obj); + return true; } /// /// Перегрузка оператора вычитания @@ -72,15 +73,14 @@ namespace ProjectBomber.Generics /// /// /// - public static bool operator -(PlanesGenericCollection collect, int - pos) + public static T operator -(PlanesGenericCollection collect, int pos) { - T obj = collect._collection.Get(pos); - if (obj == null) + T obj = collect._collection[pos]; + if (obj != null) { - return false; + collect._collection.Remove(pos); } - return collect._collection.Remove(pos); + return obj; } /// /// Получение объекта IMoveableObject @@ -89,7 +89,7 @@ namespace ProjectBomber.Generics /// public U GetU(int pos) { - return (U)_collection.Get(pos)?.GetMoveableObject; + return (U)_collection[pos]?.GetMoveableObject; } /// /// Вывод всего набора объектов @@ -126,7 +126,6 @@ namespace ProjectBomber.Generics g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, numRows * _placeSizeHeight); } } - /// /// Метод прорисовки объектов /// @@ -134,22 +133,34 @@ namespace ProjectBomber.Generics private void DrawObjects(Graphics g) { int numColumns = _pictureWidth / _placeSizeWidth; - int numRows = _pictureHeight / _placeSizeHeight; - - for (int i = 0; i < _collection.Count; i++) + int column = numColumns - 1; + int row = 0; + foreach (var plane in _collection.GetPlanes()) { - DrawningBomber plane = _collection.Get(i); + // Установка позиции бомбардировщика + int xPosition = column * _placeSizeWidth; + int yPosition = row * _placeSizeHeight; if (plane != null) { - // Вычисляем позицию объекта - int row = i / numColumns; // Номер строки - int column = numColumns - 1 - (i % numColumns); // Номер столбца, инвертируем для движения справа налево - int x = column * _placeSizeWidth; - int y = row * _placeSizeHeight; - - plane.SetPosition(x, y); + // Перемещение по ячейкам влево, вниз + column--; + if (column < 0) + { + column = numColumns - 1; + row++; + } + plane.SetPosition(xPosition, yPosition); plane.DrawTransport(g); } + else + { + column--; + if (column < 0) + { + column = numColumns - 1; + row++; + } + } } } } diff --git a/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs b/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs new file mode 100644 index 0000000..44ff999 --- /dev/null +++ b/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectBomber.DrawningObjects; +using ProjectBomber.MovementStrategy; + +namespace ProjectBomber.Generics +{ + /// + /// Класс для хранения коллекции + /// + internal class PlanesGenericStorage + { + /// + /// Словарь (хранилище) + /// + readonly Dictionary> _planeStorages; + /// + /// Возвращение списка названий наборов + /// + public List Keys => _planeStorages.Keys.ToList(); + /// + /// Ширина окна отрисовки + /// + private readonly int _pictureWidth; + /// + /// Высота окна отрисовки + /// + private readonly int _pictureHeight; + /// + /// Конструктор + /// + /// + /// + public PlanesGenericStorage(int pictureWidth, int pictureHeight) + { + _planeStorages = new Dictionary>(); + _pictureWidth = pictureWidth; + _pictureHeight = pictureHeight; + } + /// + /// Добавление набора + /// + /// Название набора + public void AddSet(string name) + { + // Создаем новый набор и добавляем его в словарь + if (!_planeStorages.ContainsKey(name)) + { + _planeStorages[name] = new PlanesGenericCollection(_pictureWidth, _pictureHeight); + } + else + { + throw new ArgumentException("Набор с таким именем уже существует"); + } + } + /// + /// Удаление набора + /// + /// Название набора + public void DelSet(string name) + { + // Удаляем набор из словаря по имени + if (_planeStorages.ContainsKey(name)) + { + _planeStorages.Remove(name); + } + else + { + throw new ArgumentException("Набор с таким именем не найден."); + } + } + /// + /// Доступ к набору + /// + /// + /// + public PlanesGenericCollection this[string ind] + { + get + { + if (_planeStorages.ContainsKey(ind)) + { + return _planeStorages[ind]; + } + else + { + throw new KeyNotFoundException($"Набор с именем '{ind}' не найден."); + } + } + } + } +} diff --git a/ProjectBomber/ProjectBomber/ProjectBomber.csproj b/ProjectBomber/ProjectBomber/ProjectBomber.csproj index 12e44ab..da00a5f 100644 --- a/ProjectBomber/ProjectBomber/ProjectBomber.csproj +++ b/ProjectBomber/ProjectBomber/ProjectBomber.csproj @@ -85,6 +85,7 @@ + diff --git a/ProjectBomber/ProjectBomber/SetGeneric.cs b/ProjectBomber/ProjectBomber/SetGeneric.cs index dd37436..7daede8 100644 --- a/ProjectBomber/ProjectBomber/SetGeneric.cs +++ b/ProjectBomber/ProjectBomber/SetGeneric.cs @@ -14,84 +14,83 @@ namespace ProjectBomber.Generics where T : class { /// - /// Массив объектов, которые храним + /// Список объектов, которые храним /// - private readonly T[] _places; + private readonly List _places; /// - /// Количество объектов в массиве + /// Количество объектов в списке /// - public int Count => _places.Length; + public int Count => _places.Count; + /// + /// Максимальное количество объектов в списке + /// + private readonly int _maxCount; /// /// Конструктор /// /// public SetGeneric(int count) { - _places = new T[count]; + _maxCount = count; + _places = new List(count); } /// /// Добавление объекта в набор /// /// Добавляемый самолет /// - public int Insert(T plane) + public bool Insert(T plane) { - int index = -1; - for (int i = 0; i < _places.Length; i++) + if (_places.Count == 0) { - if (_places[i] == null) + _places.Add(plane); + return true; + } + else + { + if (_places.Count < _maxCount) { - index = i; break; + _places.Add(plane); + for (int i = 0; i < _places.Count; i++) + { + T temp = _places[i]; + _places[i] = _places[_places.Count - 1]; + _places[_places.Count - 1] = temp; + } + return true; } } - if (index < 0) - { - return -1; - } - for (int i = index; i > 0; i--) - { - _places[i] = _places[i - 1]; - } - _places[0] = plane; - return 0; + return true; } /// /// Добавление объекта в набор на конкретную позицию /// - /// Добавляемый автомобиль + /// Добавляемый самолет /// Позиция /// - public int Insert(T plane, int position) + public bool Insert(T plane, int position) { - ///Проверка позиции - if (position < 0 || position >= _places.Length) - return -1; - /// Проверка, что элемент массива по этой позиции пустой, если нет, то проверка, - /// что после вставляемого элемента в массиве есть пустой элемент - if (_places[position] != null) + if (position < 0 || position >= _maxCount) { - /// Проверка, что после вставляемого элемента в массиве есть пустой элемент - int firstEmptyPosition = -1; - for (int i = position + 1; i < _places.Length; i++) + return false; + } + if (position < _places.Count && _places[position] == null) + { + _places[position] = plane; + } + else + { + // Ищем первую пустую позицию и вставляем туда. + for (int i = 0; i < _maxCount; i++) { if (_places[i] == null) { - firstEmptyPosition = i; + _places[i] = plane; break; } } - /// Нет пустой позиции после вставляемой - if (firstEmptyPosition == -1) - return -1; - /// Сдвиг всех объектов, находящихся справа от позиции, до первого пустого элемента - for (int i = firstEmptyPosition; i > position; i--) - { - _places[i] = _places[i - 1]; - } } - /// Вставка по позиции - _places[position] = plane; - return 0; + return true; } /// /// Удаление объекта из набора с конкретной позиции @@ -100,10 +99,8 @@ namespace ProjectBomber.Generics /// public bool Remove(int position) { - /// Проверка позиции - if (position < 0 || position >= _places.Length) + if (position < 0 || position >= _maxCount) return false; - /// Удаление объекта из массива, присвоив элементу массива значение null _places[position] = null; return true; } @@ -112,12 +109,35 @@ namespace ProjectBomber.Generics /// /// /// - public T Get(int position) + public T this[int position] { - // Проверка позиции - if (position < 0 || position >= _places.Length) - return null; - return _places[position]; + get + { + if (position < 0 || position >= _maxCount) + return null; + return _places[position]; + } + set + { + if (position < 0 || position >= _maxCount || _places.Count >= _maxCount) + return; // Неправильная позиция или нет места для вставки + _places[position] = value; + } + } + /// + /// Проход по списку + /// + /// + public IEnumerable GetPlanes(int? maxPlanes = null) + { + for (int i = 0; i < _places.Count; ++i) + { + yield return _places[i]; + if (maxPlanes.HasValue && i == maxPlanes.Value) + { + yield break; + } + } } } }