From ec73e88d075dc46f16d5f86a4a8c486e1dd1e7d0 Mon Sep 17 00:00:00 2001 From: victinass Date: Sun, 28 Apr 2024 22:22:14 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StorageCollection.cs | 168 +++++++++--------- 1 file changed, 81 insertions(+), 87 deletions(-) diff --git a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs index 61d93ad..40e4b65 100644 --- a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs +++ b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs @@ -28,6 +28,12 @@ public class StorageCollection _storages = new Dictionary>(); } + private readonly string _collectionKey = "CollectionsStorage"; + + private readonly string _separatorForKeyValue = "|"; + + private readonly string _separatorItems = ";"; + /// /// Добавление коллекции в хранилище /// @@ -35,10 +41,10 @@ public class StorageCollection /// Тип коллекции public void AddCollection(string name, CollectionType collectionType) { - // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - if (_storages.ContainsKey(name)) + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) + { return; - + } // TODO Прописать логику для добавления if (collectionType == CollectionType.List) { @@ -80,69 +86,55 @@ public class StorageCollection } } - private readonly string _collectionKey = "CollectionsStorage"; - - private readonly string _separatorForKeyValue = "|"; - - private readonly string _separatorItems = ";"; - /// /// Сохранение информации по кораблям в хранилище в файл /// /// /// - public bool SaveData(string filname) + public bool SaveData(string filename) { if (_storages.Count == 0) { return false; } - if (File.Exists(filname)) + if (File.Exists(filename)) { - File.Delete(filname); + File.Delete(filename); } - if (File.Exists(filname)) + using (StreamWriter writer = new StreamWriter(filename)) { - File.Delete(filname); - } - - StringBuilder sb = new(); - - sb.Append(_collectionKey); - foreach (KeyValuePair> value in _storages) - { - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - 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)) + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + 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); + } } } - - using FileStream fs = new(filname, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); return true; } @@ -158,62 +150,64 @@ public class StorageCollection return false; } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader reader = File.OpenText(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) - { - bufferTextFromFile += temp.GetString(b); - } - } + string str = reader.ReadLine(); - string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - if (!strs[0].Equals(_collectionKey)) - { - //если нет такой записи, то это не те файлы - return false; - } - - _storages.Clear(); - foreach (string data in strs) - { - string[] record = data.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) + if (str == null || str.Length == 0) { return false; } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + if (!str.StartsWith(_collectionKey)) { - if (elem?.CreateDrawingWarship() is T warship) - { - if (collection.Insert(warship) == -1) - { - return false; - } - } + //если нет такой записи, то это не те данные + return false; } - _storages.Add(record[0], collection); + _storages.Clear(); + string strs = ""; + while ((strs = reader.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?.CreateDrawingWarship() is T bulldozer) + { + if (collection.Insert(bulldozer) == -1) + { + return false; + } + } + } + + _storages.Add(record[0], collection); + } } return true; } + + /// + /// Создание коллекции по типу + /// + /// + /// private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { return collectionType switch From 98e674863ff81235bb1d5b470a58252cffea3122 Mon Sep 17 00:00:00 2001 From: victinass Date: Mon, 29 Apr 2024 14:27:19 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Battleship/Entities/EntityBattleship.cs | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/Battleship/Battleship/Entities/EntityBattleship.cs b/Battleship/Battleship/Entities/EntityBattleship.cs index 3ae9a41..353a60a 100644 --- a/Battleship/Battleship/Entities/EntityBattleship.cs +++ b/Battleship/Battleship/Entities/EntityBattleship.cs @@ -5,18 +5,6 @@ /// public class EntityBattleship : EntityWarship { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } /// /// /// Признак (опция) отсека для ракет /// @@ -57,6 +45,15 @@ public class EntityBattleship : EntityWarship AdditionalColor = additionalColor; } + /// + /// Получение строки с значением свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(), BodyColor.Name, Compartment.ToString(), Tower.ToString(), BodyDeck.ToString(), AdditionalColor.Name}; + } + /// /// Создание продвинутого объекта из массива строк ///