diff --git a/AircraftCarrier/AircraftCarrier/ExtentionDrawingWarship.cs b/AircraftCarrier/AircraftCarrier/ExtentionDrawingWarship.cs new file mode 100644 index 0000000..0bd7c6d --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/ExtentionDrawingWarship.cs @@ -0,0 +1,61 @@ +using ProjectAircraftCarrier.Entities; + +namespace ProjectAircraftCarrier.DrawingObjects +{ + /// + /// Расширение для класса EntityWarship + /// + public static class ExtentionDrawingWarship + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawingWarship? CreateDrawingWarship(this string info, + char separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawingWarship(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + width, height); + } + if (strs.Length == 6) + { + return new DrawingAircraftCarrier(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), width, height); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель даннных + /// Строка с данными по объекту + public static string GetDataForSave(this DrawingWarship drawingWarship, + char separatorForObject) + { + var warship = drawingWarship.EntityWarship; + if (warship == null) + { + return string.Empty; + } + var str = $"{warship.Speed}{separatorForObject}{warship.Weight}" + + $"{separatorForObject}{warship.BodyColor.Name}"; + if (warship is not EntityAircraftCarrier aircraftCarrier) + { + return str; + } + return $"{str}{separatorForObject}{aircraftCarrier.AdditionalColor.Name}{separatorForObject}{aircraftCarrier.Runway}{separatorForObject}{aircraftCarrier.Cabin}"; + } + } +} + diff --git a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.Designer.cs b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.Designer.cs index 27d0e98..0235c56 100644 --- a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.Designer.cs +++ b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.Designer.cs @@ -39,9 +39,16 @@ buttonRemoveWarship = new Button(); buttonAddWarship = new Button(); pictureBoxCollection = new PictureBox(); + menuStrip = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + openFileDialog = new System.Windows.Forms.OpenFileDialog(); + saveFileDialog = new System.Windows.Forms.SaveFileDialog(); groupBoxCollectionTools.SuspendLayout(); groupBoxCollectionSets.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxCollectionTools @@ -52,11 +59,11 @@ groupBoxCollectionTools.Controls.Add(buttonRefreshCollection); groupBoxCollectionTools.Controls.Add(buttonRemoveWarship); groupBoxCollectionTools.Controls.Add(buttonAddWarship); - groupBoxCollectionTools.Location = new Point(893, 3); + groupBoxCollectionTools.Location = new Point(893, 37); groupBoxCollectionTools.Margin = new Padding(4, 5, 4, 5); groupBoxCollectionTools.Name = "groupBoxCollectionTools"; groupBoxCollectionTools.Padding = new Padding(4, 5, 4, 5); - groupBoxCollectionTools.Size = new Size(247, 743); + groupBoxCollectionTools.Size = new Size(247, 709); groupBoxCollectionTools.TabIndex = 0; groupBoxCollectionTools.TabStop = false; groupBoxCollectionTools.Text = "Tools"; @@ -122,7 +129,7 @@ // // buttonRefreshCollection // - buttonRefreshCollection.Location = new Point(9, 688); + buttonRefreshCollection.Location = new Point(9, 654); buttonRefreshCollection.Margin = new Padding(4, 5, 4, 5); buttonRefreshCollection.Name = "buttonRefreshCollection"; buttonRefreshCollection.Size = new Size(230, 45); @@ -155,13 +162,52 @@ // // pictureBoxCollection // - pictureBoxCollection.Location = new Point(0, 2); + pictureBoxCollection.Location = new Point(0, 37); pictureBoxCollection.Margin = new Padding(4, 5, 4, 5); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new Size(893, 745); + pictureBoxCollection.Size = new Size(893, 710); pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabStop = false; // + // menuStrip1 + // + menuStrip.ImageScalingSize = new Size(24, 24); + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip1"; + menuStrip.Size = new Size(1143, 33); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(54, 29); + fileToolStripMenuItem.Text = "File"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.Size = new Size(270, 34); + saveToolStripMenuItem.Text = "Save"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.Size = new Size(270, 34); + loadToolStripMenuItem.Text = "Load"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormWarshipCollection // AutoScaleDimensions = new SizeF(10F, 25F); @@ -169,6 +215,8 @@ ClientSize = new Size(1143, 750); Controls.Add(pictureBoxCollection); Controls.Add(groupBoxCollectionTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Margin = new Padding(4, 5, 4, 5); Name = "FormWarshipCollection"; Text = "Warship Collection"; @@ -177,7 +225,10 @@ groupBoxCollectionSets.ResumeLayout(false); groupBoxCollectionSets.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -193,5 +244,11 @@ private Button buttonDelObject; private Button buttonAddObject; private TextBox textBoxStorageName; + private MenuStrip menuStrip; + private ToolStripMenuItem fileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs index db5f70d..54f43f5 100644 --- a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs +++ b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs @@ -1,6 +1,7 @@ using ProjectAircraftCarrier.DrawingObjects; using ProjectAircraftCarrier.Generics; using ProjectAircraftCarrier.MovementStrategy; +using System.Windows.Forms; namespace ProjectAircraftCarrier { /// @@ -177,5 +178,51 @@ namespace ProjectAircraftCarrier } pictureBoxCollection.Image = obj.ShowWarships(); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Save was successful", "Result", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Not preserved", "Result", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Load was successful", + "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + foreach (var collection in _storage.Keys) + { + listBoxStorages.Items.Add(collection); + } + } + else + { + MessageBox.Show("Not loaded", "Result", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.resx b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.resx index af32865..a0623c8 100644 --- a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.resx +++ b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.resx @@ -117,4 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + \ No newline at end of file diff --git a/AircraftCarrier/AircraftCarrier/WarshipsGenericCollection.cs b/AircraftCarrier/AircraftCarrier/WarshipsGenericCollection.cs index 42a736e..4e769f3 100644 --- a/AircraftCarrier/AircraftCarrier/WarshipsGenericCollection.cs +++ b/AircraftCarrier/AircraftCarrier/WarshipsGenericCollection.cs @@ -96,6 +96,10 @@ namespace ProjectAircraftCarrier.Generics return bmp; } /// + /// Получение объектов коллекции + /// + public IEnumerable GetWarships => _collection.GetWarships(); + /// /// Метод отрисовки фона /// /// diff --git a/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs b/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs index d5c9e6d..4f4ef52 100644 --- a/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs +++ b/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs @@ -1,5 +1,6 @@ using ProjectAircraftCarrier.DrawingObjects; using ProjectAircraftCarrier.MovementStrategy; +using System.Text; namespace ProjectAircraftCarrier.Generics { /// @@ -25,6 +26,18 @@ namespace ProjectAircraftCarrier.Generics /// private readonly int _pictureHeight; /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// /// @@ -79,6 +92,102 @@ namespace ProjectAircraftCarrier.Generics return null; } } + /// + /// Сохранение информации по кораблям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in + _warshipStorages) + { + StringBuilder records = new(); + foreach (DrawingWarship? elem in record.Value.GetWarships) + { + records.Append($"" + + $"{elem?.GetDataForSave(_separatorForObject)}" + + $"{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}" + + $"{records}"); + } + if (data.Length == 0) + { + return false; + } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes($"WarshipStorage" + + $"{Environment.NewLine}{data}"); + fs.Write(info, 0, info.Length); + return true; + } + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + 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); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].StartsWith("WarshipStorage")) + { + return false; + } + _warshipStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + WarshipsGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawingWarship? warship = + elem?.CreateDrawingWarship(_separatorForObject, + _pictureWidth, _pictureHeight); + if (warship != null) + { + if (!(collection + warship)) + { + return false; + } + } + } + _warshipStorages.Add(record[0], collection); + } + return true; + } } } -