diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs index eca1f2e..cade9e6 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -50,7 +50,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount - 4; + _collection.MaxCount = GetMaxCount - 4; } /// diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs index df1b6ce..3899ba4 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectAirFighter.CollectionGenericObjects; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -19,9 +20,9 @@ public interface ICollectionGenericObjects int Count { get; } /// - ///Установка максимального количества элементов + /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -50,4 +51,15 @@ public interface ICollectionGenericObjects /// /// T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлемениный вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs index 9d43c01..a51ff71 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -26,7 +26,24 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + + public CollectionType GetCollectionType => CollectionType.List; + + public int MaxCount { + get + { + return _maxCount; + } + + set + { + if (value > 0) + { + _maxCount = value; + } + } + } /// /// Конструктор @@ -80,4 +97,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/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index 24add23..0514de2 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -21,23 +21,31 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) { - if (Count > 0) + if (_collection.Length > 0) { Array.Resize(ref _collection, value); } - else { + else + { _collection = new T?[value]; } } } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -118,4 +126,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]; + } + } } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index cc7d23f..2035496 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectAirFighter.CollectionGenericObject; +using ProjectAirFighter.Drawning; using System; using System.Collections.Generic; using System.Linq; @@ -12,7 +13,7 @@ namespace ProjectAirFighter.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningWarPlane { /// /// Словарь (хранилище) с коллекциями @@ -23,7 +24,22 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); - + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + public StorageCollection() { _storages = new Dictionary>(); @@ -82,15 +98,121 @@ public class StorageCollection } } - public ICollectionGenericObjects? this[int index] - { - get - { - //логика получения объекта - if (index > Keys.Count || index < 0) - return null; + - return _storages[Keys[index]]; + public bool SaveData(string filename) + { + if (_storages.Count == 0) + return false; + + if (File.Exists(filename)) + File.Delete(filename); + + using FileStream fs = new(filename, FileMode.Create); + using StreamWriter sw = new StreamWriter(fs); + sw.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + sw.Write(Environment.NewLine); + if (value.Value.Count == 0) + { + continue; + } + + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.GetCollectionType); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sw.Write(data); + sw.Write(_separatorItems); + } } + return true; } -} + /// + /// Загрузка информации по самолетам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (FileStream fs = new(filename, FileMode.Open)) + { + using StreamReader sr = new StreamReader(fs); + + string str = sr.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + + if (!str.Equals(_collectionKey)) + { + return false; + } + _storages.Clear(); + + while (!sr.EndOfStream) + { + string[] record = sr.ReadLine().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?.CreateDrawningWarPlane() is T warPlane) + { + if (collection.Insert(warPlane) == -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, + }; + } +} \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningAirFighter.cs b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningAirFighter.cs index 16e0689..b639d60 100644 --- a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningAirFighter.cs +++ b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningAirFighter.cs @@ -27,6 +27,16 @@ public class DrawningAirFighter : DrawningWarPlane } + + /// + /// Конструктор для метода создания объекта из строки (ExtentionDrawningWarPlane) + /// + /// + public DrawningAirFighter(EntityWarPlane? warPlane) : base(warPlane) + { + if (warPlane != null) + EntityWarPlane = warPlane; + } public override void DrawTransport(Graphics g) { diff --git a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlane.cs b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlane.cs index 61248ee..5155576 100644 --- a/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlane.cs +++ b/ProjectAirFighter/ProjectAirFighter/Drawning/DrawningWarPlane.cs @@ -93,6 +93,15 @@ public class DrawningWarPlane } + /// + /// Конструктор для метода создания объекта из строки (ExtentionDrawningWarPlane) + /// + /// + public DrawningWarPlane(EntityWarPlane? warPlane) : this() + { + EntityWarPlane = warPlane; + } + /// /// Установка границ поля diff --git a/ProjectAirFighter/ProjectAirFighter/Drawning/ExtetntionDrawningWarPlane.cs b/ProjectAirFighter/ProjectAirFighter/Drawning/ExtetntionDrawningWarPlane.cs new file mode 100644 index 0000000..58530be --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawning/ExtetntionDrawningWarPlane.cs @@ -0,0 +1,60 @@ +using ProjectAirFighter.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirFighter.Drawning; + +public static class ExtetntionDrawningWarPlane +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningWarPlane? CreateDrawningWarPlane(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityWarPlane? warPlane = EntityAirFighter.CreateEntityAirFighter(strs); + + if (warPlane != null) + { + return new DrawningAirFighter(warPlane); + } + + warPlane = EntityWarPlane.CreateEntityWarPlane(strs); + + if (warPlane != null) + { + return new DrawningWarPlane(warPlane); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningWarPlane drawningWarPlane) + { + string[]? array = drawningWarPlane?.EntityWarPlane?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } + +} + diff --git a/ProjectAirFighter/ProjectAirFighter/Entities/EntityAirFighter.cs b/ProjectAirFighter/ProjectAirFighter/Entities/EntityAirFighter.cs index 07b7380..724edd3 100644 --- a/ProjectAirFighter/ProjectAirFighter/Entities/EntityAirFighter.cs +++ b/ProjectAirFighter/ProjectAirFighter/Entities/EntityAirFighter.cs @@ -4,21 +4,6 @@ /// public class EntityAirFighter : EntityWarPlane { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// /// Дополнительный цвет /// @@ -62,6 +47,34 @@ public class EntityAirFighter : EntityWarPlane AdditionalWing = additionalWing; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, + Rocket.ToString(), AdditionalWing.ToString()}; + } + + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityAirFighter? CreateEntityAirFighter(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityAirFighter)) + { + return null; + } + + return new EntityAirFighter(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), + Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } + } diff --git a/ProjectAirFighter/ProjectAirFighter/Entities/EntityWarPlane.cs b/ProjectAirFighter/ProjectAirFighter/Entities/EntityWarPlane.cs index 2c6cf4d..a069aaf 100644 --- a/ProjectAirFighter/ProjectAirFighter/Entities/EntityWarPlane.cs +++ b/ProjectAirFighter/ProjectAirFighter/Entities/EntityWarPlane.cs @@ -45,4 +45,31 @@ public class EntityWarPlane Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] {nameof(EntityWarPlane),Speed.ToString(), Weight.ToString(), BodyColor.Name}; + } + + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityWarPlane? CreateEntityWarPlane(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityWarPlane)) + { + return null; + } + + return new EntityWarPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } + + } diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs index 493e22b..4e6bf16 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.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(); groupBox1.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBox1 @@ -59,9 +66,9 @@ groupBox1.Controls.Add(panelStorage); groupBox1.Controls.Add(comboBoxSelectorCompany); groupBox1.Dock = DockStyle.Right; - groupBox1.Location = new Point(659, 0); + groupBox1.Location = new Point(659, 24); groupBox1.Name = "groupBox1"; - groupBox1.Size = new Size(174, 663); + groupBox1.Size = new Size(174, 658); groupBox1.TabIndex = 0; groupBox1.TabStop = false; groupBox1.Text = "Инструменты"; @@ -235,19 +242,61 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(659, 663); + pictureBox.Size = new Size(659, 658); 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(833, 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_1; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormWarPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(833, 663); + ClientSize = new Size(833, 682); Controls.Add(pictureBox); Controls.Add(groupBox1); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormWarPlaneCollection"; Text = "Коллекция военных самолетов"; groupBox1.ResumeLayout(false); @@ -256,7 +305,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -279,5 +331,11 @@ private Button buttonCreateCompany; private Button buttonCollectionRemove; 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/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs index 13b5741..92514cb 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs @@ -44,18 +44,19 @@ public partial class FormWarPlaneCollection : Form panelCompanyTools.Enabled = false; } - - private void ButtonAddWarPlane_Click(object sender, EventArgs e){ + + private void ButtonAddWarPlane_Click(object sender, EventArgs e) + { FormWarPlaneConfig form = new(); form.Show(); form.AddEvent(SetWarPlane); } - private void SetWarPlane(DrawningWarPlane warPlane) + private void SetWarPlane(DrawningWarPlane warPlane) { - if (_company == null || warPlane == null) + if (_company == null || warPlane == null) { return; } @@ -231,7 +232,49 @@ public partial class FormWarPlaneCollection : Form } - + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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_1(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); + } + } + } } + diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.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