diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs index 2a308f8..866e50e 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirFighter/ProjectAirFighter/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/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs index 1f90055..b4afa10 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -13,9 +13,9 @@ public interface ICollectionGenericObjects int Count { get; } /// - /// Установка максимального количества элементов - /// - int SetMaxCount { set; } + /// Установка максимального количества элементов + /// + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -45,4 +45,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 2209b76..fbd070d 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectAirFighter.CollectionGenericObjects; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -19,12 +20,24 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// - /// Конструктор - /// - public ListGenericObjects() + /// Конструктор + /// + public ListGenericObjects() { _collection = new(); } @@ -67,4 +80,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index 1693e95..9120cd0 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectAirFighter.CollectionGenericObjects; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -14,8 +15,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -32,6 +38,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -98,4 +106,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return obj; } + + 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 0b6b6d9..3768850 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Drawnings; +using System.Text; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningWarPlane { /// /// Словарь (хранилище) с коллекциями @@ -17,6 +20,22 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// /// Конструктор /// @@ -71,4 +90,118 @@ public class StorageCollection return _storages[name]; } } + + /// + /// Сохранение информации по кораблям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder sb = new(); + + using (StreamWriter sw = new StreamWriter(filename)) + { + sw.WriteLine(_collectionKey.ToString()); + foreach (KeyValuePair> kvpair in _storages) + { + // не сохраняем пустые коллекции + if (kvpair.Value.Count == 0) + continue; + sb.Append(kvpair.Key); + sb.Append(_separatorForKeyValue); + sb.Append(kvpair.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(kvpair.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in kvpair.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + continue; + sb.Append(data); + sb.Append(_separatorItems); + } + sw.WriteLine(sb.ToString()); + sb.Clear(); + } + } + return true; + } + + + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader sr = new StreamReader(filename)) + { + string? str; + str = sr.ReadLine(); + if (str != _collectionKey.ToString()) + return false; + _storages.Clear(); + while ((str = sr.ReadLine()) != null) + { + string[] record = str.Split(_separatorForKeyValue); + 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?.CreateDrawningPlane() is T ship) + { + if (collection.Insert(ship) == -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/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirFighter.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirFighter.cs index 26e6cef..c126020 100644 --- a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirFighter.cs +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningAirFighter.cs @@ -23,6 +23,15 @@ public class DrawningAirFighter : DrawningWarPlane bodyRockets, additionalWings); } + /// + /// Конструктор через сущность + /// + /// Объект класса-сущность + public DrawningAirFighter(EntityWarPlane entityWarPlane) : base() + { + EntityFighter = entityWarPlane; + } + public override void DrawTransport(Graphics g) { if (EntityFighter == null || EntityFighter is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningWarPlane.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningWarPlane.cs index b4163de..d7e0a3a 100644 --- a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningWarPlane.cs +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningWarPlane.cs @@ -82,6 +82,15 @@ public class DrawningWarPlane EntityFighter = new EntityWarPlane(speed, weight, bodyColor); } + /// + /// Конструктор через сущность + /// + /// объект класса-сущность + public DrawningWarPlane(EntityWarPlane entityWarPlane) : this() + { + EntityFighter = entityWarPlane; + } + /// /// Установка границ поля /// diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/ExtentionDrawningPlane.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/ExtentionDrawningPlane.cs new file mode 100644 index 0000000..469add9 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/ExtentionDrawningPlane.cs @@ -0,0 +1,54 @@ +using ProjectAirFighter.Entities; + +namespace ProjectAirFighter.Drawnings; + +/// +/// Расширение для класса EntityCar +/// +public static class ExtentionDrawningPlane +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningWarPlane? CreateDrawningPlane(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityWarPlane? plane = EntityAirFighter.CreateEntityAirFighter(strs); + if (plane != null) + { + return new DrawningAirFighter(plane); + } + + plane = EntityWarPlane.CreateEntityWarPlane(strs); + if (plane != null) + { + return new DrawningWarPlane(plane); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningWarPlane drawningWarPlane) + { + string[]? array = drawningWarPlane?.EntityFighter?.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 f2d35aa..0f090f8 100644 --- a/ProjectAirFighter/ProjectAirFighter/Entities/EntityAirFighter.cs +++ b/ProjectAirFighter/ProjectAirFighter/Entities/EntityAirFighter.cs @@ -1,4 +1,6 @@ -namespace ProjectAirFighter.Entities; +using System.Net.Sockets; + +namespace ProjectAirFighter.Entities; /// /// Класс-сущность "Истребитель" @@ -46,4 +48,26 @@ public class EntityAirFighter : EntityWarPlane BodyRockets = bodyRockets; AdditionalWings = additionalWings; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, BodyRockets.ToString(), AdditionalWings.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 d2e4041..2c7363f 100644 --- a/ProjectAirFighter/ProjectAirFighter/Entities/EntityWarPlane.cs +++ b/ProjectAirFighter/ProjectAirFighter/Entities/EntityWarPlane.cs @@ -46,4 +46,28 @@ 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 8f78622..0e7d2bd 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(); 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(974, 0); + groupBoxTools.Location = new Point(978, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(236, 618); + groupBoxTools.Size = new Size(236, 621); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -85,7 +92,7 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 333); + panelCompanyTools.Location = new Point(3, 336); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(230, 282); panelCompanyTools.TabIndex = 11; @@ -240,19 +247,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(974, 618); + pictureBox.Size = new Size(978, 621); 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(1214, 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.Filter = "txt file | *.txt"; + // // FormWarPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1210, 618); + ClientSize = new Size(1214, 645); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormWarPlaneCollection"; Text = "Коллекция истребителей"; groupBoxTools.ResumeLayout(false); @@ -261,7 +310,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -284,5 +336,11 @@ private Button buttonGoToCheck; private Button buttonRemoveFighter; private MaskedTextBox maskedTextBox; + 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 6151c2c..b221ff5 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs @@ -1,5 +1,6 @@ using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; +using System.Windows.Forms; namespace ProjectAirFighter; @@ -240,4 +241,46 @@ public partial class FormWarPlaneCollection : 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)) + { + RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx index af32865..3865651 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + + + 77 + \ No newline at end of file