diff --git a/Battleship/Battleship/ExtentionDrawningShip.cs b/Battleship/Battleship/ExtentionDrawningShip.cs new file mode 100644 index 0000000..cb9f40d --- /dev/null +++ b/Battleship/Battleship/ExtentionDrawningShip.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Battleship.Entities; + +namespace Battleship.DrawningObjects +{ + public static class ExtentionDrawningShip + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningShip? CreateDrawningShip(this string info, char + separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawningShip(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + if (strs.Length == 6) + { + return new DrawningBattleship(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 DrawningShip drawningShip, + char separatorForObject) + { + var ship = drawningShip.EntityShip; + if (ship == null) + { + return string.Empty; + } + var str = $"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}"; + if (ship is not EntityBattleship battleship) + { + return str; + } + return $"{str}{separatorForObject}{battleship.AdditionalColor.Name}" + + $"{separatorForObject}{battleship.Tower}{separatorForObject}{battleship.Section}"; + } + } +} + + diff --git a/Battleship/Battleship/FormShipCollection.Designer.cs b/Battleship/Battleship/FormShipCollection.Designer.cs index a597aed..cae2aff 100644 --- a/Battleship/Battleship/FormShipCollection.Designer.cs +++ b/Battleship/Battleship/FormShipCollection.Designer.cs @@ -38,9 +38,16 @@ this.buttonRefreshCollection = new System.Windows.Forms.Button(); this.buttonRemoveShip = new System.Windows.Forms.Button(); this.buttonAddShip = new System.Windows.Forms.Button(); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.groupBoxBattleShip.SuspendLayout(); this.groupBox1.SuspendLayout(); + this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); this.SuspendLayout(); // @@ -53,6 +60,7 @@ this.groupBoxBattleShip.Controls.Add(this.buttonRefreshCollection); this.groupBoxBattleShip.Controls.Add(this.buttonRemoveShip); this.groupBoxBattleShip.Controls.Add(this.buttonAddShip); + this.groupBoxBattleShip.Controls.Add(this.menuStrip1); this.groupBoxBattleShip.Location = new System.Drawing.Point(618, 1); this.groupBoxBattleShip.Name = "groupBoxBattleShip"; this.groupBoxBattleShip.Size = new System.Drawing.Size(183, 450); @@ -66,16 +74,16 @@ this.groupBox1.Controls.Add(this.listBoxStorages); this.groupBox1.Controls.Add(this.buttonAddObject); this.groupBox1.Controls.Add(this.buttonDelObject); - this.groupBox1.Location = new System.Drawing.Point(6, 22); + this.groupBox1.Location = new System.Drawing.Point(6, 61); this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(171, 253); + this.groupBox1.Size = new System.Drawing.Size(174, 223); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Набор"; // // textBoxStorageName // - this.textBoxStorageName.Location = new System.Drawing.Point(17, 40); + this.textBoxStorageName.Location = new System.Drawing.Point(17, 22); this.textBoxStorageName.Name = "textBoxStorageName"; this.textBoxStorageName.Size = new System.Drawing.Size(147, 23); this.textBoxStorageName.TabIndex = 4; @@ -84,15 +92,15 @@ // this.listBoxStorages.FormattingEnabled = true; this.listBoxStorages.ItemHeight = 15; - this.listBoxStorages.Location = new System.Drawing.Point(17, 124); + this.listBoxStorages.Location = new System.Drawing.Point(18, 95); this.listBoxStorages.Name = "listBoxStorages"; - this.listBoxStorages.Size = new System.Drawing.Size(147, 94); + this.listBoxStorages.Size = new System.Drawing.Size(147, 79); this.listBoxStorages.TabIndex = 3; this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged); // // buttonAddObject // - this.buttonAddObject.Location = new System.Drawing.Point(18, 81); + this.buttonAddObject.Location = new System.Drawing.Point(17, 51); this.buttonAddObject.Name = "buttonAddObject"; this.buttonAddObject.Size = new System.Drawing.Size(147, 23); this.buttonAddObject.TabIndex = 2; @@ -102,7 +110,7 @@ // // buttonDelObject // - this.buttonDelObject.Location = new System.Drawing.Point(17, 224); + this.buttonDelObject.Location = new System.Drawing.Point(18, 181); this.buttonDelObject.Name = "buttonDelObject"; this.buttonDelObject.Size = new System.Drawing.Size(147, 23); this.buttonDelObject.TabIndex = 1; @@ -112,16 +120,16 @@ // // maskedTextBoxNumber // - this.maskedTextBoxNumber.Location = new System.Drawing.Point(23, 330); + this.maskedTextBoxNumber.Location = new System.Drawing.Point(24, 335); this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; this.maskedTextBoxNumber.Size = new System.Drawing.Size(147, 23); this.maskedTextBoxNumber.TabIndex = 3; // // buttonRefreshCollection // - this.buttonRefreshCollection.Location = new System.Drawing.Point(23, 411); + this.buttonRefreshCollection.Location = new System.Drawing.Point(23, 406); this.buttonRefreshCollection.Name = "buttonRefreshCollection"; - this.buttonRefreshCollection.Size = new System.Drawing.Size(147, 33); + this.buttonRefreshCollection.Size = new System.Drawing.Size(147, 31); this.buttonRefreshCollection.TabIndex = 2; this.buttonRefreshCollection.Text = "Обновить коллекцию"; this.buttonRefreshCollection.UseVisualStyleBackColor = true; @@ -129,9 +137,9 @@ // // buttonRemoveShip // - this.buttonRemoveShip.Location = new System.Drawing.Point(23, 359); + this.buttonRemoveShip.Location = new System.Drawing.Point(23, 364); this.buttonRemoveShip.Name = "buttonRemoveShip"; - this.buttonRemoveShip.Size = new System.Drawing.Size(147, 33); + this.buttonRemoveShip.Size = new System.Drawing.Size(147, 36); this.buttonRemoveShip.TabIndex = 1; this.buttonRemoveShip.Text = "Удалить корабль"; this.buttonRemoveShip.UseVisualStyleBackColor = true; @@ -139,14 +147,47 @@ // // buttonAddShip // - this.buttonAddShip.Location = new System.Drawing.Point(23, 281); + this.buttonAddShip.Location = new System.Drawing.Point(23, 290); this.buttonAddShip.Name = "buttonAddShip"; - this.buttonAddShip.Size = new System.Drawing.Size(147, 33); + this.buttonAddShip.Size = new System.Drawing.Size(147, 30); this.buttonAddShip.TabIndex = 0; this.buttonAddShip.Text = "Добавить корабль"; this.buttonAddShip.UseVisualStyleBackColor = true; this.buttonAddShip.Click += new System.EventHandler(this.buttonAddShip_Click); // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.файлToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(3, 19); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(177, 24); + this.menuStrip1.TabIndex = 4; + this.menuStrip1.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.сохранениеToolStripMenuItem, + this.загрузкаToolStripMenuItem}); + this.файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20); + this.файлToolStripMenuItem.Text = "Файл"; + // + // сохранениеToolStripMenuItem + // + this.сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; + this.сохранениеToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.сохранениеToolStripMenuItem.Text = "Сохранение"; + this.сохранениеToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); + // + // загрузкаToolStripMenuItem + // + this.загрузкаToolStripMenuItem.Name = "загрузкаToolStripMenuItem"; + this.загрузкаToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.загрузкаToolStripMenuItem.Text = "Загрузка"; + this.загрузкаToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); + // // pictureBoxCollection // this.pictureBoxCollection.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) @@ -158,6 +199,14 @@ this.pictureBoxCollection.TabIndex = 0; this.pictureBoxCollection.TabStop = false; // + // openFileDialog + // + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // // FormShipCollection // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -165,12 +214,15 @@ this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.pictureBoxCollection); this.Controls.Add(this.groupBoxBattleShip); + this.MainMenuStrip = this.menuStrip1; this.Name = "FormShipCollection"; this.Text = "FormShipCollection"; this.groupBoxBattleShip.ResumeLayout(false); this.groupBoxBattleShip.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); this.ResumeLayout(false); @@ -189,5 +241,11 @@ private ListBox listBoxStorages; private Button buttonAddObject; private Button buttonDelObject; + private MenuStrip menuStrip1; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem сохранениеToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; + private ToolStripMenuItem загрузкаToolStripMenuItem; } } \ No newline at end of file diff --git a/Battleship/Battleship/FormShipCollection.cs b/Battleship/Battleship/FormShipCollection.cs index a047311..d7a3d54 100644 --- a/Battleship/Battleship/FormShipCollection.cs +++ b/Battleship/Battleship/FormShipCollection.cs @@ -27,6 +27,50 @@ namespace Battleship InitializeComponent(); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + ReloadObjects(); + } + private void ReloadObjects() { int index = listBoxStorages.SelectedIndex; diff --git a/Battleship/Battleship/FormShipCollection.resx b/Battleship/Battleship/FormShipCollection.resx index f298a7b..ddcfdb1 100644 --- a/Battleship/Battleship/FormShipCollection.resx +++ b/Battleship/Battleship/FormShipCollection.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/Battleship/Battleship/FormShipConfig.Designer.cs b/Battleship/Battleship/FormShipConfig.Designer.cs index 3c5dee8..6cd4303 100644 --- a/Battleship/Battleship/FormShipConfig.Designer.cs +++ b/Battleship/Battleship/FormShipConfig.Designer.cs @@ -119,7 +119,7 @@ // // panelPurple // - this.panelPurple.BackColor = System.Drawing.Color.Purple; + this.panelPurple.BackColor = System.Drawing.Color.Plum; this.panelPurple.Location = new System.Drawing.Point(187, 78); this.panelPurple.Name = "panelPurple"; this.panelPurple.Size = new System.Drawing.Size(50, 50); @@ -164,7 +164,7 @@ // // panelBlue // - this.panelBlue.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.panelBlue.BackColor = System.Drawing.Color.SlateBlue; this.panelBlue.Location = new System.Drawing.Point(131, 22); this.panelBlue.Name = "panelBlue"; this.panelBlue.Size = new System.Drawing.Size(50, 50); @@ -173,7 +173,7 @@ // // panelGreen // - this.panelGreen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); + this.panelGreen.BackColor = System.Drawing.Color.OliveDrab; this.panelGreen.Location = new System.Drawing.Point(75, 22); this.panelGreen.Name = "panelGreen"; this.panelGreen.Size = new System.Drawing.Size(50, 50); @@ -182,7 +182,7 @@ // // panelRed // - this.panelRed.BackColor = System.Drawing.Color.Red; + this.panelRed.BackColor = System.Drawing.Color.Maroon; this.panelRed.Location = new System.Drawing.Point(19, 22); this.panelRed.Name = "panelRed"; this.panelRed.Size = new System.Drawing.Size(50, 50); diff --git a/Battleship/Battleship/ShipGenericCollection.cs b/Battleship/Battleship/ShipGenericCollection.cs index 86d4fb8..a95b907 100644 --- a/Battleship/Battleship/ShipGenericCollection.cs +++ b/Battleship/Battleship/ShipGenericCollection.cs @@ -17,6 +17,10 @@ namespace Battleship.Generics private readonly int _placeSizeWidth = 185; private readonly int _placeSizeHeight = 90; private readonly SetGeneric _collection; + /// + /// Получение объектов коллекции + /// + public IEnumerable GetShips => _collection.GetShips(); public ShipGenericCollection(int picWidth, int picHeight) { int width = picWidth / _placeSizeWidth; diff --git a/Battleship/Battleship/ShipsGenericStorage.cs b/Battleship/Battleship/ShipsGenericStorage.cs index 6260ff3..63b6d35 100644 --- a/Battleship/Battleship/ShipsGenericStorage.cs +++ b/Battleship/Battleship/ShipsGenericStorage.cs @@ -12,13 +12,25 @@ namespace Battleship.Generics { readonly Dictionary> _shipStorages; - + public List Keys => _shipStorages.Keys.ToList(); - + private readonly int _pictureWidth; - + private readonly int _pictureHeight; - + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + public ShipsGenericStorage(int pictureWidth, int pictureHeight) { _shipStorages = new Dictionary(_pictureWidth,_pictureHeight); + _shipStorages[name] = new ShipGenericCollection(_pictureWidth, _pictureHeight); } - + public void DelSet(string name) { if (!_shipStorages.ContainsKey(name)) return; _shipStorages.Remove(name); } - + public ShipGenericCollection? this[string ind] { get { - if(_shipStorages.ContainsKey(ind)) + if (_shipStorages.ContainsKey(ind)) return _shipStorages[ind]; return null; } } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _shipStorages) + { + StringBuilder records = new(); + foreach (DrawningShip? elem in record.Value.GetShips) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write($"ShipStorage{Environment.NewLine}{data}"); + } + return true; + } + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + if (!str.StartsWith("ShipStorage")) + { + return false; + } + + _shipStorages.Clear(); + string strs = ""; + + while ((strs = fs.ReadLine()) != null) + { + if (strs == null) + { + return false; + } + + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + ShipGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningShip? plane = elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight); + if (plane != null) + { + if (!(collection + plane)) + { + return false; + } + } + } + _shipStorages.Add(record[0], collection); + } + return true; + } + } } }