From 92e7f24c625c81c137bbe3bbc5924d6d90f716cc Mon Sep 17 00:00:00 2001 From: Hells Hound Date: Mon, 14 Nov 2022 22:26:54 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AircraftCarrier/DrawingObjectWarship.cs | 12 ++- .../AircraftCarrier/ExtentionWarship.cs | 57 ++++++++++++ .../FormMapWithSetWarships.Designer.cs | 66 ++++++++++++- .../AircraftCarrier/FormMapWithSetWarships.cs | 39 ++++++++ .../FormMapWithSetWarships.resx | 9 ++ .../AircraftCarrier/IDrawingObject.cs | 5 + .../MapWithSetWarshipsGeneric.cs | 25 +++++ .../AircraftCarrier/MapsCollection.cs | 93 ++++++++++++++++++- 8 files changed, 295 insertions(+), 11 deletions(-) create mode 100644 AircraftCarrier/AircraftCarrier/ExtentionWarship.cs diff --git a/AircraftCarrier/AircraftCarrier/DrawingObjectWarship.cs b/AircraftCarrier/AircraftCarrier/DrawingObjectWarship.cs index 104b2e0..2c74cc8 100644 --- a/AircraftCarrier/AircraftCarrier/DrawingObjectWarship.cs +++ b/AircraftCarrier/AircraftCarrier/DrawingObjectWarship.cs @@ -21,6 +21,11 @@ namespace AircraftCarrier return _warship?.GetCurrentPosition() ?? default; } + public string GetInfo() + { + return _warship?.GetDataForSave(); + } + public void MoveObject(Direction direction) { _warship?.MoveTransport(direction); @@ -31,9 +36,8 @@ namespace AircraftCarrier _warship.SetPosition(x, y, width, height); } - void IDrawingObject.DrawningObject(Graphics g) - { - _warship.DrawTransport(g); - } + void IDrawingObject.DrawningObject(Graphics g) => _warship.DrawTransport(g); + + public static IDrawingObject Create(string data) => new DrawingObjectWarship(data.CreateDrawningWarship()); } } diff --git a/AircraftCarrier/AircraftCarrier/ExtentionWarship.cs b/AircraftCarrier/AircraftCarrier/ExtentionWarship.cs new file mode 100644 index 0000000..53b883c --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/ExtentionWarship.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftCarrier +{ + /// + /// Расширение для класса DrawingWarship + /// + internal static class ExtentionWarship + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawingWarship CreateDrawningWarship(this string info) + { + string[] strs = info.Split(_separatorForObject); + if (strs.Length == 3) + { + return new DrawingWarship(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + if (strs.Length == 7) + { + return new DrawingAircraftCarrier(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawingWarship drawingWarship) + { + var warship = drawingWarship.Warship; + var str = $"{warship.Speed}{_separatorForObject}{warship.Weight}{_separatorForObject}{warship.BodyColor.Name}"; + if (warship is not EntityAircraftCarrier aircraftCarrier) + { + return str; + } + return $"{str}{_separatorForObject}{aircraftCarrier.DopColor.Name}{_separatorForObject}{aircraftCarrier.BodyKit}{_separatorForObject}{aircraftCarrier.Сabin}{_separatorForObject}{aircraftCarrier.SuperEngine}"; + } + } +} diff --git a/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.Designer.cs b/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.Designer.cs index b0d9f55..5f6ed52 100644 --- a/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.Designer.cs +++ b/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.Designer.cs @@ -45,9 +45,16 @@ this.buttonUp = new System.Windows.Forms.Button(); this.buttonDown = new System.Windows.Forms.Button(); this.pictureBox = new System.Windows.Forms.PictureBox(); + this.menuStrip = new System.Windows.Forms.MenuStrip(); + this.fileToolStripMenuItem = 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.buttonUp); this.groupBoxTools.Controls.Add(this.buttonDown); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(754, 0); + this.groupBoxTools.Location = new System.Drawing.Point(754, 24); this.groupBoxTools.Name = "groupBoxTools"; - this.groupBoxTools.Size = new System.Drawing.Size(217, 649); + this.groupBoxTools.Size = new System.Drawing.Size(217, 625); this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Tools"; @@ -237,12 +244,52 @@ // 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, 24); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(754, 649); + this.pictureBox.Size = new System.Drawing.Size(754, 625); this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // + // menuStrip + // + this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.fileToolStripMenuItem}); + this.menuStrip.Location = new System.Drawing.Point(0, 0); + this.menuStrip.Name = "menuStrip"; + this.menuStrip.Size = new System.Drawing.Size(971, 24); + this.menuStrip.TabIndex = 2; + // + // fileToolStripMenuItem + // + this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem}); + this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); + this.fileToolStripMenuItem.Text = "File"; + // + // SaveToolStripMenuItem + // + this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.SaveToolStripMenuItem.Text = "Save"; + this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); + // + // LoadToolStripMenuItem + // + this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.LoadToolStripMenuItem.Text = "Load"; + this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); + // + // openFileDialog + // + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // // FormMapWithSetWarships // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -250,6 +297,8 @@ this.ClientSize = new System.Drawing.Size(971, 649); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBoxTools); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; this.Name = "FormMapWithSetWarships"; this.Text = "FormMapWithSetWarships"; this.groupBoxTools.ResumeLayout(false); @@ -257,7 +306,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(); } @@ -280,5 +332,11 @@ private Button buttonDeleteMap; private ListBox listBoxMaps; private TextBox textBoxNewMapName; + 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/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.cs b/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.cs index 1ca346a..db58c0f 100644 --- a/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.cs +++ b/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.cs @@ -229,5 +229,44 @@ namespace AircraftCarrier } 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/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.resx b/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.resx index f298a7b..934ed35 100644 --- a/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.resx +++ b/AircraftCarrier/AircraftCarrier/FormMapWithSetWarships.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 125, 17 + + + 265, 17 + \ No newline at end of file diff --git a/AircraftCarrier/AircraftCarrier/IDrawingObject.cs b/AircraftCarrier/AircraftCarrier/IDrawingObject.cs index c22daf9..1196b5d 100644 --- a/AircraftCarrier/AircraftCarrier/IDrawingObject.cs +++ b/AircraftCarrier/AircraftCarrier/IDrawingObject.cs @@ -39,5 +39,10 @@ namespace AircraftCarrier /// /// (float Left, float Right, float Top, float Bottom) GetCurrentPosition(); + /// + /// Получение информации по объекту + /// + /// + string GetInfo(); } } diff --git a/AircraftCarrier/AircraftCarrier/MapWithSetWarshipsGeneric.cs b/AircraftCarrier/AircraftCarrier/MapWithSetWarshipsGeneric.cs index 9487676..e2eb3cd 100644 --- a/AircraftCarrier/AircraftCarrier/MapWithSetWarshipsGeneric.cs +++ b/AircraftCarrier/AircraftCarrier/MapWithSetWarshipsGeneric.cs @@ -113,6 +113,31 @@ namespace AircraftCarrier return new(_pictureWidth, _pictureHeight); } /// + /// Получение данных в виде строки + /// + /// + /// + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var warship in _setWarships.GetWarships()) + { + data += $"{warship.GetInfo()}{separatorData}"; + } + return data; + } + /// + /// Загрузка списка из массива строк + /// + /// + public void LoadData(string[] records) + { + foreach (var rec in records) + { + _setWarships.Insert(DrawingObjectWarship.Create(rec) as T); + } + } + /// /// "Взбалтываем" набор, чтобы все элементы оказались в начале /// private void Shaking() diff --git a/AircraftCarrier/AircraftCarrier/MapsCollection.cs b/AircraftCarrier/AircraftCarrier/MapsCollection.cs index e12e716..d3c0b37 100644 --- a/AircraftCarrier/AircraftCarrier/MapsCollection.cs +++ b/AircraftCarrier/AircraftCarrier/MapsCollection.cs @@ -11,7 +11,7 @@ namespace AircraftCarrier /// /// Словарь (хранилище) с картами /// - readonly Dictionary> _mapStorages; + readonly Dictionary> _mapStorages; /// /// Возвращение списка названий карт /// @@ -25,13 +25,21 @@ namespace AircraftCarrier /// 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; } @@ -57,7 +65,7 @@ namespace AircraftCarrier /// /// /// - public MapWithSetWarshipsGeneric this[string ind] + public MapWithSetWarshipsGeneric this[string ind] { get { @@ -65,5 +73,84 @@ namespace AircraftCarrier return MapWithSetWarshipsGeneric; } } + /// + /// Метод записи информации в файл + /// + /// Строка, которую следует записать + /// Поток для записи + 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 "Простая карта": + map = new SimpleMap(); + break; + case "Преграды-линии": + map = new LineMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetWarshipsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + return true; + } } }