diff --git a/ProjectSeaplane/ProjectSeaplane/DrawingPlane.cs b/ProjectSeaplane/ProjectSeaplane/DrawingPlane.cs index 7abbd97..ab61751 100644 --- a/ProjectSeaplane/ProjectSeaplane/DrawingPlane.cs +++ b/ProjectSeaplane/ProjectSeaplane/DrawingPlane.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using ProjectSeaplane.Entities; using ProjectSeaplane.MovementStrategy; using static ProjectSeaplane.Direction; + namespace ProjectSeaplane.DrawningObjects { /// diff --git a/ProjectSeaplane/ProjectSeaplane/ExtentionPlane.cs b/ProjectSeaplane/ProjectSeaplane/ExtentionPlane.cs new file mode 100644 index 0000000..9ee4d4f --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/ExtentionPlane.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectSeaplane.Entities; + +namespace ProjectSeaplane.DrawningObjects +{ + /// + /// Расширение для класса EntityPlane + /// + public static class ExtentionDrawningPlane + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningPlane? CreateDrawningPlane(this string info, char + separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawningPlane(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + if (strs.Length == 6) + { + return new DrawningSeaplane(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 DrawningPlane drawningPlane, + char separatorForObject) + { + var plane = drawningPlane.EntityPlane; + if (plane == null) + { + return string.Empty; + } + var str = + $"{plane.Speed}{separatorForObject}{plane.Weight}{separatorForObject}{plane.BodyColor.Name}"; + if (plane is not EntitySeaplane seaplane) + { + return str; + } + return + $"{str}{separatorForObject}{seaplane.AdditionalColor.Name}{separatorForObject}{seaplane.Boat}{separatorForObject}{seaplane.Floater}"; + } + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs index a907cf0..60fe1f7 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs @@ -39,15 +39,22 @@ buttonRemovePlane = new Button(); maskedTextBoxNumber = new MaskedTextBox(); buttonAddPlane = new Button(); + 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(); // // pictureBoxCollection // pictureBoxCollection.Dock = DockStyle.Fill; - pictureBoxCollection.Location = new Point(0, 0); + pictureBoxCollection.Location = new Point(0, 24); pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Size = new Size(1026, 446); pictureBoxCollection.TabIndex = 1; @@ -154,13 +161,54 @@ buttonAddPlane.UseVisualStyleBackColor = true; buttonAddPlane.Click += buttonAddPlane_Click; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1026, 24); + menuStrip.TabIndex = 3; + 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"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1026, 446); + ClientSize = new Size(1026, 470); Controls.Add(groupBox1); Controls.Add(pictureBoxCollection); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormPlaneCollection"; Text = "Набор самолетов"; ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); @@ -168,7 +216,10 @@ groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -184,5 +235,11 @@ private ListBox listBoxStorages; private Button buttonAddObject; private TextBox textBoxStorageName; + 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/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs index 5a0dd88..df976d8 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs @@ -96,7 +96,7 @@ namespace ProjectSeaplane ReloadObjects(); } } - + /// /// Добавление объекта в набор @@ -115,8 +115,9 @@ namespace ProjectSeaplane return; } FormPlaneConfig form = new FormPlaneConfig(); - - Action? planeDelegate = new((m) => { + + Action? planeDelegate = new((m) => + { bool q = (obj + m); if (q) { @@ -184,5 +185,51 @@ namespace ProjectSeaplane pictureBoxCollection.Image = obj.ShowPlanes(); } } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + + 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)) + { + ReloadObjects(); + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } } diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx index f298a7b..943d36f 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 132, 17 + + + 272, 17 + \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.Designer.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.Designer.cs index 82fe3a0..bcfecb9 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.Designer.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.Designer.cs @@ -156,7 +156,7 @@ // // panelBlue // - panelBlue.BackColor = Color.FromArgb(0, 0, 192); + panelBlue.BackColor = Color.Blue; panelBlue.Location = new Point(134, 22); panelBlue.Name = "panelBlue"; panelBlue.Size = new Size(45, 45); @@ -172,7 +172,7 @@ // // panelGreen // - panelGreen.BackColor = Color.FromArgb(0, 192, 0); + panelGreen.BackColor = Color.Green; panelGreen.Location = new Point(68, 22); panelGreen.Name = "panelGreen"; panelGreen.Size = new Size(45, 45); diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.resx b/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.resx index f298a7b..af32865 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.resx +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneConfig.resx @@ -1,4 +1,64 @@ - + + + diff --git a/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs b/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs index 7c000d2..224e37e 100644 --- a/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/PlanesGenericCollection.cs @@ -12,6 +12,10 @@ namespace ProjectSeaplane.Generics where T : DrawningPlane where U : IMoveableObject { + /// + /// Получение объектов коллекции + /// + public IEnumerable GetPlanes => _collection.GetPlanes(); /// /// Ширина окна прорисовки /// diff --git a/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs b/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs index fc37b49..36df8ed 100644 --- a/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs +++ b/ProjectSeaplane/ProjectSeaplane/PlanesGenericStorage.cs @@ -6,11 +6,117 @@ using System.Threading.Tasks; using ProjectSeaplane.DrawningObjects; using ProjectSeaplane.MovementStrategy; using ProjectSeaplane.Generics; +using System.IO; namespace ProjectSeaplane.Generics { internal class PlanesGenericStorage { + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + 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 _planeStorages) + { + StringBuilder records = new(); + foreach (DrawningPlane? elem in record.Value.GetPlanes) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + using (StreamWriter writer = new StreamWriter(filename, false)) + { + writer.WriteLine("PlaneStorage"); + writer.Write(data.ToString()); + } + + 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("PlaneStorage")) + { + return false; + } + _planeStorages.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]; + PlanesGenericCollection collection = new(_pictureWidth, _pictureHeight); + foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords)) + { + DrawningPlane? plane = + data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight); + if (plane != null) + { + if (!(collection + plane)) + { + return false; + } + } + } + _planeStorages.Add(name, collection); + } + return true; + } + } + readonly Dictionary> _planeStorages; public List Keys => _planeStorages.Keys.ToList(); private readonly int _pictureWidth;