Готовая 6 лабораторная

This commit is contained in:
Даниил Путинцев 2023-11-23 00:09:21 +04:00
parent f711ae5b81
commit 450dccebf3
11 changed files with 309 additions and 57 deletions

View File

@ -24,6 +24,9 @@ namespace RoadTrain.Entities
{
BodyColor = color;
}
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса поезда

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.Entities;
namespace RoadTrain.DrawningObjects
{
public static class ExtentionDrawningTrain
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningRoadTrain ? CreateDrawningTrain(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningRoadTrain(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningTrain(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="drawningRoadTrain">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningRoadTrain drawningRoadTrain,
char separatorForObject)
{
var roadTrain = drawningRoadTrain.EntityRoadTrain;
if (roadTrain == null)
{
return string.Empty;
}
var str = $"{roadTrain.Speed}{separatorForObject}{roadTrain.Weight}{separatorForObject}{roadTrain.BodyColor.Name}";
if (roadTrain is not EntityTrain train)
{
return str;
}
return
$"{str}{separatorForObject}{train.AdditionalColor.Name}{separatorForObject}{train.WaterContainer}{separatorForObject}{train.SweepingBrush}";
}
}
}

View File

@ -44,9 +44,8 @@
// pictureBoxRoadTrain
//
pictureBoxRoadTrain.Location = new Point(0, 0);
pictureBoxRoadTrain.Margin = new Padding(3, 4, 3, 4);
pictureBoxRoadTrain.Name = "pictureBoxRoadTrain";
pictureBoxRoadTrain.Size = new Size(776, 481);
pictureBoxRoadTrain.Size = new Size(685, 361);
pictureBoxRoadTrain.TabIndex = 10;
pictureBoxRoadTrain.TabStop = false;
//
@ -55,10 +54,9 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(609, 359);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Location = new Point(533, 269);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(34, 40);
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
@ -68,10 +66,9 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(659, 297);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Location = new Point(577, 223);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(34, 40);
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
@ -81,10 +78,9 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(709, 359);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Location = new Point(620, 269);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(34, 40);
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
@ -94,10 +90,9 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(659, 420);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Location = new Point(577, 315);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(34, 40);
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
@ -107,18 +102,16 @@
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Центр формы", "Граница формы" });
comboBoxStrategy.Location = new Point(631, 16);
comboBoxStrategy.Margin = new Padding(3, 4, 3, 4);
comboBoxStrategy.Location = new Point(552, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(138, 28);
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 8;
//
// ButtonStep
//
ButtonStep.Location = new Point(664, 67);
ButtonStep.Margin = new Padding(3, 4, 3, 4);
ButtonStep.Location = new Point(581, 50);
ButtonStep.Name = "ButtonStep";
ButtonStep.Size = new Size(86, 31);
ButtonStep.Size = new Size(75, 23);
ButtonStep.TabIndex = 9;
ButtonStep.Text = "Шаг";
ButtonStep.UseVisualStyleBackColor = true;
@ -126,10 +119,9 @@
//
// ButtonCreateTrain
//
ButtonCreateTrain.Location = new Point(34, 380);
ButtonCreateTrain.Margin = new Padding(3, 4, 3, 4);
ButtonCreateTrain.Location = new Point(30, 285);
ButtonCreateTrain.Name = "ButtonCreateTrain";
ButtonCreateTrain.Size = new Size(131, 80);
ButtonCreateTrain.Size = new Size(115, 60);
ButtonCreateTrain.TabIndex = 11;
ButtonCreateTrain.Text = "Создать моющую машину";
ButtonCreateTrain.UseVisualStyleBackColor = true;
@ -137,10 +129,9 @@
//
// ButtonCreateRoadTrain
//
ButtonCreateRoadTrain.Location = new Point(206, 380);
ButtonCreateRoadTrain.Margin = new Padding(3, 4, 3, 4);
ButtonCreateRoadTrain.Location = new Point(180, 285);
ButtonCreateRoadTrain.Name = "ButtonCreateRoadTrain";
ButtonCreateRoadTrain.Size = new Size(106, 80);
ButtonCreateRoadTrain.Size = new Size(93, 60);
ButtonCreateRoadTrain.TabIndex = 12;
ButtonCreateRoadTrain.Text = "Создать поезд";
ButtonCreateRoadTrain.UseVisualStyleBackColor = true;
@ -148,10 +139,9 @@
//
// ButtonSelectTrain
//
ButtonSelectTrain.Location = new Point(648, 125);
ButtonSelectTrain.Margin = new Padding(3, 4, 3, 4);
ButtonSelectTrain.Location = new Point(567, 94);
ButtonSelectTrain.Name = "ButtonSelectTrain";
ButtonSelectTrain.Size = new Size(102, 56);
ButtonSelectTrain.Size = new Size(89, 42);
ButtonSelectTrain.TabIndex = 13;
ButtonSelectTrain.Text = "Добавить поезд";
ButtonSelectTrain.UseVisualStyleBackColor = true;
@ -159,9 +149,9 @@
//
// FormRoadTrain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(776, 484);
ClientSize = new Size(679, 363);
Controls.Add(ButtonSelectTrain);
Controls.Add(ButtonCreateRoadTrain);
Controls.Add(ButtonCreateTrain);
@ -172,7 +162,6 @@
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxRoadTrain);
Margin = new Padding(3, 4, 3, 4);
Name = "FormRoadTrain";
Text = "FormRoadTrain";
((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).EndInit();

View File

@ -42,9 +42,16 @@
label1 = new Label();
pictureBoxCollection = new PictureBox();
label = new Label();
menuStripFile = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panel1.SuspendLayout();
panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStripFile.SuspendLayout();
SuspendLayout();
//
// panel1
@ -59,7 +66,7 @@
panel1.Location = new Point(678, 0);
panel1.Margin = new Padding(3, 4, 3, 4);
panel1.Name = "panel1";
panel1.Size = new Size(236, 600);
panel1.Size = new Size(236, 572);
panel1.TabIndex = 0;
//
// label2
@ -162,7 +169,7 @@
//
// label1
//
label1.Location = new Point(0, 0);
label1.Location = new Point(0, 490);
label1.Name = "label1";
label1.Size = new Size(114, 31);
label1.TabIndex = 2;
@ -173,7 +180,7 @@
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(678, 600);
pictureBoxCollection.Size = new Size(678, 572);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
@ -186,6 +193,46 @@
label.TabIndex = 5;
label.Text = "Инструменты";
//
// menuStripFile
//
menuStripFile.Dock = DockStyle.Bottom;
menuStripFile.ImageScalingSize = new Size(20, 20);
menuStripFile.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStripFile.Location = new Point(0, 572);
menuStripFile.Name = "menuStripFile";
menuStripFile.Size = new Size(914, 28);
menuStripFile.TabIndex = 6;
menuStripFile.Text = "menuStripFile";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem, SaveToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(58, 24);
файлToolStripMenuItem.Text = "файл";
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(164, 26);
LoadToolStripMenuItem.Text = "загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(164, 26);
SaveToolStripMenuItem.Text = "сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = " «txt file | *.txt»";
//
// saveFileDialog
//
saveFileDialog.Filter = " «txt file | *.txt»";
//
// FormTrainCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -195,6 +242,7 @@
Controls.Add(pictureBoxCollection);
Controls.Add(panel1);
Controls.Add(label1);
Controls.Add(menuStripFile);
Margin = new Padding(3, 4, 3, 4);
Name = "FormTrainCollection";
Text = "FormTrainCollection";
@ -203,6 +251,8 @@
panel2.ResumeLayout(false);
panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStripFile.ResumeLayout(false);
menuStripFile.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -223,5 +273,11 @@
private Button ButtonDelObject;
private Button ButtonAddObject;
private TextBox textBoxStorageName;
private MenuStrip menuStripFile;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -72,6 +72,8 @@ pictureBoxCollection.Height);
var formTrainConfig = new FormTrainConfig();
formTrainConfig.AddEvent(AddTrain);
formTrainConfig.Show();
}
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
@ -155,5 +157,40 @@ pictureBoxCollection.Height);
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTrains();
}
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);
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="menuStripFile.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>168, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>338, 17</value>
</metadata>
</root>

View File

@ -174,7 +174,7 @@
//
// panelBlue
//
panelBlue.BackColor = Color.FromArgb(0, 0, 192);
panelBlue.BackColor = Color.Navy;
panelBlue.Location = new Point(146, 32);
panelBlue.Margin = new Padding(3, 4, 3, 4);
panelBlue.Name = "panelBlue";
@ -184,7 +184,7 @@
//
// panelGreen
//
panelGreen.BackColor = Color.FromArgb(0, 192, 0);
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(83, 32);
panelGreen.Margin = new Padding(3, 4, 3, 4);
panelGreen.Name = "panelGreen";

View File

@ -159,14 +159,3 @@ namespace RoadTrain
}
}
}
//case "labelSimpleObject":
// obj = new DrawningRoadTrain((int)numericUpDownSpeed.Value,
// (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
// pictureBoxObject.Height);
// break;
//case "labelModifiedObject":
// obj = new DrawningTrain((int)numericUpDownSpeed.Value,
// (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxWaterContainer.Checked,
// checkBoxSweepingBrush.Checked, pictureBoxObject.Width,
// pictureBoxObject.Height);
// break;

View File

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

View File

@ -31,6 +31,19 @@ namespace RoadTrain.Generics
/// Высота окна отрисовки
/// </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>
@ -75,6 +88,94 @@ namespace RoadTrain.Generics
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,
RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain>> record in _trainStorages)
{
StringBuilder records = new();
foreach (DrawningRoadTrain? elem in record.Value.GetTrains)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
string dataStr = data.ToString();
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine("TrainStorage");
writer.WriteLine(dataStr);
}
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 checker = reader.ReadLine();
if (checker == null)
{
return false;
}
if (!checker.StartsWith("TrainStorage"))
{
return false;
}
_trainStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
return false;
if (strs == null)
break;
if (strs == String.Empty)
break;
firstinit = false;
string name = strs.Split('|')[0];
RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';').Reverse())
{
DrawningRoadTrain? train =
data?.CreateDrawningTrain(_separatorForObject, _pictureWidth, _pictureHeight);
if (train != null)
{
if (collection + train == -1)
{
return false;
}
}
}
_trainStorages.Add(name, collection);
}
return true;
}
}
}
}