diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningEllipseOrnament.cs b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningEllipseOrnament.cs index d3633d4..e3580b2 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningEllipseOrnament.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningEllipseOrnament.cs @@ -6,6 +6,10 @@ public int WheelsNum { + get + { + return (int)wheelsNumber; + } set { if (value < 2 || value > 4) diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningObjectLocomotive.cs b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningObjectLocomotive.cs index 02c9c82..097173b 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningObjectLocomotive.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningObjectLocomotive.cs @@ -30,6 +30,7 @@ { _locomotive.DrawTransport(g); } - + public string GetInfo() => _locomotive?.GetDataForSave(); + public static IDrawningObject Create(string data) => new DrawningObjectLocomotive(data.CreateDrawningLocomotive()); } } diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningRectOrnament.cs b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningRectOrnament.cs index e6189ea..7a8ee24 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningRectOrnament.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningRectOrnament.cs @@ -6,6 +6,10 @@ public int WheelsNum { + get + { + return (int)wheelsNumber; + } set { if (value < 2 || value > 4) diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningWheels.cs b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningWheels.cs index 552ed41..32aee4d 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/DrawningWheels.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/DrawningWheels.cs @@ -6,6 +6,10 @@ public int WheelsNum { + get + { + return (int)wheelsNumber; + } set { if (value < 2 || value > 4) diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/ExtentionLocomotive.cs b/LocomotivesAdvanced/LocomotivesAdvanced/ExtentionLocomotive.cs new file mode 100644 index 0000000..849dfaf --- /dev/null +++ b/LocomotivesAdvanced/LocomotivesAdvanced/ExtentionLocomotive.cs @@ -0,0 +1,64 @@ +namespace WarmlyLocomotove +{ + /// + /// Расширение для класса DrawningLocomotive + /// + internal static class ExtentionLocomotive + { + /// + /// Разделитель для записи информации + /// + private static readonly char _separatorForObject = ':'; + /// + /// Получаем данные для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningLocomotive drawningLocomotive) + { + var locomotive = drawningLocomotive.Locomotive; + var str = $"{locomotive.Speed}{_separatorForObject}{locomotive.Weight}{_separatorForObject}{locomotive.BodyColor.Name}{_separatorForObject}{drawningLocomotive.AdditionalElements.WheelsNum}{_separatorForObject}{drawningLocomotive.AdditionalElements.GetType().Name}"; + if (locomotive is not EntityWarmlyLocomotive warmlyLocomotive) + { + return str; + } + return $"{str}{_separatorForObject}{warmlyLocomotive.AdditionalColor.Name}{_separatorForObject}{warmlyLocomotive.HasPipe}{_separatorForObject}{warmlyLocomotive.HasFuelTank}"; + } + /// + /// Восстанавливаем объект по полученной из файла информации + /// + /// + /// + public static DrawningLocomotive CreateDrawningLocomotive(this string info) + { + string[] strs = info.Split(_separatorForObject); + DrawningLocomotive recreatedLocomotive = null; + if (strs.Length == 5) + { + recreatedLocomotive = new DrawningLocomotive(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + if (strs.Length == 8) + { + recreatedLocomotive = new DrawningWarmlyLocomotive + ( + Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), 160, 85, + Color.FromName(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]) + ); + } + switch (strs[4]) + { + case "DrawningWheels": + recreatedLocomotive.AdditionalElements = new DrawningWheels(); + break; + case "DrawningRectOrnament": + recreatedLocomotive.AdditionalElements = new DrawningRectOrnament(); + break; + case "DrawningEllipseOrnament": + recreatedLocomotive.AdditionalElements = new DrawningEllipseOrnament(); + break; + } + recreatedLocomotive.AdditionalElements.WheelsNum = Convert.ToInt32(strs[3]); + return recreatedLocomotive; + } + } +} diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.Designer.cs b/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.Designer.cs index 97f53b8..dd852d1 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.Designer.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.Designer.cs @@ -29,6 +29,7 @@ private void InitializeComponent() { this.groupBoxTools = new System.Windows.Forms.GroupBox(); + this.buttonShowLastRemovedObject = new System.Windows.Forms.Button(); this.groupBoxMaps = new System.Windows.Forms.GroupBox(); this.buttonDeleteMap = new System.Windows.Forms.Button(); this.listBoxMaps = new System.Windows.Forms.ListBox(); @@ -45,10 +46,18 @@ this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox(); this.buttonAddCar = new System.Windows.Forms.Button(); this.pictureBoxLocomotives = new System.Windows.Forms.PictureBox(); - this.buttonShowLastRemovedObject = new System.Windows.Forms.Button(); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.saveSelectedMapToolstripmenu = new System.Windows.Forms.ToolStripMenuItem(); + this.loadMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.groupBoxTools.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocomotives)).BeginInit(); + this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // groupBoxTools @@ -72,6 +81,16 @@ this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Инструменты"; // + // buttonShowLastRemovedObject + // + this.buttonShowLastRemovedObject.Location = new System.Drawing.Point(31, 517); + this.buttonShowLastRemovedObject.Name = "buttonShowLastRemovedObject"; + this.buttonShowLastRemovedObject.Size = new System.Drawing.Size(164, 40); + this.buttonShowLastRemovedObject.TabIndex = 2; + this.buttonShowLastRemovedObject.Text = "Показать последний удалённый элемент"; + this.buttonShowLastRemovedObject.UseVisualStyleBackColor = true; + this.buttonShowLastRemovedObject.Click += new System.EventHandler(this.ButtonShowLastRemovedObject_Click); + // // groupBoxMaps // this.groupBoxMaps.Anchor = System.Windows.Forms.AnchorStyles.Right; @@ -242,21 +261,69 @@ this.pictureBoxLocomotives.TabIndex = 1; this.pictureBoxLocomotives.TabStop = false; // - // buttonShowLastRemovedObject + // menuStrip1 // - this.buttonShowLastRemovedObject.Location = new System.Drawing.Point(31, 517); - this.buttonShowLastRemovedObject.Name = "buttonShowLastRemovedObject"; - this.buttonShowLastRemovedObject.Size = new System.Drawing.Size(164, 40); - this.buttonShowLastRemovedObject.TabIndex = 2; - this.buttonShowLastRemovedObject.Text = "Показать последний удалённый элемент"; - this.buttonShowLastRemovedObject.UseVisualStyleBackColor = true; - this.buttonShowLastRemovedObject.Click += new System.EventHandler(this.ButtonShowLastRemovedObject_Click); + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.FileToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(464, 24); + this.menuStrip1.TabIndex = 3; + this.menuStrip1.Text = "menuStrip"; + // + // FileToolStripMenuItem + // + this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem, + this.saveSelectedMapToolstripmenu, + this.loadMapToolStripMenuItem}); + this.FileToolStripMenuItem.Name = "FileToolStripMenuItem"; + this.FileToolStripMenuItem.Size = new System.Drawing.Size(48, 20); + this.FileToolStripMenuItem.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); + // + // saveSelectedMapToolstripmenu + // + this.saveSelectedMapToolstripmenu.Name = "saveSelectedMapToolstripmenu"; + this.saveSelectedMapToolstripmenu.Size = new System.Drawing.Size(180, 22); + this.saveSelectedMapToolstripmenu.Text = "Сохранить карту"; + this.saveSelectedMapToolstripmenu.Click += new System.EventHandler(this.SaveSelectedMapToolStripMenu_Click); + // + // loadMapToolStripMenuItem + // + this.loadMapToolStripMenuItem.Name = "loadMapToolStripMenuItem"; + this.loadMapToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.loadMapToolStripMenuItem.Text = "Загрузить карту"; + this.loadMapToolStripMenuItem.Click += new System.EventHandler(this.LoadMapToolStripMenu_Click); + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file|*.txt"; + // + // openFileDialog + // + this.openFileDialog.Filter = "txt file|*.txt"; // // FormMapWithSetLocomotives // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(687, 760); + this.Controls.Add(this.menuStrip1); this.Controls.Add(this.pictureBoxLocomotives); this.Controls.Add(this.groupBoxTools); this.Name = "FormMapWithSetLocomotives"; @@ -266,7 +333,10 @@ this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocomotives)).EndInit(); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); this.ResumeLayout(false); + this.PerformLayout(); } @@ -290,5 +360,13 @@ private Button buttonAddMap; private TextBox textBoxNewMapName; private Button buttonShowLastRemovedObject; + private MenuStrip menuStrip1; + private ToolStripMenuItem FileToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; + private ToolStripMenuItem saveSelectedMapToolstripmenu; + private ToolStripMenuItem loadMapToolStripMenuItem; } } \ No newline at end of file diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.cs b/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.cs index 9434ce4..e750c56 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.cs @@ -235,5 +235,91 @@ formWithLastRemovedObject.Draw(); _mapsCollection.RemoveLastObject(); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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); + } + } + } + /// + /// Обработка нажатия "Сохранить выбранную карту" + /// + /// + /// + private void SaveSelectedMapToolStripMenu_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_mapsCollection.SaveMap(saveFileDialog.FileName, listBoxMaps.SelectedItem?.ToString() ?? string.Empty)) + { + MessageBox.Show("Сохранение карты прошло успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Карта не сохранилась", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + /// + /// Обработка нажатия "Загрузить карту" + /// + /// + /// + private void LoadMapToolStripMenu_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_mapsCollection.LoadMap(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); + } + else + { + MessageBox.Show("Не удалось загрузить файл", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.resx b/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.resx index f298a7b..548a037 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.resx +++ b/LocomotivesAdvanced/LocomotivesAdvanced/FormMapWithSetLocomotives.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 265, 17 + + + 132, 17 + \ No newline at end of file diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningAdditionalElements.cs b/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningAdditionalElements.cs index 968e2f7..f0a6c3a 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningAdditionalElements.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningAdditionalElements.cs @@ -8,7 +8,7 @@ /// /// Свойство получения количества колёс /// - public int WheelsNum { set; } + public int WheelsNum { get; set; } /// /// Отрисовка колёс /// diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningObject.cs b/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningObject.cs index aba66f1..c0eb361 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningObject.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/IDrawningObject.cs @@ -32,5 +32,10 @@ /// /// (float Top, float Bottom, float Left, float Right) GetCurrentPosition(); + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/MapWithSetLocomotivesGeneric.cs b/LocomotivesAdvanced/LocomotivesAdvanced/MapWithSetLocomotivesGeneric.cs index e8530a6..2a4cf40 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/MapWithSetLocomotivesGeneric.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/MapWithSetLocomotivesGeneric.cs @@ -178,5 +178,39 @@ CurrentLocomotiveNumber++; } } + /// + /// Получение данных в виде строки + /// + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + //Получаем название карты + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var locomotive in _setLocomotives.GetLocomotives()) + { + data += $"{locomotive.GetInfo()}{separatorData}"; + } + return data; + } + /// + /// Загрузка списка из массива строк + /// + /// + public void LoadData(string[] records) + { + foreach (var record in records) + { + _setLocomotives.Insert(DrawningObjectLocomotive.Create(record) as T, 0); + } + } + /// + /// Очистка содержимого карты + /// + public void ClearObjectCollection() + { + _setLocomotives.ClearLocomotives(); + } } } diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/MapsCollection.cs b/LocomotivesAdvanced/LocomotivesAdvanced/MapsCollection.cs index 3394c2c..4f16402 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/MapsCollection.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/MapsCollection.cs @@ -22,6 +22,14 @@ /// private readonly int _pictureHeight; /// + /// Разделитель для записи информации по элементу словаря в файл + /// + private readonly char separatorDict = '|'; + /// + /// Разделитель для записи коллекции данных в файл + /// + private readonly char separatorData = ';'; + /// /// Конструктор /// /// @@ -45,6 +53,62 @@ _mapStorages.Add(name, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); } } + public bool SaveMap(string filename, string maptosave) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter sw = new(filename)) + { + sw.Write("Map\n"); + sw.Write(maptosave + "\n"); + sw.Write($"{_mapStorages[maptosave].GetData(separatorDict, separatorData)}"); + sw.Close(); + } + return true; + } + public bool LoadMap(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader sr = new(filename)) + { + string firstStr = sr.ReadLine(); + if (firstStr == null || !firstStr.Contains("Map")) + { + return false; + } + string mapName = sr.ReadLine(); + string mapInfo = sr.ReadLine(); + AbstractMap newMap = null; + var info = mapInfo.Split(separatorDict); + switch (info[0]) + { + case "SimpleMap": + newMap = new SimpleMap(); + break; + case "CrossMap": + newMap = new CrossMap(); + break; + case "RoadsMap": + newMap = new RoadsMap(); + break; + } + if (_mapStorages.ContainsKey(mapName)) + { + _mapStorages[mapName].ClearObjectCollection(); + } + else + { + _mapStorages.Add(mapName, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, newMap)); + } + _mapStorages[mapName].LoadData(info[1].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + return true; + } /// /// Удаление карты /// @@ -115,6 +179,61 @@ { _removedObjects.RemoveLast(); } + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter sw = new(filename)) + { + sw.Write("MapsCollection\n"); + foreach (var storage in _mapStorages) + { + sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}\n"); + } + sw.Close(); + } + return true; + } + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader sr = new(filename)) + { + string firstStr = sr.ReadLine(); + if (firstStr == null || !firstStr.Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + return false; + } + string? currentString; + while ((currentString = sr.ReadLine()) != null) + { + var elem = currentString.Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "CrossMap": + map = new CrossMap(); + break; + case "RoadsMap": + map = new RoadsMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + sr.Close(); + return true; + } + } } } diff --git a/LocomotivesAdvanced/LocomotivesAdvanced/SetLocomotivesGeneric.cs b/LocomotivesAdvanced/LocomotivesAdvanced/SetLocomotivesGeneric.cs index 96751a6..56d6144 100644 --- a/LocomotivesAdvanced/LocomotivesAdvanced/SetLocomotivesGeneric.cs +++ b/LocomotivesAdvanced/LocomotivesAdvanced/SetLocomotivesGeneric.cs @@ -97,5 +97,12 @@ } } } + /// + /// Очистка списка объектов + /// + public void ClearLocomotives() + { + _places.Clear(); + } } }