diff --git a/Bulldozer/Bulldozer/DrawingObjects/ExtentionDrawingBulldozer.cs b/Bulldozer/Bulldozer/DrawingObjects/ExtentionDrawingBulldozer.cs new file mode 100644 index 0000000..6e30586 --- /dev/null +++ b/Bulldozer/Bulldozer/DrawingObjects/ExtentionDrawingBulldozer.cs @@ -0,0 +1,48 @@ +using Bulldozer.Entities; + +namespace Bulldozer.DrawingObjects +{ + public static class ExtentionDrawingBulldozer + { + public static DrawingBulldozer? CreateDrawingBulldozer(this string info, char separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 4) + { + return new DrawingBulldozer(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), Color.FromName(strs[3]), width, height); + } + if (strs.Length == 7) + { + return new DrawingBulldozerUpgraded(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + Color.FromName(strs[3]), + Color.FromName(strs[4]), + Convert.ToBoolean(strs[5]), + Convert.ToBoolean(strs[6]), width, height); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель даннных + /// Строка с данными по объекту + public static string GetDataForSave(this DrawingBulldozer drawingBulldozer, char separatorForObject) + { + var bulldozer = drawingBulldozer.EntityBulldozer; + if (bulldozer == null) + { + return string.Empty; + } + var str = $"{bulldozer.Speed}{separatorForObject}{bulldozer.Weight}{separatorForObject}{bulldozer.BodyColor.Name}{separatorForObject}{bulldozer.AdditionalColor.Name}"; + if (bulldozer is not EntityBulldozerUpgraded bulldozerUpgraded) + { + return str; + } + return $"{str}{separatorForObject}{bulldozerUpgraded.DopColor.Name}{separatorForObject}{bulldozerUpgraded.Ripper}{separatorForObject}{bulldozerUpgraded.Blade}"; + } + } +} diff --git a/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs b/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs index a784a61..9ecba64 100644 --- a/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs +++ b/Bulldozer/Bulldozer/FormBulldozerCollection.Designer.cs @@ -39,9 +39,16 @@ this.buttonUpdateColletion = new System.Windows.Forms.Button(); this.buttonDeleteBulldozer = new System.Windows.Forms.Button(); this.buttonAddBulldozer = new System.Windows.Forms.Button(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); + 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(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); this.panelTools.SuspendLayout(); this.groupListBulldozersBox.SuspendLayout(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // pictureBoxCollection @@ -163,12 +170,56 @@ this.buttonAddBulldozer.UseVisualStyleBackColor = true; this.buttonAddBulldozer.Click += new System.EventHandler(this.buttonAddBulldozer_Click); // + // openFileDialog + // + this.openFileDialog.FileName = "openFileDialog"; + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // + // menuStrip + // + this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); + 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(1110, 28); + this.menuStrip.TabIndex = 2; + this.menuStrip.Text = "menuStrip"; + // + // toolStripMenuItem + // + this.toolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem}); + this.toolStripMenuItem.Name = "toolStripMenuItem"; + this.toolStripMenuItem.Size = new System.Drawing.Size(59, 24); + this.toolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.SaveToolStripMenuItem.Text = "Сохранить"; + this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); + // + // LoadToolStripMenuItem + // + this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.LoadToolStripMenuItem.Text = "Загрузить"; + this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); + // // FormBulldozerCollection // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1110, 793); this.Controls.Add(this.panelTools); + this.Controls.Add(this.menuStrip); this.Controls.Add(this.pictureBoxCollection); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.Name = "FormBulldozerCollection"; @@ -178,7 +229,10 @@ this.panelTools.PerformLayout(); this.groupListBulldozersBox.ResumeLayout(false); this.groupListBulldozersBox.PerformLayout(); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); this.ResumeLayout(false); + this.PerformLayout(); } @@ -195,5 +249,11 @@ private GroupBox groupListBulldozersBox; private Button buttonDeleteBulldozersList; private Button buttonAddBulldozersList; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; + private MenuStrip menuStrip; + private ToolStripMenuItem toolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; } } \ No newline at end of file diff --git a/Bulldozer/Bulldozer/FormBulldozerCollection.cs b/Bulldozer/Bulldozer/FormBulldozerCollection.cs index f498020..38d1a6f 100644 --- a/Bulldozer/Bulldozer/FormBulldozerCollection.cs +++ b/Bulldozer/Bulldozer/FormBulldozerCollection.cs @@ -1,6 +1,7 @@ using Bulldozer.DrawingObjects; using Bulldozer.Generics; using Bulldozer.MovementStrategy; +using System.Windows.Forms; namespace Bulldozer @@ -12,7 +13,7 @@ namespace Bulldozer /// private readonly BulldozersGenericStorage _storage; - + public FormBulldozerCollection() { InitializeComponent(); @@ -90,13 +91,14 @@ namespace Bulldozer /// /// /// + private void buttonAddBulldozer_Click(object sender, EventArgs e) { if (listBoxBulldozerStorages.SelectedIndex == -1) { - MessageBox.Show("Выберите набор в списке.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + MessageBox.Show("Выберите набор в списке.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } var formBulldozerConfig = new FormBulldozerConfig(); formBulldozerConfig.AddEvent(AddBulldozer); @@ -176,5 +178,46 @@ namespace Bulldozer } pictureBoxCollection.Image = obj.ShowBulldozers(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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 f298a7b..860e1db 100644 --- a/Bulldozer/Bulldozer/FormBulldozerCollection.resx +++ b/Bulldozer/Bulldozer/FormBulldozerCollection.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 184, 17 + + + 338, 17 + \ No newline at end of file diff --git a/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs b/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs index 31c227c..4e6e5b9 100644 --- a/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs +++ b/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs @@ -7,6 +7,10 @@ namespace Bulldozer.Generics where T : DrawingBulldozer where U : IMoveableObject { + /// + /// Получение объектов коллекции + /// + public IEnumerable GetBulldozers => _collection.GetBulldozers(); /// /// Ширина окна прорисовки /// @@ -141,7 +145,7 @@ namespace Bulldozer.Generics return; } } - } + } } diff --git a/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs b/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs index 41934ac..f6c3a31 100644 --- a/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs +++ b/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs @@ -1,5 +1,6 @@ using Bulldozer.DrawingObjects; using Bulldozer.MovementStrategy; +using System.Text; namespace Bulldozer.Generics { @@ -66,12 +67,10 @@ namespace Bulldozer.Generics /// /// /// - public BulldozersGenericCollection? - this[string ind] + public BulldozersGenericCollection ? this[string ind] { get { - // TODO: Продумать логику получения набора if (_bulldozerStorages.ContainsKey(ind)) { return _bulldozerStorages[ind]; @@ -82,6 +81,104 @@ namespace Bulldozer.Generics } } } - } + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _bulldozerStorages) + { + StringBuilder records = new(); + foreach (DrawingBulldozer? elem in record.Value.GetBulldozers) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes($"BulldozerStorage{Environment.NewLine}{data}"); + fs.Write(info, 0, info.Length); + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].StartsWith("BulldozerStorage")) + { + return false; + } + _bulldozerStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + BulldozersGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + + foreach (string elem in set) + { + DrawingBulldozer? bulldozer = elem?.CreateDrawingBulldozer(_separatorForObject, _pictureWidth, _pictureHeight); + if (bulldozer != null) + { + if ((collection + bulldozer) == -1) + { + return false; + } + } + } + _bulldozerStorages.Add(record[0], collection); + } + return true; + } + } }