From 53148d85e4af0212062d9bfd115435d22d69d696 Mon Sep 17 00:00:00 2001 From: SAliulov <146759803+SAliulov@users.noreply.github.com> Date: Thu, 25 Apr 2024 02:16:35 +0300 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=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListGenericObjects.cs | 27 +++- .../MassiveGenericObjects.cs | 16 +- .../StorageCollection.cs | 147 +++++++++++++++++- .../Drawnings/DrawningAirBomber.cs | 10 ++ .../Drawnings/DrawningBomber.cs | 9 ++ .../Drawnings/ExtentionDrawningBomber.cs | 53 +++++++ .../Entities/EntityAirBomber.cs | 29 +++- .../ProjectAirBomber/Entities/EntityBomber.cs | 24 +++ .../FormBomberCollection.Designer.cs | 69 +++++++- .../ProjectAirBomber/FormBomberCollection.cs | 44 ++++++ .../FormBomberCollection.resx | 9 ++ 13 files changed, 437 insertions(+), 15 deletions(-) create mode 100644 ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs index 76662de..d6b240f 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs @@ -48,7 +48,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs index e1c31a3..1e630c8 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -17,7 +17,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -47,4 +47,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs index b11e83c..e43b802 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs @@ -23,7 +23,24 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public CollectionType GetCollectionType => CollectionType.List; + + public int MaxCount + { + get + { + return _collection.Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + /// /// Конструктор /// @@ -56,4 +73,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs index e94f886..d27fe74 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs @@ -18,8 +18,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -36,6 +40,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -131,4 +137,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs index ef5175c..a4b3ee7 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using ProjectAirBomber.Drawnings; using System.Text; -using System.Threading.Tasks; namespace ProjectAirBomber.CollectionGenericObjects; @@ -11,7 +8,7 @@ namespace ProjectAirBomber.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningBomber { /// /// Словарь (хранилище) с коллекциями @@ -23,6 +20,21 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -71,4 +83,129 @@ public class StorageCollection return null; } } + + /// + /// Сохранение информации по самолётам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + StringBuilder sb = new(); + sb.Append(Environment.NewLine); + + // не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + sb.Append(data); + sb.Append(_separatorItems); + } + writer.Write(sb); + } + + } + return true; + } + + /// + /// Загрузка информации по самолётам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + if (!str.StartsWith(_collectionKey)) + { + return false; + } + _storages.Clear(); + string strs = ""; + while ((strs = fs.ReadLine()) != null) + { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningBomber() is T bomber) + { + if (collection.Insert(bomber) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + } + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs index 4295c92..89d3ab7 100644 --- a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs @@ -26,6 +26,16 @@ public class DrawningAirBomber : DrawningBomber EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, fuelTanks, bombs); } + /// + /// Конструктор для Extention + /// + /// + + public DrawningAirBomber(EntityAirBomber bomber) : base(66, 74) + { + EntityBomber = new EntityAirBomber(bomber.Speed, bomber.Weight, bomber.BodyColor, bomber.AdditionalColor, bomber.FuelTanks, bomber.Bombs); + } + public override void DrawTransport(Graphics g) { if (EntityBomber == null || EntityBomber is not EntityAirBomber airBomber || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs index 5bc6542..e01b9e1 100644 --- a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs @@ -96,6 +96,15 @@ public class DrawningBomber _drawningAirBomberHeight = drawningAirBomberHeight; } + /// + /// Конструктор для Extention + /// + /// + public DrawningBomber(EntityBomber bomber) : this() + { + EntityBomber = new EntityBomber(bomber.Speed, bomber.Weight, bomber.BodyColor); + } + /// /// Установка границ поля /// diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs new file mode 100644 index 0000000..54f8144 --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs @@ -0,0 +1,53 @@ +using ProjectAirBomber.Entities; +namespace ProjectAirBomber.Drawnings; + +// +/// Расширение для класса EntityBomber +/// +public static class ExtentionDrawningBomber +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBomber? CreateDrawningBomber(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBomber? bomber = EntityAirBomber.CreateEntityAirBomber(strs); + if (bomber != null) + { + return new DrawningAirBomber((EntityAirBomber)bomber); + } + + bomber = EntityBomber.CreateEntityBomber(strs); + if (bomber != null) + { + return new DrawningBomber(bomber); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBomber drawningBomber) + { + string[]? array = drawningBomber?.EntityBomber?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs b/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs index 04ae9db..e9fc7f8 100644 --- a/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs @@ -1,4 +1,6 @@ -namespace ProjectAirBomber.Entities; +using System.Net.Sockets; + +namespace ProjectAirBomber.Entities; /// /// Класс-сущность "Бомбардировщик" @@ -39,4 +41,29 @@ public class EntityAirBomber : EntityBomber FuelTanks = fuelTanks; Bombs = bombs; } + + /// + /// Получение строк со значениями свойств продвинутого объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, + FuelTanks.ToString(), Bombs.ToString()}; + } + + /// + /// Создание продвинутого объекта из массива строк + /// + /// + /// + public static EntityAirBomber? CreateEntityAirBomber(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber)) + { + return null; + } + return new EntityAirBomber(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), + Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs b/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs index 5ffec41..8df0244 100644 --- a/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs @@ -41,4 +41,28 @@ public class EntityBomber Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBomber? CreateEntityBomber(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBomber)) + { + return null; + } + + return new EntityBomber(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs index dd4d5f5..29914ad 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(1104, 0); + groupBoxTools.Location = new Point(1104, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(268, 833); + groupBoxTools.Size = new Size(268, 809); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -75,7 +82,7 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 545); + panelCompanyTools.Location = new Point(3, 521); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(262, 285); panelCompanyTools.TabIndex = 9; @@ -240,12 +247,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1104, 833); + pictureBox.Size = new Size(1104, 809); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1372, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(181, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(181, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file|*.txt"; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file|*.txt"; + // // FormBomberCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -253,6 +301,8 @@ ClientSize = new Size(1372, 833); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBomberCollection"; Text = "Коллекция самолетов"; groupBoxTools.ResumeLayout(false); @@ -261,7 +311,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } @@ -286,5 +339,11 @@ private Button buttonCollectionDel; private ListBox listBoxCollection; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs index e46c138..9fbf2de 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs @@ -253,4 +253,48 @@ public partial class FormBomberCollection : Form panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } + + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + \ No newline at end of file -- 2.25.1