diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/DrawningUsta.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/DrawningUsta.cs index 8f5ecf9..8095c73 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/DrawningUsta.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/DrawningUsta.cs @@ -95,7 +95,7 @@ namespace SelfPropelledArtilleryUnit.DrawningObjects public void SetPosition(int x, int y) { // TODO: Изменение x, y, если при установке объект выходит за границы - if (x < 0 || y < 0 || x + _ustaWidth > _pictureWidth || y + _ustaHeight > _pictureHeight) + if (x < 0 || y < 0 ) { x = 10; y = 10; diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/ExtentionDrawningUsta.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/ExtentionDrawningUsta.cs new file mode 100644 index 0000000..6ce5b99 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/ExtentionDrawningUsta.cs @@ -0,0 +1,61 @@ +using SelfPropelledArtilleryUnit.Entities; +namespace SelfPropelledArtilleryUnit.DrawningObjects +{ + /// + /// Расширение для класса EntityUsta + /// + public static class ExtentionDrawningUsta + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningUsta? CreateDrawningUsta(this string info, char + separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawningUsta(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + else if (strs.Length == 6) + { + return new DrawningUstaBat(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 DrawningUsta drawningUsta, + char separatorForUsta) + { + var usta = drawningUsta.EntityUsta; + if (usta == null) + { + return string.Empty; + } + var str = + $"{usta.Speed}{separatorForUsta}{usta.Weight}{separatorForUsta}{usta.BodyColor.Name}"; + if (usta is not EntityUstaBat sportUsta) + { + return str; + } + return $"{str}{separatorForUsta}{sportUsta.AdditionalColor.Name}{separatorForUsta}{sportUsta.BodyKit}{separatorForUsta}{sportUsta.Pushka}"; + } + } +} + diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.Designer.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.Designer.cs index a171aca..3170d81 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.Designer.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.Designer.cs @@ -39,14 +39,21 @@ 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(); // // ButtonAddUsta // - ButtonAddUsta.Location = new Point(26, 314); + ButtonAddUsta.Location = new Point(26, 366); ButtonAddUsta.Name = "ButtonAddUsta"; ButtonAddUsta.Size = new Size(166, 40); ButtonAddUsta.TabIndex = 0; @@ -56,7 +63,7 @@ // // ButtonRemoveUsta // - ButtonRemoveUsta.Location = new Point(26, 400); + ButtonRemoveUsta.Location = new Point(26, 457); ButtonRemoveUsta.Name = "ButtonRemoveUsta"; ButtonRemoveUsta.Size = new Size(166, 39); ButtonRemoveUsta.TabIndex = 1; @@ -66,7 +73,7 @@ // // ButtonRefreshCollection // - ButtonRefreshCollection.Location = new Point(26, 478); + ButtonRefreshCollection.Location = new Point(26, 502); ButtonRefreshCollection.Name = "ButtonRefreshCollection"; ButtonRefreshCollection.Size = new Size(166, 40); ButtonRefreshCollection.TabIndex = 2; @@ -86,7 +93,7 @@ // maskedTextBoxNumber // maskedTextBoxNumber.Font = new Font("Showcard Gothic", 9F, FontStyle.Regular, GraphicsUnit.Point); - maskedTextBoxNumber.Location = new Point(56, 371); + maskedTextBoxNumber.Location = new Point(58, 429); maskedTextBoxNumber.Mask = "00"; maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Size = new Size(100, 22); @@ -100,9 +107,10 @@ groupBox1.Controls.Add(ButtonRefreshCollection); groupBox1.Controls.Add(maskedTextBoxNumber); groupBox1.Controls.Add(ButtonRemoveUsta); + groupBox1.Controls.Add(menuStrip); groupBox1.Location = new Point(643, 12); groupBox1.Name = "groupBox1"; - groupBox1.Size = new Size(209, 533); + groupBox1.Size = new Size(209, 560); groupBox1.TabIndex = 5; groupBox1.TabStop = false; groupBox1.Text = "Инструменты"; @@ -113,7 +121,7 @@ groupBox2.Controls.Add(ButtonDelObject); groupBox2.Controls.Add(ButtonAddObject); groupBox2.Controls.Add(textBoxStorageName); - groupBox2.Location = new Point(6, 22); + groupBox2.Location = new Point(6, 64); groupBox2.Name = "groupBox2"; groupBox2.Size = new Size(197, 274); groupBox2.TabIndex = 6; @@ -157,6 +165,47 @@ textBoxStorageName.Size = new Size(158, 23); textBoxStorageName.TabIndex = 0; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip.Location = new Point(3, 19); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(203, 24); + menuStrip.TabIndex = 7; + 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 = "Выберите текстовый файл"; + // // FormSelfPropelledArtilleryUnitCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -164,6 +213,7 @@ ClientSize = new Size(867, 584); Controls.Add(groupBox1); Controls.Add(pictureBoxCollection); + MainMenuStrip = menuStrip; Name = "FormSelfPropelledArtilleryUnitCollection"; Text = "Набор арт. установок"; ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); @@ -171,6 +221,8 @@ groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); } @@ -187,5 +239,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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs index 0143e21..8858335 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs @@ -131,7 +131,7 @@ namespace SelfPropelledArtilleryUnit formSelfPropelledArtilleryUnitConfig.Show(); } - + /// /// Удаление объекта из набора /// @@ -185,6 +185,50 @@ namespace SelfPropelledArtilleryUnit } pictureBoxCollection.Image = obj.ShowUsta(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.resx b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.resx index af32865..df0e6be 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.resx +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 259, 17 + \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs index a221de8..4de0d4f 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs @@ -13,6 +13,11 @@ namespace SelfPropelledArtilleryUnit.Generics where T : DrawningUsta where U : IMoveableObject { + /// + /// Получение объектов коллекции + /// + public IEnumerable GetUsta => _collection.GetUsta(); + /// /// Ширина окна прорисовки /// diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs index 3c3fac3..cc3fc80 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; +using System.IO; using System.Text; -using System.Threading.Tasks; using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.MovementStrategy; @@ -30,6 +29,18 @@ namespace SelfPropelledArtilleryUnit.Generics /// private readonly int _pictureHeight; /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// /// @@ -84,6 +95,101 @@ namespace SelfPropelledArtilleryUnit.Generics } } + /// + /// Сохранение информации по установкам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _ustaStorages) + { + StringBuilder records = new(); + foreach (DrawningUsta? elem in record.Value.GetUsta) + { + 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($"UstaStorage{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("UstaStorage")) + { + //если нет такой записи, то это не те данные + return false; + } + _ustaStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + UstaGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningUsta? usta = + elem?.CreateDrawningUsta(_separatorForObject, _pictureWidth, _pictureHeight); + if (usta != null) + { + int? result = collection + usta; + if (result == null || result.Value == -1) + { + return false; + } + } + } + _ustaStorages.Add(record[0], collection); + } + return true; + } } }