This commit is contained in:
Dasha 2023-12-15 20:50:00 +04:00
parent ecffc2f002
commit 44df2f7cac
5 changed files with 280 additions and 3 deletions

View File

@ -0,0 +1,61 @@
using WarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityShip
/// </summary>
public static class ExtentionDrawningShip
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningShip? CreateDrawningShip(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningWarmlyShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningShip">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningShip drawningship, char separatorForObject)
{
var ship = drawningship.EntityShip;
if (ship == null)
{
return string.Empty;
}
var str = $"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityWarmlyShip warmlyShip)
{
return str;
}
return
$"{str}{separatorForObject}{warmlyShip.AdditionalColor.Name}{separatorForObject}{warmlyShip.Pipe}" +
$"{separatorForObject}{warmlyShip.FuelCompartment}";
}
}
}

View File

@ -41,17 +41,23 @@
ButtonDeleteShip = new Button();
maskedTextBoxNumber = new TextBox();
ButtonAddShip = new Button();
menuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new System.Windows.Forms.OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
toolsPanel.SuspendLayout();
panelSets.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(-1, 0);
pictureBoxCollection.Location = new Point(1, 31);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(655, 507);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.Size = new Size(655, 471);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
@ -172,6 +178,46 @@
ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(889, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(141, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(141, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -179,6 +225,8 @@
ClientSize = new Size(889, 508);
Controls.Add(toolsPanel);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "Набор кораблей";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
@ -186,10 +234,17 @@
toolsPanel.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private void LoadToolStripMenuItem_Click1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private PictureBox pictureBoxCollection;
@ -205,5 +260,11 @@
private TextBox textBoxStorageName;
private Button ButtonDelObject;
private Button ButtonAddObject;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -191,5 +191,49 @@ namespace WarmlyShip
}
pictureBoxCollection.Image = obj.ShowShips();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.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 (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
ListBoxObjects.Items.Add(collection);
}
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -18,6 +18,11 @@ namespace WarmlyShip.Generics
where T : DrawningShip
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetShips => _collection.GetShips();
/// <summary>
/// Ширина окна прорисовки
/// </summary>

View File

@ -34,6 +34,19 @@ namespace WarmlyShip.Generics
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
@ -46,6 +59,99 @@ namespace WarmlyShip.Generics
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawningShip? elem in record.Value.GetShips)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
string toWrite = $"ShipStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
return true;
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].StartsWith("ShipStorage"))
{
return false;
}
_shipStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningShip? ship =
elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
if (!(collection + ship))
{
return false;
}
}
}
_shipStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
/// <summary>
/// Добавление набора
/// </summary>