почти готово

This commit is contained in:
1SooNoo1 2023-11-20 23:24:07 +04:00
parent 3898aac199
commit a8323ce73c
6 changed files with 297 additions and 15 deletions

View File

@ -18,6 +18,10 @@ namespace ProjectExcavator.Generic
private readonly int _placeSizeWidth = 200;
private readonly int _placeSizeHeight = 110;
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCars => _collection.GetExcavators();
public ExcavatorGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;

View File

@ -27,6 +27,19 @@ namespace ProjectExcavator.Generic
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
@ -40,16 +53,107 @@ namespace ProjectExcavator.Generic
_pictureHeight = pictureHeight;
}
/// <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<DrawningExcavator, DrawningObjectExcavator>> record in _excavatorStorages)
{
StringBuilder records = new();
foreach (DrawningExcavator? elem in record.Value.GetCars)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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 == null || strs.Length == 0)
{
return false;
}
if (!strs[0].StartsWith("ExcavatorStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_excavatorStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
ExcavatorGenericCollection<DrawningExcavator,DrawningObjectExcavator> collection = new(_pictureWidth,_pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach(string elem in set)
{
DrawningExcavator? excavator = elem?.CreateDrawningExcavator(_separatorForObject, _pictureWidth, _pictureHeight);
if(excavator != null)
{
if (collection + excavator == -1)
{
return false;
}
}
}
_excavatorStorages.Add(record[0], collection);
}
return true;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if(_excavatorStorages.ContainsKey(name))
if (_excavatorStorages.ContainsKey(name))
{
return;
}
_excavatorStorages[name] = new ExcavatorGenericCollection<DrawningExcavator, DrawningObjectExcavator>(_pictureWidth,_pictureHeight);
_excavatorStorages[name] = new ExcavatorGenericCollection<DrawningExcavator, DrawningObjectExcavator>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
namespace ProjectExcavator
{
public static class ExtentionDrawningExcavator
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningExcavator? CreateDrawningExcavator(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningExcavator(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningExcavatorBodyKits(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="drawningExcavator">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningExcavator drawningExcavator,
char separatorForObject)
{
var excavator = drawningExcavator.EntityExcavator;
if (excavator == null)
{
return string.Empty;
}
var str = $"{excavator.Speed}{separatorForObject}{excavator.Weight}{separatorForObject}{excavator.BodyColor.Name}";
if (excavator is not EntityExcavatorBodyKits excavatorBodyKits)
{
return str;
}
return $"{str}{separatorForObject}{excavatorBodyKits.AdditionalColor.Name}{separatorForObject}{excavatorBodyKits.BodyKit}{separatorForObject}{excavatorBodyKits.Bucket}";
}
}
}

View File

@ -37,7 +37,15 @@
AddCollectButton = new Button();
DeleteCollectButton = new Button();
textBoxStorageName = new TextBox();
menuStripItem = new MenuStrip();
StripMenuItem = new ToolStripMenuItem();
toolStripMenuItem1 = new ToolStripMenuItem();
сохранитьToolStripMenuItem = new ToolStripMenuItem();
загрузитьToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStripItem.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
@ -50,7 +58,7 @@
//
// buttonAddExcavator
//
buttonAddExcavator.Location = new Point(623, 244);
buttonAddExcavator.Location = new Point(623, 275);
buttonAddExcavator.Name = "buttonAddExcavator";
buttonAddExcavator.Size = new Size(174, 51);
buttonAddExcavator.TabIndex = 1;
@ -60,14 +68,14 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(623, 301);
maskedTextBoxNumber.Location = new Point(623, 332);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(174, 23);
maskedTextBoxNumber.TabIndex = 2;
//
// buttonRemoveExcavator
//
buttonRemoveExcavator.Location = new Point(623, 330);
buttonRemoveExcavator.Location = new Point(623, 361);
buttonRemoveExcavator.Name = "buttonRemoveExcavator";
buttonRemoveExcavator.Size = new Size(174, 38);
buttonRemoveExcavator.TabIndex = 3;
@ -77,7 +85,7 @@
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(623, 374);
buttonRefreshCollection.Location = new Point(623, 405);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(174, 33);
buttonRefreshCollection.TabIndex = 4;
@ -89,7 +97,7 @@
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(623, 90);
listBoxStorages.Location = new Point(623, 156);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(174, 79);
listBoxStorages.TabIndex = 5;
@ -97,7 +105,7 @@
//
// AddCollectButton
//
AddCollectButton.Location = new Point(623, 53);
AddCollectButton.Location = new Point(623, 119);
AddCollectButton.Name = "AddCollectButton";
AddCollectButton.Size = new Size(174, 31);
AddCollectButton.TabIndex = 6;
@ -107,7 +115,7 @@
//
// DeleteCollectButton
//
DeleteCollectButton.Location = new Point(623, 175);
DeleteCollectButton.Location = new Point(623, 241);
DeleteCollectButton.Name = "DeleteCollectButton";
DeleteCollectButton.Size = new Size(174, 28);
DeleteCollectButton.TabIndex = 7;
@ -117,11 +125,52 @@
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(623, 24);
textBoxStorageName.Location = new Point(623, 90);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(174, 23);
textBoxStorageName.TabIndex = 8;
//
// menuStripItem
//
menuStripItem.Anchor = AnchorStyles.Top | AnchorStyles.Right;
menuStripItem.Dock = DockStyle.None;
menuStripItem.Items.AddRange(new ToolStripItem[] { StripMenuItem });
menuStripItem.Location = new Point(623, 9);
menuStripItem.Name = "menuStripItem";
menuStripItem.Size = new Size(170, 24);
menuStripItem.TabIndex = 9;
menuStripItem.Text = "File";
//
// StripMenuItem
//
StripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem1, сохранитьToolStripMenuItem, загрузитьToolStripMenuItem });
StripMenuItem.Name = "StripMenuItem";
StripMenuItem.Size = new Size(42, 20);
StripMenuItem.Text = "Files";
//
// toolStripMenuItem1
//
toolStripMenuItem1.Name = "toolStripMenuItem1";
toolStripMenuItem1.Size = new Size(133, 22);
//
// сохранитьToolStripMenuItem
//
сохранитьToolStripMenuItem.Name = "сохранитьToolStripMenuItem";
сохранитьToolStripMenuItem.Size = new Size(133, 22);
сохранитьToolStripMenuItem.Text = "Сохранить";
сохранитьToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// загрузитьToolStripMenuItem
//
загрузитьToolStripMenuItem.Name = агрузитьToolStripMenuItem";
загрузитьToolStripMenuItem.Size = new Size(133, 22);
загрузитьToolStripMenuItem.Text = "Загрузить";
загрузитьToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
//
// FormExcavatorCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -136,9 +185,13 @@
Controls.Add(maskedTextBoxNumber);
Controls.Add(buttonAddExcavator);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStripItem);
MainMenuStrip = menuStripItem;
Name = "FormExcavatorCollection";
Text = "Набор экскаваторов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStripItem.ResumeLayout(false);
menuStripItem.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -154,5 +207,12 @@
private Button AddCollectButton;
private Button DeleteCollectButton;
private TextBox textBoxStorageName;
private MenuStrip menuStripItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private ToolStripMenuItem StripMenuItem;
private ToolStripMenuItem toolStripMenuItem1;
private ToolStripMenuItem сохранитьToolStripMenuItem;
private ToolStripMenuItem загрузитьToolStripMenuItem;
}
}

View File

@ -2,7 +2,7 @@
using ProjectExcavator.Generic;
using ProjectExcavator.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
@ -14,7 +14,7 @@ using System.Windows.Forms;
namespace ProjectExcavator
{
public partial class FormExcavatorCollection : Form
{
{
/// <summary>
/// Набор объектов
/// </summary>
@ -86,7 +86,7 @@ pictureBoxCollection.Height);
}
private void AddExcavator(DrawningExcavator excavator)
{
if(listBoxStorages.SelectedIndex == -1)
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
@ -95,7 +95,7 @@ pictureBoxCollection.Height);
{
return;
}
if((obj + excavator) != -1)
if ((obj + excavator) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowExcavator();
@ -166,6 +166,48 @@ e)
}
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)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadObjects();
}
}
}

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="menuStripItem.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>149, 22</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>289, 17</value>
</metadata>
</root>