Potapov N.S. LabWork06 #8

Closed
ns.potapov wants to merge 11 commits from LabWork06 into LabWork05
11 changed files with 301 additions and 15 deletions

View File

@ -30,5 +30,7 @@ namespace Boats
{
_boat.DrawTransport(g);
}
public string GetInfo() => _boat?.GetDataForSave();
public static IDrawingObject Create(string data) => new DrawingObjectBoat(data.CreateDrawingBoat());
}
}

View File

@ -37,5 +37,9 @@ namespace Boats
Bobbers = bobbers;
Sail = sail;
}
public void SetDopColor(Color color)
{
DopColor = color;
}
}
}

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Boats
{
/// <summary>
/// Расширение для класса DrawingBoat
/// </summary>
internal static class ExtentionBoat
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawingBoat CreateDrawingBoat(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2])
);
}
if (strs.Length == 6)
{
return new DrawingCatamaran(
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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingBoat"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawingBoat drawingBoat)
{
var boat = drawingBoat.Boat;
var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntityCatamaran catamaran)
{
return str;
}
return $"{str}{_separatorForObject}{catamaran.DopColor.Name}{_separatorForObject}{catamaran.Bobbers}{_separatorForObject}{catamaran.Sail}";
}
}
}

View File

@ -147,10 +147,9 @@ namespace Boats
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
labelBaseColor.BackColor = (Color)e.Data.GetData(typeof(Color).ToString());
if (_boat == null)
return;
_boat.Boat.BodyColor = labelBaseColor.BackColor;
_boat.Boat.BodyColor = (Color)e.Data.GetData(typeof(Color).ToString());
DrawBoat();
}
/// <summary>
@ -176,10 +175,9 @@ namespace Boats
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
labelDopColor.BackColor = (Color)e.Data.GetData(typeof(Color).ToString());
if (_boat == null || _boat is not DrawingCatamaran)
return;
(_boat.Boat as EntityCatamaran).DopColor = labelDopColor.BackColor;
(_boat.Boat as EntityCatamaran).SetDopColor((Color)e.Data.GetData(typeof(Color).ToString()));
DrawBoat();
}
/// <summary>

View File

@ -45,9 +45,16 @@
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.ButtonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
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.groupBoxInstruments.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.groupBoxMaps.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxInstruments
@ -62,9 +69,9 @@
this.groupBoxInstruments.Controls.Add(this.ButtonRemoveBoat);
this.groupBoxInstruments.Controls.Add(this.ButtonAddBoat);
this.groupBoxInstruments.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxInstruments.Location = new System.Drawing.Point(901, 0);
this.groupBoxInstruments.Location = new System.Drawing.Point(901, 28);
this.groupBoxInstruments.Name = "groupBoxInstruments";
this.groupBoxInstruments.Size = new System.Drawing.Size(250, 768);
this.groupBoxInstruments.Size = new System.Drawing.Size(250, 783);
this.groupBoxInstruments.TabIndex = 0;
this.groupBoxInstruments.TabStop = false;
this.groupBoxInstruments.Text = "Инструменты";
@ -182,9 +189,9 @@
// 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, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(901, 768);
this.pictureBox.Size = new System.Drawing.Size(901, 783);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
@ -240,14 +247,59 @@
this.textBoxNewMapName.Size = new System.Drawing.Size(220, 27);
this.textBoxNewMapName.TabIndex = 0;
//
// 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(1151, 28);
this.menuStrip.TabIndex = 12;
this.menuStrip.Text = "menuStrip1";
//
// 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(59, 24);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Text = "Сохранить";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.LoadToolStripMenuItem.Text = "Загрузить";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = " txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = " txt file | *.txt";
//
// FormMapWithSetBoats
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1151, 768);
this.ClientSize = new System.Drawing.Size(1151, 811);
this.Controls.Add(this.groupBoxMaps);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxInstruments);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetBoats";
this.Text = "Карта с набором элементов";
this.groupBoxInstruments.ResumeLayout(false);
@ -255,7 +307,10 @@
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@ -278,5 +333,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

@ -261,5 +261,45 @@ namespace Boats
MessageBox.Show("Не удалось добавить объект");
}
}
/// <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();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
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>152, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>319, 17</value>
</metadata>
</root>

View File

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

View File

@ -239,5 +239,30 @@ namespace Boats
i++;
}
}
/// <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(DrawingObjectBoat.Create(rec) as T);
}
}
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace Boats
{
@ -14,7 +15,7 @@ namespace Boats
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@ -28,13 +29,21 @@ namespace Boats
/// </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<DrawingObjectBoat, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -46,7 +55,7 @@ namespace Boats
public void AddMap(string name, AbstractMap map)
{
// Добавление карты
MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
_mapStorages.Add(name, newMap);
}
/// <summary>
@ -67,7 +76,7 @@ namespace Boats
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap> this[string index]
public MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> this[string index]
{
get
{
@ -79,5 +88,75 @@ namespace Boats
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 = File.CreateText(filename))
{
sw.WriteLine($"MapsCollection");
foreach (var storage in _mapStorages)
{
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
}
}
return true;
}
/// <summary>
/// Загрузка нформации по лодкам в гавани из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = File.OpenText(filename))
{
string? currentLine = sr.ReadLine();
if (currentLine == null || !currentLine.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
}
//очищаем записи
_mapStorages.Clear();
currentLine = sr.ReadLine();
while (currentLine != null)
{
var elem = currentLine.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "OceanMap":
map = new OceanMap();
break;
case "LineMap":
map = new LineMap();
break;
}
_mapStorages.Add(
elem[0],
new MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map)
);
_mapStorages[elem[0]].LoadData(
elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
currentLine = sr.ReadLine();
}
}
return true;
}
}
}

View File

@ -69,10 +69,10 @@ namespace Boats
public T Remove(int position)
{
// Проверка позиции
if (Count == 0 || position < 0 || position >= _maxCount)
if (position < 0 || position >= Count)
return null;
T boat = _places[position];
_places[position] = null;
_places.RemoveAt(position);
return boat;
}
public T this[int position]