diff --git a/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs b/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs index 27ff7f5..5898eec 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -41,7 +41,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса diff --git a/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index 46edeb4..a55e162 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -19,7 +19,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию /// @@ -46,4 +46,14 @@ public interface ICollectionGenericObjects /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); + } diff --git a/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs index 8887373..64df773 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -21,7 +21,23 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get + { + return Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -76,4 +92,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index ab0a3d4..0194fec 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -18,8 +18,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -35,6 +39,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } + + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -110,4 +117,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/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs index 302a14e..e0aad9b 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectStormtrooper.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,7 +11,7 @@ namespace ProjectStormtrooper.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningStormtrooperBase { /// /// Словарь(хранилище) с коллекциями @@ -77,4 +78,131 @@ public class StorageCollection } } + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// + /// Сохранение информации по штурмовику в хранилище в файл + /// + /// Путь и имя файла + /// 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) + { + writer.Write(Environment.NewLine); + if (value.Value.Count == 0) + { + continue; + } + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + writer.Write(data); + writer.Write(_separatorItems); + } + } + 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?.CreateDrawningStormtrooper() is T stormtrooper) + { + if (collection.Insert(stormtrooper) == -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/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs b/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs index 9db8277..eae3cd5 100644 --- a/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs +++ b/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs @@ -26,6 +26,10 @@ public class DrawingStormtrooper: DrawningStormtrooperBase } + public DrawingStormtrooper(EntityStormtrooper entityStormtrooperBase) : base(140, 135) + { + EntityStormtrooperBase = new EntityStormtrooper(entityStormtrooperBase.Speed, entityStormtrooperBase.Weight, entityStormtrooperBase.BodyColor, entityStormtrooperBase.AdditionalColor, entityStormtrooperBase.Bombs, entityStormtrooperBase.Rockets); + } /// diff --git a/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs b/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs index ee891db..e386756 100644 --- a/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs +++ b/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs @@ -94,6 +94,10 @@ public class DrawningStormtrooperBase _drawningStormtooperHeight = drawningStormtooperHeight; } + public DrawningStormtrooperBase(EntityStormtrooperBase entityStormtrooperBase) : this() + { + EntityStormtrooperBase = new EntityStormtrooperBase(entityStormtrooperBase.Speed, entityStormtrooperBase.Weight, entityStormtrooperBase.BodyColor); + } /// /// Установка границ поля /// diff --git a/ProjectStormtrooper/Drawnings/ExtentionDrawningStormtrooper.cs b/ProjectStormtrooper/Drawnings/ExtentionDrawningStormtrooper.cs new file mode 100644 index 0000000..24f4101 --- /dev/null +++ b/ProjectStormtrooper/Drawnings/ExtentionDrawningStormtrooper.cs @@ -0,0 +1,53 @@ +using ProjectStormtrooper.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectStormtrooper.Drawnings +{ + public static class ExtentionDrawningStormtrooper + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningStormtrooperBase? CreateDrawningStormtrooper(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityStormtrooperBase? stormtrooper = EntityStormtrooper.CreateEntityStormtrooper(strs); + if (stormtrooper != null) + { + return new DrawingStormtrooper((EntityStormtrooper)stormtrooper); + } + + stormtrooper = EntityStormtrooperBase.CreateEntityBaseStormtrooper(strs); + + if (stormtrooper != null) + { + return new DrawningStormtrooperBase(stormtrooper); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningStormtrooperBase drawningBaseStormtrooper) + { + string[]? array = drawningBaseStormtrooper?.EntityStormtrooperBase?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } + } +} diff --git a/ProjectStormtrooper/Entities/EntityStormtrooper.cs b/ProjectStormtrooper/Entities/EntityStormtrooper.cs index dc19cc3..06a5d6c 100644 --- a/ProjectStormtrooper/Entities/EntityStormtrooper.cs +++ b/ProjectStormtrooper/Entities/EntityStormtrooper.cs @@ -42,5 +42,27 @@ public class EntityStormtrooper: EntityStormtrooperBase Bombs = bombs; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityStormtrooper), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), Rockets.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityStormtrooper? 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/ProjectStormtrooper/Entities/EntityStormtrooperBase.cs b/ProjectStormtrooper/Entities/EntityStormtrooperBase.cs index df4cc3e..7a89df0 100644 --- a/ProjectStormtrooper/Entities/EntityStormtrooperBase.cs +++ b/ProjectStormtrooper/Entities/EntityStormtrooperBase.cs @@ -46,4 +46,26 @@ public class EntityStormtrooperBase } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityStormtrooperBase), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityStormtrooperBase? CreateEntityBaseStormtrooper(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityStormtrooperBase)) + { + return null; + } + return new EntityStormtrooperBase(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs b/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs index 2a8d3b1..1992de9 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs +++ b/ProjectStormtrooper/FormStormtrooperCollection.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(911, 0); + groupBoxTools.Location = new Point(911, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(173, 628); + groupBoxTools.Size = new Size(173, 604); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -239,12 +246,52 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(911, 628); + pictureBox.Size = new Size(911, 604); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1084, 24); + menuStrip.TabIndex = 4; + menuStrip.Text = "menuStrip"; + // + // файл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"; + // // FormStormtrooperCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -252,6 +299,8 @@ ClientSize = new Size(1084, 628); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormStormtrooperCollection"; Text = "Коллекция штурмовиков"; groupBoxTools.ResumeLayout(false); @@ -260,7 +309,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -283,5 +335,11 @@ private Button buttonCreateCompany; private Button buttonCollectionDel; 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/ProjectStormtrooper/FormStormtrooperCollection.cs b/ProjectStormtrooper/FormStormtrooperCollection.cs index 0a28287..348a4e8 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.cs +++ b/ProjectStormtrooper/FormStormtrooperCollection.cs @@ -44,7 +44,7 @@ public partial class FormStormtrooperCollection : Form { panelCompanyTools.Enabled = true; } - + /// /// Добавление базового штурмовика @@ -245,6 +245,55 @@ public partial class FormStormtrooperCollection : Form 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) + { + // TODO продумать логику + 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/ProjectStormtrooper/FormStormtrooperCollection.resx b/ProjectStormtrooper/FormStormtrooperCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.resx +++ b/ProjectStormtrooper/FormStormtrooperCollection.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