diff --git a/RoadTrain/RoadTrain/DrawningObjectRoadTrain.cs b/RoadTrain/RoadTrain/DrawningObjectRoadTrain.cs index e2bf95f..0c47a96 100644 --- a/RoadTrain/RoadTrain/DrawningObjectRoadTrain.cs +++ b/RoadTrain/RoadTrain/DrawningObjectRoadTrain.cs @@ -30,5 +30,9 @@ { _roadTrain.DrawTransport(g); } + + public string GetInfo() => _roadTrain?.GetDataForSave(); + + public static IDrawningObject Create(string data) => new DrawningObjectRoadTrain(data.CreateDrawningRoadTrain()); } } diff --git a/RoadTrain/RoadTrain/ExtentionRoadTrain.cs b/RoadTrain/RoadTrain/ExtentionRoadTrain.cs new file mode 100644 index 0000000..b35bc0e --- /dev/null +++ b/RoadTrain/RoadTrain/ExtentionRoadTrain.cs @@ -0,0 +1,58 @@ +namespace RoadTrain +{ + /// + /// Расширение для класса DrawningRoadTrain + /// + internal static class ExtentionRoadTrain + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawningRoadTrain CreateDrawningRoadTrain(this string info) + { + string[] strs = info.Split(_separatorForObject); + + if (strs.Length == 3) + { + return new DrawningRoadTrain(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + + if (strs.Length == 6) + { + return new DrawningSweeperRoadTrain(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 DrawningRoadTrain drawningRoadTrain) + { + var roadTrain = drawningRoadTrain.RoadTrain; + var str = $"{roadTrain.Speed}{_separatorForObject}{roadTrain.Weight}" + + $"{_separatorForObject}{roadTrain.BodyColor. Name}"; + + if (roadTrain is not EntitySweeperRoadTrain sweeperRoadTrain) + { + return str; + } + + return $"{str}{_separatorForObject}{sweeperRoadTrain.DopColor.Name}{_separatorForObject}" + + $"{sweeperRoadTrain.WaterTank}{_separatorForObject}{sweeperRoadTrain.SweepingBush}"; + } + } +} diff --git a/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.Designer.cs b/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.Designer.cs index a63e02d..6f8efce 100644 --- a/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.Designer.cs +++ b/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.Designer.cs @@ -45,16 +45,22 @@ this.buttonShowStorage = new System.Windows.Forms.Button(); this.buttonRemoveRoadTrain = new System.Windows.Forms.Button(); this.buttonAddRoadTrain = new System.Windows.Forms.Button(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.groupBox.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); + this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // pictureBox // - this.pictureBox.Location = new System.Drawing.Point(3, 3); + this.pictureBox.Location = new System.Drawing.Point(3, 27); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(644, 445); + this.pictureBox.Size = new System.Drawing.Size(644, 421); this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; // @@ -240,6 +246,40 @@ this.buttonAddRoadTrain.UseVisualStyleBackColor = true; this.buttonAddRoadTrain.Click += new System.EventHandler(this.ButtonAddRoadTrain_Click); // + // openFileDialog + // + this.openFileDialog.FileName = "openFileDialog1"; + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(831, 24); + this.menuStrip1.TabIndex = 2; + this.menuStrip1.Text = "menuStrip1"; + // + // SaveToolStripMenuItem + // + this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(86, 20); + this.SaveToolStripMenuItem.Text = "Сохранение"; + this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); + // + // LoadToolStripMenuItem + // + this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(67, 20); + this.LoadToolStripMenuItem.Text = "Загрузка"; + this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); + // // FormMapWithSetRoadTrains // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -247,6 +287,8 @@ this.ClientSize = new System.Drawing.Size(831, 450); this.Controls.Add(this.groupBox); this.Controls.Add(this.pictureBox); + this.Controls.Add(this.menuStrip1); + this.MainMenuStrip = this.menuStrip1; this.Name = "FormMapWithSetRoadTrains"; this.Text = "Карта с набором объектов"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); @@ -254,7 +296,11 @@ this.groupBox.PerformLayout(); this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.PerformLayout(); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); this.ResumeLayout(false); + this.PerformLayout(); + } #endregion @@ -276,5 +322,10 @@ private Button buttonRemoveMap; private ListBox listBoxMaps; private TextBox textBoxNewMapName; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; + private MenuStrip menuStrip1; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; } } \ No newline at end of file diff --git a/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.cs b/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.cs index 7487ecc..396de92 100644 --- a/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.cs +++ b/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.cs @@ -1,4 +1,6 @@ -namespace RoadTrain +using static System.Net.Mime.MediaTypeNames; + +namespace RoadTrain { public partial class FormMapWithSetRoadTrains : Form { @@ -231,5 +233,46 @@ } 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) + { + if (_mapsCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Ошибка загрузки", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + ReloadMaps(); + } } } diff --git a/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.resx b/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.resx index 1af7de1..4092092 100644 --- a/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.resx +++ b/RoadTrain/RoadTrain/FormMapWithSetRoadTrains.resx @@ -1,64 +1,4 @@ - - - + @@ -117,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 157, 17 + + + 286, 17 + \ No newline at end of file diff --git a/RoadTrain/RoadTrain/IDrawningObject.cs b/RoadTrain/RoadTrain/IDrawningObject.cs index 8d87cef..57e5aa6 100644 --- a/RoadTrain/RoadTrain/IDrawningObject.cs +++ b/RoadTrain/RoadTrain/IDrawningObject.cs @@ -33,5 +33,11 @@ /// /// (float Left, float Top, float Right, float Bottom) GetCurrentPosition(); + + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } diff --git a/RoadTrain/RoadTrain/MapWithSetRoadTrainsGeneric.cs b/RoadTrain/RoadTrain/MapWithSetRoadTrainsGeneric.cs index a0fb24f..d92ef94 100644 --- a/RoadTrain/RoadTrain/MapWithSetRoadTrainsGeneric.cs +++ b/RoadTrain/RoadTrain/MapWithSetRoadTrainsGeneric.cs @@ -188,5 +188,32 @@ j++; } } + + /// + /// Получение данных в виде строки + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var roadTrain in _setRoadTrains.GetRoadTrains()) + { + data += $"{roadTrain.GetInfo()}{separatorData}"; + } + return data; + } + + /// + /// Загрузка списка из массива строк + /// + /// + public void LoadData(string[] records) + { + foreach (var rec in records) + { + _setRoadTrains.Insert(DrawningObjectRoadTrain.Create(rec) as T); + } + } } } diff --git a/RoadTrain/RoadTrain/MapsCollection.cs b/RoadTrain/RoadTrain/MapsCollection.cs index 72243da..5327baf 100644 --- a/RoadTrain/RoadTrain/MapsCollection.cs +++ b/RoadTrain/RoadTrain/MapsCollection.cs @@ -1,4 +1,6 @@ -namespace RoadTrain +using System.Text; + +namespace RoadTrain { /// /// Класс для хранения коллекции карт @@ -8,7 +10,7 @@ /// /// Словарь (хранилище) с картами /// - readonly Dictionary> _mapStorages; + readonly Dictionary> _mapStorages; /// /// Возвращение списка названий карт @@ -25,6 +27,16 @@ /// private readonly int _pictureHeight; + /// + /// Знак-разделитель для карт + /// + private readonly char separatorDict = '|'; + + /// + /// Знак-разделитель для объектов + /// + private readonly char separatorData = ';'; + /// /// Конструктор /// @@ -32,7 +44,7 @@ /// public MapsCollection(int pictureWidth, int pictureHeight) { - _mapStorages = new Dictionary>(); + _mapStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -51,7 +63,7 @@ } else { - _mapStorages.Add(name, new MapWithSetRoadTrainsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages.Add(name, new MapWithSetRoadTrainsGeneric(_pictureWidth, _pictureHeight, map)); } } @@ -69,7 +81,7 @@ /// /// /// - public MapWithSetRoadTrainsGeneric this[string ind] + public MapWithSetRoadTrainsGeneric this[string ind] { get { @@ -78,5 +90,78 @@ return null; } } + + /// + /// Метод записи информации в файл + /// + /// Строка, которую следует записать + /// Поток для записи + 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 (StreamWriter sw = new(filename)) + { + sw.Write($"MapsCollection{Environment.NewLine}"); + foreach (var storage in _mapStorages) + { + sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); + } + } + return true; + } + + /// + /// Загрузка нформации по грузовикам на парковках из файла + /// + /// + /// + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + string bufferTextFromFile = ""; + using (StreamReader sr = new(filename)) + { + string str = ""; + if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) + { + return false; + } + _mapStorages.Clear(); + while ((str = sr.ReadLine()) != null) + { + var elem = str.Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "RoadMap": + map = new RoadMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetRoadTrainsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + } + return true; + } } }