diff --git a/WarmlyLocomotive/WarmlyLocomotive/DrawningObjectLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/DrawningObjectLocomotive.cs index 4cbcdab..ad0c7d7 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/DrawningObjectLocomotive.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/DrawningObjectLocomotive.cs @@ -30,5 +30,7 @@ namespace WarmlyLocomotive { _locomotive.SetPosition(x, y, width, height); } + public string GetInfo() => _locomotive?.GetDataForSave(); + public static IDrawningObject Create(string data) => new DrawningObjectLocomotive(data.CreateDrawningLocomotive()); } } diff --git a/WarmlyLocomotive/WarmlyLocomotive/ExtentionLocomotive.cs b/WarmlyLocomotive/WarmlyLocomotive/ExtentionLocomotive.cs new file mode 100644 index 0000000..efccd5b --- /dev/null +++ b/WarmlyLocomotive/WarmlyLocomotive/ExtentionLocomotive.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WarmlyLocomotive +{ + internal static class ExtentionLocomotive + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawningLocomotive CreateDrawningLocomotive(this string info) + { + string[] strs = info.Split(_separatorForObject); + if (strs.Length == 3) + { + return new DrawningLocomotive(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + if (strs.Length == 7) + { + return new DrawningWarmlyLocomotive(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningLocomotive drawningLocomotive) + { + var locomotive = drawningLocomotive.Locomotive; + var str = $"{locomotive.Speed}{_separatorForObject}{locomotive.Weight}{_separatorForObject}{locomotive.BodyColor.Name}"; + if (locomotive is not EntityWarmlyLocomotive warmlyLocomotive) + { + return str; + } + return $"{str}{_separatorForObject}{warmlyLocomotive.DopColor.Name}{_separatorForObject}{warmlyLocomotive.Pipe}{_separatorForObject}{warmlyLocomotive.FuelCompartment}{_separatorForObject}{warmlyLocomotive.WarmlyLines}"; + } + } +} diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.Designer.cs b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.Designer.cs index e0342dd..3f38d09 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.Designer.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.Designer.cs @@ -45,9 +45,16 @@ this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox(); this.buttonAddLocomotive = new System.Windows.Forms.Button(); this.pictureBox = new System.Windows.Forms.PictureBox(); + this.menuStrip = 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.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.groupBox.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // groupBox @@ -63,9 +70,9 @@ this.groupBox.Controls.Add(this.maskedTextBoxPosition); this.groupBox.Controls.Add(this.buttonAddLocomotive); this.groupBox.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBox.Location = new System.Drawing.Point(668, 0); + this.groupBox.Location = new System.Drawing.Point(668, 24); this.groupBox.Name = "groupBox"; - this.groupBox.Size = new System.Drawing.Size(200, 629); + this.groupBox.Size = new System.Drawing.Size(200, 605); this.groupBox.TabIndex = 0; this.groupBox.TabStop = false; this.groupBox.Text = "Инструменты"; @@ -140,7 +147,7 @@ this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowDown; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonDown.Location = new System.Drawing.Point(87, 582); + this.buttonDown.Location = new System.Drawing.Point(87, 558); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(30, 30); this.buttonDown.TabIndex = 9; @@ -152,7 +159,7 @@ this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowRight; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonRight.Location = new System.Drawing.Point(123, 582); + this.buttonRight.Location = new System.Drawing.Point(123, 558); this.buttonRight.Name = "buttonRight"; this.buttonRight.Size = new System.Drawing.Size(30, 30); this.buttonRight.TabIndex = 8; @@ -164,7 +171,7 @@ this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowLeft; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonLeft.Location = new System.Drawing.Point(51, 582); + this.buttonLeft.Location = new System.Drawing.Point(51, 558); this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Size = new System.Drawing.Size(30, 30); this.buttonLeft.TabIndex = 7; @@ -176,7 +183,7 @@ this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowUp; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonUp.Location = new System.Drawing.Point(87, 546); + this.buttonUp.Location = new System.Drawing.Point(87, 522); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(30, 30); this.buttonUp.TabIndex = 6; @@ -186,7 +193,7 @@ // buttonShowOnMap // this.buttonShowOnMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonShowOnMap.Location = new System.Drawing.Point(19, 491); + this.buttonShowOnMap.Location = new System.Drawing.Point(19, 467); this.buttonShowOnMap.Name = "buttonShowOnMap"; this.buttonShowOnMap.Size = new System.Drawing.Size(169, 30); this.buttonShowOnMap.TabIndex = 5; @@ -197,7 +204,7 @@ // buttonShowStorage // this.buttonShowStorage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonShowStorage.Location = new System.Drawing.Point(19, 443); + this.buttonShowStorage.Location = new System.Drawing.Point(19, 419); this.buttonShowStorage.Name = "buttonShowStorage"; this.buttonShowStorage.Size = new System.Drawing.Size(169, 30); this.buttonShowStorage.TabIndex = 4; @@ -208,7 +215,7 @@ // buttonRemoveLocomotive // this.buttonRemoveLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonRemoveLocomotive.Location = new System.Drawing.Point(19, 397); + this.buttonRemoveLocomotive.Location = new System.Drawing.Point(19, 373); this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive"; this.buttonRemoveLocomotive.Size = new System.Drawing.Size(169, 30); this.buttonRemoveLocomotive.TabIndex = 3; @@ -219,7 +226,7 @@ // maskedTextBoxPosition // this.maskedTextBoxPosition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 368); + this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 344); this.maskedTextBoxPosition.Mask = "00"; this.maskedTextBoxPosition.Name = "maskedTextBoxPosition"; this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23); @@ -228,7 +235,7 @@ // buttonAddLocomotive // this.buttonAddLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonAddLocomotive.Location = new System.Drawing.Point(19, 332); + this.buttonAddLocomotive.Location = new System.Drawing.Point(19, 308); this.buttonAddLocomotive.Name = "buttonAddLocomotive"; this.buttonAddLocomotive.Size = new System.Drawing.Size(169, 30); this.buttonAddLocomotive.TabIndex = 1; @@ -239,13 +246,53 @@ // 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(668, 629); + this.pictureBox.Size = new System.Drawing.Size(668, 605); this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // + // menuStrip + // + this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.FileToolStripMenuItem}); + this.menuStrip.Location = new System.Drawing.Point(0, 0); + this.menuStrip.Name = "menuStrip"; + this.menuStrip.Size = new System.Drawing.Size(868, 24); + this.menuStrip.TabIndex = 2; + // + // FileToolStripMenuItem + // + this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem}); + 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); + // + // openFileDialog + // + this.openFileDialog.Filter = "txt file|*.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file|*.txt"; + // // FormMapWithSetLocomotives // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -253,6 +300,8 @@ this.ClientSize = new System.Drawing.Size(868, 629); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBox); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; this.Name = "FormMapWithSetLocomotives"; this.Text = "Карта с набором объектов"; this.groupBox.ResumeLayout(false); @@ -260,6 +309,8 @@ 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(); @@ -284,5 +335,11 @@ private ListBox listBoxMaps; private Button buttonAddMap; private TextBox textBoxNewMapName; + private MenuStrip menuStrip; + private ToolStripMenuItem FileToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs index 868365e..e22baef 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs @@ -191,6 +191,11 @@ namespace WarmlyLocomotive MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } + if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';')) + { + MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); } @@ -221,5 +226,45 @@ namespace WarmlyLocomotive ReloadMaps(); } } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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) + { + // TODO продумать логику + if(openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_mapsCollection.LoadData(openFileDialog.FileName)) + { + ReloadMaps(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.resx b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.resx index f298a7b..934ed35 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.resx +++ b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.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/WarmlyLocomotive/WarmlyLocomotive/IDrawningObject.cs b/WarmlyLocomotive/WarmlyLocomotive/IDrawningObject.cs index 7a8d7d1..57e5e4a 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/IDrawningObject.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/IDrawningObject.cs @@ -36,5 +36,10 @@ namespace WarmlyLocomotive /// /// (float Left, float Right, float Top, float Bottom) GetCurrentPosition(); + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } diff --git a/WarmlyLocomotive/WarmlyLocomotive/MapWithSetLocomotivesGeneric.cs b/WarmlyLocomotive/WarmlyLocomotive/MapWithSetLocomotivesGeneric.cs index c5cf58b..ef78bcd 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/MapWithSetLocomotivesGeneric.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/MapWithSetLocomotivesGeneric.cs @@ -108,6 +108,31 @@ namespace WarmlyLocomotive return new(_pictureWidth, _pictureHeight); } /// + /// Получение данных в виде строки + /// + /// + /// + 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 rec in records) + { + _setLocomotives.Insert(DrawningObjectLocomotive.Create(rec) as T); + } + } + /// /// "Взбалтываем" набор, чтобы все элементы оказались в начале /// private void Shaking() diff --git a/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs index 6abc264..9788743 100644 --- a/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs +++ b/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs @@ -14,7 +14,7 @@ namespace WarmlyLocomotive /// /// Словарь (хранилище) с картами /// - readonly Dictionary> _mapStorages; + readonly Dictionary> _mapStorages; /// /// Возвращение списка названий карт /// @@ -28,13 +28,21 @@ namespace WarmlyLocomotive /// private readonly int _pictureHeight; /// + /// Разделитель для записи информации по элементу словаря в файл + /// + private readonly char separatorDict = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char separatorData = ';'; + /// /// Конструктор /// /// /// public MapsCollection(int pictureWidth, int pictureHeight) { - _mapStorages = new Dictionary>(); + _mapStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -47,7 +55,7 @@ namespace WarmlyLocomotive { if (!_mapStorages.ContainsKey(name)) { - _mapStorages.Add(name, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages.Add(name, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); } } /// @@ -62,17 +70,17 @@ namespace WarmlyLocomotive } } /// - /// Доступ к парковке + /// Доступ к депо /// /// /// - public MapWithSetLocomotivesGeneric this[string ind] + public MapWithSetLocomotivesGeneric this[string ind] { get { if (ind != String.Empty) { - MapWithSetLocomotivesGeneric value; + MapWithSetLocomotivesGeneric value; if (_mapStorages.TryGetValue(ind, out value)) { return value; @@ -81,5 +89,80 @@ namespace WarmlyLocomotive return null; } } + /// + /// Сохранение информации по локомотивам в хранилище в файл + /// + /// Путь и имя файла + /// + 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; + } + using (StreamReader sr = new(filename)) + { + bool isFirst = true; + string str; + while((str = sr.ReadLine()) != null) + { + if (isFirst) + { + if (!str.Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + return false; + } + else + { + //очищаем записи + _mapStorages.Clear(); + } + isFirst = false; + } + else + { + var elem = str.Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "BigBarriersMap": + map = new BigBarriersMap(); + break; + case "CirclesMap": + map = new CirclesMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + } + } + return true; + } } }