6 лаба (непроверенная)

This commit is contained in:
Danil Malin 2022-11-03 19:18:35 +04:00
parent 5c51aa1122
commit 314d2c3b15
8 changed files with 298 additions and 19 deletions

View File

@ -30,5 +30,7 @@ namespace WarmlyLocomotive
{ {
_locomotive.SetPosition(x, y, width, height); _locomotive.SetPosition(x, y, width, height);
} }
public string GetInfo() => _locomotive?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectLocomotive(data.CreateDrawningLocomotive());
} }
} }

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyLocomotive
{
internal static class ExtentionLocomotive
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningLocomotive CreateDrawningLocomotive(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningLocomotive(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningWarmlyLocomotive(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]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLocomotive"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningLocomotive drawningLocomotive)
{
var locomotive = drawningLocomotive.Locomotive;
var str = $"{locomotive.Speed}{_separatorForObject}{locomotive.Weight}{_separatorForObject}{locomotive.BodyColor.Name}";
if (locomotive is not EntityWarmlyLocomotive warmlyLocomotive)
{
return str;
}
return $"{str}{_separatorForObject}{warmlyLocomotive.DopColor.Name}{_separatorForObject}{warmlyLocomotive.Pipe}{_separatorForObject}{warmlyLocomotive.FuelCompartment}{_separatorForObject}{warmlyLocomotive.WarmlyLines}";
}
}
}

View File

@ -45,9 +45,16 @@
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox(); this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddLocomotive = new System.Windows.Forms.Button(); this.buttonAddLocomotive = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox(); this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBox.SuspendLayout(); this.groupBox.SuspendLayout();
this.groupBoxMaps.SuspendLayout(); this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// groupBox // groupBox
@ -63,9 +70,9 @@
this.groupBox.Controls.Add(this.maskedTextBoxPosition); this.groupBox.Controls.Add(this.maskedTextBoxPosition);
this.groupBox.Controls.Add(this.buttonAddLocomotive); this.groupBox.Controls.Add(this.buttonAddLocomotive);
this.groupBox.Dock = System.Windows.Forms.DockStyle.Right; this.groupBox.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox.Location = new System.Drawing.Point(668, 0); this.groupBox.Location = new System.Drawing.Point(668, 24);
this.groupBox.Name = "groupBox"; this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(200, 629); this.groupBox.Size = new System.Drawing.Size(200, 605);
this.groupBox.TabIndex = 0; this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false; this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты"; this.groupBox.Text = "Инструменты";
@ -140,7 +147,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowDown; this.buttonDown.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(87, 582); this.buttonDown.Location = new System.Drawing.Point(87, 558);
this.buttonDown.Name = "buttonDown"; this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30); this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 9; this.buttonDown.TabIndex = 9;
@ -152,7 +159,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowRight; this.buttonRight.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(123, 582); this.buttonRight.Location = new System.Drawing.Point(123, 558);
this.buttonRight.Name = "buttonRight"; this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30); this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 8; this.buttonRight.TabIndex = 8;
@ -164,7 +171,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowLeft; this.buttonLeft.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(51, 582); this.buttonLeft.Location = new System.Drawing.Point(51, 558);
this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30); this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 7; this.buttonLeft.TabIndex = 7;
@ -176,7 +183,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowUp; this.buttonUp.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(87, 546); this.buttonUp.Location = new System.Drawing.Point(87, 522);
this.buttonUp.Name = "buttonUp"; this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30); this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 6; this.buttonUp.TabIndex = 6;
@ -186,7 +193,7 @@
// buttonShowOnMap // buttonShowOnMap
// //
this.buttonShowOnMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonShowOnMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowOnMap.Location = new System.Drawing.Point(19, 491); this.buttonShowOnMap.Location = new System.Drawing.Point(19, 467);
this.buttonShowOnMap.Name = "buttonShowOnMap"; this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(169, 30); this.buttonShowOnMap.Size = new System.Drawing.Size(169, 30);
this.buttonShowOnMap.TabIndex = 5; this.buttonShowOnMap.TabIndex = 5;
@ -197,7 +204,7 @@
// buttonShowStorage // buttonShowStorage
// //
this.buttonShowStorage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonShowStorage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowStorage.Location = new System.Drawing.Point(19, 443); this.buttonShowStorage.Location = new System.Drawing.Point(19, 419);
this.buttonShowStorage.Name = "buttonShowStorage"; this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(169, 30); this.buttonShowStorage.Size = new System.Drawing.Size(169, 30);
this.buttonShowStorage.TabIndex = 4; this.buttonShowStorage.TabIndex = 4;
@ -208,7 +215,7 @@
// buttonRemoveLocomotive // buttonRemoveLocomotive
// //
this.buttonRemoveLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRemoveLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(19, 397); this.buttonRemoveLocomotive.Location = new System.Drawing.Point(19, 373);
this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive"; this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
this.buttonRemoveLocomotive.Size = new System.Drawing.Size(169, 30); this.buttonRemoveLocomotive.Size = new System.Drawing.Size(169, 30);
this.buttonRemoveLocomotive.TabIndex = 3; this.buttonRemoveLocomotive.TabIndex = 3;
@ -219,7 +226,7 @@
// maskedTextBoxPosition // maskedTextBoxPosition
// //
this.maskedTextBoxPosition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.maskedTextBoxPosition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 368); this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 344);
this.maskedTextBoxPosition.Mask = "00"; this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition"; this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23); this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23);
@ -228,7 +235,7 @@
// buttonAddLocomotive // buttonAddLocomotive
// //
this.buttonAddLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonAddLocomotive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAddLocomotive.Location = new System.Drawing.Point(19, 332); this.buttonAddLocomotive.Location = new System.Drawing.Point(19, 308);
this.buttonAddLocomotive.Name = "buttonAddLocomotive"; this.buttonAddLocomotive.Name = "buttonAddLocomotive";
this.buttonAddLocomotive.Size = new System.Drawing.Size(169, 30); this.buttonAddLocomotive.Size = new System.Drawing.Size(169, 30);
this.buttonAddLocomotive.TabIndex = 1; this.buttonAddLocomotive.TabIndex = 1;
@ -239,13 +246,53 @@
// pictureBox // pictureBox
// //
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0); this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox"; this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(668, 629); this.pictureBox.Size = new System.Drawing.Size(668, 605);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox.TabIndex = 1; this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false; this.pictureBox.TabStop = false;
// //
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(868, 24);
this.menuStrip.TabIndex = 2;
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file|*.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file|*.txt";
//
// FormMapWithSetLocomotives // FormMapWithSetLocomotives
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -253,6 +300,8 @@
this.ClientSize = new System.Drawing.Size(868, 629); this.ClientSize = new System.Drawing.Size(868, 629);
this.Controls.Add(this.pictureBox); this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox); this.Controls.Add(this.groupBox);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetLocomotives"; this.Name = "FormMapWithSetLocomotives";
this.Text = "Карта с набором объектов"; this.Text = "Карта с набором объектов";
this.groupBox.ResumeLayout(false); this.groupBox.ResumeLayout(false);
@ -260,6 +309,8 @@
this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout(); this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
@ -284,5 +335,11 @@
private ListBox listBoxMaps; private ListBox listBoxMaps;
private Button buttonAddMap; private Button buttonAddMap;
private TextBox textBoxNewMapName; private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -191,6 +191,11 @@ namespace WarmlyLocomotive
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
{
MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
} }
@ -221,5 +226,45 @@ namespace WarmlyLocomotive
ReloadMaps(); ReloadMaps();
} }
} }
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.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 (_mapsCollection.LoadData(openFileDialog.FileName))
{
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }

View File

@ -57,4 +57,13 @@
<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="menuStrip.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>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root> </root>

View File

@ -36,5 +36,10 @@ namespace WarmlyLocomotive
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition(); (float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
} }
} }

View File

@ -108,6 +108,31 @@ namespace WarmlyLocomotive
return new(_pictureWidth, _pictureHeight); return new(_pictureWidth, _pictureHeight);
} }
/// <summary> /// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var locomotive in _setLocomotives.GetLocomotives())
{
data += $"{locomotive.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setLocomotives.Insert(DrawningObjectLocomotive.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале /// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary> /// </summary>
private void Shaking() private void Shaking()

View File

@ -14,7 +14,7 @@ namespace WarmlyLocomotive
/// <summary> /// <summary>
/// Словарь (хранилище) с картами /// Словарь (хранилище) с картами
/// </summary> /// </summary>
readonly Dictionary<string, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>> _mapStorages; readonly Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary> /// <summary>
/// Возвращение списка названий карт /// Возвращение списка названий карт
/// </summary> /// </summary>
@ -28,13 +28,21 @@ namespace WarmlyLocomotive
/// </summary> /// </summary>
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary> /// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="pictureWidth"></param> /// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight) public MapsCollection(int pictureWidth, int pictureHeight)
{ {
_mapStorages = new Dictionary<string, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>>(); _mapStorages = new Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -47,7 +55,7 @@ namespace WarmlyLocomotive
{ {
if (!_mapStorages.ContainsKey(name)) if (!_mapStorages.ContainsKey(name))
{ {
_mapStorages.Add(name, new MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>(_pictureWidth, _pictureHeight, map)); _mapStorages.Add(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
} }
} }
/// <summary> /// <summary>
@ -62,17 +70,17 @@ namespace WarmlyLocomotive
} }
} }
/// <summary> /// <summary>
/// Доступ к парковке /// Доступ к депо
/// </summary> /// </summary>
/// <param name="ind"></param> /// <param name="ind"></param>
/// <returns></returns> /// <returns></returns>
public MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> this[string ind] public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> this[string ind]
{ {
get get
{ {
if (ind != String.Empty) if (ind != String.Empty)
{ {
MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> value; MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> value;
if (_mapStorages.TryGetValue(ind, out value)) if (_mapStorages.TryGetValue(ind, out value))
{ {
return value; return value;
@ -81,5 +89,80 @@ namespace WarmlyLocomotive
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по локомотивам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка информации по локомотивам в депо из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new(filename))
{
bool isFirst = true;
string str;
while((str = sr.ReadLine()) != null)
{
if (isFirst)
{
if (!str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
}
else
{
//очищаем записи
_mapStorages.Clear();
}
isFirst = false;
}
else
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "BigBarriersMap":
map = new BigBarriersMap();
break;
case "CirclesMap":
map = new CirclesMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
return true;
}
} }
} }