From 8f7affcd70cd5175ff078d7fec80300dc81a1f97 Mon Sep 17 00:00:00 2001 From: elizaveta Date: Thu, 13 Jun 2024 05:13:10 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B4=D1=84=D0=B86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 11 +- .../ListGenericObjects.cs | 70 +++++--- .../MassiveGenericObjects.cs | 20 ++- .../StorageCollection.cs | 166 ++++++++++++++++-- Tank/Tank/Drowings/DrawningMachine.cs | 4 +- Tank/Tank/Drowings/DrawningTank.cs | 4 + .../Tank/Drowings/ExtentionDrawningMachine.cs | 51 ++++++ Tank/Tank/Entities/EntityMachine.cs | 24 +++ Tank/Tank/Entities/EntityTank.cs | 11 ++ Tank/Tank/FormTankCollection.Designer.cs | 69 +++++++- Tank/Tank/FormTankCollection.cs | 43 ++++- Tank/Tank/FormTankCollection.resx | 9 + 13 files changed, 428 insertions(+), 56 deletions(-) create mode 100644 Tank/Tank/Drowings/ExtentionDrawningMachine.cs diff --git a/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs b/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs index 1f7651d..4b8d090 100644 --- a/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs +++ b/Tank/Tank/CollectionGenericObjects/AbstractCompany.cs @@ -47,7 +47,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs b/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs index 6373b8d..9c6944d 100644 --- a/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Tank/Tank/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -17,7 +17,7 @@ where T : class /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию /// @@ -43,4 +43,13 @@ where T : class /// Позиция /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } \ No newline at end of file diff --git a/Tank/Tank/CollectionGenericObjects/ListGenericObjects.cs b/Tank/Tank/CollectionGenericObjects/ListGenericObjects.cs index 1bdc5d0..6a6b319 100644 --- a/Tank/Tank/CollectionGenericObjects/ListGenericObjects.cs +++ b/Tank/Tank/CollectionGenericObjects/ListGenericObjects.cs @@ -6,19 +6,26 @@ using System.Threading.Tasks; namespace Tank.CollectionGenericObjects; -public class ListGenericObjects : ICollectionGenericObjects - where T : class +public class ListGenericObjects : ICollectionGenericObjects where T : class { - /// - /// Список объектов, которые храним - /// private readonly List _collection; - /// - /// Максимально допустимое число объектов в списке - /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public int MaxCount + { + get + { + return _maxCount; + } + set + { + if (value > 0) _maxCount = value; + } + } + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -26,46 +33,51 @@ public class ListGenericObjects : ICollectionGenericObjects { _collection = new(); } + public T? Get(int position) { - // TODO проверка позиции - if (position <= Count) + if (position >= 0 && position < Count) { return _collection[position]; } else + { return null; + } + } + public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count + 1 > _maxCount) - return -1; + if (Count == _maxCount) { return -1; } _collection.Add(obj); return Count; } + public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count + 1 > _maxCount) - return -1; - if (position < 0 || position > Count) + if (position < 0 || position >= Count || Count == _maxCount) + { return -1; + } _collection.Insert(position, obj); - return 1; + return position; } + public T? Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка - if (position < 0 || position > Count) - return null; - T? temp = _collection[position]; - _collection.RemoveAt(position); - return temp; + if (position >= Count || position < 0) return null; + T? obj = _collection[position]; + _collection?.RemoveAt(position); + return obj; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; i++) + { + yield return _collection[i]; + } } } diff --git a/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs b/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs index 83c6b45..6adcad3 100644 --- a/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Tank/Tank/CollectionGenericObjects/MassiveGenericObjects.cs @@ -12,11 +12,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) @@ -32,6 +33,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } + public int Count => _collection.Length; + + public CollectionType GetCollectionType => CollectionType.Massive; /// /// Конструктор @@ -128,4 +132,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/Tank/Tank/CollectionGenericObjects/StorageCollection.cs b/Tank/Tank/CollectionGenericObjects/StorageCollection.cs index 0e31968..f9e24bf 100644 --- a/Tank/Tank/CollectionGenericObjects/StorageCollection.cs +++ b/Tank/Tank/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,6 @@ using Tank.CollectionGenericObjects; +using Tank.Drawnings; +using Tank.Drowings; namespace Tank.CollectionGenericObjects; @@ -7,16 +9,18 @@ namespace Tank.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningMachine { /// /// Словарь (хранилище) с коллекциями /// readonly Dictionary> _storages; + /// /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + /// /// Конструктор /// @@ -24,6 +28,7 @@ public class StorageCollection { _storages = new Dictionary>(); } + /// /// Добавление коллекции в хранилище /// @@ -31,33 +36,36 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - // TODO Прописать логику для добавления - if (name == null || _storages.ContainsKey(name)) + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) + { return; + } switch (collectionType) { - case CollectionType.None: - return; case CollectionType.Massive: _storages[name] = new MassiveGenericObjects(); - return; + break; case CollectionType.List: _storages[name] = new ListGenericObjects(); + break; + default: return; } - } + /// /// Удаление коллекции /// /// Название коллекции public void DelCollection(string name) { - // TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(name)) + { _storages.Remove(name); + } + } + /// /// Доступ к коллекции /// @@ -67,11 +75,143 @@ public class StorageCollection { get { - // TODO Продумать логику получения объекта - if (name == null || !_storages.ContainsKey(name)) - return null; - return _storages[name]; + if (_storages.ContainsKey(name)) + { + return _storages[name]; + } + return null; } } + /// + /// Ключевое слово, с которого должен начинаться файл + /// + 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 FileStream fs = new(filename, FileMode.Create); + using StreamWriter sw = new(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(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?.CreateDrawningMachine() is T drawningMachine) + { + if (collection.Insert(drawningMachine) == -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/Tank/Tank/Drowings/DrawningMachine.cs b/Tank/Tank/Drowings/DrawningMachine.cs index 8889412..e722d06 100644 --- a/Tank/Tank/Drowings/DrawningMachine.cs +++ b/Tank/Tank/Drowings/DrawningMachine.cs @@ -211,8 +211,8 @@ public class DrawningMachine } - internal void SetPictureSize(object width, object height) + public DrawningMachine(EntityMachine machine) { - throw new NotImplementedException(); + EntityMachine = machine; } } diff --git a/Tank/Tank/Drowings/DrawningTank.cs b/Tank/Tank/Drowings/DrawningTank.cs index b141379..1c4d352 100644 --- a/Tank/Tank/Drowings/DrawningTank.cs +++ b/Tank/Tank/Drowings/DrawningTank.cs @@ -49,4 +49,8 @@ public class DrawningTank : DrawningMachine g.FillPolygon(additionalBrush, p_pulemet1); } } + public DrawningTank(EntityTank machine) : base(218, 105) + { + EntityMachine = machine; + } } \ No newline at end of file diff --git a/Tank/Tank/Drowings/ExtentionDrawningMachine.cs b/Tank/Tank/Drowings/ExtentionDrawningMachine.cs new file mode 100644 index 0000000..bf60207 --- /dev/null +++ b/Tank/Tank/Drowings/ExtentionDrawningMachine.cs @@ -0,0 +1,51 @@ +using Tank.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tank.Drowings; + +namespace Tank.Drawnings; + +public static class ExtentionDrawningMachine +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningMachine? CreateDrawningMachine(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityMachine? machine = EntityTank.CreateEntityTank(strs); + if (machine != null && machine is EntityTank machine1) + { + return new DrawningTank(machine1); + } + machine = EntityMachine.CreateEntityMachine(strs); + if (machine != null) + { + return new DrawningMachine(machine); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningMachine drawningMachine) + { + string[]? array = drawningMachine?.EntityMachine?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/Tank/Tank/Entities/EntityMachine.cs b/Tank/Tank/Entities/EntityMachine.cs index 0f50398..1622fb4 100644 --- a/Tank/Tank/Entities/EntityMachine.cs +++ b/Tank/Tank/Entities/EntityMachine.cs @@ -41,4 +41,28 @@ public class EntityMachine { BodyColor = color; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityMachine), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityMachine? CreateEntityMachine(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityMachine)) + { + return null; + } + return new EntityMachine(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } + } diff --git a/Tank/Tank/Entities/EntityTank.cs b/Tank/Tank/Entities/EntityTank.cs index 5ed0f6a..45617ce 100644 --- a/Tank/Tank/Entities/EntityTank.cs +++ b/Tank/Tank/Entities/EntityTank.cs @@ -38,4 +38,15 @@ public class EntityTank : EntityMachine { AdditionalColor = color; } + + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityTank), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Pushka.ToString(), Pulemet.ToString() }; + } + public static EntityTank? CreateEntityTank(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityTank)) { return null; } + + return new EntityTank(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/Tank/Tank/FormTankCollection.Designer.cs b/Tank/Tank/FormTankCollection.Designer.cs index c832fe2..d45b602 100644 --- a/Tank/Tank/FormTankCollection.Designer.cs +++ b/Tank/Tank/FormTankCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip1 = 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(); + menuStrip1.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(1174, 0); + groupBoxTools.Location = new Point(1174, 40); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(371, 1030); + groupBoxTools.Size = new Size(371, 990); 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, 717); + panelCompanyTools.Location = new Point(3, 677); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(365, 310); panelCompanyTools.TabIndex = 9; @@ -241,12 +248,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1174, 1030); + pictureBox.Size = new Size(1174, 990); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(32, 32); + menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(1545, 40); + menuStrip1.TabIndex = 2; + menuStrip1.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(90, 36); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(361, 44); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(361, 44); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormTankCollection // AutoScaleDimensions = new SizeF(13F, 32F); @@ -254,6 +302,8 @@ ClientSize = new Size(1545, 1030); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; Name = "FormTankCollection"; Text = "Коллекция танков"; groupBoxTools.ResumeLayout(false); @@ -262,7 +312,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +338,11 @@ private Button buttonCollectionAdd; private Button buttonCreateCompany; private Panel panelCompanyTools; + private MenuStrip menuStrip1; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/Tank/Tank/FormTankCollection.cs b/Tank/Tank/FormTankCollection.cs index e57003a..85b4449 100644 --- a/Tank/Tank/FormTankCollection.cs +++ b/Tank/Tank/FormTankCollection.cs @@ -42,7 +42,7 @@ public partial class FormTankCollection : Form { panelCompanyTools.Enabled = false; } - + /// ///Создание объекта класса-перемещения @@ -230,4 +230,45 @@ public partial class FormTankCollection : Form form.Show(); form.AddEvent(SetMachine); } + + /// + /// + /// + /// + /// + 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); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } \ No newline at end of file diff --git a/Tank/Tank/FormTankCollection.resx b/Tank/Tank/FormTankCollection.resx index af32865..67e4ed1 100644 --- a/Tank/Tank/FormTankCollection.resx +++ b/Tank/Tank/FormTankCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 217, 17 + + + 460, 17 + \ No newline at end of file -- 2.25.1