init full

This commit is contained in:
Калышев Ян 2022-11-06 17:17:49 +04:00
parent 37d7812381
commit 4664385343
8 changed files with 292 additions and 13 deletions

View File

@ -22,6 +22,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
return _boat?.GetCurrentPosition() ?? default;
}
public string GetInfo() => _boat?.GetDataForSave();
public void MoveObject(Direction direction)
{
_boat.MoveTransport(direction);
@ -30,5 +31,6 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
_boat.SetPosition(x, y, width, height);
}
public static IDrawningObject Create(string data) => new DrawningObjectBoat(data.CreateDrawningBoat());
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
/// <summary>
/// Расширение для класса DrawningBoat
/// </summary>
internal static class ExtentionBoat
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningBoat CreateDrawningBoat(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningSpeedboat(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="drawningBoat"></param>
/// <returns></returns>
public static string GetDataForSave (this DrawningBoat drawningBoat)
{
var boat = drawningBoat.Boat;
var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntitySpeedboat speedboat)
{
return str;
}
return $"{str}{_separatorForObject}{speedboat.DopColor.Name}{_separatorForObject}{speedboat.BodyKit}{_separatorForObject}{speedboat.Wing}{_separatorForObject}{speedboat.SportLine}";
}
}
}

View File

@ -45,9 +45,16 @@
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonAddBoat = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = 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.groupBoxTools.SuspendLayout();
this.groupBoxMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
@ -63,9 +70,9 @@
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonAddBoat);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(690, 0);
this.groupBoxTools.Location = new System.Drawing.Point(690, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(204, 587);
this.groupBoxTools.Size = new System.Drawing.Size(204, 563);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@ -167,7 +174,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::PIbd_22_Kalyshev_Y_V_MotorBoat_Base.Properties.Resources.down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(91, 537);
this.buttonDown.Location = new System.Drawing.Point(91, 513);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 10;
@ -179,7 +186,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::PIbd_22_Kalyshev_Y_V_MotorBoat_Base.Properties.Resources.right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(127, 537);
this.buttonRight.Location = new System.Drawing.Point(127, 513);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 9;
@ -191,7 +198,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::PIbd_22_Kalyshev_Y_V_MotorBoat_Base.Properties.Resources.left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(55, 537);
this.buttonLeft.Location = new System.Drawing.Point(55, 513);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
@ -203,7 +210,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::PIbd_22_Kalyshev_Y_V_MotorBoat_Base.Properties.Resources.up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(91, 501);
this.buttonUp.Location = new System.Drawing.Point(91, 477);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 7;
@ -233,12 +240,50 @@
// 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(690, 587);
this.pictureBox.Size = new System.Drawing.Size(690, 563);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(894, 24);
this.menuStrip.TabIndex = 2;
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetBoats
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -246,6 +291,8 @@
this.ClientSize = new System.Drawing.Size(894, 587);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetBoats";
this.Text = "Карта с набором объектов";
this.groupBoxTools.ResumeLayout(false);
@ -253,7 +300,10 @@
this.groupBoxMap.ResumeLayout(false);
this.groupBoxMap.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@ -276,5 +326,11 @@
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -1,4 +1,5 @@
using static System.Windows.Forms.DataFormats;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
@ -211,5 +212,43 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ??
string.Empty].MoveObject(dir);
}
/// <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))
{
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,6 +36,11 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// <returns></returns>
(float Left, float Right, float Top, float Bottom)
GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -109,6 +109,31 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
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 boat in _setBoats.GetBoats())
{
data += $"{boat.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setBoats.Insert(DrawningObjectBoat.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()

View File

@ -14,7 +14,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@ -28,13 +28,21 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// </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, MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -45,7 +53,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
_mapStorages.Add(name, new MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
@ -60,7 +68,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetBoatsGeneric<DrawningObjectBoat, AbstractMap> this[string ind]
public MapWithSetBoatsGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@ -71,5 +79,83 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
return null;
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (FileStream fs = new(filename, FileMode.Create))
{
WriteToFile($"MapsCollection{Environment.NewLine}", fs);
foreach (var storage in _mapStorages)
{
WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}", fs);
}
}
return true;
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (!strs[0].Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
}
//очищаем записи
_mapStorages.Clear();
for (int i = 1; i < strs.Length; ++i)
{
var elem = strs[i].Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MySecondMap":
map = new MySecondMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}