Шестая базовая лабораторная

This commit is contained in:
Pyatkin I.A 2023-11-24 14:14:47 +04:00
parent 722e5ec1ab
commit 2f82585838
5 changed files with 379 additions and 103 deletions

View File

@ -42,6 +42,7 @@ namespace ProjectExcavator.Generics
/// </summary> /// </summary>
/// <param name="picWidth"></param> /// <param name="picWidth"></param>
/// <param name="picHeight"></param> /// <param name="picHeight"></param>
public IEnumerable<T?> GetExcavators => _collection.GetExcavators();
public ExcavatorGenericCollection(int picWidth, int picHeight) public ExcavatorGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectExcavator.DrawingObjects; using ProjectExcavator.DrawingObjects;
using ProjectExcavator.Generics;
using ProjectExcavator.MovementStrategy; using ProjectExcavator.MovementStrategy;
namespace ProjectExcavator.Generics namespace ProjectExcavator.Generics
@ -35,6 +36,18 @@ namespace ProjectExcavator.Generics
/// </summary> /// </summary>
/// <param name="pictureWidth"></param> /// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
public ExcavatorGenericStorage(int pictureWidth, int pictureHeight) public ExcavatorGenericStorage(int pictureWidth, int pictureHeight)
{ {
_excavatorStorages = new Dictionary<string, _excavatorStorages = new Dictionary<string,
@ -83,5 +96,89 @@ namespace ProjectExcavator.Generics
return null; return null;
} }
} }
/// <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();
foreach (KeyValuePair<string,
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>> record in _excavatorStorages)
{
StringBuilder records = new();
foreach (DrawingExcavator? elem in record.Value.GetExcavators)
{
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("excavatorStorages");
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 proverkaline = reader.ReadLine();
if (proverkaline == null || !proverkaline.StartsWith("excavatorStorages"))
{
return false;
}
_excavatorStorages.Clear();
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split('|');
if (parts.Length != 2)
{
return false;
}
string namestorage = parts[0];
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in parts[1].Split(';'))
{
DrawingExcavator? excavator = data?.CreateDrawingExcavator(_separatorForObject, _pictureWidth, _pictureHeight);
if (excavator != null)
{
if (!(collection + excavator))
{
return false;
}
}
}
_excavatorStorages.Add(namestorage, collection);
}
return true;
}
}
} }
} }

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
namespace ProjectExcavator.DrawingObjects
{
/// <summary>
/// Расширение для класса EntityEx
/// </summary>
public static class ExtentionDrawingExcavator
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingExcavator? CreateDrawingExcavator(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingExcavator(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingExcavatorKovsh(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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingExcavator">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingExcavator drawingExcavator, char separatorForObject)
{
var excavator = drawingExcavator.EntityExcavator;
if (excavator == null)
{
return string.Empty;
}
var str = $"{excavator.Speed}{separatorForObject}{excavator.Weight}{separatorForObject}{excavator.BodyColor.Name}";
if (excavator is not EntityExcavatorKovsh excavatorKovsh)
{
return str;
}
return $"{str}{separatorForObject}{excavatorKovsh.AdditionalColor.Name}{separatorForObject}{excavatorKovsh.Kovsh}{separatorForObject}{excavatorKovsh.Katki}";
}
}
}

View File

@ -28,145 +28,195 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); pictureBoxCollection = new PictureBox();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox(); maskedTextBoxNumber = new MaskedTextBox();
this.buttonAddEx = new System.Windows.Forms.Button(); buttonAddEx = new Button();
this.buttonRemoveEx = new System.Windows.Forms.Button(); buttonRemoveEx = new Button();
this.buttonRefreshCollection = new System.Windows.Forms.Button(); buttonRefreshCollection = new Button();
this.groupBox1 = new System.Windows.Forms.GroupBox(); groupBox1 = new GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox(); groupBox2 = new GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox(); textBoxStorageName = new TextBox();
this.buttonDelObject = new System.Windows.Forms.Button(); buttonDelObject = new Button();
this.listBoxStorages = new System.Windows.Forms.ListBox(); listBoxStorages = new ListBox();
this.buttonAddObject = new System.Windows.Forms.Button(); buttonAddObject = new Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); FilemenuStrip = new MenuStrip();
this.groupBox1.SuspendLayout(); FileToolStripMenuItem = new ToolStripMenuItem();
this.groupBox2.SuspendLayout(); SaveToolStripMenuItem = new ToolStripMenuItem();
this.SuspendLayout(); LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
FilemenuStrip.SuspendLayout();
SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
// //
this.pictureBoxCollection.Dock = System.Windows.Forms.DockStyle.Fill; pictureBoxCollection.Dock = DockStyle.Fill;
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0); pictureBoxCollection.Location = new Point(0, 24);
this.pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(909, 461); pictureBoxCollection.Size = new Size(909, 437);
this.pictureBoxCollection.TabIndex = 0; pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
this.maskedTextBoxNumber.Location = new System.Drawing.Point(35, 339); maskedTextBoxNumber.Location = new Point(35, 339);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(100, 23); maskedTextBoxNumber.Size = new Size(100, 23);
this.maskedTextBoxNumber.TabIndex = 1; maskedTextBoxNumber.TabIndex = 1;
// //
// buttonAddEx // buttonAddEx
// //
this.buttonAddEx.Location = new System.Drawing.Point(13, 310); buttonAddEx.Location = new Point(13, 310);
this.buttonAddEx.Name = "buttonAddEx"; buttonAddEx.Name = "buttonAddEx";
this.buttonAddEx.Size = new System.Drawing.Size(150, 23); buttonAddEx.Size = new Size(150, 23);
this.buttonAddEx.TabIndex = 2; buttonAddEx.TabIndex = 2;
this.buttonAddEx.Text = "Добавить экскаватор"; buttonAddEx.Text = "Добавить экскаватор";
this.buttonAddEx.UseVisualStyleBackColor = true; buttonAddEx.UseVisualStyleBackColor = true;
this.buttonAddEx.Click += new System.EventHandler(this.ButtonAddEx_Click); buttonAddEx.Click += ButtonAddEx_Click;
// //
// buttonRemoveEx // buttonRemoveEx
// //
this.buttonRemoveEx.Location = new System.Drawing.Point(13, 368); buttonRemoveEx.Location = new Point(13, 368);
this.buttonRemoveEx.Name = "buttonRemoveEx"; buttonRemoveEx.Name = "buttonRemoveEx";
this.buttonRemoveEx.Size = new System.Drawing.Size(150, 23); buttonRemoveEx.Size = new Size(150, 23);
this.buttonRemoveEx.TabIndex = 3; buttonRemoveEx.TabIndex = 3;
this.buttonRemoveEx.Text = "Удалить экскаватор"; buttonRemoveEx.Text = "Удалить экскаватор";
this.buttonRemoveEx.UseVisualStyleBackColor = true; buttonRemoveEx.UseVisualStyleBackColor = true;
this.buttonRemoveEx.Click += new System.EventHandler(this.ButtonRemoveEx_Click); buttonRemoveEx.Click += ButtonRemoveEx_Click;
// //
// buttonRefreshCollection // buttonRefreshCollection
// //
this.buttonRefreshCollection.Location = new System.Drawing.Point(13, 432); buttonRefreshCollection.Location = new Point(13, 432);
this.buttonRefreshCollection.Name = "buttonRefreshCollection"; buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(148, 23); buttonRefreshCollection.Size = new Size(148, 23);
this.buttonRefreshCollection.TabIndex = 4; buttonRefreshCollection.TabIndex = 4;
this.buttonRefreshCollection.Text = "Обновить коллекцию"; buttonRefreshCollection.Text = "Обновить коллекцию";
this.buttonRefreshCollection.UseVisualStyleBackColor = true; buttonRefreshCollection.UseVisualStyleBackColor = true;
this.buttonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click); buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
// //
// groupBox1 // groupBox1
// //
this.groupBox1.Controls.Add(this.groupBox2); groupBox1.Controls.Add(groupBox2);
this.groupBox1.Controls.Add(this.buttonAddEx); groupBox1.Controls.Add(buttonAddEx);
this.groupBox1.Controls.Add(this.buttonRefreshCollection); groupBox1.Controls.Add(buttonRefreshCollection);
this.groupBox1.Controls.Add(this.maskedTextBoxNumber); groupBox1.Controls.Add(maskedTextBoxNumber);
this.groupBox1.Controls.Add(this.buttonRemoveEx); groupBox1.Controls.Add(buttonRemoveEx);
this.groupBox1.Location = new System.Drawing.Point(741, 0); groupBox1.Location = new Point(741, 0);
this.groupBox1.Name = "groupBox1"; groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(168, 461); groupBox1.Size = new Size(168, 461);
this.groupBox1.TabIndex = 5; groupBox1.TabIndex = 5;
this.groupBox1.TabStop = false; groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты"; groupBox1.Text = "Инструменты";
// //
// groupBox2 // groupBox2
// //
this.groupBox2.Controls.Add(this.textBoxStorageName); groupBox2.Controls.Add(textBoxStorageName);
this.groupBox2.Controls.Add(this.buttonDelObject); groupBox2.Controls.Add(buttonDelObject);
this.groupBox2.Controls.Add(this.listBoxStorages); groupBox2.Controls.Add(listBoxStorages);
this.groupBox2.Controls.Add(this.buttonAddObject); groupBox2.Controls.Add(buttonAddObject);
this.groupBox2.Location = new System.Drawing.Point(13, 28); groupBox2.Location = new Point(13, 28);
this.groupBox2.Name = "groupBox2"; groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(143, 214); groupBox2.Size = new Size(143, 214);
this.groupBox2.TabIndex = 5; groupBox2.TabIndex = 5;
this.groupBox2.TabStop = false; groupBox2.TabStop = false;
this.groupBox2.Text = "Наборы"; groupBox2.Text = "Наборы";
// //
// textBoxStorageName // textBoxStorageName
// //
this.textBoxStorageName.Location = new System.Drawing.Point(15, 30); textBoxStorageName.Location = new Point(15, 30);
this.textBoxStorageName.Name = "textBoxStorageName"; textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(122, 23); textBoxStorageName.Size = new Size(122, 23);
this.textBoxStorageName.TabIndex = 6; textBoxStorageName.TabIndex = 6;
// //
// buttonDelObject // buttonDelObject
// //
this.buttonDelObject.Location = new System.Drawing.Point(15, 185); buttonDelObject.Location = new Point(15, 185);
this.buttonDelObject.Name = "buttonDelObject"; buttonDelObject.Name = "buttonDelObject";
this.buttonDelObject.Size = new System.Drawing.Size(122, 23); buttonDelObject.Size = new Size(122, 23);
this.buttonDelObject.TabIndex = 8; buttonDelObject.TabIndex = 8;
this.buttonDelObject.Text = "Удалить набор"; buttonDelObject.Text = "Удалить набор";
this.buttonDelObject.UseVisualStyleBackColor = true; buttonDelObject.UseVisualStyleBackColor = true;
this.buttonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click); buttonDelObject.Click += ButtonDelObject_Click;
// //
// listBoxStorages // listBoxStorages
// //
this.listBoxStorages.FormattingEnabled = true; listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 15; listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(15, 88); listBoxStorages.Location = new Point(15, 88);
this.listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(122, 79); listBoxStorages.Size = new Size(122, 79);
this.listBoxStorages.TabIndex = 6; listBoxStorages.TabIndex = 6;
this.listBoxStorages.Click += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged); listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
// //
// buttonAddObject // buttonAddObject
// //
this.buttonAddObject.Location = new System.Drawing.Point(15, 59); buttonAddObject.Location = new Point(15, 59);
this.buttonAddObject.Name = "buttonAddObject"; buttonAddObject.Name = "buttonAddObject";
this.buttonAddObject.Size = new System.Drawing.Size(122, 23); buttonAddObject.Size = new Size(122, 23);
this.buttonAddObject.TabIndex = 7; buttonAddObject.TabIndex = 7;
this.buttonAddObject.Text = "Добавить набор"; buttonAddObject.Text = "Добавить набор";
this.buttonAddObject.UseVisualStyleBackColor = true; buttonAddObject.UseVisualStyleBackColor = true;
this.buttonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click); buttonAddObject.Click += ButtonAddObject_Click;
//
// FilemenuStrip
//
FilemenuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
FilemenuStrip.Location = new Point(0, 0);
FilemenuStrip.Name = "FilemenuStrip";
FilemenuStrip.Size = new Size(909, 24);
FilemenuStrip.TabIndex = 6;
FilemenuStrip.Text = "menuStrip1";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(133, 22);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(133, 22);
LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "\"txt file|*.txt|Все файлы|*.*\".";
//
// saveFileDialog
//
saveFileDialog.Filter = "\"txt file|*.txt|Все файлы|*.*\".";
// //
// FormExcavatorCollection // FormExcavatorCollection
// //
this.ClientSize = new System.Drawing.Size(909, 461); ClientSize = new Size(909, 461);
this.Controls.Add(this.groupBox1); Controls.Add(groupBox1);
this.Controls.Add(this.pictureBoxCollection); Controls.Add(pictureBoxCollection);
this.Name = "FormExcavatorCollection"; Controls.Add(FilemenuStrip);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); MainMenuStrip = FilemenuStrip;
this.groupBox1.ResumeLayout(false); Name = "FormExcavatorCollection";
this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
this.groupBox2.ResumeLayout(false); groupBox1.ResumeLayout(false);
this.groupBox2.PerformLayout(); groupBox1.PerformLayout();
this.ResumeLayout(false); groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
FilemenuStrip.ResumeLayout(false);
FilemenuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -182,5 +232,11 @@
private Button buttonDelObject; private Button buttonDelObject;
private ListBox listBoxStorages; private ListBox listBoxStorages;
private Button buttonAddObject; private Button buttonAddObject;
private MenuStrip FilemenuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -2,6 +2,8 @@
using ProjectExcavator.Generics; using ProjectExcavator.Generics;
using ProjectExcavator.MovementStrategy; using ProjectExcavator.MovementStrategy;
using ProjectExcavator.Excavators; using ProjectExcavator.Excavators;
using System.Windows.Forms;
namespace ProjectExcavator namespace ProjectExcavator
{ {
/// <summary> /// <summary>
@ -182,5 +184,60 @@ namespace ProjectExcavator
} }
pictureBoxCollection.Image = obj.ShowExcavator(); pictureBoxCollection.Image = obj.ShowExcavator();
} }
/// <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)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowExcavator();
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }