From ceb90e2be8df9b97f9b162d3f8a22110b33400a2 Mon Sep 17 00:00:00 2001 From: safia Date: Thu, 2 May 2024 08:44:37 +0300 Subject: [PATCH] LabWork06 --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 20 ++- .../ListGenericObjects.cs | 69 +++++--- .../MassiveGenericObjects.cs | 71 +++++--- .../StorageCollection.cs | 165 +++++++++++++++--- .../DrawingObject/DrawingBattleship.cs | 7 + .../DrawingObject/DrawingWarship.cs | 10 ++ .../DrawingObject/ExtentionDrawingWarship.cs | 46 +++++ .../Entities/EntityBattleship.cs | 28 ++- .../Entities/EntityWarship.cs | 25 ++- .../FormWarshipCollection.Designer.cs | 79 +++++++-- .../FormWarshipCollection.cs | 46 ++++- .../FormWarshipCollection.resx | 11 +- 13 files changed, 489 insertions(+), 90 deletions(-) create mode 100644 ProjectBattleship/ProjectBattleship/DrawingObject/ExtentionDrawingWarship.cs diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs index 28f64c2..481d134 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs @@ -44,7 +44,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 a01ac3a..21ad617 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -4,22 +4,25 @@ /// /// Параметр: ограничение - ссылочный тип public interface ICollectionGenericObjects - where T : class +where T : class { /// /// Количество объектов в коллекции /// int Count { get; } + /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj); + /// /// Добавление объекта в коллекцию на конкретную позицию /// @@ -27,16 +30,29 @@ public interface ICollectionGenericObjects /// Позиция /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj, int position); + /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось T? Remove(int position); + /// /// Получение объекта по позиции /// /// Позиция /// Объект 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 6205713..f719f85 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs @@ -4,21 +4,21 @@ /// /// Параметр: ограничение - ссылочный тип public class ListGenericObjects : ICollectionGenericObjects - where T : class +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 { set { if (value > 0) { _maxCount = value; } } get { return Count; } } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -27,33 +27,48 @@ public class ListGenericObjects : ICollectionGenericObjects { _collection = new(); } - public T? Get(int position) { - if (position < 0 || position >= Count) return null; - return _collection[position]; + if (position >= 0 && position < Count) + { + return _collection[position]; + } + return null; + } + public int Insert(T obj) + { + if (Count <= _maxCount) + { + _collection.Add(obj); + return Count; + } + return -1; + } + public int Insert(T obj, int position) + { + if (Count < _maxCount && position >= 0 && position < _maxCount) + { + _collection.Insert(position, obj); + return position; + } + return -1; + } + public T Remove(int position) + { + T temp = _collection[position]; + if (position >= 0 && position < _maxCount) + { + _collection.RemoveAt(position); + return temp; + } + return null; } - public int Insert(T? obj) + public IEnumerable GetItems() { - if (Count == _maxCount) return -1; - _collection.Add(obj); - return Count - 1; - } - - public int Insert(T? obj, int position) - { - if (Count == _maxCount) return -1; - if (position < 0 || position >= Count) return -1; - _collection.Insert(position, obj); - return position; - } - - public T? Remove(int position) - { - if (position < 0 || position >= Count) return null; - T? obj = _collection[position]; - _collection.RemoveAt(position); - return obj; + for (int i = 0; i < 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 75ba788..d6e9692 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -4,15 +4,21 @@ /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects - where T : class +where T : class { /// /// Массив объектов, которые храним /// private T?[] _collection; + public int Count => _collection.Length; - public int SetMaxCount + + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -28,6 +34,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } + + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -37,7 +46,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position < 0 || position > Count) + if (position >= _collection.Length || position < 0) { return null; } @@ -45,50 +54,64 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public int Insert(T obj) { - return Insert(obj, 0); + int index = 0; + while (index < _collection.Length) + { + if (_collection[index] == null) + { + _collection[index] = obj; + return index; + } + index++; + } + return -1; } public int Insert(T obj, int position) { - if (position < 0 || position > Count) - { - return -1; - } + + if (position >= _collection.Length || position < 0) + { return -1; } if (_collection[position] == null) { _collection[position] = obj; return position; } + int index; - for (int i = position + 1; i < Count; i++) + for (index = position + 1; index < _collection.Length; ++index) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; + _collection[position] = obj; return position; } } - for (int i = position - 1; i >= 0; i--) + for (index = position - 1; index >= 0; --index) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; + _collection[position] = obj; return position; } } - return -1; } - public T? Remove(int position) + public T Remove(int position) { - if (position < 0 || position > Count || _collection[position] == null) - { - return null; - } - - T? obj = _collection[position]; + if (position >= _collection.Length || position < 0) + { return null; } + T DrawningWarship = _collection[position]; _collection[position] = null; - return obj; + return DrawningWarship; } -} + + 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 4d83a30..4cbf3e0 100644 --- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs @@ -1,21 +1,37 @@ -namespace ProjectBattleship.CollectionGenericObjects; +using ProjectBattleship.DrawingObject; + +namespace ProjectBattleship.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection -where T : class +where T : DrawingWarship { /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; - + private Dictionary> _storages; /// /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -23,7 +39,6 @@ where T : class { _storages = new Dictionary>(); } - /// /// Добавление коллекции в хранилище /// @@ -31,31 +46,26 @@ where T : class /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (string.IsNullOrEmpty(name)) return; - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - if (collectionType == CollectionType.Massive) + if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) { - _storages[name] = new MassiveGenericObjects(); - } - else if (collectionType == CollectionType.List) - { - _storages[name] = new ListGenericObjects(); + if (collectionType == CollectionType.List) + { + _storages.Add(name, new ListGenericObjects()); + } + else if (collectionType == CollectionType.Massive) + { + _storages.Add(name, new MassiveGenericObjects()); + } } } - /// /// Удаление коллекции /// /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } + if (_storages.ContainsKey(name)) { _storages.Remove(name); } } - /// /// Доступ к коллекции /// @@ -65,6 +75,7 @@ where T : class { get { + // TODO Продумать логику получения объекта if (_storages.ContainsKey(name)) { return _storages[name]; @@ -72,4 +83,116 @@ where T : class return null; } } -} \ No newline at end of file + /// + /// Сохранение информации по самолетам в хранилище в файл + /// + /// Путь и имя файла + /// 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 streamWriter = new StreamWriter(fs); + streamWriter.Write(_collectionKey); + + foreach (KeyValuePair> value in _storages) + { + streamWriter.Write(Environment.NewLine); + + if (value.Value.Count == 0) + { + continue; + } + + streamWriter.Write(value.Key); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.GetCollectionType); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.MaxCount); + streamWriter.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + streamWriter.Write(data); + streamWriter.Write(_separatorItems); + } + } + return true; + } + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + 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?.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/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingBattleship.cs b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingBattleship.cs index 4d6c068..febd5f4 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingBattleship.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingBattleship.cs @@ -5,6 +5,12 @@ namespace ProjectBattleship.DrawingObject; /// public class DrawingBattleship : DrawingWarship { + public DrawingBattleship(EntityWarship warship) : base(150, 50) + { + EntityWarship = warship; + } + + /// /// Конструктор /// @@ -19,6 +25,7 @@ public class DrawingBattleship : DrawingWarship { EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment); } + public override void DrawTransport(Graphics g) { if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || diff --git a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarship.cs b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarship.cs index ba283dd..069dfa8 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarship.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingObject/DrawingWarship.cs @@ -25,6 +25,8 @@ public class DrawingWarship /// Верхняя кооридната прорисовки военного корабля /// protected int? _startPosY; + private EntityWarship warship; + /// /// Ширина прорисовки военного корабля /// @@ -63,6 +65,14 @@ public class DrawingWarship _drawingWarshipWidth = drawingWarshipWidth; _pictureHeight = drawingWarshipHeight; } + + public DrawingWarship(EntityWarship warship) + { + EntityWarship = warship; + } + + + /// /// Установка границ поля /// diff --git a/ProjectBattleship/ProjectBattleship/DrawingObject/ExtentionDrawingWarship.cs b/ProjectBattleship/ProjectBattleship/DrawingObject/ExtentionDrawingWarship.cs new file mode 100644 index 0000000..ae609e4 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/DrawingObject/ExtentionDrawingWarship.cs @@ -0,0 +1,46 @@ +using ProjectBattleship.Entities; +namespace ProjectBattleship.DrawingObject; +/// +/// Расширение для класса 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(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); + } +} \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/Entities/EntityBattleship.cs b/ProjectBattleship/ProjectBattleship/Entities/EntityBattleship.cs index 0b47d90..cf8cd87 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; /// /// Класс-сущность "Линкор" /// @@ -19,4 +21,28 @@ public class EntityBattleship : EntityWarship Turret = turret; RocketCompartment = rocketCompartment; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(), + BodyColor.Name, AdditionalColor.Name, RocketCompartment.ToString(), Turret.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityWarship? 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])); + } } diff --git a/ProjectBattleship/ProjectBattleship/Entities/EntityWarship.cs b/ProjectBattleship/ProjectBattleship/Entities/EntityWarship.cs index e4f9969..716827f 100644 --- a/ProjectBattleship/ProjectBattleship/Entities/EntityWarship.cs +++ b/ProjectBattleship/ProjectBattleship/Entities/EntityWarship.cs @@ -1,6 +1,6 @@ namespace ProjectBattleship.Entities; /// -/// Класс-сущность "Автомобиль" +/// Класс-сущность "Военный корабль" /// public class EntityWarship { @@ -18,4 +18,27 @@ 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])); + } } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs index 7539743..7d455d9 100644 --- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs +++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs @@ -49,10 +49,17 @@ namespace ProjectBattleship textBoxCollectionName = new TextBox(); labelCollection = new Label(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBoxCollectionTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelCollection.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxCollectionTools @@ -62,9 +69,9 @@ namespace ProjectBattleship groupBoxCollectionTools.Controls.Add(buttonCreateCompany); groupBoxCollectionTools.Controls.Add(comboBoxSelectorCompany); groupBoxCollectionTools.Controls.Add(panelCollection); - groupBoxCollectionTools.Location = new Point(694, 0); + groupBoxCollectionTools.Location = new Point(699, 27); groupBoxCollectionTools.Name = "groupBoxCollectionTools"; - groupBoxCollectionTools.Size = new Size(279, 594); + groupBoxCollectionTools.Size = new Size(279, 618); groupBoxCollectionTools.TabIndex = 1; groupBoxCollectionTools.TabStop = false; groupBoxCollectionTools.Text = "Инструменты"; @@ -78,9 +85,9 @@ namespace ProjectBattleship panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonRemoveWarship); panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(6, 348); + panelCompanyTools.Location = new Point(6, 354); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(267, 240); + panelCompanyTools.Size = new Size(267, 234); panelCompanyTools.TabIndex = 11; // // buttonRefresh @@ -144,7 +151,7 @@ namespace ProjectBattleship // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(14, 314); + buttonCreateCompany.Location = new Point(14, 320); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(251, 34); buttonCreateCompany.TabIndex = 10; @@ -157,7 +164,7 @@ namespace ProjectBattleship comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(14, 275); + comboBoxSelectorCompany.Location = new Point(14, 281); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(251, 33); comboBoxSelectorCompany.TabIndex = 0; @@ -172,7 +179,7 @@ namespace ProjectBattleship panelCollection.Controls.Add(radioButtonMassive); panelCollection.Controls.Add(textBoxCollectionName); panelCollection.Controls.Add(labelCollection); - panelCollection.Location = new Point(6, 25); + panelCollection.Location = new Point(6, 30); panelCollection.Name = "panelCollection"; panelCollection.Size = new Size(267, 246); panelCollection.TabIndex = 9; @@ -247,19 +254,62 @@ namespace ProjectBattleship // pictureBox // pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 51); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(688, 594); + pictureBox.Size = new Size(688, 567); pictureBox.TabIndex = 2; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(24, 24); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(978, 33); + menuStrip.TabIndex = 3; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(69, 29); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(278, 34); + saveToolStripMenuItem.Text = "Сохранение "; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(278, 34); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormWarshipCollection // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(978, 594); + ClientSize = new Size(978, 618); Controls.Add(groupBoxCollectionTools); Controls.Add(pictureBox); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormWarshipCollection"; Text = "Коллекция военных кораблей"; groupBoxCollectionTools.ResumeLayout(false); @@ -268,7 +318,10 @@ namespace ProjectBattleship panelCollection.ResumeLayout(false); panelCollection.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -291,5 +344,11 @@ namespace ProjectBattleship private Button buttonCollectionDel; private ListBox listBoxCollection; 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/FormWarshipCollection.cs b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs index c126e11..12430a6 100644 --- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs +++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs @@ -1,5 +1,6 @@ using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.DrawingObject; +using System.Windows.Forms; namespace ProjectBattleship; /// @@ -132,12 +133,12 @@ public partial class FormWarshipCollection : Form /// private void ButtonRemoveWarship_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; @@ -292,4 +293,45 @@ public partial class FormWarshipCollection : 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)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.resx b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.resx index af32865..9ab5233 100644 --- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.resx +++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.resx @@ -18,7 +18,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, ... System.Resources.ResXResourceWriter, System.Windows.Forms, ... this is my long stringthis is a comment - Blue + Blue [base64 mime encoded serialized .NET Framework object] @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 163, 17 + + + 351, 17 + \ No newline at end of file