From f177ed3b2ca7112551b3f0fce3abf7f07d595adf Mon Sep 17 00:00:00 2001 From: "leonteva.v" Date: Sat, 18 May 2024 17:32:59 +0400 Subject: [PATCH] lab 6 --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 16 ++- .../ListGenericObjects.cs | 24 +++- .../MassiveGenericObjects.cs | 19 +++- .../StorageCollection.cs | 103 +++++++++++++++++- .../Drawnings/DrawingBattleship.cs | 14 ++- .../Drawnings/DrawingShip.cs | 6 +- .../Drawnings/ExtentionDrawingShip.cs | 53 +++++++++ .../Entities/EntityBattleship.cs | 21 +++- .../ProjectBattleship/Entities/EntityShip.cs | 18 +++ .../FormShipCollection.Designer.cs | 69 +++++++++++- .../ProjectBattleship/FormShipCollection.cs | 51 +++++++-- .../ProjectBattleship/FormShipCollection.resx | 12 ++ 13 files changed, 373 insertions(+), 35 deletions(-) create mode 100644 ProjectBattleship/ProjectBattleship/Drawnings/ExtentionDrawingShip.cs diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs index b93c54a..886bd27 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs @@ -51,7 +51,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs index 2f06573..57262eb 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -17,7 +17,7 @@ namespace ProjectBattleship.CollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -38,7 +38,7 @@ namespace ProjectBattleship.CollectionGenericObjects /// /// Позиция /// true - удачно, false - удаление не удалось - T? Remove(int position); + T Remove(int position); /// /// Получение объекта по позиции @@ -46,5 +46,15 @@ namespace ProjectBattleship.CollectionGenericObjects /// Позиция /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } -} +} \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs index 1de2e66..bc92291 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs @@ -19,7 +19,18 @@ 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; /// /// Конструктор /// @@ -49,12 +60,19 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.Insert(position, obj); return true; } - public T? Remove(int position) + public T Remove(int position) { if (position < 0 || position >= _collection.Count) return null; - T? temp = _collection[position]; + T temp = _collection[position]; _collection.RemoveAt(position); return temp; } + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs index 1c997e0..bf4ca02 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -22,8 +22,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// /// Установка максимального кол-ва объектов /// - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -39,7 +43,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - + public CollectionType GetCollectionType => CollectionType.Massive; /// /// Конструктор /// @@ -97,13 +101,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects } return false; } - public T? Remove(int position) + public T Remove(int position) { if (position < 0 || position >= _collection.Length || _collection[position] == null) // проверка позиции и наличия объекта return null; - T? temp = _collection[position]; + T temp = _collection[position]; _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/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs index b8377e5..621ca3a 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs @@ -1,13 +1,15 @@ using ProjectBattleship.CollectionGenericObjects; +using ProjectBattleship.Drawnings; +using System.Text; -namespace ProjectSportCar.CollectionGenericObjects; +namespace ProjectBattleship.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawingShip { /// /// Словарь (хранилище) с коллекциями @@ -20,6 +22,9 @@ public class StorageCollection /// /// Конструктор /// + private readonly string _collectionKey = "CollectionsStorage"; + private readonly string _separatorForKeyValue = "|"; + private readonly string _separatorItems = ";"; public StorageCollection() { _storages = new Dictionary>(); @@ -68,4 +73,98 @@ public class StorageCollection return null; } } + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder sb = new(); + using (StreamWriter sw = new StreamWriter(filename)) + { + sw.WriteLine(_collectionKey.ToString()); + foreach (KeyValuePair> kvpair in _storages) + { + // не сохраняем пустые коллекции + if (kvpair.Value.Count == 0) + continue; + sb.Append(kvpair.Key); + sb.Append(_separatorForKeyValue); + sb.Append(kvpair.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(kvpair.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in kvpair.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + continue; + sb.Append(data); + sb.Append(_separatorItems); + } + sw.WriteLine(sb.ToString()); + sb.Clear(); + } + } + return true; + } + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader sr = new StreamReader(filename)) + { + string? str; + str = sr.ReadLine(); + if (str != _collectionKey.ToString()) + return false; + _storages.Clear(); + while ((str = sr.ReadLine()) != null) + { + string[] record = str.Split(_separatorForKeyValue); + 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?.CreateDrawningShip() is T ship) + { + if (collection.Insert(ship) == -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, + }; + } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/Drawnings/DrawingBattleship.cs b/ProjectBattleship/ProjectBattleship/Drawnings/DrawingBattleship.cs index 2b8e5ad..46d576e 100644 --- a/ProjectBattleship/ProjectBattleship/Drawnings/DrawingBattleship.cs +++ b/ProjectBattleship/ProjectBattleship/Drawnings/DrawingBattleship.cs @@ -3,11 +3,15 @@ namespace ProjectBattleship.Drawnings; public class DrawingBattleship : DrawingShip { - public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool turret, bool rocketLauncher) : base(150, 50) - { - EntityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketLauncher); - } - public override void DrawTransport(Graphics g) + public DrawingBattleship(EntityShip ship) : base(143, 75) + { + EntityShip = ship; + } + public DrawingBattleship(int speed, double weight, Color bodycolor, Color additionalcolor, bool turret, bool rocketLauncher) : base(143, 75) + { + EntityShip = new EntityBattleship(speed, weight, bodycolor, additionalcolor, turret, rocketLauncher); + } + public override void DrawTransport(Graphics g) { if (EntityShip == null || EntityShip is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue) { diff --git a/ProjectBattleship/ProjectBattleship/Drawnings/DrawingShip.cs b/ProjectBattleship/ProjectBattleship/Drawnings/DrawingShip.cs index 0394421..7823d75 100644 --- a/ProjectBattleship/ProjectBattleship/Drawnings/DrawingShip.cs +++ b/ProjectBattleship/ProjectBattleship/Drawnings/DrawingShip.cs @@ -34,7 +34,11 @@ public class DrawingShip _shipWidth = shipWidth; _shipHeight = shipHeight; } - public bool SetPictureSize(int width, int height) + public DrawingShip(EntityShip ship) : this() + { + EntityShip = ship; + } + public bool SetPictureSize(int width, int height) { if (width >= _shipWidth || height >= _shipHeight) { diff --git a/ProjectBattleship/ProjectBattleship/Drawnings/ExtentionDrawingShip.cs b/ProjectBattleship/ProjectBattleship/Drawnings/ExtentionDrawingShip.cs new file mode 100644 index 0000000..48fb925 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/Drawnings/ExtentionDrawingShip.cs @@ -0,0 +1,53 @@ +using ProjectBattleship.Entities; +using ProjectBattleship.Drawnings; +using ProjectBattleship.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBattleship.Drawnings; +public static class ExtentionDrawingShip +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawingShip? CreateDrawningShip(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityShip? ship = EntityBattleship.CreateEntityBattleship(strs); + if (ship != null) + { + return new DrawingBattleship(ship); + } + ship = EntityShip.CreateEntityShip(strs); + if (ship != null) + { + return new DrawingShip(ship); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawingShip drawningShip) + { + string[]? array = drawningShip?.EntityShip?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/Entities/EntityBattleship.cs b/ProjectBattleship/ProjectBattleship/Entities/EntityBattleship.cs index c87c5e0..8e02902 100644 --- a/ProjectBattleship/ProjectBattleship/Entities/EntityBattleship.cs +++ b/ProjectBattleship/ProjectBattleship/Entities/EntityBattleship.cs @@ -1,4 +1,6 @@ -namespace ProjectBattleship.Entities; +using System.Net.Sockets; + +namespace ProjectBattleship.Entities; public class EntityBattleship : EntityShip { public Color AdditionalColor { get; private set; } @@ -15,4 +17,21 @@ public class EntityBattleship : EntityShip { AdditionalColor = addColor ?? AdditionalColor; } + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Turret.ToString(), RocketLauncher.ToString() }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBattleship? CreateEntityBattleship(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityBattleship)) + { + return null; + } + return new EntityBattleship(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/ProjectBattleship/ProjectBattleship/Entities/EntityShip.cs b/ProjectBattleship/ProjectBattleship/Entities/EntityShip.cs index 9097330..51097c2 100644 --- a/ProjectBattleship/ProjectBattleship/Entities/EntityShip.cs +++ b/ProjectBattleship/ProjectBattleship/Entities/EntityShip.cs @@ -15,4 +15,22 @@ public class EntityShip { BodyColor = color ?? BodyColor; } + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityShip? CreateEntityShip(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityShip)) + { + return null; + } + + return new EntityShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs b/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs index d98eb94..af1d2dd 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipCollection.Designer.cs +++ b/ProjectBattleship/ProjectBattleship/FormShipCollection.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(); Tools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // Tools @@ -59,9 +66,9 @@ Tools.Controls.Add(panelStorage); Tools.Controls.Add(comboBoxSelectorCompany); Tools.Dock = DockStyle.Right; - Tools.Location = new Point(1605, 0); + Tools.Location = new Point(1605, 40); Tools.Name = "Tools"; - Tools.Size = new Size(488, 1236); + Tools.Size = new Size(488, 1224); Tools.TabIndex = 0; Tools.TabStop = false; Tools.Text = "Инструменты"; @@ -240,19 +247,62 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1605, 1236); + pictureBox.Size = new Size(1605, 1224); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(32, 32); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(2093, 40); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файл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(343, 44); + saveToolStripMenuItem.Text = "Сохранить"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(343, 44); + loadToolStripMenuItem.Text = "Загрузить"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormShipCollection // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(2093, 1236); + ClientSize = new Size(2093, 1264); Controls.Add(pictureBox); Controls.Add(Tools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormShipCollection"; Text = "Коллекция кораблей"; Tools.ResumeLayout(false); @@ -261,7 +311,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -284,5 +337,11 @@ private Button buttonCollectionAdd; private Button buttonCreateCompany; 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/ProjectBattleship/ProjectBattleship/FormShipCollection.cs b/ProjectBattleship/ProjectBattleship/FormShipCollection.cs index a1e51f0..502752a 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipCollection.cs +++ b/ProjectBattleship/ProjectBattleship/FormShipCollection.cs @@ -1,16 +1,7 @@ using ProjectBattleship; using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.Drawnings; -using ProjectSportCar.CollectionGenericObjects; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; + namespace Battleship; @@ -200,6 +191,7 @@ public partial class FormShipCollection : Form listBoxCollection.Items.Add(colName); } } + } /// /// Создание компании @@ -231,4 +223,43 @@ public partial class FormShipCollection : Form 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 (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectBattleship/ProjectBattleship/FormShipCollection.resx b/ProjectBattleship/ProjectBattleship/FormShipCollection.resx index af32865..9340a84 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipCollection.resx +++ b/ProjectBattleship/ProjectBattleship/FormShipCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 204, 17 + + + 447, 17 + + + 25 + \ No newline at end of file -- 2.25.1