Malin D.V. Lab work 6 #6

Closed
Danil_Malin wants to merge 4 commits from LabWork_06 into LabWork_05
8 changed files with 286 additions and 20 deletions

View File

@ -30,5 +30,7 @@ namespace WarmlyLocomotive
{
_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.buttonAddLocomotive = new System.Windows.Forms.Button();
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.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox
@ -63,9 +70,9 @@
this.groupBox.Controls.Add(this.maskedTextBoxPosition);
this.groupBox.Controls.Add(this.buttonAddLocomotive);
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.Size = new System.Drawing.Size(200, 629);
this.groupBox.Size = new System.Drawing.Size(200, 638);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
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.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowDown;
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, 591);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
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.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowRight;
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, 591);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
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.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowLeft;
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, 591);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
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.BackgroundImage = global::WarmlyLocomotive.Properties.Resources.arrowUp;
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, 555);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 6;
@ -186,7 +193,7 @@
// buttonShowOnMap
//
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, 500);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(169, 30);
this.buttonShowOnMap.TabIndex = 5;
@ -197,7 +204,7 @@
// buttonShowStorage
//
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, 452);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(169, 30);
this.buttonShowStorage.TabIndex = 4;
@ -208,7 +215,7 @@
// buttonRemoveLocomotive
//
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, 406);
this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
this.buttonRemoveLocomotive.Size = new System.Drawing.Size(169, 30);
this.buttonRemoveLocomotive.TabIndex = 3;
@ -219,7 +226,7 @@
// maskedTextBoxPosition
//
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, 377);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23);
@ -228,7 +235,7 @@
// buttonAddLocomotive
//
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, 341);
this.buttonAddLocomotive.Name = "buttonAddLocomotive";
this.buttonAddLocomotive.Size = new System.Drawing.Size(169, 30);
this.buttonAddLocomotive.TabIndex = 1;
@ -239,20 +246,62 @@
// pictureBox
//
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.Size = new System.Drawing.Size(668, 629);
this.pictureBox.Size = new System.Drawing.Size(668, 638);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox.TabIndex = 1;
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(141, 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(141, 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
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(868, 629);
this.ClientSize = new System.Drawing.Size(868, 662);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetLocomotives";
this.Text = "Карта с набором объектов";
this.groupBox.ResumeLayout(false);
@ -260,6 +309,8 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
@ -284,5 +335,11 @@
private ListBox listBoxMaps;
private Button buttonAddMap;
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);
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]);
ReloadMaps();
}
@ -221,5 +226,44 @@ namespace WarmlyLocomotive
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)
{
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">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</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>

View File

@ -36,5 +36,10 @@ namespace WarmlyLocomotive
/// </summary>
/// <returns></returns>
(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);
}
/// <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>
private void Shaking()

View File

@ -14,7 +14,7 @@ namespace WarmlyLocomotive
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@ -28,13 +28,21 @@ namespace WarmlyLocomotive
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -47,7 +55,7 @@ namespace WarmlyLocomotive
{
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>
@ -62,17 +70,17 @@ namespace WarmlyLocomotive
}
}
/// <summary>
/// Доступ к парковке
/// Доступ к депо
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> this[string ind]
public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
if (ind != String.Empty)
{
MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> value;
MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> value;
if (_mapStorages.TryGetValue(ind, out value))
{
return value;
@ -81,5 +89,68 @@ namespace WarmlyLocomotive
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))
{
string str = sr.ReadLine();
if (!str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
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;
}
}
}