From 4f2b31bf11f4012dfcd2789f212e372ff243b39a Mon Sep 17 00:00:00 2001 From: VanyaAlekseev Date: Tue, 12 Dec 2023 16:27:38 +0400 Subject: [PATCH 1/2] SemesterFirstLabSeventhBomberBase --- .../ProjectBomber/DrawiningPlaneEqutables.cs | 60 ++++++++++++++++++ .../ProjectBomber/PlaneCompareByColor.cs | 15 +++++ .../ProjectBomber/PlaneCompareByType.cs | 35 +++++++++++ .../ProjectBomber/ProjectBomber.csproj | 3 + ProjectBomber/ProjectBomber/SetGeneric.cs | 61 +++++-------------- 5 files changed, 128 insertions(+), 46 deletions(-) create mode 100644 ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs create mode 100644 ProjectBomber/ProjectBomber/PlaneCompareByColor.cs create mode 100644 ProjectBomber/ProjectBomber/PlaneCompareByType.cs diff --git a/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs b/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs new file mode 100644 index 0000000..fed76b6 --- /dev/null +++ b/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectBomber.DrawningObjects; +using ProjectBomber.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectBomber.Generics +{ + internal class DrawiningPlaneEqutables : IEqualityComparer + { + public bool Equals(DrawningBomber x, DrawningBomber y) + { + if (x == null || x.EntityBomber == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityBomber == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityBomber.Speed != y.EntityBomber.Speed) + { + return false; + } + if (x.EntityBomber.Weight != y.EntityBomber.Weight) + { + return false; + } + if (x.EntityBomber.BodyColor != y.EntityBomber.BodyColor) + { + return false; + } + if (x is DrawningBomberAdvanced && y is DrawningBomberAdvanced) + { + EntityBomberAdvanced EntityX = (EntityBomberAdvanced)x.EntityBomber; + EntityBomberAdvanced EntityY = (EntityBomberAdvanced)y.EntityBomber; + if (EntityX.Bombs != EntityY.Bombs) + return false; + if (EntityX.FuelTanks != EntityY.FuelTanks) + return false; + if (EntityX.Line != EntityY.Line) + return false; + if (EntityX.AdditionalColor != EntityY.AdditionalColor) + return false; + } + return true; + } + public int GetHashCode([DisallowNull] DrawningBomber obj) + { + return obj.GetHashCode(); + } + } +} diff --git a/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs b/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs new file mode 100644 index 0000000..11462a6 --- /dev/null +++ b/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectBomber.Entities; +using ProjectBomber.DrawningObjects; + +namespace ProjectBomber +{ + internal class PlaneCompareByColor : IComparer + { + + } +} diff --git a/ProjectBomber/ProjectBomber/PlaneCompareByType.cs b/ProjectBomber/ProjectBomber/PlaneCompareByType.cs new file mode 100644 index 0000000..b0dcb68 --- /dev/null +++ b/ProjectBomber/ProjectBomber/PlaneCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectBomber.Entities; +using ProjectBomber.DrawningObjects; + +namespace ProjectBomber.Generics +{ + internal class PlaneCompareByType : IComparer + { + public int Compare(DrawningBomber x, DrawningBomber y) + { + if (x == null || x.EntityBomber == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityBomber == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityBomber.Speed.CompareTo(y.EntityBomber.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBomber.Weight.CompareTo(y.EntityBomber.Weight); + } + } +} diff --git a/ProjectBomber/ProjectBomber/ProjectBomber.csproj b/ProjectBomber/ProjectBomber/ProjectBomber.csproj index 8651292..e8d5d14 100644 --- a/ProjectBomber/ProjectBomber/ProjectBomber.csproj +++ b/ProjectBomber/ProjectBomber/ProjectBomber.csproj @@ -162,6 +162,7 @@ + @@ -190,6 +191,8 @@ + + diff --git a/ProjectBomber/ProjectBomber/SetGeneric.cs b/ProjectBomber/ProjectBomber/SetGeneric.cs index 7bc9b89..7f0225d 100644 --- a/ProjectBomber/ProjectBomber/SetGeneric.cs +++ b/ProjectBomber/ProjectBomber/SetGeneric.cs @@ -39,30 +39,13 @@ namespace ProjectBomber.Generics /// /// Добавляемый самолет /// - public int Insert(T plane) + public bool Insert(T plane, IEqualityComparer equal = null) { - if (_places.Count == 0) - { - _places.Add(plane); - return 0; - } - else - { - if (_places.Count < _maxCount) - { - _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 0; - } - else { - throw new StorageOverflowException(_places.Count); - } - } + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + Insert(plane, 0); + Insert(plane, 0, equal); + return true; } /// /// Добавление объекта в набор на конкретную позицию @@ -70,33 +53,19 @@ namespace ProjectBomber.Generics /// Добавляемый самолет /// Позиция /// - public bool Insert(T plane, int position) + public bool Insert(T plane, int position, IEqualityComparer equal = null) { - if (position < 0 || position >= _maxCount) - { + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) return false; - } - if (_places[position] == null) + if (equal != null) { - _places[position] = plane; - return true; - } - - if (_places.Count < _maxCount) - { - _places.Add(plane); - for (int i = position; i < _places.Count; i++) - { - T temp = _places[i]; - _places[i] = _places[_places.Count - 1]; - _places[_places.Count - 1] = temp; - } - return true; - } - else - { - throw new StorageOverflowException(); + if (_places.Contains(plane, equal)) + throw new ArgumentException(nameof(plane)); } + _places.Insert(position, plane); + return true; } /// /// Удаление объекта из набора с конкретной позиции -- 2.25.1 From 0a0ac93219936a53af8bcbd9c1512b468281b8a6 Mon Sep 17 00:00:00 2001 From: VanyaAlekseev Date: Thu, 14 Dec 2023 13:41:09 +0400 Subject: [PATCH 2/2] SemesterFirstLabEighthBomberBase --- ProjectBomber/ProjectBomber/App.config | 32 ++--- .../ProjectBomber/DrawiningPlaneEqutables.cs | 2 +- .../FormPlaneCollection.Designer.cs | 53 +++++--- .../ProjectBomber/FormPlaneCollection.cs | 22 +++- .../ProjectBomber/FormPlaneCollection.resx | 3 + .../ProjectBomber/PlaneCompareByColor.cs | 34 ++++- .../ProjectBomber/PlanesCollectionInfo.cs | 28 +++++ .../ProjectBomber/PlanesGenericCollection.cs | 7 +- .../ProjectBomber/PlanesGenericStorage.cs | 94 ++++++-------- ProjectBomber/ProjectBomber/Program.cs | 1 - .../ProjectBomber/ProjectBomber.csproj | 24 +--- .../Properties/Resources.Designer.cs | 63 ---------- .../ProjectBomber/Properties/Resources.resx | 117 ------------------ .../Properties/Settings.Designer.cs | 26 ---- .../Properties/Settings.settings | 7 -- ProjectBomber/ProjectBomber/SetGeneric.cs | 10 +- ProjectBomber/ProjectBomber/packages.config | 34 ----- 17 files changed, 195 insertions(+), 362 deletions(-) create mode 100644 ProjectBomber/ProjectBomber/PlanesCollectionInfo.cs delete mode 100644 ProjectBomber/ProjectBomber/Properties/Resources.Designer.cs delete mode 100644 ProjectBomber/ProjectBomber/Properties/Resources.resx delete mode 100644 ProjectBomber/ProjectBomber/Properties/Settings.Designer.cs delete mode 100644 ProjectBomber/ProjectBomber/Properties/Settings.settings delete mode 100644 ProjectBomber/ProjectBomber/packages.config diff --git a/ProjectBomber/ProjectBomber/App.config b/ProjectBomber/ProjectBomber/App.config index c1409ef..95bf21e 100644 --- a/ProjectBomber/ProjectBomber/App.config +++ b/ProjectBomber/ProjectBomber/App.config @@ -1,37 +1,37 @@ - + - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + diff --git a/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs b/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs index fed76b6..9063f02 100644 --- a/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs +++ b/ProjectBomber/ProjectBomber/DrawiningPlaneEqutables.cs @@ -52,7 +52,7 @@ namespace ProjectBomber.Generics } return true; } - public int GetHashCode([DisallowNull] DrawningBomber obj) + public int GetHashCode(DrawningBomber obj) { return obj.GetHashCode(); } diff --git a/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs b/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs index ae3f215..729bad3 100644 --- a/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs +++ b/ProjectBomber/ProjectBomber/FormPlaneCollection.Designer.cs @@ -29,6 +29,8 @@ private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.ButtonSortByColor = new System.Windows.Forms.Button(); + this.ButtonSortByType = new System.Windows.Forms.Button(); this.groupBoxSet = new System.Windows.Forms.GroupBox(); this.ButtonDelObject = new System.Windows.Forms.Button(); this.ListBoxStorages = new System.Windows.Forms.ListBox(); @@ -47,12 +49,13 @@ this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.groupBox1.SuspendLayout(); this.groupBoxSet.SuspendLayout(); - this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); this.SuspendLayout(); // // groupBox1 // + this.groupBox1.Controls.Add(this.ButtonSortByColor); + this.groupBox1.Controls.Add(this.ButtonSortByType); this.groupBox1.Controls.Add(this.groupBoxSet); this.groupBox1.Controls.Add(this.ButtonRefreshCollection); this.groupBox1.Controls.Add(this.ButtonRemovePlane); @@ -66,15 +69,35 @@ this.groupBox1.TabStop = false; this.groupBox1.Text = "Инструменты"; // + // ButtonSortByColor + // + this.ButtonSortByColor.Location = new System.Drawing.Point(20, 333); + this.ButtonSortByColor.Name = "ButtonSortByColor"; + this.ButtonSortByColor.Size = new System.Drawing.Size(181, 28); + this.ButtonSortByColor.TabIndex = 7; + this.ButtonSortByColor.Text = "Сортировка по цвету"; + this.ButtonSortByColor.UseVisualStyleBackColor = true; + this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click); + // + // ButtonSortByType + // + this.ButtonSortByType.Location = new System.Drawing.Point(20, 294); + this.ButtonSortByType.Name = "ButtonSortByType"; + this.ButtonSortByType.Size = new System.Drawing.Size(180, 33); + this.ButtonSortByType.TabIndex = 6; + this.ButtonSortByType.Text = "Сортировка по типу"; + this.ButtonSortByType.UseVisualStyleBackColor = true; + this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click); + // // 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.Location = new System.Drawing.Point(21, 19); this.groupBoxSet.Name = "groupBoxSet"; - this.groupBoxSet.Size = new System.Drawing.Size(180, 274); + this.groupBoxSet.Size = new System.Drawing.Size(180, 269); this.groupBoxSet.TabIndex = 4; this.groupBoxSet.TabStop = false; this.groupBoxSet.Text = "Наборы"; @@ -117,9 +140,9 @@ // // ButtonRefreshCollection // - this.ButtonRefreshCollection.Location = new System.Drawing.Point(20, 492); + this.ButtonRefreshCollection.Location = new System.Drawing.Point(21, 492); this.ButtonRefreshCollection.Name = "ButtonRefreshCollection"; - this.ButtonRefreshCollection.Size = new System.Drawing.Size(178, 41); + this.ButtonRefreshCollection.Size = new System.Drawing.Size(177, 41); this.ButtonRefreshCollection.TabIndex = 3; this.ButtonRefreshCollection.Text = "Обновить коллекцию"; this.ButtonRefreshCollection.UseVisualStyleBackColor = true; @@ -137,16 +160,16 @@ // // maskedTextBoxNumber // - this.maskedTextBoxNumber.Location = new System.Drawing.Point(18, 351); + this.maskedTextBoxNumber.Location = new System.Drawing.Point(21, 413); 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(18, 305); + this.ButtonAddPlane.Location = new System.Drawing.Point(21, 367); this.ButtonAddPlane.Name = "ButtonAddPlane"; - this.ButtonAddPlane.Size = new System.Drawing.Size(185, 40); + this.ButtonAddPlane.Size = new System.Drawing.Size(180, 40); this.ButtonAddPlane.TabIndex = 0; this.ButtonAddPlane.Text = "Добавить самолет"; this.ButtonAddPlane.UseVisualStyleBackColor = true; @@ -155,8 +178,6 @@ // menuStrip // this.menuStrip.Dock = System.Windows.Forms.DockStyle.Bottom; - this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.fileToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(3, 536); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(204, 24); @@ -175,23 +196,23 @@ // saveToolStripMenuItem // this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - this.saveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.saveToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.saveToolStripMenuItem.Text = "Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // loadToolStripMenuItem // this.loadToolStripMenuItem.Name = "loadToolStripMenuItem"; - this.loadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.loadToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.loadToolStripMenuItem.Text = "Load"; this.loadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); // // pictureBoxCollection // - this.pictureBoxCollection.Location = new System.Drawing.Point(0, 2); + this.pictureBoxCollection.Location = new System.Drawing.Point(1, 2); this.pictureBoxCollection.Name = "pictureBoxCollection"; this.pictureBoxCollection.Size = new System.Drawing.Size(600, 565); - this.pictureBoxCollection.TabIndex = 1; + this.pictureBoxCollection.TabIndex = 0; this.pictureBoxCollection.TabStop = false; // // openFileDialog @@ -217,8 +238,6 @@ this.groupBox1.PerformLayout(); this.groupBoxSet.ResumeLayout(false); this.groupBoxSet.PerformLayout(); - this.menuStrip.ResumeLayout(false); - this.menuStrip.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); this.ResumeLayout(false); @@ -243,5 +262,7 @@ private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; + private System.Windows.Forms.Button ButtonSortByColor; + private System.Windows.Forms.Button ButtonSortByType; } } \ No newline at end of file diff --git a/ProjectBomber/ProjectBomber/FormPlaneCollection.cs b/ProjectBomber/ProjectBomber/FormPlaneCollection.cs index b3e6f23..eac2cdf 100644 --- a/ProjectBomber/ProjectBomber/FormPlaneCollection.cs +++ b/ProjectBomber/ProjectBomber/FormPlaneCollection.cs @@ -46,7 +46,7 @@ namespace ProjectBomber ListBoxStorages.Items.Clear(); for (int i = 0; i < _storage.Keys.Count; i++) { - ListBoxStorages.Items.Add(_storage.Keys[i]); + ListBoxStorages.Items.Add(_storage.Keys[i].Name); } if (ListBoxStorages.Items.Count > 0 && (index == -1 || index >= ListBoxStorages.Items.Count)) @@ -268,5 +268,25 @@ _storage[ListBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowPlanes() } } } + private void ButtonSortByType_Click(object sender, EventArgs e) => ComparePlanes(new PlaneCompareByType()); + private void ButtonSortByColor_Click(object sender, EventArgs e) => ComparePlanes(new PlaneCompareByColor()); + /// + /// Сортировка по сравнителю + /// + /// + private void ComparePlanes(IComparer comparer) + { + if (ListBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[ListBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + return; + } + obj.Sort(comparer); + pictureBoxCollection.Image = obj.ShowPlanes(); + } } } diff --git a/ProjectBomber/ProjectBomber/FormPlaneCollection.resx b/ProjectBomber/ProjectBomber/FormPlaneCollection.resx index da29420..bf5d8cb 100644 --- a/ProjectBomber/ProjectBomber/FormPlaneCollection.resx +++ b/ProjectBomber/ProjectBomber/FormPlaneCollection.resx @@ -120,6 +120,9 @@ 17, 17 + + 17, 17 + 132, 17 diff --git a/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs b/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs index 11462a6..d19a023 100644 --- a/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs +++ b/ProjectBomber/ProjectBomber/PlaneCompareByColor.cs @@ -8,8 +8,38 @@ using ProjectBomber.DrawningObjects; namespace ProjectBomber { - internal class PlaneCompareByColor : IComparer + internal class PlaneCompareByColor : IComparer { - + public int Compare(DrawningBomber x, DrawningBomber y) + { + if (x == null || x.EntityBomber == null) + throw new ArgumentNullException(nameof(x)); + if (y == null || y.EntityBomber == null) + throw new ArgumentNullException(nameof(y)); + if (x.EntityBomber.BodyColor.Name != y.EntityBomber.BodyColor.Name) + { + return x.EntityBomber.BodyColor.Name.CompareTo(y.EntityBomber.BodyColor.Name); + } + if (x.GetType().Name != y.GetType().Name) + { + if (x is DrawningBomber) + return -1; + else + return 1; + } + if (x.GetType().Name == y.GetType().Name && x is DrawningBomberAdvanced) + { + EntityBomberAdvanced EntityX = (EntityBomberAdvanced)x.EntityBomber; + EntityBomberAdvanced EntityY = (EntityBomberAdvanced)y.EntityBomber; + if (EntityX.AdditionalColor.Name != EntityY.AdditionalColor.Name) + { + return EntityX.AdditionalColor.Name.CompareTo(EntityY.AdditionalColor.Name); + } + } + var speedCompare = x.EntityBomber.Speed.CompareTo(y.EntityBomber.Speed); + if (speedCompare != 0) + return speedCompare; + return x.EntityBomber.Weight.CompareTo(y.EntityBomber.Weight); + } } } diff --git a/ProjectBomber/ProjectBomber/PlanesCollectionInfo.cs b/ProjectBomber/ProjectBomber/PlanesCollectionInfo.cs new file mode 100644 index 0000000..7461d5e --- /dev/null +++ b/ProjectBomber/ProjectBomber/PlanesCollectionInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBomber +{ + internal class PlanesCollectionInfo : IEquatable + { + public string Name { get; private set; } + public string Description { get; private set; } + public PlanesCollectionInfo(string name, string description) + { + Name = name; + Description = description; + } + public bool Equals(PlanesCollectionInfo other) + { + return Name == other.Name; + /* throw new NotImplementedException();*/ + } + public override int GetHashCode() + { + return this.Name.GetHashCode(); + } + } +} diff --git a/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs b/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs index 1e75ebf..9a90c91 100644 --- a/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs +++ b/ProjectBomber/ProjectBomber/PlanesGenericCollection.cs @@ -52,6 +52,11 @@ namespace ProjectBomber.Generics _collection = new SetGeneric(width * height); } /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => _collection.SortSet(comparer); + /// /// Получение объектов коллекции /// public IEnumerable GetPlanes => _collection.GetPlanes(); @@ -68,7 +73,7 @@ namespace ProjectBomber.Generics { return -1; } - return collect?._collection.Insert(obj) ?? -1; + return collect?._collection.Insert(obj, new DrawiningPlaneEqutables()) ?? -1; } /// /// Перегрузка оператора вычитания diff --git a/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs b/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs index a27ee57..ba5090b 100644 --- a/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs +++ b/ProjectBomber/ProjectBomber/PlanesGenericStorage.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Windows.Forms; using ProjectBomber.DrawningObjects; using ProjectBomber.MovementStrategy; @@ -17,12 +18,12 @@ namespace ProjectBomber.Generics /// /// Словарь (хранилище) /// - readonly Dictionary> _planeStorages; /// /// Возвращение списка названий наборов /// - public List Keys => _planeStorages.Keys.ToList(); + public List Keys => _planeStorages.Keys.ToList(); /// /// Ширина окна отрисовки /// @@ -38,7 +39,7 @@ namespace ProjectBomber.Generics /// public PlanesGenericStorage(int pictureWidth, int pictureHeight) { - _planeStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; @@ -61,14 +62,14 @@ namespace ProjectBomber.Generics /// Название набора public void AddSet(string name) { - // Создаем новый набор и добавляем его в словарь - if (!_planeStorages.ContainsKey(name)) + if (_planeStorages.ContainsKey(new PlanesCollectionInfo(name, string.Empty))) { - _planeStorages[name] = new PlanesGenericCollection(_pictureWidth, _pictureHeight); + MessageBox.Show("Словарь уже содержит набор с таким названием", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); } else { - throw new ArgumentException("Набор с таким именем уже существует"); + _planeStorages.Add(new PlanesCollectionInfo(name, string.Empty), new PlanesGenericCollection(_pictureWidth, _pictureHeight)); } } /// @@ -77,15 +78,9 @@ namespace ProjectBomber.Generics /// Название набора public void DelSet(string name) { - // Удаляем набор из словаря по имени - if (_planeStorages.ContainsKey(name)) - { - _planeStorages.Remove(name); - } - else - { - throw new ArgumentException("Набор с таким именем не найден."); - } + if (!_planeStorages.ContainsKey(new PlanesCollectionInfo(name, string.Empty))) + return; + _planeStorages.Remove(new PlanesCollectionInfo(name, string.Empty)); } /// /// Доступ к набору @@ -96,14 +91,10 @@ namespace ProjectBomber.Generics { get { - if (_planeStorages.ContainsKey(ind)) - { - return _planeStorages[ind]; - } - else - { - throw new KeyNotFoundException($"Набор с именем '{ind}' не найден."); - } + PlanesCollectionInfo indObj = new PlanesCollectionInfo(ind, string.Empty); + if (_planeStorages.ContainsKey(indObj)) + return _planeStorages[indObj]; + return null; } } /// @@ -120,7 +111,7 @@ namespace ProjectBomber.Generics File.Delete(filename); } StringBuilder data = new StringBuilder(); - foreach (KeyValuePair> record in _planeStorages) { StringBuilder records = new StringBuilder(); @@ -128,11 +119,11 @@ namespace ProjectBomber.Generics { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { - throw new InvalidOperationException("Невалидная операция, нет данных для сохранения"); + throw new Exception("Невалидная операция: нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { @@ -147,40 +138,34 @@ namespace ProjectBomber.Generics public void LoadData(string filename) { if (!File.Exists(filename)) - { throw new FileNotFoundException("Файл не найден"); - } - using (StreamReader reader = new StreamReader(filename)) + + using (StreamReader sr = new StreamReader(filename)) { - string cheker = reader.ReadLine(); - if (cheker == null || cheker.Length == 0) + if (sr.ReadLine() != "PlanesStorage") + throw new FormatException("Неверный формат данных"); + + string str = sr.ReadLine(); + var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) { - throw new NullReferenceException("Нет данных для загрузки"); - } - if (!cheker.StartsWith("PlanesStorage")) - { - //если нет такой записи, то это не те данные - throw new InvalidDataException("Неверный формат данных"); + throw new Exception("Нет данных для загрузки"); } _planeStorages.Clear(); - string strs; - bool firstinit = true; - while ((strs = reader.ReadLine()) != null) + do { - if (strs == null && firstinit) + string[] record = str.Split(new[] { _separatorForKeyValue }, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - throw new Exception("Нет данных для загрузки"); + str = sr.ReadLine(); + continue; } - if (strs == null) + PlanesGenericCollection + collection = new PlanesGenericCollection(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(new[] { _separatorRecords, }, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) { - break; - } - firstinit = false; - string name = strs.Split(_separatorForKeyValue)[0]; - PlanesGenericCollection collection = new PlanesGenericCollection(_pictureWidth, _pictureHeight); - foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords)) - { - DrawningBomber plane = data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight); + DrawningBomber plane = elem?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight); if (plane != null) { try { _ = collection + plane; } @@ -194,8 +179,9 @@ namespace ProjectBomber.Generics } } } - _planeStorages.Add(name, collection); - } + _planeStorages.Add(new PlanesCollectionInfo(record[0], string.Empty), collection); + str = sr.ReadLine(); + } while (str != null); } } } diff --git a/ProjectBomber/ProjectBomber/Program.cs b/ProjectBomber/ProjectBomber/Program.cs index 1fbce1b..c1ef0a9 100644 --- a/ProjectBomber/ProjectBomber/Program.cs +++ b/ProjectBomber/ProjectBomber/Program.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; diff --git a/ProjectBomber/ProjectBomber/ProjectBomber.csproj b/ProjectBomber/ProjectBomber/ProjectBomber.csproj index e8d5d14..fa028a0 100644 --- a/ProjectBomber/ProjectBomber/ProjectBomber.csproj +++ b/ProjectBomber/ProjectBomber/ProjectBomber.csproj @@ -49,6 +49,9 @@ 4 + + ..\packages\JetBrains.Annotations.2023.3.0\lib\net20\JetBrains.Annotations.dll + ..\packages\Microsoft.Bcl.AsyncInterfaces.8.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll @@ -194,6 +197,7 @@ + @@ -210,29 +214,9 @@ FormPlaneConfig.cs - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - Always - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - diff --git a/ProjectBomber/ProjectBomber/Properties/Resources.Designer.cs b/ProjectBomber/ProjectBomber/Properties/Resources.Designer.cs deleted file mode 100644 index d6021ae..0000000 --- a/ProjectBomber/ProjectBomber/Properties/Resources.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Этот код создан программой. -// Исполняемая версия:4.0.30319.42000 -// -// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае -// повторной генерации кода. -// -//------------------------------------------------------------------------------ - -namespace ProjectBomber.Properties { - using System; - - - /// - /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. - /// - // Этот класс создан автоматически классом StronglyTypedResourceBuilder - // с помощью такого средства, как ResGen или Visual Studio. - // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen - // с параметром /str или перестройте свой проект VS. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectBomber.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Перезаписывает свойство CurrentUICulture текущего потока для всех - /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/ProjectBomber/ProjectBomber/Properties/Resources.resx b/ProjectBomber/ProjectBomber/Properties/Resources.resx deleted file mode 100644 index af7dbeb..0000000 --- a/ProjectBomber/ProjectBomber/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/ProjectBomber/ProjectBomber/Properties/Settings.Designer.cs b/ProjectBomber/ProjectBomber/Properties/Settings.Designer.cs deleted file mode 100644 index f4ae919..0000000 --- a/ProjectBomber/ProjectBomber/Properties/Settings.Designer.cs +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Этот код создан программой. -// Исполняемая версия:4.0.30319.42000 -// -// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае -// повторной генерации кода. -// -//------------------------------------------------------------------------------ - -namespace ProjectBomber.Properties { - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.3.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default { - get { - return defaultInstance; - } - } - } -} diff --git a/ProjectBomber/ProjectBomber/Properties/Settings.settings b/ProjectBomber/ProjectBomber/Properties/Settings.settings deleted file mode 100644 index 3964565..0000000 --- a/ProjectBomber/ProjectBomber/Properties/Settings.settings +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/ProjectBomber/ProjectBomber/SetGeneric.cs b/ProjectBomber/ProjectBomber/SetGeneric.cs index 7f0225d..aff6cfc 100644 --- a/ProjectBomber/ProjectBomber/SetGeneric.cs +++ b/ProjectBomber/ProjectBomber/SetGeneric.cs @@ -35,17 +35,21 @@ namespace ProjectBomber.Generics _places = new List(count); } /// + /// Сортировка набора объектов + /// + /// + public void SortSet(IComparer comparer) => _places.Sort(comparer); + /// /// Добавление объекта в набор /// /// Добавляемый самолет /// - public bool Insert(T plane, IEqualityComparer equal = null) + public int Insert(T plane, IEqualityComparer equal = null) { if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); - Insert(plane, 0); Insert(plane, 0, equal); - return true; + return 0; } /// /// Добавление объекта в набор на конкретную позицию diff --git a/ProjectBomber/ProjectBomber/packages.config b/ProjectBomber/ProjectBomber/packages.config deleted file mode 100644 index 7097d8b..0000000 --- a/ProjectBomber/ProjectBomber/packages.config +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file -- 2.25.1