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..073c34e 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs +++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs @@ -57,6 +57,13 @@ 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.SaveMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.groupBoxTools.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); this.groupBoxGenerate.SuspendLayout(); @@ -64,6 +71,7 @@ ((System.ComponentModel.ISupportInitialize)(this.numericUpDownEngines)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericWeight)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // comboTypeEngines @@ -94,9 +102,9 @@ this.groupBoxTools.Controls.Add(this.buttonLeft); this.groupBoxTools.Controls.Add(this.buttonUp); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(811, 0); + this.groupBoxTools.Location = new System.Drawing.Point(811, 24); this.groupBoxTools.Name = "groupBoxTools"; - this.groupBoxTools.Size = new System.Drawing.Size(204, 810); + this.groupBoxTools.Size = new System.Drawing.Size(204, 786); this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Инструменты"; @@ -325,7 +333,7 @@ this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.BackgroundImage = global::AirBomber.Properties.Resources.arrowDown; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonDown.Location = new System.Drawing.Point(90, 774); + this.buttonDown.Location = new System.Drawing.Point(90, 750); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(30, 30); this.buttonDown.TabIndex = 10; @@ -337,7 +345,7 @@ this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.BackgroundImage = global::AirBomber.Properties.Resources.arrowRight; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonRight.Location = new System.Drawing.Point(126, 774); + this.buttonRight.Location = new System.Drawing.Point(126, 750); this.buttonRight.Name = "buttonRight"; this.buttonRight.Size = new System.Drawing.Size(30, 30); this.buttonRight.TabIndex = 9; @@ -349,7 +357,7 @@ this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.BackgroundImage = global::AirBomber.Properties.Resources.arrowLeft; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonLeft.Location = new System.Drawing.Point(54, 774); + this.buttonLeft.Location = new System.Drawing.Point(54, 750); this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Size = new System.Drawing.Size(30, 30); this.buttonLeft.TabIndex = 8; @@ -361,7 +369,7 @@ this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.BackgroundImage = global::AirBomber.Properties.Resources.arrowUp; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonUp.Location = new System.Drawing.Point(90, 738); + this.buttonUp.Location = new System.Drawing.Point(90, 714); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(30, 30); this.buttonUp.TabIndex = 7; @@ -371,12 +379,60 @@ // pictureBox // this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.pictureBox.Location = new System.Drawing.Point(0, 0); + this.pictureBox.Location = new System.Drawing.Point(0, 24); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(811, 810); + this.pictureBox.Size = new System.Drawing.Size(811, 786); 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.SaveMapToolStripMenuItem, + 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(280, 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(280, 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"; + // + // SaveMapToolStripMenuItem + // + this.SaveMapToolStripMenuItem.Name = "SaveMapToolStripMenuItem"; + this.SaveMapToolStripMenuItem.Size = new System.Drawing.Size(280, 22); + this.SaveMapToolStripMenuItem.Text = "Сохранение Выбранного хранилища"; + this.SaveMapToolStripMenuItem.Click += new System.EventHandler(this.SaveMapToolStripMenuItem_Click); + // // FormMapWithSetAirplanes // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -384,6 +440,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,7 +454,10 @@ ((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); + this.PerformLayout(); } @@ -431,5 +492,12 @@ 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; + private ToolStripMenuItem SaveMapToolStripMenuItem; } } \ No newline at end of file diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs index 88ec025..fb182f6 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,61 @@ namespace AirBomber AddAirplaneInMap(form.SelectedAirplane); } } + /// + /// В зависимости от успешности сохранения показывает разные всплывающие окна + /// + private void ShowStatusSaveFile(bool succesfullSave) + { + if (succesfullSave) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + ShowStatusSaveFile(_mapsCollection.SaveData(saveFileDialog.FileName)); + } + } + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + 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); + } + } + } + + private void SaveMapToolStripMenuItem_Click(object sender, EventArgs e) + { + saveFileDialog.FileName = NameMap; + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + ShowStatusSaveFile(_mapsCollection.SaveMap(saveFileDialog.FileName, NameMap)); + } + } } } \ No newline at end of file diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.resx b/AirBomber/AirBomber/FormMapWithSetAirplanes.resx index f298a7b..1d824c7 100644 --- a/AirBomber/AirBomber/FormMapWithSetAirplanes.resx +++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 125, 17 + + + 258, 17 + \ 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..387b58d 100644 --- a/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs +++ b/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs @@ -179,5 +179,36 @@ namespace AirBomber airplane?.DrawObject(g); } } + + public void Clear() + { + SetAirplanes.Clear(); + } + + /// + /// Получение данных в виде строки + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var airplane in SetAirplanes.GetAirplanes()) + { + data += $"{airplane.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..a789dee 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,107 @@ 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 SaveMap(string filename, string nameMap) + { + if (!_mapStorages.ContainsKey(nameMap)) + { + return false; + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter fs = new(filename)) + { + fs.Write($"Map{Environment.NewLine}"); + fs.Write($"Name: {nameMap}{Environment.NewLine}"); + fs.Write(_mapStorages[nameMap].GetData(separatorDict, separatorData)); + } + return true; + } + + private bool LoadMap(string nameMapStorage, string nameMap, string lineData) + { + AbstractMap map = null; + switch (nameMap) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "WallMap": + map = new WallMap(); + break; + } + if (_mapStorages.ContainsKey(nameMapStorage)) + { + _mapStorages[nameMapStorage].Clear(); + } + else + { + _mapStorages[nameMapStorage] = new(_pictureWidth, _pictureHeight, map); + } + _mapStorages[nameMapStorage].LoadData(lineData.Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + return true; + } + + /// + /// Загрузка информации по самолетам в ангарах из файла + /// + /// + /// + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader fs = new(filename)) + { + var formatData = fs.ReadLine() ?? string.Empty; + bool isNotMapsCollection = !formatData.Contains("MapsCollection"); + if (formatData.Contains("Map") && isNotMapsCollection) + { + var nameMap = fs.ReadLine().Replace("Name: ", ""); + var elem = fs.ReadLine().Split(separatorDict); + return LoadMap(nameMap, elem[0], elem[1]); + } + if (isNotMapsCollection) + { + //если нет такой записи, то это не те данные + return false; + } + //очищаем записи + _mapStorages.Clear(); + while (!fs.EndOfStream) + { + var elem = fs.ReadLine().Split(separatorDict); + LoadMap(elem[0], elem[1], elem[2]); + } + return true; + } + } } } diff --git a/AirBomber/AirBomber/SetAirplanesGeneric.cs b/AirBomber/AirBomber/SetAirplanesGeneric.cs index fffa285..b044dcc 100644 --- a/AirBomber/AirBomber/SetAirplanesGeneric.cs +++ b/AirBomber/AirBomber/SetAirplanesGeneric.cs @@ -109,5 +109,10 @@ namespace AirBomber } } + + public void Clear() + { + _places.Clear(); + } } }