From 69ba7b26d666ba7167483787e09926cec02716a5 Mon Sep 17 00:00:00 2001 From: victinass Date: Mon, 15 Apr 2024 08:55:03 +0400 Subject: [PATCH 1/3] =?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 --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 14 +- .../ListGenericObjects.cs | 26 ++- .../MassiveGenericObjects.cs | 19 ++- .../StorageCollection.cs | 153 +++++++++++++++++- .../Battleship/Drawings/DrawingBattleship.cs | 8 +- .../Battleship/Drawings/DrawingWarship.cs | 9 +- .../Drawings/ExtentionDrawingWarship.cs | 53 ++++++ .../Battleship/Entities/EntityBattleship.cs | 18 ++- .../Battleship/Entities/EntityWarship.cs | 37 ++++- .../FormWarshipCollection.Designer.cs | 90 +++++++++-- .../Battleship/FormWarshipCollection.cs | 52 +++++- .../Battleship/FormWarshipCollection.resx | 9 ++ Battleship/Battleship/FormWarshipConfig.cs | 3 +- 14 files changed, 449 insertions(+), 44 deletions(-) create mode 100644 Battleship/Battleship/Drawings/ExtentionDrawingWarship.cs diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs index 2ad89f3..886dc4a 100644 --- a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs +++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs @@ -45,7 +45,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs index ec93c9b..5400905 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,8 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + /// + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -45,4 +46,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// + IEnumerable GetItems(); } \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs index f75ef90..b302e2a 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs @@ -11,14 +11,28 @@ public class ListGenericObjects : ICollectionGenericObjects /// Список объектов, которые храним /// private readonly List _collection; - + public CollectionType GetCollectionType => CollectionType.List; + /// /// Максимально допустимое число объектов в списке /// 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; + } + } + } /// /// Конструктор @@ -73,4 +87,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs index df3df6f..8fd73ff 100644 --- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace Battleship.CollectionGenericObjects; + +namespace Battleship.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -14,8 +15,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -32,6 +37,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -113,4 +120,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs index 51ff3c0..61d93ad 100644 --- a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs +++ b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace Battleship.CollectionGenericObjects; +using Battleship.Drawings; +using System.Text; + +namespace Battleship.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawingWarship { /// /// Словарь (хранилище) с коллекциями @@ -60,7 +63,7 @@ public class StorageCollection } /// - /// Удаление коллекции + /// Доступ к коллекции /// /// /// @@ -76,4 +79,148 @@ public class StorageCollection return null; } } + + private readonly string _collectionKey = "CollectionsStorage"; + + private readonly string _separatorForKeyValue = "|"; + + private readonly string _separatorItems = ";"; + + /// + /// Сохранение информации по кораблям в хранилище в файл + /// + /// + /// + public bool SaveData(string filname) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filname)) + { + File.Delete(filname); + } + + if (File.Exists(filname)) + { + File.Delete(filname); + } + + StringBuilder sb = new(); + + sb.Append(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + 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); + } + } + + using FileStream fs = new(filname, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + return true; + } + + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// + /// + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + + 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) + { + 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 warship) + { + if (collection.Insert(warship) == -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/Battleship/Battleship/Drawings/DrawingBattleship.cs b/Battleship/Battleship/Drawings/DrawingBattleship.cs index 490fc08..38b9470 100644 --- a/Battleship/Battleship/Drawings/DrawingBattleship.cs +++ b/Battleship/Battleship/Drawings/DrawingBattleship.cs @@ -16,11 +16,17 @@ public class DrawingBattleship : DrawingWarship /// Признак наличия палубы /// Признак наличия отсека для ракет /// Признак наличия башни - public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 80) + public DrawingBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(129, 80) { EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor); } + public DrawingBattleship(EntityBattleship warship) : base(129, 80) + { + EntityWarship = new EntityBattleship(warship.Speed, warship.Weight, warship.BodyColor, warship.Compartment, warship.Tower, warship.BodyDeck, warship.AdditionalColor); + } + + public override void DrawTransport(Graphics g) { if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/Battleship/Battleship/Drawings/DrawingWarship.cs b/Battleship/Battleship/Drawings/DrawingWarship.cs index 5d6e271..6bc16eb 100644 --- a/Battleship/Battleship/Drawings/DrawingWarship.cs +++ b/Battleship/Battleship/Drawings/DrawingWarship.cs @@ -88,8 +88,13 @@ public class DrawingWarship /// Высота прорисовки военного корабля protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this() { - _drawingWarshipWidth = drawingWarshipWidth; - _drawingWarshipHeight = drawingWarshipHeight; + this._drawingWarshipWidth = drawingWarshipWidth; + this._drawingWarshipHeight = drawingWarshipHeight; + } + + public DrawingWarship(EntityWarship ship) : this() + { + EntityWarship = new EntityWarship(ship.Speed, ship.Weight, ship.BodyColor); } /// diff --git a/Battleship/Battleship/Drawings/ExtentionDrawingWarship.cs b/Battleship/Battleship/Drawings/ExtentionDrawingWarship.cs new file mode 100644 index 0000000..3d66afc --- /dev/null +++ b/Battleship/Battleship/Drawings/ExtentionDrawingWarship.cs @@ -0,0 +1,53 @@ +using Battleship.Entities; + +namespace Battleship.Drawings; + +/// +/// Расширение для класса EntityWarship +/// +public static class ExtentionDrawingWarship +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawingWarship? CreateDrawingWarship(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityWarship? warship = EntityBattleship.CreateEntityBattleship(strs); + if (warship != null) + { + return new DrawingBattleship((EntityBattleship)warship); + } + + warship = EntityWarship.CreateEntityWarship(strs); + if (warship != null) + { + return new DrawingWarship(warship); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawingWarship drawingWarship) + { + string[]? array = drawingWarship?.EntityWarship?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/Battleship/Battleship/Entities/EntityBattleship.cs b/Battleship/Battleship/Entities/EntityBattleship.cs index edeccf6..3ae9a41 100644 --- a/Battleship/Battleship/Entities/EntityBattleship.cs +++ b/Battleship/Battleship/Entities/EntityBattleship.cs @@ -37,6 +37,7 @@ public class EntityBattleship : EntityWarship { AdditionalColor = color; } + /// /// Перемещение линкора /// @@ -50,12 +51,23 @@ public class EntityBattleship : EntityWarship /// public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; Compartment = compartment; Tower = tower; BodyDeck = bodyDeck; AdditionalColor = additionalColor; } + + /// + /// Создание продвинутого объекта из массива строк + /// + /// + /// + public static EntityBattleship? CreateEntityBattleship(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityBattleship)) + { + return null; + } + return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Color.FromName(strs[7])); + } } \ No newline at end of file diff --git a/Battleship/Battleship/Entities/EntityWarship.cs b/Battleship/Battleship/Entities/EntityWarship.cs index ec342a9..fb4d652 100644 --- a/Battleship/Battleship/Entities/EntityWarship.cs +++ b/Battleship/Battleship/Entities/EntityWarship.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Battleship.Entities; +namespace Battleship.Entities; /// /// Класс-сущность Военный корабль /// @@ -22,6 +16,11 @@ public class EntityWarship /// Основной цвет /// public Color BodyColor { get; private set; } + + /// + /// Основной цвет + /// + /// public void SetBodyColor(Color color) { BodyColor = color; @@ -44,4 +43,28 @@ public class EntityWarship Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строки с значением свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityWarship), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из строки + /// + /// + /// + public static EntityWarship? CreateEntityWarship(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityWarship)) + { + return null; + } + + return new EntityWarship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/Battleship/Battleship/FormWarshipCollection.Designer.cs b/Battleship/Battleship/FormWarshipCollection.Designer.cs index 31efc86..a2f2871 100644 --- a/Battleship/Battleship/FormWarshipCollection.Designer.cs +++ b/Battleship/Battleship/FormWarshipCollection.Designer.cs @@ -46,10 +46,17 @@ textBoxCollectionName = new TextBox(); labelCollectionName = new Label(); pictureBox = new PictureBox(); + menuStrip1 = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog1 = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip1.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -57,9 +64,9 @@ groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(876, 0); + groupBoxTools.Location = new Point(876, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(292, 656); + groupBoxTools.Size = new Size(292, 628); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -72,17 +79,17 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonAddWarship); panelCompanyTools.Controls.Add(buttonRemoveWarship); - panelCompanyTools.Location = new Point(6, 374); + panelCompanyTools.Location = new Point(6, 367); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(283, 276); + panelCompanyTools.Size = new Size(283, 255); panelCompanyTools.TabIndex = 10; // // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 228); + buttonRefresh.Location = new Point(0, 214); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(277, 42); + buttonRefresh.Size = new Size(280, 42); buttonRefresh.TabIndex = 6; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -91,7 +98,7 @@ // maskedTextBox1 // maskedTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox1.Location = new Point(3, 99); + maskedTextBox1.Location = new Point(3, 85); maskedTextBox1.Mask = "00"; maskedTextBox1.Name = "maskedTextBox1"; maskedTextBox1.Size = new Size(277, 27); @@ -100,9 +107,9 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 180); + buttonGoToCheck.Location = new Point(0, 166); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(277, 42); + buttonGoToCheck.Size = new Size(283, 42); buttonGoToCheck.TabIndex = 5; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -111,9 +118,9 @@ // buttonAddWarship // buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddWarship.Location = new Point(3, 3); + buttonAddWarship.Location = new Point(0, 7); buttonAddWarship.Name = "buttonAddWarship"; - buttonAddWarship.Size = new Size(277, 42); + buttonAddWarship.Size = new Size(280, 42); buttonAddWarship.TabIndex = 1; buttonAddWarship.Text = "Добавление корабля"; buttonAddWarship.UseVisualStyleBackColor = true; @@ -122,9 +129,9 @@ // buttonRemoveWarship // buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveWarship.Location = new Point(0, 132); + buttonRemoveWarship.Location = new Point(0, 118); buttonRemoveWarship.Name = "buttonRemoveWarship"; - buttonRemoveWarship.Size = new Size(280, 42); + buttonRemoveWarship.Size = new Size(283, 42); buttonRemoveWarship.TabIndex = 4; buttonRemoveWarship.Text = "Удалить корабль"; buttonRemoveWarship.UseVisualStyleBackColor = true; @@ -244,12 +251,54 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(876, 656); + pictureBox.Size = new Size(876, 628); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(1168, 28); + menuStrip1.TabIndex = 2; + menuStrip1.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(59, 24); + файлToolStripMenuItem.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 = "text file | *.txt"; + // + // openFileDialog1 + // + openFileDialog1.FileName = "openFileDialog"; + openFileDialog1.Filter = "text file | *.txt"; + // // FormWarshipCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -257,6 +306,8 @@ ClientSize = new Size(1168, 656); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; Name = "FormWarshipCollection"; Text = "Коллекция кораблей"; groupBoxTools.ResumeLayout(false); @@ -265,7 +316,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -287,5 +341,11 @@ private Button buttonCreateCompany; private Button buttonCollectionDel; private Panel panelCompanyTools; + private MenuStrip menuStrip1; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog1; } } \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipCollection.cs b/Battleship/Battleship/FormWarshipCollection.cs index e73f788..fa18518 100644 --- a/Battleship/Battleship/FormWarshipCollection.cs +++ b/Battleship/Battleship/FormWarshipCollection.cs @@ -1,5 +1,6 @@ using Battleship.CollectionGenericObjects; using Battleship.Drawings; +using System.Windows.Forms; namespace Battleship; @@ -34,7 +35,7 @@ public partial class FormWarshipCollection : Form /// private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { - panelCompanyTools.Enabled = false; + panelCompanyTools.Enabled = false; } /// @@ -71,7 +72,7 @@ public partial class FormWarshipCollection : Form MessageBox.Show("Не удалось добавить объект"); } - } + } /// /// Удаление объекта @@ -228,7 +229,7 @@ public partial class FormWarshipCollection : Form } ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - + if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -241,8 +242,49 @@ public partial class FormWarshipCollection : Form _company = new WarshipSharingService(pictureBox.Width, pictureBox.Height, collection); break; } - + panelCompanyTools.Enabled = true; 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) + { + if (openFileDialog1.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog1.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipCollection.resx b/Battleship/Battleship/FormWarshipCollection.resx index af32865..925a73e 100644 --- a/Battleship/Battleship/FormWarshipCollection.resx +++ b/Battleship/Battleship/FormWarshipCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 153, 17 + + + 318, 17 + \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipConfig.cs b/Battleship/Battleship/FormWarshipConfig.cs index a83f1b0..d6115b6 100644 --- a/Battleship/Battleship/FormWarshipConfig.cs +++ b/Battleship/Battleship/FormWarshipConfig.cs @@ -107,8 +107,7 @@ public partial class FormWarshipConfig : Form _warship = new DrawingWarship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White); break; case "labelModifiedObject": - _warship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, - Color.Black, checkBoxBodyDeck.Checked, checkBoxCompartment.Checked, checkBoxTower.Checked); + _warship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, checkBoxCompartment.Checked, checkBoxTower.Checked, checkBoxBodyDeck.Checked, Color.Black); break; } -- 2.25.1 From ec73e88d075dc46f16d5f86a4a8c486e1dd1e7d0 Mon Sep 17 00:00:00 2001 From: victinass Date: Sun, 28 Apr 2024 22:22:14 +0400 Subject: [PATCH 2/3] =?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 -- 2.25.1 From 98e674863ff81235bb1d5b470a58252cffea3122 Mon Sep 17 00:00:00 2001 From: victinass Date: Mon, 29 Apr 2024 14:27:19 +0400 Subject: [PATCH 3/3] =?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}; + } + /// /// Создание продвинутого объекта из массива строк /// -- 2.25.1