diff --git a/WarmlyShip/DrawningObjects/ExtentionDrawningShip.cs b/WarmlyShip/DrawningObjects/ExtentionDrawningShip.cs
new file mode 100644
index 0000000..d378c19
--- /dev/null
+++ b/WarmlyShip/DrawningObjects/ExtentionDrawningShip.cs
@@ -0,0 +1,61 @@
+using WarmlyShip.Entities;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace WarmlyShip.DrawningObjects
+{
+ ///
+ /// Расширение для класса EntityShip
+ ///
+ public static class ExtentionDrawningShip
+ {
+ ///
+ /// Создание объекта из строки
+ ///
+ /// Строка с данными для создания объекта
+ /// Разделитель даннных
+ /// Ширина
+ /// Высота
+ /// Объект
+ public static DrawningShip? CreateDrawningShip(this string info, char separatorForObject, int width, int height)
+ {
+ string[] strs = info.Split(separatorForObject);
+ if (strs.Length == 3)
+ {
+ return new DrawningShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
+ }
+ if (strs.Length == 6)
+ {
+ return new DrawningWarmlyShip(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 DrawningShip drawningship, char separatorForObject)
+ {
+ var ship = drawningship.EntityShip;
+ if (ship == null)
+ {
+ return string.Empty;
+ }
+ var str = $"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}";
+ if (ship is not EntityWarmlyShip warmlyShip)
+ {
+ return str;
+ }
+ return
+ $"{str}{separatorForObject}{warmlyShip.AdditionalColor.Name}{separatorForObject}{warmlyShip.Pipe}" +
+ $"{separatorForObject}{warmlyShip.FuelCompartment}";
+ }
+ }
+}
diff --git a/WarmlyShip/FormShipCollection.Designer.cs b/WarmlyShip/FormShipCollection.Designer.cs
index 0a63cd1..1237368 100644
--- a/WarmlyShip/FormShipCollection.Designer.cs
+++ b/WarmlyShip/FormShipCollection.Designer.cs
@@ -41,17 +41,23 @@
ButtonDeleteShip = new Button();
maskedTextBoxNumber = new TextBox();
ButtonAddShip = new Button();
+ menuStrip = new MenuStrip();
+ FileToolStripMenuItem = new ToolStripMenuItem();
+ SaveToolStripMenuItem = new ToolStripMenuItem();
+ LoadToolStripMenuItem = new ToolStripMenuItem();
+ openFileDialog = new System.Windows.Forms.OpenFileDialog();
+ saveFileDialog = new System.Windows.Forms.SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
toolsPanel.SuspendLayout();
panelSets.SuspendLayout();
+ menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
- pictureBoxCollection.Location = new Point(-1, 0);
+ pictureBoxCollection.Location = new Point(1, 31);
pictureBoxCollection.Name = "pictureBoxCollection";
- pictureBoxCollection.Size = new Size(655, 507);
- pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
+ pictureBoxCollection.Size = new Size(655, 471);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
@@ -172,6 +178,46 @@
ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click;
//
+ // menuStrip
+ //
+ menuStrip.ImageScalingSize = new Size(20, 20);
+ menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
+ menuStrip.Location = new Point(0, 0);
+ menuStrip.Name = "menuStrip";
+ menuStrip.Size = new Size(889, 24);
+ menuStrip.TabIndex = 2;
+ menuStrip.Text = "menuStrip";
+ //
+ // FileToolStripMenuItem
+ //
+ FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
+ FileToolStripMenuItem.Name = "FileToolStripMenuItem";
+ FileToolStripMenuItem.Size = new Size(48, 20);
+ FileToolStripMenuItem.Text = "Файл";
+ //
+ // SaveToolStripMenuItem
+ //
+ SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
+ SaveToolStripMenuItem.Size = new Size(141, 22);
+ SaveToolStripMenuItem.Text = "Сохранение";
+ SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
+ //
+ // LoadToolStripMenuItem
+ //
+ LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
+ LoadToolStripMenuItem.Size = new Size(141, 22);
+ LoadToolStripMenuItem.Text = "Загрузка";
+ LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
+ //
+ // openFileDialog
+ //
+ openFileDialog.FileName = "openFileDialog";
+ openFileDialog.Filter = "txt file | *.txt";
+ //
+ // saveFileDialog
+ //
+ saveFileDialog.Filter = "txt file | *.txt";
+ //
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@@ -179,6 +225,8 @@
ClientSize = new Size(889, 508);
Controls.Add(toolsPanel);
Controls.Add(pictureBoxCollection);
+ Controls.Add(menuStrip);
+ MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "Набор кораблей";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
@@ -186,10 +234,17 @@
toolsPanel.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
+ menuStrip.ResumeLayout(false);
+ menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
+ private void LoadToolStripMenuItem_Click1(object sender, EventArgs e)
+ {
+ throw new NotImplementedException();
+ }
+
#endregion
private PictureBox pictureBoxCollection;
@@ -205,5 +260,11 @@
private TextBox textBoxStorageName;
private Button ButtonDelObject;
private Button ButtonAddObject;
+ 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/WarmlyShip/FormShipCollection.cs b/WarmlyShip/FormShipCollection.cs
index ecb63d3..e7605aa 100644
--- a/WarmlyShip/FormShipCollection.cs
+++ b/WarmlyShip/FormShipCollection.cs
@@ -191,5 +191,49 @@ namespace WarmlyShip
}
pictureBoxCollection.Image = obj.ShowShips();
}
+
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ if (_storage.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 (_storage.LoadData(openFileDialog.FileName))
+ {
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ foreach (var collection in _storage.Keys)
+ {
+ ListBoxObjects.Items.Add(collection);
+ }
+ }
+ else
+ {
+ MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+ }
}
}
diff --git a/WarmlyShip/Generics/ShipsGenericCollection.cs b/WarmlyShip/Generics/ShipsGenericCollection.cs
index 67edce7..1e9aa6d 100644
--- a/WarmlyShip/Generics/ShipsGenericCollection.cs
+++ b/WarmlyShip/Generics/ShipsGenericCollection.cs
@@ -18,6 +18,11 @@ namespace WarmlyShip.Generics
where T : DrawningShip
where U : IMoveableObject
{
+ ///
+ /// Получение объектов коллекции
+ ///
+ public IEnumerable GetShips => _collection.GetShips();
+
///
/// Ширина окна прорисовки
///
diff --git a/WarmlyShip/Generics/ShipsGenericStorage.cs b/WarmlyShip/Generics/ShipsGenericStorage.cs
index 82845a9..2d5d987 100644
--- a/WarmlyShip/Generics/ShipsGenericStorage.cs
+++ b/WarmlyShip/Generics/ShipsGenericStorage.cs
@@ -34,6 +34,19 @@ namespace WarmlyShip.Generics
///
private readonly int _pictureHeight;
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private static readonly char _separatorForKeyValue = '|';
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly char _separatorRecords = ';';
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly char _separatorForObject = ':';
+
///
/// Конструктор
///
@@ -46,6 +59,99 @@ namespace WarmlyShip.Generics
_pictureHeight = pictureHeight;
}
+ ///
+ /// Сохранение информации по кораблям в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public bool SaveData(string filename)
+ {
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+ StringBuilder data = new();
+ foreach (KeyValuePair> record in _shipStorages)
+ {
+ StringBuilder records = new();
+ foreach (DrawningShip? elem in record.Value.GetShips)
+ {
+ records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
+ }
+ data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
+ }
+
+ if (data.Length == 0)
+ {
+ return false;
+ }
+ string toWrite = $"ShipStorage{Environment.NewLine}{data}";
+ var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
+
+ using (StreamWriter sw = new(filename))
+ {
+ foreach (var str in strs)
+ {
+ sw.WriteLine(str);
+ }
+ }
+ return true;
+ }
+
+ ///
+ /// Загрузка информации по кораблям в хранилище из файла
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public bool LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ return false;
+ }
+ using (StreamReader sr = new(filename))
+ {
+ string str = sr.ReadLine();
+ var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
+ if (strs == null || strs.Length == 0)
+ {
+ return false;
+ }
+ if (!strs[0].StartsWith("ShipStorage"))
+ {
+ return false;
+ }
+ _shipStorages.Clear();
+ do
+ {
+ string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ if (record.Length != 2)
+ {
+ str = sr.ReadLine();
+ continue;
+ }
+ ShipsGenericCollection collection = new(_pictureWidth, _pictureHeight);
+ string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
+ {
+ DrawningShip? ship =
+ elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
+ if (ship != null)
+ {
+ if (!(collection + ship))
+ {
+ return false;
+ }
+ }
+ }
+ _shipStorages.Add(record[0], collection);
+
+ str = sr.ReadLine();
+ } while (str != null);
+ }
+ return true;
+ }
+
///
/// Добавление набора
///