SemesterFirstLabSixthBomberBase

This commit is contained in:
VanyaAlekseev 2023-11-28 22:11:08 +04:00
parent 8647cc572a
commit 3070770d5a
7 changed files with 301 additions and 16 deletions

View File

@ -0,0 +1,69 @@
using ProjectBomber.Entities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityBomber
/// </summary>
public static class ExtentionDrawningPlane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningBomber CreateDrawningPlane(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningBomber(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawningBomberAdvanced(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]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningPlane">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBomber drawningPlane,
char separatorForObject)
{
var plane = drawningPlane.EntityBomber;
if (plane == null)
{
return string.Empty;
}
var str = $"{plane.Speed}{separatorForObject}{plane.Weight}{separatorForObject}{plane.BodyColor.Name}";
if (!(plane is EntityBomberAdvanced bomberAdvanced))
{
return str;
}
return
$"{str}{separatorForObject}{bomberAdvanced.AdditionalColor.Name}{separatorForObject}{bomberAdvanced.Bombs}" +
$"{separatorForObject}{bomberAdvanced.FuelTanks}{separatorForObject}{bomberAdvanced.Line}";
}
}
}

View File

@ -29,6 +29,7 @@
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBoxSet = new System.Windows.Forms.GroupBox();
this.ButtonDelObject = new System.Windows.Forms.Button();
this.ListBoxStorages = new System.Windows.Forms.ListBox();
@ -38,10 +39,16 @@
this.ButtonRemovePlane = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.ButtonAddPlane = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.menuStrip1 = 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.groupBox1.SuspendLayout();
this.groupBoxSet.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.groupBoxSet.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
@ -51,13 +58,22 @@
this.groupBox1.Controls.Add(this.ButtonRemovePlane);
this.groupBox1.Controls.Add(this.maskedTextBoxNumber);
this.groupBox1.Controls.Add(this.ButtonAddPlane);
this.groupBox1.Location = new System.Drawing.Point(586, 2);
this.groupBox1.Controls.Add(this.menuStrip1);
this.groupBox1.Location = new System.Drawing.Point(592, 2);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(216, 563);
this.groupBox1.Size = new System.Drawing.Size(210, 563);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 2);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(600, 565);
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
//
// groupBoxSet
//
this.groupBoxSet.Controls.Add(this.ButtonDelObject);
@ -109,7 +125,7 @@
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(18, 509);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(20, 492);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(178, 41);
this.ButtonRefreshCollection.TabIndex = 3;
@ -119,7 +135,7 @@
//
// ButtonRemovePlane
//
this.ButtonRemovePlane.Location = new System.Drawing.Point(18, 430);
this.ButtonRemovePlane.Location = new System.Drawing.Point(21, 445);
this.ButtonRemovePlane.Name = "ButtonRemovePlane";
this.ButtonRemovePlane.Size = new System.Drawing.Size(179, 41);
this.ButtonRemovePlane.TabIndex = 2;
@ -129,14 +145,14 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(18, 388);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(18, 351);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(180, 20);
this.maskedTextBoxNumber.TabIndex = 1;
//
// ButtonAddPlane
//
this.ButtonAddPlane.Location = new System.Drawing.Point(18, 327);
this.ButtonAddPlane.Location = new System.Drawing.Point(18, 305);
this.ButtonAddPlane.Name = "ButtonAddPlane";
this.ButtonAddPlane.Size = new System.Drawing.Size(185, 40);
this.ButtonAddPlane.TabIndex = 0;
@ -144,13 +160,48 @@
this.ButtonAddPlane.UseVisualStyleBackColor = true;
this.ButtonAddPlane.Click += new System.EventHandler(this.ButtonAddPlane_Click);
//
// pictureBoxCollection
// menuStrip1
//
this.pictureBoxCollection.Location = new System.Drawing.Point(-2, 2);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(600, 563);
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(3, 536);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(204, 24);
this.menuStrip1.TabIndex = 5;
this.menuStrip1.Text = "menuStrip1";
//
// 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.FileName = "openFileDialog";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormPlaneCollection
//
@ -159,13 +210,16 @@
this.ClientSize = new System.Drawing.Size(800, 564);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.groupBox1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormPlaneCollection";
this.Text = "Набор самолетов";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.groupBoxSet.ResumeLayout(false);
this.groupBoxSet.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
}
@ -183,5 +237,11 @@
private System.Windows.Forms.ListBox ListBoxStorages;
private System.Windows.Forms.Button ButtonAddObject;
private System.Windows.Forms.TextBox textBoxStorageName;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
}
}

View File

@ -188,5 +188,47 @@ _storage[ListBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowPlanes()
}
pictureBoxCollection.Image = obj.ShowPlanes();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>244, 19</value>
</metadata>
</root>

View File

@ -52,6 +52,10 @@ namespace ProjectBomber.Generics
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T> GetPlanes => _collection.GetPlanes();
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -43,6 +44,18 @@ namespace ProjectBomber.Generics
_pictureHeight = pictureHeight;
}
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
@ -93,5 +106,92 @@ namespace ProjectBomber.Generics
}
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new StringBuilder();
foreach (KeyValuePair<string,
PlanesGenericCollection<DrawningBomber, DrawningObjectBomber>> record in _planeStorages)
{
StringBuilder records = new StringBuilder();
foreach (DrawningBomber 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))
{
writer.Write($"PlanesStorage{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по самолетам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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("PlanesStorage"))
{
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<DrawningBomber, DrawningObjectBomber> collection = new PlanesGenericCollection<DrawningBomber, DrawningObjectBomber>(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
{
DrawningBomber plane = data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight);
if (plane != null)
{
int? result = collection + plane;
if (result == null || result.Value == -1)
{
return false;
}
}
}
_planeStorages.Add(name, collection);
}
return true;
}
}
}
}

View File

@ -12,6 +12,7 @@
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
@ -24,7 +25,6 @@
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
@ -68,6 +68,7 @@
<Compile Include="DrawningObjectBomber.cs" />
<Compile Include="EntityBomber.cs" />
<Compile Include="EntityBomberAdvanced.cs" />
<Compile Include="ExtentionDrawningPlane.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>