diff --git a/ProjectMachine/ProjectMachine/DrawningObject.cs b/ProjectMachine/ProjectMachine/DrawningObject.cs index 64d03d3..6ebde9b 100644 --- a/ProjectMachine/ProjectMachine/DrawningObject.cs +++ b/ProjectMachine/ProjectMachine/DrawningObject.cs @@ -36,5 +36,9 @@ namespace ProjectMachine { _machine.DrawTransport(g); } + + public string GetInfo() => _machine?.GetDataForSave(); + + public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningMachine()); } } diff --git a/ProjectMachine/ProjectMachine/ExtentionTank.cs b/ProjectMachine/ProjectMachine/ExtentionTank.cs new file mode 100644 index 0000000..f9c9bb8 --- /dev/null +++ b/ProjectMachine/ProjectMachine/ExtentionTank.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMachine +{ + /// + /// Расширение для класса DrawningMachine + /// + internal static class ExtentionTank + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawningMachine CreateDrawningMachine(this string info) + { + string[] strs = info.Split(_separatorForObject); + if (strs.Length == 3) + { + return new DrawningMachine(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + if (strs.Length == 6) + { + return new DrawningTank(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5])); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningMachine drawningMachine) + { + var machine = drawningMachine.Machine; + var str = $"{machine.Speed}{_separatorForObject}{machine.Weight}{_separatorForObject}{machine.BodyColor.Name}"; + if (machine is not EntityTank tank) + { + return str; + } + return + $"{str}{_separatorForObject}{tank.DopColor.Name}{_separatorForObject}{tank.Turret}{_separatorForObject}{tank.Gun}"; + } + } +} diff --git a/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs b/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs index 64987ea..5434bca 100644 --- a/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs +++ b/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs @@ -45,9 +45,16 @@ this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox(); this.buttonAddTank = new System.Windows.Forms.Button(); this.pictureBox = new System.Windows.Forms.PictureBox(); + 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(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.groupBoxTools.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // groupBoxTools @@ -63,9 +70,9 @@ this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition); this.groupBoxTools.Controls.Add(this.buttonAddTank); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(819, 0); + this.groupBoxTools.Location = new System.Drawing.Point(819, 28); this.groupBoxTools.Name = "groupBoxTools"; - this.groupBoxTools.Size = new System.Drawing.Size(233, 766); + this.groupBoxTools.Size = new System.Drawing.Size(233, 738); this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Инструменты"; @@ -143,7 +150,7 @@ this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.BackgroundImage = global::ProjectMachine.Properties.Resources.лево; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonLeft.Location = new System.Drawing.Point(69, 711); + this.buttonLeft.Location = new System.Drawing.Point(69, 683); this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Size = new System.Drawing.Size(34, 30); this.buttonLeft.TabIndex = 13; @@ -156,7 +163,7 @@ this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.BackgroundImage = global::ProjectMachine.Properties.Resources.вверх; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonUp.Location = new System.Drawing.Point(105, 675); + this.buttonUp.Location = new System.Drawing.Point(105, 647); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(34, 30); this.buttonUp.TabIndex = 12; @@ -169,7 +176,7 @@ this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.BackgroundImage = global::ProjectMachine.Properties.Resources.право; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonRight.Location = new System.Drawing.Point(141, 711); + this.buttonRight.Location = new System.Drawing.Point(141, 683); this.buttonRight.Name = "buttonRight"; this.buttonRight.Size = new System.Drawing.Size(34, 30); this.buttonRight.TabIndex = 11; @@ -182,7 +189,7 @@ this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.BackgroundImage = global::ProjectMachine.Properties.Resources.вниз; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonDown.Location = new System.Drawing.Point(105, 711); + this.buttonDown.Location = new System.Drawing.Point(105, 683); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(34, 30); this.buttonDown.TabIndex = 10; @@ -247,12 +254,54 @@ // 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, 28); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(819, 766); + this.pictureBox.Size = new System.Drawing.Size(819, 738); this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // + // 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(1052, 28); + this.menuStrip.TabIndex = 2; + this.menuStrip.Text = "menuStrip1"; + // + // файл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); + // + // openFileDialog + // + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // // FormMapWithSetTank // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); @@ -260,6 +309,8 @@ this.ClientSize = new System.Drawing.Size(1052, 766); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBoxTools); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; this.Name = "FormMapWithSetTank"; this.Text = "FormMapWithSetTank"; this.groupBoxTools.ResumeLayout(false); @@ -267,7 +318,10 @@ 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(); } @@ -290,5 +344,11 @@ private Button buttonDeleteMap; private TextBox textBoxNewMapName; private ListBox listBoxMaps; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs b/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs index 30822e6..9502968 100644 --- a/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs +++ b/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs @@ -33,7 +33,7 @@ namespace ProjectMachine InitializeComponent(); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); - foreach(var elem in _mapsDict) + foreach (var elem in _mapsDict) { comboBoxSelectorMap.Items.Add(elem.Key); } @@ -154,7 +154,7 @@ namespace ProjectMachine return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos!=null) + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); @@ -221,6 +221,45 @@ namespace ProjectMachine } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_mapsCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/ProjectMachine/ProjectMachine/FormMapWithSetTank.resx b/ProjectMachine/ProjectMachine/FormMapWithSetTank.resx index f298a7b..985a3e4 100644 --- a/ProjectMachine/ProjectMachine/FormMapWithSetTank.resx +++ b/ProjectMachine/ProjectMachine/FormMapWithSetTank.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 144, 17 + + + 311, 17 + \ No newline at end of file diff --git a/ProjectMachine/ProjectMachine/IDrawningObject.cs b/ProjectMachine/ProjectMachine/IDrawningObject.cs index 7078235..ceaf61f 100644 --- a/ProjectMachine/ProjectMachine/IDrawningObject.cs +++ b/ProjectMachine/ProjectMachine/IDrawningObject.cs @@ -39,5 +39,10 @@ namespace ProjectMachine /// /// (float Left, float Right, float Top, float Bottom) GetCurrentPosition(); + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } diff --git a/ProjectMachine/ProjectMachine/MapWithSetTankGeneric.cs b/ProjectMachine/ProjectMachine/MapWithSetTankGeneric.cs index ff90b2e..1e9a657 100644 --- a/ProjectMachine/ProjectMachine/MapWithSetTankGeneric.cs +++ b/ProjectMachine/ProjectMachine/MapWithSetTankGeneric.cs @@ -114,6 +114,31 @@ namespace ProjectMachine return new(_pictureWidth, _pictureHeight); } /// + /// Получение данных в виде строки + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var tank in _setTank.GetTanks()) + { + data += $"{tank.GetInfo()}{separatorData}"; + } + return data; + } + /// + /// Загрузка списка из массива строк + /// + /// + public void LoadData(string[] records) + { + foreach (var rec in records) + { + _setTank.Insert(DrawningObject.Create(rec) as T); + } + } + /// /// "Взбалтываем" набор, чтобы все элементы оказались в начале /// private void Shaking() diff --git a/ProjectMachine/ProjectMachine/MapsCollection.cs b/ProjectMachine/ProjectMachine/MapsCollection.cs index 3dc922e..0d1235b 100644 --- a/ProjectMachine/ProjectMachine/MapsCollection.cs +++ b/ProjectMachine/ProjectMachine/MapsCollection.cs @@ -14,8 +14,7 @@ namespace ProjectMachine /// /// Словарь (хранилище) с картами /// - readonly Dictionary> _mapStorages; + readonly Dictionary> _mapStorages; /// /// Возвращение списка названий карт /// @@ -29,14 +28,21 @@ namespace ProjectMachine /// 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; } @@ -48,7 +54,7 @@ namespace ProjectMachine public void AddMap(string name, AbstractMap map) { if (!Keys.Contains(name)) - _mapStorages.Add(name, new MapWithSetTankGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages.Add(name, new MapWithSetTankGeneric(_pictureWidth, _pictureHeight, map)); } /// /// Удаление карты @@ -64,8 +70,7 @@ namespace ProjectMachine /// /// /// - public MapWithSetTankGeneric this[string - ind] + public MapWithSetTankGeneric this[string ind] { get { @@ -74,7 +79,87 @@ namespace ProjectMachine return null; } } - } + /// + /// Метод записи информации в файл + /// + /// Строка, которую следует записать + /// Поток для записи + private static void WriteToFile(string text, FileStream stream) + { + byte[] info = new UTF8Encoding(true).GetBytes(text); + stream.Write(info, 0, info.Length); + } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (FileStream fs = new(filename, FileMode.Create)) + { + WriteToFile($"MapsCollection{Environment.NewLine}", fs); + foreach (var storage in _mapStorages) + { + WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}", fs); + } + } + return true; + } + /// + /// Загрузка нформации по автомобилям на парковках из файла + /// + /// + /// + 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[0].Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + return false; + } + //очищаем записи + _mapStorages.Clear(); + for (int i = 1; i < strs.Length; ++i) + { + var elem = strs[i].Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "TownMap": + map = new TownMap(); + break; + } + _mapStorages.Add(elem[0], new + MapWithSetTankGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData,StringSplitOptions.RemoveEmptyEntries)); + } + return true; + } + } }