From 629074b06e78aab8ba6a6da06be7aee73158aa8a Mon Sep 17 00:00:00 2001 From: "[USERNAME]" Date: Sat, 2 Dec 2023 02:06:45 +0400 Subject: [PATCH] Lab6 --- .../Bulldozer/BulldozerGenericCollection.cs | 4 + .../Bulldozer/BulldozersGenericStorage.cs | 101 ++++++++++++++++++ .../Bulldozer/ExtentionDrawningBulldozer.cs | 67 ++++++++++++ .../FormBulldozerCollection.Designer.cs | 62 ++++++++++- .../Bulldozer/FormBulldozerCollection.cs | 44 ++++++++ .../Bulldozer/FormBulldozerCollection.resx | 9 ++ 6 files changed, 286 insertions(+), 1 deletion(-) create mode 100644 Bulldozer/Bulldozer/ExtentionDrawningBulldozer.cs diff --git a/Bulldozer/Bulldozer/BulldozerGenericCollection.cs b/Bulldozer/Bulldozer/BulldozerGenericCollection.cs index a5fece3..f2879f5 100644 --- a/Bulldozer/Bulldozer/BulldozerGenericCollection.cs +++ b/Bulldozer/Bulldozer/BulldozerGenericCollection.cs @@ -13,6 +13,10 @@ namespace Bulldozer.Generics where T : DrawningBulldozer where U : IMoveableObject { + /// + /// Получение объектов коллекции + /// + public IEnumerable GetBulldozer => _collection.GetBulldozer(); /// /// Ширина окна прорисовки /// diff --git a/Bulldozer/Bulldozer/BulldozersGenericStorage.cs b/Bulldozer/Bulldozer/BulldozersGenericStorage.cs index 50800b2..16f47d5 100644 --- a/Bulldozer/Bulldozer/BulldozersGenericStorage.cs +++ b/Bulldozer/Bulldozer/BulldozersGenericStorage.cs @@ -30,6 +30,18 @@ namespace Bulldozer.Generics /// private readonly int _pictureHeight; /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// /// @@ -83,5 +95,94 @@ namespace Bulldozer.Generics return null; } } + /// + /// Сохранение информации по установкам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _tractorStorages) + { + StringBuilder records = new(); + foreach (DrawningBulldozer? elem in record.Value.GetBulldozer) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write($"BulldozerStorage{Environment.NewLine}{data}"); + } + + return true; + } + /// + /// Загрузка информации по установкам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader reader = new StreamReader(filename)) + { + string cheker = reader.ReadLine(); + if (cheker == null) + { + return false; + } + if (!cheker.StartsWith("BulldozerStorage")) + { + return false; + } + _tractorStorages.Clear(); + string strs; + bool firstinit = true; + while ((strs = reader.ReadLine()) != null) + { + if (strs == null && firstinit) + { + return false; + } + if (strs == null) + { + return false; + } + firstinit = false; + string name = strs.Split(_separatorForKeyValue)[0]; + BulldozerGenericCollection collection = new(_pictureWidth, _pictureHeight); + foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords)) + { + DrawningBulldozer? bulldozer = + data?.CreateDrawningBulldozer(_separatorForObject, _pictureWidth, _pictureHeight); + if (bulldozer != null) + { + int? result = collection + bulldozer; + if (result == null || result.Value == -1) + { + return false; + } + } + } + _tractorStorages.Add(name, collection); + } + return true; + } + } } } diff --git a/Bulldozer/Bulldozer/ExtentionDrawningBulldozer.cs b/Bulldozer/Bulldozer/ExtentionDrawningBulldozer.cs new file mode 100644 index 0000000..d4317de --- /dev/null +++ b/Bulldozer/Bulldozer/ExtentionDrawningBulldozer.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Bulldozer.DrawningObjects; +using Bulldozer.Entities; + +namespace Bulldozer +{ + /// + /// Расширение для класса EntityUsta + /// + public static class ExtentionDrawningBulldozer + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningBulldozer? CreateDrawningBulldozer(this string info, char + separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawningBulldozer(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + else if (strs.Length == 6) + { + return new DrawningFastBulldozer(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + Color.FromName(strs[3]), + Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), width, height); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель даннных + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBulldozer drawningBulldozer, + char separatorForBulldozer) + { + var bulldozer = drawningBulldozer.EntityTractor; + if (bulldozer == null) + { + return string.Empty; + } + var str = + $"{bulldozer.Speed}{separatorForBulldozer}{bulldozer.Weight}{separatorForBulldozer}{bulldozer.MainColor.Name}"; + if (bulldozer is not EntityFastBulldozer sportBulldozer) + { + return str; + } + return $"{str}{separatorForBulldozer}{sportBulldozer.OptionalColor.Name}{separatorForBulldozer}{sportBulldozer.Covsh}{separatorForBulldozer}{sportBulldozer.Rearbucket}"; + } + } +} diff --git a/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs b/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs index ede372e..aded9be 100644 --- a/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs +++ b/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs @@ -39,9 +39,16 @@ ButtonDelObject = new Button(); ButtonAddObject = new Button(); textBoxStorageName = new TextBox(); + menuStrip = new MenuStrip(); + FileToolStripMenuItem = new ToolStripMenuItem(); + SaveToolStripMenuItem = new ToolStripMenuItem(); + LoadToolStripMenuItem = new ToolStripMenuItem(); + openFileDialog = new OpenFileDialog(); + saveFileDialog = new SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); groupBox1.SuspendLayout(); groupBox2.SuspendLayout(); + menuStrip.SuspendLayout(); SuspendLayout(); // // ButtonAddBulldozer @@ -100,7 +107,7 @@ groupBox1.Controls.Add(ButtonRefreshCollection); groupBox1.Controls.Add(maskedTextBoxNumber); groupBox1.Controls.Add(ButtonRemoveBulldozer); - groupBox1.Location = new Point(643, 12); + groupBox1.Location = new Point(643, 30); groupBox1.Name = "groupBox1"; groupBox1.Size = new Size(209, 533); groupBox1.TabIndex = 5; @@ -157,6 +164,48 @@ textBoxStorageName.Size = new Size(158, 23); textBoxStorageName.TabIndex = 0; // + // menuStrip + // + menuStrip.Dock = DockStyle.None; + menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem }); + menuStrip.Location = new Point(649, 3); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(176, 24); + menuStrip.TabIndex = 6; + menuStrip.Text = "menuStrip1"; + // + // FileToolStripMenuItem + // + FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem }); + FileToolStripMenuItem.Name = "FileToolStripMenuItem"; + FileToolStripMenuItem.Size = new Size(48, 20); + FileToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.Size = new Size(180, 22); + SaveToolStripMenuItem.Text = "Сохранить"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // LoadToolStripMenuItem + // + LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + LoadToolStripMenuItem.Size = new Size(180, 22); + LoadToolStripMenuItem.Text = "Загрузить"; + LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + openFileDialog.Title = "Сохранить текстовый файл"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + saveFileDialog.Title = "Выберите текстовый файл"; + // // FormBulldozerCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -164,6 +213,8 @@ ClientSize = new Size(867, 584); Controls.Add(groupBox1); Controls.Add(pictureBoxCollection); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBulldozerCollection"; Text = "Набор тракторов"; ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); @@ -171,7 +222,10 @@ groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -187,5 +241,11 @@ private ListBox listBoxStorage; private Button ButtonDelObject; private Button ButtonAddObject; + 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/Bulldozer/Bulldozer/FormBulldozerCollection.cs b/Bulldozer/Bulldozer/FormBulldozerCollection.cs index dd74621..4c91b56 100644 --- a/Bulldozer/Bulldozer/FormBulldozerCollection.cs +++ b/Bulldozer/Bulldozer/FormBulldozerCollection.cs @@ -3,6 +3,7 @@ using Bulldozer.DrawningObjects; using Bulldozer.Drawnings; using Bulldozer.Generics; using Bulldozer.MovementStrategy; +using System.Windows.Forms; namespace Bulldozer { @@ -104,6 +105,7 @@ namespace Bulldozer return; } var formBulldozerConfig = new FormBulldozerConfig(); + formBulldozerConfig.AddEvent(usta => { if (listBoxStorage.SelectedIndex != -1) @@ -123,6 +125,7 @@ namespace Bulldozer } } }); + formBulldozerConfig.Show(); } /// @@ -178,6 +181,47 @@ namespace Bulldozer } pictureBoxCollection.Image = obj.ShowBulldozer(); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.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 (_storage.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Данные успешно загружены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadObjects(); + } + else + { + MessageBox.Show("Ошибка при загрузке данных.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/Bulldozer/Bulldozer/FormBulldozerCollection.resx b/Bulldozer/Bulldozer/FormBulldozerCollection.resx index af32865..f53194e 100644 --- a/Bulldozer/Bulldozer/FormBulldozerCollection.resx +++ b/Bulldozer/Bulldozer/FormBulldozerCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 132, 17 + + + 271, 17 + \ No newline at end of file