From c33afe18fdce8d3360fcbb833d9240d029c5075f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D1=8F=D1=80=20=D0=90=D0=B3=D0=BB?= =?UTF-8?q?=D0=B8=D1=83=D0=BB=D0=BB=D0=BE=D0=B2?= Date: Fri, 28 Oct 2022 00:52:49 +0400 Subject: [PATCH] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B8=D0=B7=20=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B9=20=D1=87=D0=B0=D1=81=D1=82=D0=B8=206=20=D0=BB?= =?UTF-8?q?=D0=B0=D0=B1=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AirBomber/AirBomber/DrawningObject.cs | 4 + AirBomber/AirBomber/ExtentionAirplane.cs | 66 +++++++++++++++ .../FormMapWithSetAirplanes.Designer.cs | 56 +++++++++++++ .../AirBomber/FormMapWithSetAirplanes.cs | 42 +++++++++- AirBomber/AirBomber/IDrawningObject.cs | 8 +- .../AirBomber/MapWithSetAirplanesGeneric.cs | 26 ++++++ AirBomber/AirBomber/MapsCollection.cs | 84 ++++++++++++++++++- 7 files changed, 280 insertions(+), 6 deletions(-) create mode 100644 AirBomber/AirBomber/ExtentionAirplane.cs diff --git a/AirBomber/AirBomber/DrawningObject.cs b/AirBomber/AirBomber/DrawningObject.cs index 2556d39..f2d1a16 100644 --- a/AirBomber/AirBomber/DrawningObject.cs +++ b/AirBomber/AirBomber/DrawningObject.cs @@ -43,5 +43,9 @@ namespace AirBomber /// The drawning object. /// public static explicit operator DrawningAirplane(DrawningObject drawningObject) => drawningObject._airplane; + + public string GetInfo() => _airplane?.GetDataForSave(); + + public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningAirplane()); } } diff --git a/AirBomber/AirBomber/ExtentionAirplane.cs b/AirBomber/AirBomber/ExtentionAirplane.cs new file mode 100644 index 0000000..70c023d --- /dev/null +++ b/AirBomber/AirBomber/ExtentionAirplane.cs @@ -0,0 +1,66 @@ +namespace AirBomber +{ + /// + /// Расширение для класса DrawningAirplane + /// + internal static class ExtentionAirplane + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// + /// Получение цвета из строки 16-ричных чисел, либо из его имени + /// + /// + /// + private static Color GetColor(string hexOrName) + { + try + { + return Color.FromArgb(Convert.ToInt32(hexOrName, 16)); + } + catch (Exception) + { + return Color.FromName(hexOrName); + } + } + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawningAirplane CreateDrawningAirplane(this string info) + { + string[] strs = info.Split(_separatorForObject); + if (strs.Length == 3) + { + return new DrawningAirplane(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), GetColor(strs[2])); + } + if (strs.Length == 6) + { + return new DrawningAirBomber(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), GetColor(strs[2]), + GetColor(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5])); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningAirplane drawningAirplane) + { + var Airplane = drawningAirplane.Airplane; + var str = $"{Airplane.Speed}{_separatorForObject}{Airplane.Weight}{_separatorForObject}{Airplane.BodyColor.Name}"; + if (Airplane is not EntityAirBomber AirBomber) + { + return str; + } + return $"{str}{_separatorForObject}{AirBomber.DopColor.Name}{_separatorForObject}{AirBomber.HasBombs}{_separatorForObject}{AirBomber.HasFuelTanks}"; + } + } +} \ No newline at end of file diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs index 8ca3cf0..c6fab16 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs +++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs @@ -57,6 +57,12 @@ this.buttonLeft = new System.Windows.Forms.Button(); this.buttonUp = 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(); this.groupBoxGenerate.SuspendLayout(); @@ -377,6 +383,46 @@ 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(1015, 24); + this.menuStrip.TabIndex = 2; + // + // файл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"; + // // FormMapWithSetAirplanes // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -384,6 +430,8 @@ this.ClientSize = new System.Drawing.Size(1015, 810); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBoxTools); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; this.Name = "FormMapWithSetAirplanes"; this.Text = "Генератор самолетов"; this.groupBoxTools.ResumeLayout(false); @@ -396,6 +444,8 @@ ((System.ComponentModel.ISupportInitialize)(this.numericUpDownEngines)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericWeight)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); this.ResumeLayout(false); } @@ -431,5 +481,11 @@ private ListBox listBoxMaps; private TextBox textBoxNewMapName; private Button btnAddDeletedObject; + 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/AirBomber/AirBomber/FormMapWithSetAirplanes.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs index 88ec025..0fba014 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs +++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs @@ -20,7 +20,7 @@ namespace AirBomber /// /// Все объекты удаленные с каких либо карт /// - private LinkedList _deletedObjects; + private LinkedList _deletedObjects; /// /// Конструктор /// @@ -304,5 +304,45 @@ namespace AirBomber AddAirplaneInMap(form.SelectedAirplane); } } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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) + { + if (_mapsCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); + } + else + { + MessageBox.Show("Не удалось открыть", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } \ No newline at end of file diff --git a/AirBomber/AirBomber/IDrawningObject.cs b/AirBomber/AirBomber/IDrawningObject.cs index a2afce7..2394173 100644 --- a/AirBomber/AirBomber/IDrawningObject.cs +++ b/AirBomber/AirBomber/IDrawningObject.cs @@ -9,7 +9,7 @@ namespace AirBomber /// /// Интерфейс для работы с объектом, прорисовываемым на форме /// - internal interface IDrawningObject + public interface IDrawningObject { /// /// Шаг перемещения объекта @@ -39,5 +39,11 @@ namespace AirBomber /// /// RectangleF GetCurrentPosition(); + + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } diff --git a/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs b/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs index d9d7b55..6c98db3 100644 --- a/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs +++ b/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs @@ -179,5 +179,31 @@ namespace AirBomber airplane?.DrawObject(g); } } + + /// + /// Получение данных в виде строки + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var car in SetAirplanes.GetAirplanes()) + { + data += $"{car.GetInfo()}{separatorData}"; + } + return data; + } + /// + /// Загрузка списка из массива строк + /// + /// + public void LoadData(string[] records) + { + foreach (var rec in records) + { + SetAirplanes.Insert(DrawningObject.Create(rec) as T); + } + } } } diff --git a/AirBomber/AirBomber/MapsCollection.cs b/AirBomber/AirBomber/MapsCollection.cs index 523f035..ca33b83 100644 --- a/AirBomber/AirBomber/MapsCollection.cs +++ b/AirBomber/AirBomber/MapsCollection.cs @@ -15,7 +15,7 @@ namespace AirBomber /// /// Словарь (хранилище) с картами /// - readonly Dictionary> _mapStorages; /// /// Возвращение списка названий карт @@ -30,6 +30,14 @@ namespace AirBomber /// private readonly int _pictureHeight; /// + /// Разделитель для записи информации по элементу словаря в файл + /// + private readonly char separatorDict = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char separatorData = ';'; + /// /// Конструктор /// /// @@ -37,7 +45,7 @@ namespace AirBomber public MapsCollection(int pictureWidth, int pictureHeight) { _mapStorages = new Dictionary>(); + MapWithSetAirplanesGeneric>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -63,7 +71,7 @@ namespace AirBomber /// /// /// - public MapWithSetAirplanesGeneric this[string ind] + public MapWithSetAirplanesGeneric this[string ind] { get { @@ -72,7 +80,7 @@ namespace AirBomber } } - public DrawningObject this[string ind, int indDrawningObject] + public IDrawningObject this[string ind, int indDrawningObject] { get { @@ -80,5 +88,73 @@ namespace AirBomber return mapWithSetAirplanesGeneric?.SetAirplanes[indDrawningObject]; } } + + /// + /// Сохранение информации по самолетам в хранилище в файл + /// + /// Путь и имя файла + /// + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter fs = new(filename)) + { + fs.Write($"MapsCollection{Environment.NewLine}"); + foreach (var storage in _mapStorages) + { + fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); + } + } + return true; + } + /// + /// Загрузка информации по самолетам в ангарах из файла + /// + /// + /// + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + List strs = new List(); + using (StreamReader fs = new(filename)) + { + while (!fs.EndOfStream) + { + strs.Add(fs.ReadLine()); + } + } + if (!strs[0].Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + return false; + } + //очищаем записи + _mapStorages.Clear(); + for (int i = 1; i < strs.Count; ++i) + { + var elem = strs[i].Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "WallMap": + map = new WallMap(); + break; + } + _mapStorages.Add(elem[0], new + MapWithSetAirplanesGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, + StringSplitOptions.RemoveEmptyEntries)); + } + return true; + } } }