Kasatkin S.P. LabWork6 #6

Closed
Sem730 wants to merge 7 commits from LabWork6 into LabWork5
11 changed files with 245 additions and 19 deletions

View File

@ -40,7 +40,6 @@ namespace ProjectLocomotive
return;
}
Pen pen = new(Color.Black);
if (elLocc.ElectroLines)
{
g.DrawLine(pen, _startPosX + 20, _startPosY, _startPosX + 5, _startPosY - 12);

View File

@ -31,5 +31,7 @@ namespace ProjectLocomotive
// TODO
_loc.DrawTransport(g);
}
public string getInfo() => _loc?.getDataForSave();
public static IDrawningObject Create(string data) => new DrawningObject(data.createDrawningLocomotive());
}
}

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive
{
internal static class ExtentionLocomotive
{
private static readonly char _separatorForObject = ':';
public static string getDataForSave(this DrawningLocomotive drawningLocomotive)
{
var locomotive = drawningLocomotive.Locomotivе;
var str = $"{locomotive.Speed}{_separatorForObject}{locomotive.Weight}{_separatorForObject}{locomotive.BodyColor.Name}";
if (locomotive is not EntityElectricLocomotive warmlyLocomotive)
{
return str;
}
return $"{str}{_separatorForObject}{warmlyLocomotive.DopColor.Name}{_separatorForObject}{warmlyLocomotive.ElectroLines}{_separatorForObject}{warmlyLocomotive.ElectroBattery}";
}
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 == 6)
{
return new DrawningElectroLocomotive(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5])
);
}
return null;
}
}
}

View File

@ -19,9 +19,7 @@
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.

View File

@ -172,7 +172,7 @@
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(90, 39);
this.panelGreen.Margin = new System.Windows.Forms.Padding(4);
this.panelGreen.Name = "panelGreen";
@ -360,7 +360,6 @@
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;

View File

@ -44,9 +44,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.loadFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxTools.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
@ -62,11 +69,11 @@
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddLocomotive);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(794, 0);
this.groupBoxTools.Location = new System.Drawing.Point(580, 33);
this.groupBoxTools.Margin = new System.Windows.Forms.Padding(4);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Padding = new System.Windows.Forms.Padding(4);
this.groupBoxTools.Size = new System.Drawing.Size(220, 654);
this.groupBoxTools.Size = new System.Drawing.Size(220, 535);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@ -83,7 +90,7 @@
this.groupBox1.Size = new System.Drawing.Size(208, 250);
this.groupBox1.TabIndex = 8;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Maps";
this.groupBox1.Text = "Карты";
//
// buttonDeleteMap
//
@ -238,20 +245,63 @@
// 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, 33);
this.pictureBox.Margin = new System.Windows.Forms.Padding(4);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(794, 654);
this.pictureBox.Size = new System.Drawing.Size(580, 535);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
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(800, 33);
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(69, 29);
this.fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(200, 34);
this.saveToolStripMenuItem.Text = "Сохранить";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// loadToolStripMenuItem
//
this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
this.loadToolStripMenuItem.Size = new System.Drawing.Size(200, 34);
this.loadToolStripMenuItem.Text = "Загрузить";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.loadToolStripMenuItem_Click);
//
// loadFileDialog
//
this.loadFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetLocomotives
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1014, 654);
this.ClientSize = new System.Drawing.Size(800, 568);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "FormMapWithSetLocomotives";
this.Text = "Карта с набором объектов";
@ -260,7 +310,11 @@
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
@ -280,5 +334,11 @@
private Button buttonAddMap;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog loadFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -65,7 +65,6 @@ namespace ProjectLocomotive
{
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(locomotive) != -1)
{
MessageBox.Show("Объект добавлен");
@ -75,7 +74,6 @@ namespace ProjectLocomotive
{
MessageBox.Show("Ошибка при добавлении объекта");
}
}
/// Удаление объекта
private void buttonRemoveLocomotive_Click(object sender, EventArgs e)
@ -184,5 +182,35 @@ namespace ProjectLocomotive
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Saved successfully", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Saving failed", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(loadFileDialog.FileName))
{
MessageBox.Show("Loaded successfully", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Loading failed", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}
}

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

View File

@ -39,6 +39,8 @@ namespace ProjectLocomotive
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
// Получение информации по объекту
string getInfo();
}
}

View File

@ -137,7 +137,7 @@ namespace ProjectLocomotive
int curHeight = 0;
foreach (var locomotive in _setLocomotives.GetLocomotives())
{
locomotive?.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 560, _pictureWidth, _pictureHeight);
locomotive?.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 380, _pictureWidth, _pictureHeight);
locomotive?.DrawningObject(g);
if (curWidth < width) curWidth++;
else
@ -147,5 +147,23 @@ namespace ProjectLocomotive
}
}
}
/// Получение данных в виде строки
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;
}
/// Загрузка списка из массива строк
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setLocomotives.Insert(DrawningObject.Create(rec) as T);
}
}
}
}

View File

@ -10,7 +10,7 @@ namespace Locomotive
internal class MapsCollection
{
/// Словарь (хранилище) с картами
readonly Dictionary<string, MapWithSetLocomotivesGeneric<DrawningObject,
readonly Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject,
AbstractMap>> _mapStorages;
/// Возвращение списка названий карт
public List<string> Keys => _mapStorages.Keys.ToList();
@ -18,11 +18,14 @@ namespace Locomotive
private readonly int _pictureWidth;
/// Высота окна отрисовки
private readonly int _pictureHeight;
// Сепараторы
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
/// Конструктор
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string,
MapWithSetLocomotivesGeneric<DrawningObject, AbstractMap>>();
MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -30,7 +33,7 @@ namespace Locomotive
public void AddMap(string name, AbstractMap map)
{
// Логика для добавления
if (!_mapStorages.ContainsKey(name)) _mapStorages.Add(name, new MapWithSetLocomotivesGeneric<DrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
if (!_mapStorages.ContainsKey(name)) _mapStorages.Add(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// Удаление карты
public void DelMap(string name)
@ -38,8 +41,8 @@ namespace Locomotive
// Логика для удаления
if (_mapStorages.ContainsKey(name)) _mapStorages.Remove(name);
}
/// Доступ к парковке
public MapWithSetLocomotivesGeneric<DrawningObject, AbstractMap> this[string ind]
/// Доступ к депо
public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@ -48,5 +51,66 @@ namespace Locomotive
return null;
}
}
/// Сохранение информации по локомотивам в хранилище в файл
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (FileStream fs = new(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine("MapsCollection");
foreach (var storage in _mapStorages)
{
sw.WriteLine(
$"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"
);
}
}
return true;
}
/// Загрузка информации по локомотивам в депо из файла
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
string curLine = sr.ReadLine();
if (!curLine.Contains("MapsCollection"))
Review

Файл может быть пустым и тогда возникнет ошибка

Файл может быть пустым и тогда возникнет ошибка
{
return false;
}
_mapStorages.Clear();
while ((curLine = sr.ReadLine()) != null)
{
var elems = curLine.Split(separatorDict);
AbstractMap map = null;
switch (elems[1])
{
case "Simple Map":
map = new SimpleMap();
break;
case "Spike Map":
map = new SpikeMap();
break;
case "Rail Map":
map = new RailroadMap();
break;
}
_mapStorages.Add(elems[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elems[0]].LoadData(elems[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}
}