diff --git a/.gitignore b/.gitignore index ca1c7a3..de8b24f 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,4 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml +/Stormtrooper/Stormtrooper/Drawnings/ExtentionDrawningCar.cs diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs index 2d7e417..7fa344c 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -49,7 +49,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index 5a5c6b1..29e71ba 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,16 +11,19 @@ where T : class /// Количество объектов в коллекции /// int Count { get; } + /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj); + /// /// Добавление объекта в коллекцию на конкретную позицию /// @@ -28,16 +31,29 @@ where T : class /// Позиция /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj, int position); + /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось T? Remove(int position); + /// /// Получение объекта по позиции /// /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs index 607ad12..bf71592 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -22,7 +22,11 @@ where T : class /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } } + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -75,5 +79,12 @@ where T : class return null; } + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 17be693..aebd7fc 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -13,8 +13,14 @@ where T : class /// Массив объектов, которые храним /// private T?[] _collection; + public int Count => _collection.Length; - public int SetMaxCount { + + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) { @@ -30,6 +36,8 @@ where T : class } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -101,4 +109,12 @@ where T : class _collection[position] = null; return DrawningAircraft; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs index ee0023b..20407b5 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using Stormtrooper.CollectionGenericObjects; +using Stormtrooper.Drawnings; using System; using System.Collections.Generic; using System.Linq; @@ -12,16 +13,32 @@ namespace Stormtrooper.CollectionGenericObjects; /// /// public class StorageCollection -where T : class +where T : DrawningAircraft { /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + private Dictionary> _storages; /// /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -76,5 +93,125 @@ where T : class return null; } } + /// + /// Сохранение информации по самолетам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + 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 streamWriter = new StreamWriter(fs); + streamWriter.Write(_collectionKey); + + foreach (KeyValuePair> value in _storages) + { + streamWriter.Write(Environment.NewLine); + + if (value.Value.Count == 0) + { + continue; + } + + streamWriter.Write(value.Key); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.GetCollectionType); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.MaxCount); + streamWriter.Write(_separatorForKeyValue); + + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + + streamWriter.Write(data); + streamWriter.Write(_separatorItems); + + } + } + 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?.CreateDrawningAircraft() is T aircraft) + { + if (collection.Insert(aircraft) == -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/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraft.cs b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraft.cs index 3127ca7..0f04c15 100644 --- a/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraft.cs +++ b/Stormtrooper/Stormtrooper/Drawnings/DrawningAircraft.cs @@ -49,7 +49,7 @@ public class DrawningAircraft /// public int GetHeight => _drawningAircraftHeight; - // Пустой конструктор + /// Пустой конструктор private DrawningAircraft() { _pictureWidth = null; @@ -77,6 +77,15 @@ public class DrawningAircraft _pictureHeight = drawningAircraftHeight; } + /// + /// Конструктор + /// + /// + public DrawningAircraft(EntityAircraft aircraft) : this() + { + EntityAircraft = new EntityAircraft(aircraft.Speed, aircraft.Weight, aircraft.BodyColor); + } + /// Прорисовка объекта /// /// // Установка границ поля diff --git a/Stormtrooper/Stormtrooper/Drawnings/DrawningStormtrooper.cs b/Stormtrooper/Stormtrooper/Drawnings/DrawningStormtrooper.cs index aeabdad..46768e9 100644 --- a/Stormtrooper/Stormtrooper/Drawnings/DrawningStormtrooper.cs +++ b/Stormtrooper/Stormtrooper/Drawnings/DrawningStormtrooper.cs @@ -27,6 +27,15 @@ public class DrawningStormtrooper : DrawningAircraft } + + public DrawningStormtrooper(EntityAircraft? entityAircraft) : base(140, 70) + { + if (entityAircraft != null) + { + EntityAircraft = entityAircraft; + } + } + public override void DrawTransport(Graphics g) { if (EntityAircraft == null || EntityAircraft is not EntityStormtrooper entityStormtrooper|| !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/Stormtrooper/Stormtrooper/Drawnings/ExtentionDrawningAircraft.cs b/Stormtrooper/Stormtrooper/Drawnings/ExtentionDrawningAircraft.cs new file mode 100644 index 0000000..eac4d49 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Drawnings/ExtentionDrawningAircraft.cs @@ -0,0 +1,59 @@ +using Stormtrooper.Drawnings; +using Stormtrooper.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Stormtrooper.Drawnings; +/// +/// Расширение для класса EntityCar +/// +public static class ExtentionDrawningAircraft +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningAircraft? CreateDrawningAircraft(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityAircraft? aircraft = EntityStormtrooper.CreateEntityStormtrooper(strs); + if (aircraft != null) + { + return new DrawningStormtrooper(aircraft); + } + + aircraft = EntityAircraft.CreateEntityAicraft(strs); + if (aircraft != null) + { + return new DrawningAircraft(aircraft); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningAircraft drawningAircraft) + { + string[]? array = drawningAircraft?.EntityAircraft?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs b/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs index 985683d..81a0be7 100644 --- a/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs +++ b/Stormtrooper/Stormtrooper/Entities/EntityAircraft.cs @@ -33,6 +33,28 @@ public class EntityAircraft Speed = speed; Weight = weight; BodyColor = bodyColor; + } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityAircraft? CreateEntityAicraft(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityAircraft)) + { + return null; + } + + return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); } } diff --git a/Stormtrooper/Stormtrooper/Entities/EntityStormtrooper.cs b/Stormtrooper/Stormtrooper/Entities/EntityStormtrooper.cs index 3dc1ddc..2542d79 100644 --- a/Stormtrooper/Stormtrooper/Entities/EntityStormtrooper.cs +++ b/Stormtrooper/Stormtrooper/Entities/EntityStormtrooper.cs @@ -38,4 +38,28 @@ public class EntityStormtrooper : EntityAircraft Rocket = rocket; Bomb = bomb; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityStormtrooper), Speed.ToString(), Weight.ToString(), + BodyColor.Name, AdditionalColor.Name, Rocket.ToString(), Bomb.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityAircraft? CreateEntityStormtrooper(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityStormtrooper)) + { + return null; + } + return new EntityStormtrooper(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/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs index b5f3397..0613a06 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + fileToolStripMenuItem = 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(980, 0); + groupBoxTools.Location = new Point(980, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(264, 677); + groupBoxTools.Size = new Size(264, 649); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Tag = ""; @@ -77,7 +84,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 391); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(258, 286); + panelCompanyTools.Size = new Size(258, 262); panelCompanyTools.TabIndex = 9; // // buttonAddAiracft @@ -94,7 +101,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 224); + buttonRefresh.Location = new Point(0, 207); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(252, 41); buttonRefresh.TabIndex = 6; @@ -105,7 +112,7 @@ // maskedTextBox // maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(3, 97); + maskedTextBox.Location = new Point(0, 80); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(252, 27); @@ -115,7 +122,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 177); + buttonGoToCheck.Location = new Point(0, 160); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(252, 41); buttonGoToCheck.TabIndex = 5; @@ -126,7 +133,7 @@ // buttonRemoveAircraft // buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveAircraft.Location = new Point(3, 130); + buttonRemoveAircraft.Location = new Point(0, 113); buttonRemoveAircraft.Name = "buttonRemoveAircraft"; buttonRemoveAircraft.Size = new Size(252, 41); buttonRemoveAircraft.TabIndex = 4; @@ -241,12 +248,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(980, 677); + pictureBox.Size = new Size(980, 649); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1244, 28); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(59, 24); + fileToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(227, 26); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(227, 26); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormAircraftCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -254,6 +302,8 @@ ClientSize = new Size(1244, 677); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormAircraftCollection"; Text = "Коллекция самолетов"; groupBoxTools.ResumeLayout(false); @@ -262,7 +312,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +338,11 @@ private ListBox listBoxCollection; private Button buttonCollectionAdd; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem fileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs index 3e3eccf..c550944 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs @@ -234,4 +234,45 @@ public partial class FormAircraftCollection : 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(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/Stormtrooper/Stormtrooper/FormAircraftCollection.resx b/Stormtrooper/Stormtrooper/FormAircraftCollection.resx index af32865..b5b741b 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.resx +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 1 + + + 145, 1 + + + 310, 1 + + + 25 + \ No newline at end of file