diff --git a/WarPlanes/WarPlanes/DrawningObjectWarPlane.cs b/WarPlanes/WarPlanes/DrawningObjectWarPlane.cs index bb74e90..0b186b6 100644 --- a/WarPlanes/WarPlanes/DrawningObjectWarPlane.cs +++ b/WarPlanes/WarPlanes/DrawningObjectWarPlane.cs @@ -30,5 +30,10 @@ { _warplane.DrawTransport(g); } + + public string GetInfo() => _warplane?.GetDataForSave(); + + public static IDrawningObject Create(string data) => new DrawningObjectWarPlane(data.CreateDrawningWarPlane()); + } } \ No newline at end of file diff --git a/WarPlanes/WarPlanes/ExtentionWarPlane.cs b/WarPlanes/WarPlanes/ExtentionWarPlane.cs new file mode 100644 index 0000000..a391048 --- /dev/null +++ b/WarPlanes/WarPlanes/ExtentionWarPlane.cs @@ -0,0 +1,50 @@ +namespace AirFighter +{ + /// + /// Расширение для класса DrawningWarPlane + /// + internal static class ExtentionWarPlane + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawningWarPlane CreateDrawningWarPlane(this string info) + { + string[] strs = info.Split(_separatorForObject); + if (strs.Length == 3) + { + return new DrawningWarPlane(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + if (strs.Length == 7) + { + return new DrawningFighter(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5])); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningWarPlane drawningWarPlane) + { + var warplane = drawningWarPlane.WarPlane; + var str = $"{warplane.Speed}{_separatorForObject}{warplane.Weight}{_separatorForObject}{warplane.BodyColor.Name}"; + if (warplane is not EntityFighter Fighter) + { + return str; + } + return $"{str}{_separatorForObject}{Fighter.DopColor.Name}{_separatorForObject}{_separatorForObject}{Fighter.Wing}{_separatorForObject}"; + } + } +} \ No newline at end of file diff --git a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.Designer.cs b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.Designer.cs index 6e7001e..ad22ce6 100644 --- a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.Designer.cs +++ b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.Designer.cs @@ -45,9 +45,16 @@ this.buttonShowOnMap = new System.Windows.Forms.Button(); this.buttonAddWarPlane = new System.Windows.Forms.Button(); this.pictureBox = new System.Windows.Forms.PictureBox(); + this.menuStrip = new System.Windows.Forms.MenuStrip(); + this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.groupBoxTools.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // groupBoxTools @@ -238,11 +245,52 @@ this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // + // menuStrip + // + this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.файлToolStripMenuItem}); + this.menuStrip.Location = new System.Drawing.Point(0, 0); + this.menuStrip.Name = "menuStrip"; + this.menuStrip.Size = new System.Drawing.Size(811, 24); + this.menuStrip.TabIndex = 3; + // + // файлToolStripMenuItem + // + this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem}); + this.файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20); + this.файлToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.SaveToolStripMenuItem.Text = "Сохранение"; + this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); + // + // LoadToolStripMenuItem + // + this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.LoadToolStripMenuItem.Text = "Загрузка"; + this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); + // + // openFileDialog + // + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // // FormMapWithSetWarPlanes // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1015, 600); + this.Controls.Add(this.menuStrip); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBoxTools); this.Name = "FormMapWithSetWarPlanes"; @@ -252,7 +300,10 @@ this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); this.ResumeLayout(false); + this.PerformLayout(); } @@ -275,5 +326,11 @@ private ListBox listBoxMaps; private TextBox textBoxNewMapName; private ComboBox comboBoxSelectorMap; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs index b25742d..03348d1 100644 --- a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs +++ b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs @@ -214,5 +214,37 @@ } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir); } + + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_mapsCollection.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) + { + try + { + _mapsCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); + } + catch (Exception ex) + { + MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } \ No newline at end of file diff --git a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.resx b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.resx index f298a7b..934ed35 100644 --- a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.resx +++ b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 125, 17 + + + 265, 17 + \ No newline at end of file diff --git a/WarPlanes/WarPlanes/IDrawningObject.cs b/WarPlanes/WarPlanes/IDrawningObject.cs index 3d6457c..85e23e6 100644 --- a/WarPlanes/WarPlanes/IDrawningObject.cs +++ b/WarPlanes/WarPlanes/IDrawningObject.cs @@ -30,5 +30,10 @@ /// /// RectangleF GetCurrentPosition(); + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } \ No newline at end of file diff --git a/WarPlanes/WarPlanes/MapWithSetWarPlanesGeneric.cs b/WarPlanes/WarPlanes/MapWithSetWarPlanesGeneric.cs index c739395..653306b 100644 --- a/WarPlanes/WarPlanes/MapWithSetWarPlanesGeneric.cs +++ b/WarPlanes/WarPlanes/MapWithSetWarPlanesGeneric.cs @@ -49,6 +49,31 @@ _map = map; } /// + /// Получение данных в виде строки + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var warplane in _setWarPlanes.GetWarPlanes()) + { + data += $"{warplane.GetInfo()}{separatorData}"; + } + return data; + } + /// + /// Загрузка списка из массива строк + /// + /// + public void LoadData(string[] records) + { + foreach (var rec in records) + { + _setWarPlanes.Insert(DrawningObjectWarPlane.Create(rec) as T); + } + } + /// /// Перегрузка оператора сложения /// /// diff --git a/WarPlanes/WarPlanes/MapsCollection.cs b/WarPlanes/WarPlanes/MapsCollection.cs index 47df4fc..7ad6e0e 100644 --- a/WarPlanes/WarPlanes/MapsCollection.cs +++ b/WarPlanes/WarPlanes/MapsCollection.cs @@ -1,4 +1,6 @@ -namespace AirFighter +using System.Text; + +namespace AirFighter { /// /// Класс для хранения коллекции карт @@ -22,6 +24,14 @@ /// private readonly int _pictureHeight; /// + /// Разделитель для записи информации по элементу словаря в файл + /// + private readonly char separatorDict = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char separatorData = ';'; + /// /// Конструктор /// /// @@ -53,6 +63,86 @@ { _mapStorages.Remove(name); } + + + + /// + /// Метод записи информации в файл + /// + /// Строка, которую следует записать + /// Поток для записи + private static void WriteToFile(string text, FileStream stream) + { + byte[] info = new UTF8Encoding(true).GetBytes(text); + stream.Write(info, 0, info.Length); + } + /// + /// Сохранение информации по объектам в хранилище в файл + /// + /// Путь и имя файла + /// + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (FileStream fs = new(filename, FileMode.Create)) + { + WriteToFile($"MapsCollection{Environment.NewLine}", fs); + foreach (var storage in _mapStorages) + { + WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", fs); + } + } + 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); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (!strs[0].Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + return false; + } + //очищаем записи + _mapStorages.Clear(); + for (int i = 1; i < strs.Length; ++i) + { + var elem = strs[i].Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + } + //_mapStorages.Add(elem[0], new MapWithSetWarPlanesGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + return true; + } + /// /// Доступ к парковке ///