diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs index b8b8f2f..77e0f65 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectTank/ProjectTank/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/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionType.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionType.cs index 35061b2..62cbc3b 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionType.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/CollectionType.cs @@ -1,15 +1,19 @@ namespace ProjectTank.CollectionGenericObjects; - +/// +/// Тип коллекции +/// public enum CollectionType { /// /// Неопределено /// None = 0, + /// /// Массив /// Massive = 1, + /// /// Список /// diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs index ec1ba1f..3a42d62 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,7 @@ /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -46,5 +46,15 @@ /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементный вывод элементов коллекции + IEnumerable GetItems(); } } diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs index bc45ea5..f683a7d 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs @@ -17,7 +17,21 @@ 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 => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -27,7 +41,6 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - // TODO проверка позиции if (position <= Count) { return _collection[position]; @@ -37,18 +50,15 @@ public class ListGenericObjects : ICollectionGenericObjects } public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора if (Count + 1 > _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) @@ -59,12 +69,17 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка if (position < 0 || position > Count) return null; T? temp = _collection[position]; _collection.RemoveAt(position); return temp; } + public IEnumerable GetItems() + { + for (int i = 0; i < Count; i++) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs index 022bd14..32ea0fd 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs @@ -12,6 +12,28 @@ public class MassiveGenericObjects : ICollectionGenericObjects private T?[] _collection; public int Count => _collection.Length; + public int MaxCount + { + get + { + return _collection.Length; + } + set + { + if (value > 0) + { + if (Count > 0) + { + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; + } + } + } + } + public CollectionType GetCollectionType => CollectionType.Massive; public int SetMaxCount { set @@ -29,6 +51,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } + //public CollectionType GetCollectionType => CollectionType.Massive; /// /// Конструктор @@ -116,4 +139,11 @@ 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/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs index e172f1b..360b6d3 100644 --- a/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs @@ -1,8 +1,12 @@ namespace ProjectTank.CollectionGenericObjects { + /// + /// Класс-хранилище коллекций + /// + /// public class StorageCollection - where T : class + where T : DrawningTank { /// /// Словарь (хранилище) с коллекциями @@ -12,6 +16,21 @@ namespace ProjectTank.CollectionGenericObjects /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; /// /// Конструктор /// @@ -68,6 +87,134 @@ namespace ProjectTank.CollectionGenericObjects return _storages[name]; } } + 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) + { + StringBuilder sb = new(); + + sb.Append(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + + writer.Write(sb); + } + + } + + 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?.CreateDrawningTank() is T airbus) + { + if (collection.Insert(airbus) == -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/ProjectTank/ProjectTank/Drawning/DrawningBattleTank.cs b/ProjectTank/ProjectTank/Drawning/DrawningBattleTank.cs index b7525e7..38d6179 100644 --- a/ProjectTank/ProjectTank/Drawning/DrawningBattleTank.cs +++ b/ProjectTank/ProjectTank/Drawning/DrawningBattleTank.cs @@ -19,6 +19,14 @@ public class DrawningBattleTank :DrawningTank { EntityTank = new EntityBattleTank(speed, weight, bodyColor, additionalColor, gun, machinGun); } + /// + /// Конструктор + /// + /// Класс-сущность + public DrawningBattleTank(EntityBattleTank tank) : base(145, 60) + { + EntityTank = new EntityBattleTank(tank.Speed, tank.Weight, tank.BodyColor, tank.AdditionalColor, tank.Gun, tank.MachinGun); + } /// /// Прорисовка объекта diff --git a/ProjectTank/ProjectTank/Drawning/DrawningTank.cs b/ProjectTank/ProjectTank/Drawning/DrawningTank.cs index a497d50..12650e6 100644 --- a/ProjectTank/ProjectTank/Drawning/DrawningTank.cs +++ b/ProjectTank/ProjectTank/Drawning/DrawningTank.cs @@ -89,6 +89,15 @@ namespace ProjectTank.Drawning _drawningTankWidth = drawningTankWidth; _drawningTankHeight = drawningTankHeight; } + /// + /// Конструктор + /// + /// Класс-сущность + public DrawningTank(EntityTank tank) : this() + { + EntityTank = new EntityTank(tank.Speed, tank.Weight, tank.BodyColor); + } + /// /// Установка границ поля /// diff --git a/ProjectTank/ProjectTank/Drawning/ExtensionDrawningTank.cs b/ProjectTank/ProjectTank/Drawning/ExtensionDrawningTank.cs new file mode 100644 index 0000000..b6c9e2c --- /dev/null +++ b/ProjectTank/ProjectTank/Drawning/ExtensionDrawningTank.cs @@ -0,0 +1,58 @@ +using ProjectTank.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectTank.Drawning +{ + public static class ExtensionDrawningTank + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTank? CreateDrawningTank(this string info) + { + string[] strs = info.Split(_separatorForObject); + + EntityTank? tank = EntityBattleTank.CreateEntityBattleTank(strs); + if (tank != null) + { + return new DrawningBattleTank((EntityBattleTank)tank); + } + + tank = EntityTank.CreateEntityTank(strs); + if (tank != null) + { + return new DrawningTank(tank); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTank drawningTank) + { + string[]? array = drawningTank?.EntityTank?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } + } +} diff --git a/ProjectTank/ProjectTank/Entities/EntityTank.cs b/ProjectTank/ProjectTank/Entities/EntityTank.cs index a1b9484..e2bb06f 100644 --- a/ProjectTank/ProjectTank/Entities/EntityTank.cs +++ b/ProjectTank/ProjectTank/Entities/EntityTank.cs @@ -41,5 +41,24 @@ namespace ProjectTank.Entities BodyColor = bodyColor; } + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTank), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTank? CreateEntityTank(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityTank)) + { + return null; + } + + return new EntityTank(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } } diff --git a/ProjectTank/ProjectTank/Entities/EntiyBattleTank.cs b/ProjectTank/ProjectTank/Entities/EntiyBattleTank.cs index 9b82b31..d5fbcce 100644 --- a/ProjectTank/ProjectTank/Entities/EntiyBattleTank.cs +++ b/ProjectTank/ProjectTank/Entities/EntiyBattleTank.cs @@ -44,6 +44,30 @@ namespace ProjectTank MachinGun= machinGun; Gun = gun; } + /// + /// Получение строк со значениями свойств объекта продвинутого класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityBattleTank), Speed.ToString(), Weight.ToString(), BodyColor.Name, + AdditionalColor.Name, Gun.ToString(), MachinGun.ToString() }; + } + /// + /// Создание продвинутого объекта из массива строк + /// + /// + /// + public static EntityTank? CreateEntityBattleTank(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityBattleTank)) + { + return null; + } + + return new EntityBattleTank(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/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs b/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs index 67ca06b..7e189c4 100644 --- a/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs +++ b/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs @@ -1,4 +1,6 @@ -namespace ProjectTank +using System.Windows.Forms; + +namespace ProjectTank { partial class FormBattleTankCollection { @@ -46,10 +48,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 +68,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(815, 0); + groupBoxTools.Location = new Point(798, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(187, 610); + groupBoxTools.Size = new Size(187, 611); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; @@ -239,19 +248,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(815, 610); + pictureBox.Size = new Size(798, 611); 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(985, 24); + menuStrip.TabIndex = 8; + 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"; + // // FormBattleTankCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1002, 610); + ClientSize = new Size(985, 635); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBattleTankCollection"; Text = "Коллекция танков"; groupBoxTools.ResumeLayout(false); @@ -260,9 +311,14 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } + + #endregion private GroupBox groupBoxTools; @@ -283,5 +339,11 @@ private ListBox listBoxСollection; private Button buttonCollectionAdd; 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/ProjectTank/ProjectTank/FormBattleTankCollection.resx b/ProjectTank/ProjectTank/FormBattleTankCollection.resx index af32865..7dc5378 100644 --- a/ProjectTank/ProjectTank/FormBattleTankCollection.resx +++ b/ProjectTank/ProjectTank/FormBattleTankCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 255, 17 + \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs index e725302..40eeb71 100644 --- a/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs @@ -51,7 +51,7 @@ namespace ProjectTank.MovementStrategy MovementDirection.Right => DirectionType.Right, MovementDirection.Up => DirectionType.Up, MovementDirection.Down => DirectionType.Down, - _ => DirectionType.Unknow, + _=> DirectionType.Unknow, }; } }