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

This commit is contained in:
Илья 2023-11-21 15:07:16 +04:00
parent f69bc78105
commit 4d599ac689
8 changed files with 287 additions and 7 deletions

View File

@ -0,0 +1,61 @@
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.Entities;
namespace ProjectMonorail
{
/// <summary>
/// Расширение для класса EntityMonorail
/// </summary>
public static class ExtentionDrawingMonorail
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingMonorail? CreateDrawingMonorail(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingMonorail(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingExtendedMonorail(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="drawingMonorail">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingMonorail drawingMonorail, char separatorForObject)
{
var monorail = drawingMonorail.EntityMonorail;
if (monorail == null)
{
return string.Empty;
}
var str = $"{monorail.Speed}{separatorForObject}{monorail.Weight}{separatorForObject}{monorail.MainColor.Name}";
if (monorail is not EntityExtendedMonorail extendedMonorail)
{
return str;
}
return $"{str}{separatorForObject}{extendedMonorail.AdditionalColor.Name}{separatorForObject}{extendedMonorail.MagneticRail}{separatorForObject}{extendedMonorail.ExtraCabin}";
}
}
}

View File

@ -41,9 +41,16 @@
buttonRemoveMonorail = new Button(); buttonRemoveMonorail = new Button();
buttonAddMonorail = new Button(); buttonAddMonorail = new Button();
pictureBoxCollection = new PictureBox(); pictureBoxCollection = new PictureBox();
menuStripFile = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panelTools.SuspendLayout(); panelTools.SuspendLayout();
panelSets.SuspendLayout(); panelSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStripFile.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// panelTools // panelTools
@ -56,7 +63,7 @@
panelTools.Controls.Add(maskedTextBoxNumber); panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveMonorail); panelTools.Controls.Add(buttonRemoveMonorail);
panelTools.Controls.Add(buttonAddMonorail); panelTools.Controls.Add(buttonAddMonorail);
panelTools.Location = new Point(788, 10); panelTools.Location = new Point(784, 38);
panelTools.Name = "panelTools"; panelTools.Name = "panelTools";
panelTools.Size = new Size(187, 580); panelTools.Size = new Size(187, 580);
panelTools.TabIndex = 0; panelTools.TabIndex = 0;
@ -196,27 +203,74 @@
// //
// pictureBoxCollection // pictureBoxCollection
// //
pictureBoxCollection.Location = new Point(12, 10); pictureBoxCollection.Location = new Point(8, 38);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(774, 580); pictureBoxCollection.Size = new Size(774, 580);
pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
// //
// menuStripFile
//
menuStripFile.Dock = DockStyle.None;
menuStripFile.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStripFile.Location = new Point(0, 4);
menuStripFile.Name = "menuStripFile";
menuStripFile.Padding = new Padding(3, 2, 0, 2);
menuStripFile.Size = new Size(42, 24);
menuStripFile.TabIndex = 2;
menuStripFile.Text = "menuStrip";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(37, 20);
fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(100, 22);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new Size(100, 22);
loadToolStripMenuItem.Text = "Load";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormMonorailCollection // FormMonorailCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(974, 589); ClientSize = new Size(974, 626);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Controls.Add(panelTools); Controls.Add(panelTools);
Controls.Add(menuStripFile);
MainMenuStrip = menuStripFile;
Name = "FormMonorailCollection"; Name = "FormMonorailCollection";
StartPosition = FormStartPosition.CenterScreen;
Text = "Monorail collection"; Text = "Monorail collection";
panelTools.ResumeLayout(false); panelTools.ResumeLayout(false);
panelTools.PerformLayout(); panelTools.PerformLayout();
panelSets.ResumeLayout(false); panelSets.ResumeLayout(false);
panelSets.PerformLayout(); panelSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStripFile.ResumeLayout(false);
menuStripFile.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -234,5 +288,11 @@
private Button ButtonDelSet; private Button ButtonDelSet;
private Button buttonAddSet; private Button buttonAddSet;
private TextBox textBoxNameSet; private TextBox textBoxNameSet;
private MenuStrip menuStripFile;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -1,5 +1,6 @@
using ProjectMonorail.DrawingObjects; using ProjectMonorail.DrawingObjects;
using ProjectMonorail.Generics; using ProjectMonorail.Generics;
using System.Windows.Forms;
namespace ProjectMonorail namespace ProjectMonorail
{ {
@ -111,7 +112,7 @@ namespace ProjectMonorail
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} }
/// <summary> /// <summary>
@ -186,5 +187,50 @@ namespace ProjectMonorail
pictureBoxCollection.Image = obj.ShowMonorails(); pictureBoxCollection.Image = obj.ShowMonorails();
} }
/// <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("Save was successful",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Save failed", "Result",
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("Load was successful",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
}
else
{
MessageBox.Show("Load failed", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }

View File

@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStripFile.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 10</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>136, 10</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>269, 10</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>

View File

@ -136,7 +136,7 @@
// //
// panelBlue // panelBlue
// //
panelBlue.BackColor = Color.FromArgb(0, 0, 192); panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(114, 16); panelBlue.Location = new Point(114, 16);
panelBlue.Name = "panelBlue"; panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(32, 34); panelBlue.Size = new Size(32, 34);

View File

@ -37,6 +37,11 @@ namespace ProjectMonorail.Generics
/// </summary> /// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetMonorails => _collection.GetMonorails();
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>

View File

@ -1,5 +1,6 @@
using ProjectMonorail.DrawingObjects; using ProjectMonorail.DrawingObjects;
using ProjectMonorail.MovementStrategy; using ProjectMonorail.MovementStrategy;
using System.Text;
namespace ProjectMonorail.Generics namespace ProjectMonorail.Generics
{ {
@ -8,6 +9,21 @@ namespace ProjectMonorail.Generics
/// </summary> /// </summary>
internal class MonorailsGenericStorage internal class MonorailsGenericStorage
{ {
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
@ -74,5 +90,85 @@ namespace ProjectMonorail.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, MonorailsGenericCollection<DrawingMonorail, DrawingObjectMonorail>> record in _monorailsStorages)
{
StringBuilder records = new();
foreach (DrawingMonorail? elem in record.Value.GetMonorails)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using StreamWriter sw = new(filename);
sw.Write($"MonorailStorage{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 sr = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith("MonorailStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_monorailsStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
MonorailsGenericCollection<DrawingMonorail, DrawingObjectMonorail> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set.Reverse())
{
DrawingMonorail? monorail = elem?.CreateDrawingMonorail(_separatorForObject, _pictureWidth, _pictureHeight);
if (monorail != null)
{
if (collection + monorail == -1)
{
return false;
}
}
}
_monorailsStorages.Add(record[0], collection);
}
}
return true;
}
} }
} }

View File

@ -95,12 +95,12 @@
/// Проход по списку /// Проход по списку
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public IEnumerable<T?> GetMonorails(int? maxCars = null) public IEnumerable<T?> GetMonorails(int? maxMonorails = null)
{ {
for (int i = 0; i < _places.Count; ++i) for (int i = 0; i < _places.Count; ++i)
{ {
yield return _places[i]; yield return _places[i];
if (maxCars.HasValue && i == maxCars.Value) if (maxMonorails.HasValue && i == maxMonorails.Value)
{ {
yield break; yield break;
} }