PIbd-22 Gerimovich I.M. Lab Work 6 #7

Closed
Gerimovich_Ilya wants to merge 4 commits from LabWork6 into LabWork5
9 changed files with 329 additions and 26 deletions

View File

@ -30,7 +30,6 @@ namespace Tank.DrawingObjects
additionalColor, bodyKit, wing, sportLine);
}
}
public override void DrawTransport(Graphics g)
{
if (Tank is not EntityTank ArmoredCar)

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawingObjects;
using Tank.Entites;
namespace Tank.Drawings
{
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningCar
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingArmoredCar? CreateDrawTank(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingArmoredCar(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawingTank(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="drawningTank">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingArmoredCar armoredCar, char separatorForObject)
{
var ArmoredCar = armoredCar.Tank;
if (ArmoredCar == null)
{
return string.Empty;
}
var str =$"{ArmoredCar.Speed}{separatorForObject}{ArmoredCar.Weight}{separatorForObject}{ArmoredCar.BodyColor.Name}";
if (ArmoredCar is not EntityTank Tank)
{
return str;
}
return
$"{str}{separatorForObject}{Tank.AdditionalColor.Name}{separatorForObject}{Tank.BodyKit}" +
$"{separatorForObject}{Tank.Trunk}{separatorForObject}{Tank.Line}";
}
}
}

View File

@ -15,7 +15,7 @@ namespace Tank.Entites
public bool BodyKit { get; private set; }
// Признак (опция) наличия Багажника
public bool Trunk { get; private set; }
// Признак (опция) наличия гоночной полосы
// Признак (опция) наличия полосы
public bool Line { get; private set; }
/// Шаг перемещения танка
/// Инициализация полей объекта-класса спортивного автомобиля
@ -25,7 +25,8 @@ namespace Tank.Entites
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="trunk">Признак наличия багажника</param>
/// <param name="line">Признак наличия гоночной полосы</param>
/// <param name="line">Признак наличия полосы</param>
public EntityTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool trunk, bool line) : base(speed, weight, bodyColor)
{
@ -38,7 +39,6 @@ namespace Tank.Entites
{
AdditionalColor = color;
}
}
}

View File

@ -39,9 +39,18 @@
this.ButtonRemoveArmoredCar = new System.Windows.Forms.Button();
this.ButtonAddArmoredCar = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.panelStrip = new System.Windows.Forms.Panel();
this.StripMenu = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelStrip.SuspendLayout();
this.StripMenu.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
@ -51,9 +60,9 @@
this.groupBox1.Controls.Add(this.ButtonRefreshCollection);
this.groupBox1.Controls.Add(this.ButtonRemoveArmoredCar);
this.groupBox1.Controls.Add(this.ButtonAddArmoredCar);
this.groupBox1.Location = new System.Drawing.Point(579, 12);
this.groupBox1.Location = new System.Drawing.Point(579, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 426);
this.groupBox1.Size = new System.Drawing.Size(194, 343);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
@ -64,9 +73,9 @@
this.groupBox2.Controls.Add(this.listBoxStorages);
this.groupBox2.Controls.Add(this.ButtonDelObject);
this.groupBox2.Controls.Add(this.ButtonAddObject);
this.groupBox2.Location = new System.Drawing.Point(13, 22);
this.groupBox2.Location = new System.Drawing.Point(6, 22);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(181, 219);
this.groupBox2.Size = new System.Drawing.Size(172, 162);
this.groupBox2.TabIndex = 8;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Наборы";
@ -75,7 +84,7 @@
//
this.textBoxStorageName.Location = new System.Drawing.Point(27, 18);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(129, 23);
this.textBoxStorageName.Size = new System.Drawing.Size(114, 23);
this.textBoxStorageName.TabIndex = 7;
//
// listBoxStorages
@ -84,15 +93,15 @@
this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(27, 76);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(129, 94);
this.listBoxStorages.Size = new System.Drawing.Size(114, 49);
this.listBoxStorages.TabIndex = 6;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxStorages_SelectedIndexChanged);
//
// ButtonDelObject
//
this.ButtonDelObject.Location = new System.Drawing.Point(12, 176);
this.ButtonDelObject.Location = new System.Drawing.Point(12, 131);
this.ButtonDelObject.Name = "ButtonDelObject";
this.ButtonDelObject.Size = new System.Drawing.Size(154, 23);
this.ButtonDelObject.Size = new System.Drawing.Size(144, 23);
this.ButtonDelObject.TabIndex = 5;
this.ButtonDelObject.Text = "Удалить набор";
this.ButtonDelObject.UseVisualStyleBackColor = true;
@ -102,7 +111,7 @@
//
this.ButtonAddObject.Location = new System.Drawing.Point(12, 47);
this.ButtonAddObject.Name = "ButtonAddObject";
this.ButtonAddObject.Size = new System.Drawing.Size(154, 23);
this.ButtonAddObject.Size = new System.Drawing.Size(144, 23);
this.ButtonAddObject.TabIndex = 4;
this.ButtonAddObject.Text = "Добавить набор";
this.ButtonAddObject.UseVisualStyleBackColor = true;
@ -110,16 +119,16 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(40, 295);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(18, 235);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(129, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(13, 389);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(6, 310);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(187, 31);
this.ButtonRefreshCollection.Size = new System.Drawing.Size(172, 27);
this.ButtonRefreshCollection.TabIndex = 2;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
@ -127,9 +136,9 @@
//
// ButtonRemoveArmoredCar
//
this.ButtonRemoveArmoredCar.Location = new System.Drawing.Point(13, 324);
this.ButtonRemoveArmoredCar.Location = new System.Drawing.Point(6, 264);
this.ButtonRemoveArmoredCar.Name = "ButtonRemoveArmoredCar";
this.ButtonRemoveArmoredCar.Size = new System.Drawing.Size(181, 40);
this.ButtonRemoveArmoredCar.Size = new System.Drawing.Size(172, 40);
this.ButtonRemoveArmoredCar.TabIndex = 1;
this.ButtonRemoveArmoredCar.Text = "Удалить бронированную машину";
this.ButtonRemoveArmoredCar.UseVisualStyleBackColor = true;
@ -137,9 +146,9 @@
//
// ButtonAddArmoredCar
//
this.ButtonAddArmoredCar.Location = new System.Drawing.Point(13, 247);
this.ButtonAddArmoredCar.Location = new System.Drawing.Point(6, 190);
this.ButtonAddArmoredCar.Name = "ButtonAddArmoredCar";
this.ButtonAddArmoredCar.Size = new System.Drawing.Size(181, 42);
this.ButtonAddArmoredCar.Size = new System.Drawing.Size(172, 39);
this.ButtonAddArmoredCar.TabIndex = 0;
this.ButtonAddArmoredCar.Text = "Добавить бронированную машину";
this.ButtonAddArmoredCar.UseVisualStyleBackColor = true;
@ -153,11 +162,62 @@
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
//
// panelStrip
//
this.panelStrip.Controls.Add(this.StripMenu);
this.panelStrip.Location = new System.Drawing.Point(585, 349);
this.panelStrip.Name = "panelStrip";
this.panelStrip.Size = new System.Drawing.Size(172, 89);
this.panelStrip.TabIndex = 2;
//
// StripMenu
//
this.StripMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.StripMenu.Location = new System.Drawing.Point(0, 0);
this.StripMenu.Name = "StripMenu";
this.StripMenu.Size = new System.Drawing.Size(172, 24);
this.StripMenu.TabIndex = 0;
this.StripMenu.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.openFileDialog});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Name = "openFileDialog";
this.openFileDialog.Size = new System.Drawing.Size(141, 22);
this.openFileDialog.Text = "Загрузка";
this.openFileDialog.Click += new System.EventHandler(this.openFileDialog_Click);
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog";
this.openFileDialog1.Filter = "txt file | *.txt";
//
// FormArmoredCarCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.panelStrip);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.groupBox1);
this.Name = "FormArmoredCarCollection";
@ -167,6 +227,10 @@
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.panelStrip.ResumeLayout(false);
this.panelStrip.PerformLayout();
this.StripMenu.ResumeLayout(false);
this.StripMenu.PerformLayout();
this.ResumeLayout(false);
}
@ -184,5 +248,12 @@
private Button ButtonAddObject;
private GroupBox groupBox2;
private TextBox textBoxStorageName;
private Panel panelStrip;
private MenuStrip StripMenu;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem openFileDialog;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog1;
}
}

View File

@ -122,7 +122,6 @@ namespace Tank
{
RefreshCollection();
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
@ -133,8 +132,6 @@ namespace Tank
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -148,11 +145,42 @@ namespace Tank
ReloadObjects();
}
}
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTanks();
RefreshCollection();
}
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 openFileDialog_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog1.FileName))
{
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -57,4 +57,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="StripMenu.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>57, 7</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>165, 7</value>
</metadata>
<metadata name="openFileDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>294, 7</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>67</value>
</metadata>
</root>

View File

@ -39,6 +39,10 @@ namespace Tank.Generics
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTanks => _collection.GetTanks();
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>

View File

@ -7,6 +7,8 @@ using Tank.Generics;
using Tank.DrawingObjects;
using Tank.MovementStrategy;
using System.Globalization;
using Tank.Drawings;
using System.Xml.Linq;
namespace Tank.Generics
{
@ -15,6 +17,23 @@ namespace Tank.Generics
/// </summary>
internal class TanksGenericStorage
{
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
/// <summary>
/// Словарь (хранилище)
/// </summary>
@ -34,7 +53,7 @@ namespace Tank.Generics
public TanksGenericStorage(int pictureWidth, int pictureHeight)
{
_tankStorages = new Dictionary<string,TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>>();
_tankStorages = new Dictionary<string, TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -86,5 +105,106 @@ namespace Tank.Generics
}
}
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>> record in _tankStorages)
{
StringBuilder Records = new();
foreach (DrawingArmoredCar? elem in record.Value.GetTanks)
{
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.WriteLine("TankStorage");
writer.Write(data.ToString());
return true;
}
}
public bool SaveCollection(string filename)
Review

Зачни 2 одинаковых метода?

Зачни 2 одинаковых метода?
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>> record in _tankStorages)
{
StringBuilder Records = new();
foreach (DrawingArmoredCar? elem in record.Value.GetTanks)
{
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.WriteLine("TankStorage");
writer.Write(data.ToString());
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 strCheck = reader.ReadLine();
if (!strCheck.StartsWith("TankStorage"))
return false;
_tankStorages.Clear();
string Str;
while ((Str = reader.ReadLine()) != null)
{
if (Str == null)
break;
string name = Str.Split('|')[0];
TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in Str.Split('|')[1].Split(';'))
{
DrawingArmoredCar? ArmoredCar = data?.CreateDrawTank(_separatorForObject, _pictureWidth, _pictureHeight);
if (ArmoredCar != null)
{
if (!(collection + ArmoredCar))
{
return false;
}
}
}
_tankStorages.Add(name, collection);
}
return true;
}
}
}
}

View File

@ -24,7 +24,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Drawings\" />
<Folder Include="MovementStrategy\" />
</ItemGroup>