diff --git a/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.Designer.cs b/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.Designer.cs index 4779870..cd568ed 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.Designer.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.Designer.cs @@ -30,12 +30,18 @@ { this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); this.panelTools = new System.Windows.Forms.Panel(); - this.textBox = new System.Windows.Forms.TextBox(); + this.panel1 = new System.Windows.Forms.Panel(); + this.textBoxStorageName = new System.Windows.Forms.TextBox(); + this.listBoxStorages = new System.Windows.Forms.ListBox(); + this.buttonAddCollection = new System.Windows.Forms.Button(); + this.buttonDelCollection = new System.Windows.Forms.Button(); + this.maskedTextBoxNumber = new System.Windows.Forms.TextBox(); this.buttonUpdateColletion = new System.Windows.Forms.Button(); this.buttonDeleteZenit = new System.Windows.Forms.Button(); this.buttonAddZenit = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); this.panelTools.SuspendLayout(); + this.panel1.SuspendLayout(); this.SuspendLayout(); // // pictureBoxCollection @@ -48,7 +54,8 @@ // // panelTools // - this.panelTools.Controls.Add(this.textBox); + this.panelTools.Controls.Add(this.panel1); + this.panelTools.Controls.Add(this.maskedTextBoxNumber); this.panelTools.Controls.Add(this.buttonUpdateColletion); this.panelTools.Controls.Add(this.buttonDeleteZenit); this.panelTools.Controls.Add(this.buttonAddZenit); @@ -58,16 +65,65 @@ this.panelTools.TabIndex = 1; this.panelTools.Tag = ""; // - // textBox + // panel1 // - this.textBox.Location = new System.Drawing.Point(23, 164); - this.textBox.Name = "textBox"; - this.textBox.Size = new System.Drawing.Size(193, 23); - this.textBox.TabIndex = 3; + this.panel1.Controls.Add(this.textBoxStorageName); + this.panel1.Controls.Add(this.listBoxStorages); + this.panel1.Controls.Add(this.buttonAddCollection); + this.panel1.Controls.Add(this.buttonDelCollection); + this.panel1.Location = new System.Drawing.Point(15, 52); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(215, 294); + this.panel1.TabIndex = 8; + this.panel1.Tag = "Наборы"; + // + // textBoxStorageName + // + this.textBoxStorageName.Location = new System.Drawing.Point(12, 53); + this.textBoxStorageName.Name = "textBoxStorageName"; + this.textBoxStorageName.Size = new System.Drawing.Size(193, 23); + this.textBoxStorageName.TabIndex = 7; + // + // listBoxStorages + // + this.listBoxStorages.FormattingEnabled = true; + this.listBoxStorages.ItemHeight = 15; + this.listBoxStorages.Location = new System.Drawing.Point(12, 137); + this.listBoxStorages.Name = "listBoxStorages"; + this.listBoxStorages.Size = new System.Drawing.Size(191, 94); + this.listBoxStorages.TabIndex = 6; + this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged); + // + // buttonAddCollection + // + this.buttonAddCollection.Location = new System.Drawing.Point(10, 92); + this.buttonAddCollection.Name = "buttonAddCollection"; + this.buttonAddCollection.Size = new System.Drawing.Size(193, 40); + this.buttonAddCollection.TabIndex = 5; + this.buttonAddCollection.Text = "Добавить набор"; + this.buttonAddCollection.UseVisualStyleBackColor = true; + this.buttonAddCollection.Click += new System.EventHandler(this.ButtonAddObject_Click); + // + // buttonDelCollection + // + this.buttonDelCollection.Location = new System.Drawing.Point(12, 249); + this.buttonDelCollection.Name = "buttonDelCollection"; + this.buttonDelCollection.Size = new System.Drawing.Size(193, 40); + this.buttonDelCollection.TabIndex = 4; + this.buttonDelCollection.Text = "Удалить набор"; + this.buttonDelCollection.UseVisualStyleBackColor = true; + this.buttonDelCollection.Click += new System.EventHandler(this.ButtonDelObject_Click); + // + // maskedTextBoxNumber + // + this.maskedTextBoxNumber.Location = new System.Drawing.Point(23, 435); + this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; + this.maskedTextBoxNumber.Size = new System.Drawing.Size(193, 23); + this.maskedTextBoxNumber.TabIndex = 3; // // buttonUpdateColletion // - this.buttonUpdateColletion.Location = new System.Drawing.Point(23, 263); + this.buttonUpdateColletion.Location = new System.Drawing.Point(23, 525); this.buttonUpdateColletion.Name = "buttonUpdateColletion"; this.buttonUpdateColletion.Size = new System.Drawing.Size(193, 40); this.buttonUpdateColletion.TabIndex = 2; @@ -77,7 +133,7 @@ // // buttonDeleteZenit // - this.buttonDeleteZenit.Location = new System.Drawing.Point(23, 193); + this.buttonDeleteZenit.Location = new System.Drawing.Point(23, 464); this.buttonDeleteZenit.Name = "buttonDeleteZenit"; this.buttonDeleteZenit.Size = new System.Drawing.Size(193, 40); this.buttonDeleteZenit.TabIndex = 1; @@ -87,7 +143,7 @@ // // buttonAddZenit // - this.buttonAddZenit.Location = new System.Drawing.Point(23, 32); + this.buttonAddZenit.Location = new System.Drawing.Point(23, 389); this.buttonAddZenit.Name = "buttonAddZenit"; this.buttonAddZenit.Size = new System.Drawing.Size(193, 40); this.buttonAddZenit.TabIndex = 0; @@ -107,6 +163,8 @@ ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); this.panelTools.ResumeLayout(false); this.panelTools.PerformLayout(); + this.panel1.ResumeLayout(false); + this.panel1.PerformLayout(); this.ResumeLayout(false); } @@ -115,9 +173,14 @@ private PictureBox pictureBoxCollection; private Panel panelTools; - private TextBox textBox; + private TextBox maskedTextBoxNumber; private Button buttonUpdateColletion; private Button buttonDeleteZenit; private Button buttonAddZenit; + private Panel panel1; + private TextBox textBoxStorageName; + private ListBox listBoxStorages; + private Button buttonAddCollection; + private Button buttonDelCollection; } } \ No newline at end of file diff --git a/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs b/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs index 0a15fc1..e70e4a7 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs @@ -15,54 +15,151 @@ namespace AntiAircraftGun { public partial class FormAntiAirCraftGunCollection : Form { - private readonly AntiAirCraftGunGenericCollection _zenits; + private readonly AntiAirCraftGunGenericStorage _storage; public FormAntiAirCraftGunCollection() { InitializeComponent(); - _zenits = new AntiAirCraftGunGenericCollection(pictureBoxCollection.Width, pictureBoxCollection.Height); + _storage = new AntiAirCraftGunGenericStorage(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 ListBoxObjects_SelectedIndexChanged(object sender, + EventArgs e) + { + pictureBoxCollection.Image = + _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowZenits(); + } + /// + /// Удаление набора + /// + /// + /// + 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(); + } + } private void ButtonAddZenit_Click(object sender, EventArgs e) { + if (listBoxStorages.SelectedIndex == -1) + { + MessageBox.Show("Выберите набор в списке.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + MessageBox.Show("Выбранный набор не найден.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } FormAntiAirCraftGun form = new(); if (form.ShowDialog() == DialogResult.OK) { - if (_zenits + form.SelectedZenit != null) + if (obj + form.SelectedZenit) { MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = _zenits.ShowZenits(); + pictureBoxCollection.Image = obj.ShowZenits(); } else { MessageBox.Show("Не удалось добавить объект"); } - } } private void ButtonDeleteZenit_Click(object sender, EventArgs e) { - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - + if (listBoxStorages.SelectedIndex == -1) { return; } - int pos = Convert.ToInt32(textBox.Text); - if (_zenits - pos != null) + 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 (obj - pos != null) { MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = _zenits.ShowZenits(); + pictureBoxCollection.Image = obj.ShowZenits(); } else { MessageBox.Show("Не удалось удалить объект"); } } + private void ButtonUpdateCollection_Click(object sender, EventArgs e) { - pictureBoxCollection.Image = _zenits.ShowZenits(); + if (listBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + pictureBoxCollection.Image = obj.ShowZenits(); } } diff --git a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs index 3ff0441..2df4441 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs @@ -51,11 +51,11 @@ namespace AntiAircraftGun.Generics /// /// /// - public static int operator +(AntiAirCraftGunGenericCollection collect, T? obj) + public static bool operator +(AntiAirCraftGunGenericCollection collect, T? obj) { if (obj == null) - return -1; - return collect?._collection.Insert(obj) ?? -1; + return false; + return collect?._collection.Insert(obj) ?? false; } /// /// Перегрузка оператора вычитания @@ -63,12 +63,12 @@ namespace AntiAircraftGun.Generics /// /// /// - public static bool operator -(AntiAirCraftGunGenericCollection collect, int pos) + public static T? operator -(AntiAirCraftGunGenericCollection collect, int pos) { - T? obj = collect._collection.Get(pos); - if (obj != null) - return collect._collection.Remove(pos); - return false; + T? obj = collect._collection.Get(pos); + if (obj != null) + collect._collection.Remove(pos); + return obj; } /// @@ -78,7 +78,7 @@ namespace AntiAircraftGun.Generics /// public U? GetU(int pos) { - return (U?)_collection.Get(pos)?.GetMoveableObject; + return (U?)_collection[pos]?.GetMoveableObject; } /// /// Вывод всего набора объектов @@ -123,10 +123,11 @@ namespace AntiAircraftGun.Generics int maxX = _pictureWidth; // Максимальное значение X, при достижении которого будет ошибка int maxY = _pictureHeight; // Максимальное значение Y, когда нужно изменить X int distance_between_objects = _placeSizeHeight; - for (int i = 0; i < _collection.Count; i++) + + foreach (var zenit in _collection.GetZenits()) { // TODO: Получение объекта - T? obj = _collection.Get(i); + T? obj = zenit; if (obj != null) { @@ -134,20 +135,20 @@ namespace AntiAircraftGun.Generics if (x >= maxX) { MessageBox.Show("Не хватает места для объекта."); - break; + break; } // Устанавливаем позицию - obj.SetPosition(x, y+10); + obj.SetPosition(x, y + 10); // TODO: Прорисовка объекта obj.DrawTransport(g); // Увеличиваем координату Y для следующего объекта - y += distance_between_objects; + y += distance_between_objects; // Проверяем, если Y достигло максимума, изменяем X и сбрасываем Y - if (y+distance_between_objects >= maxY) + if (y + distance_between_objects >= maxY) { y = 0; x += _placeSizeWidth; diff --git a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs new file mode 100644 index 0000000..3eb2608 --- /dev/null +++ b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs @@ -0,0 +1,95 @@ +using AntiAircraftGun.DrawingObjects; +using AntiAircraftGun.MovementStrategy; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Generics +{ + /// + /// Класс для хранения коллекции + /// + internal class AntiAirCraftGunGenericStorage + { + /// + /// Словарь (хранилище) + /// + readonly Dictionary> _zenitStorages; + /// + /// Возвращение списка названий наборов + /// + public List Keys => _zenitStorages.Keys.ToList(); + /// + /// Ширина окна отрисовки + /// + private readonly int _pictureWidth; + /// + /// Высота окна отрисовки + /// + private readonly int _pictureHeight; + /// + /// Конструктор + /// + /// + /// + public AntiAirCraftGunGenericStorage(int pictureWidth, int pictureHeight) + { + _zenitStorages = new Dictionary>(); + _pictureWidth = pictureWidth; + _pictureHeight = pictureHeight; + } + /// + /// Добавление набора + /// + /// Название набора + public void AddSet(string name) + { + // TODO: Прописать логику для добавления набора + if (_zenitStorages.ContainsKey(name)) + { + MessageBox.Show("Набор с таким именем уже существует"); + return; + } + + _zenitStorages.Add(name, new AntiAirCraftGunGenericCollection(_pictureWidth, _pictureHeight)); + } + + /// + /// Удаление набора + /// + /// Название набора + public void DelSet(string name) + { + // TODO: Прописать логику для удаления набора + if (_zenitStorages.ContainsKey(name) == null) + { + return; + } + + _zenitStorages.Remove(name); + } + /// + /// Доступ к набору + /// + /// + /// + public AntiAirCraftGunGenericCollection? + this[string ind] + { + get + { + // TODO: Продумать логику получения набора + if (_zenitStorages.ContainsKey(ind)) + { + return _zenitStorages[ind]; + } + else + { + return null; + } + } + } + } +} diff --git a/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs b/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs index bdfeac1..abcfa88 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs @@ -12,70 +12,45 @@ namespace AntiAircraftGun.Generics /// /// Массив объектов, которые храним /// - 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 car) + public bool Insert(T car) { - // Вставка в начало набора - for (int i = 0; i < _places.Length; i++) - { - if (_places[i] == null) - { - _places[i] = car; - return 1; - } - } - return -1; // Если нет пустых мест + if (_places.Count == _maxCount) + return false; + Insert(car, 0); + return true; } - /// - /// Добавление объекта в набор на конкретную позицию - /// /// - /// Добавляемый автомобиль - /// Позиция - /// - public int Insert(T car, int position) + + public bool Insert(T car, int position) { - // Проверка позиции - if (position < 0 || position >= _places.Length) - return -1; - - // Проверка, что элемент массива по этой позиции пустой - if (_places[position] != null) - return -1; - - // Проверка, что после вставляемого элемента в массиве есть пустой элемент - for (int i = position + 1; i < _places.Length; i++) - { - if (_places[i] == null) - { - // Сдвиг всех объектов справа от позиции до первого пустого элемента - for (int j = i; j > position; j--) - { - _places[j] = _places[j - 1]; - } - _places[position] = car; - return 1; - } - } - - return -1; // Если нет пустых мест справа + if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) + return false; + _places.Insert(position, car); + return true; } + /// /// Удаление объекта из набора с конкретной позиции /// @@ -84,11 +59,11 @@ namespace AntiAircraftGun.Generics public bool Remove(int position) { // Проверка позиции - if (position < 0 || position >= _places.Length) + if (position < 0 || position >= Count) return false; - // Удаление объекта из массива, присвоив элементу массива значение null - _places[position] = null; + + _places.RemoveAt(position); return true; } /// @@ -96,9 +71,40 @@ namespace AntiAircraftGun.Generics /// /// /// + public T? this[int position] + { + get + { + if (!(position >= 0 && position < Count)) + return null; + return _places[position]; + } + set + { + if (!(position >= 0 && position < Count && _places.Count < _maxCount)) + return; + _places.Insert(position, value); + return; + } + } + /// + /// Проход по списку + /// + /// + public IEnumerable GetZenits(int? maxCars = null) + { + for (int i = 0; i < _places.Count; ++i) + { + yield return _places[i]; + if (maxCars.HasValue && i == maxCars.Value) + { + yield break; + } + } + } public T? Get(int position) { - if (position < 0 || position >= _places.Length) + if (position < 0 || position >= Count) { // Позиция находится за пределами допустимого диапазона, вернем null return null;