lab_6 #6

Closed
chtzsch wants to merge 4 commits from lab_6 into lab_5
6 changed files with 293 additions and 7 deletions

View File

@ -14,6 +14,10 @@ namespace speed_Boat.Generics
where T : DrawingBoat
where U : IMovementObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBoats => _collection.GetBoats();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
@ -119,10 +123,10 @@ namespace speed_Boat.Generics
int width_Col = _pictureWidth / _placeSizeWidth;//количество колонок в окне прорисовки
foreach (var boat in _collection.GetBoats())
{
boat.screenWidth = _pictureWidth;
boat.screenHeight = _pictureHeight;
if(boat != null)
{
boat.screenWidth = _pictureWidth;
boat.screenHeight = _pictureHeight;
boat.SetPosition(col * _placeSizeWidth, (i / width_Col) * _placeSizeHeight);
col++;
if (col > 2)

View File

@ -2,6 +2,7 @@
using SpeedBoatLab.Drawings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -30,6 +31,20 @@ namespace speed_Boat.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>
@ -39,7 +54,96 @@ namespace speed_Boat.Generics
_pictureWidth = pictureWidth;
_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, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using (StreamWriter sw = new (filename))
{
sw.WriteLine($"BoatStorage{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по катерам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
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("BoatStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_boatStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
if (!(collection + boat))
{
return false;
}
}
}
_boatStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
///<summary>
/// Добавление набора
/// </summary>

View File

@ -0,0 +1,65 @@
using SpeedBoatLab.Entity;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpeedBoatLab.Drawings
{
public static class ExtentionBoat
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель данных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingBoat? CreateDrawingBoat(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingSpeedBoat(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="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель данных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingBoat drawingBoat, char separatorForObject)
{
var boat = drawingBoat._entityBoat;
if (boat == null)
{
return string.Empty;
}
var str =
$"{boat.Speed}{separatorForObject}{boat.Weight}{separatorForObject}{boat.MainColor.Name}";
if (boat is not EntitySpeedboat speedBoat)
{
return str;
}
return
$"{str}{separatorForObject}{speedBoat.SecondColor.Name}{separatorForObject}" +
$"{speedBoat.isMotor}{separatorForObject}{speedBoat.isProtectedGlass}";
}
}
}

View File

@ -40,9 +40,16 @@ namespace SpeedBoatLab
UpdateCollectionButton = new System.Windows.Forms.Button();
DeleteBoatButton = new System.Windows.Forms.Button();
AddBoatButton = new System.Windows.Forms.Button();
menuStrip1 = new System.Windows.Forms.MenuStrip();
файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
pictureBoxCollection = new System.Windows.Forms.PictureBox();
openFileDialog = new System.Windows.Forms.OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
@ -54,9 +61,10 @@ namespace SpeedBoatLab
groupBox1.Controls.Add(UpdateCollectionButton);
groupBox1.Controls.Add(DeleteBoatButton);
groupBox1.Controls.Add(AddBoatButton);
groupBox1.Controls.Add(menuStrip1);
groupBox1.Location = new System.Drawing.Point(581, 2);
groupBox1.Name = "groupBox1";
groupBox1.Size = new System.Drawing.Size(205, 436);
groupBox1.Size = new System.Drawing.Size(205, 471);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Настройки";
@ -157,27 +165,71 @@ namespace SpeedBoatLab
AddBoatButton.UseVisualStyleBackColor = true;
AddBoatButton.Click += ButtonAddBoat_Click;
//
// menuStrip1
//
menuStrip1.Dock = System.Windows.Forms.DockStyle.Bottom;
menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new System.Drawing.Point(3, 440);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new System.Drawing.Size(199, 28);
menuStrip1.TabIndex = 6;
menuStrip1.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { загрузкаToolStripMenuItem, сохранениеToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// загрузкаToolStripMenuItem
//
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// сохранениеToolStripMenuItem
//
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new System.Drawing.Point(12, 12);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new System.Drawing.Size(554, 425);
pictureBoxCollection.Size = new System.Drawing.Size(554, 527);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBoatCollection
//
AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
ClientSize = new System.Drawing.Size(800, 450);
ClientSize = new System.Drawing.Size(800, 551);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBox1);
MainMenuStrip = menuStrip1;
Name = "FormBoatCollection";
Text = "Коллекция катеров";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
}
@ -196,5 +248,11 @@ namespace SpeedBoatLab
private System.Windows.Forms.Button addStorageButton;
private System.Windows.Forms.TextBox nameStorageTextBox;
private System.Windows.Forms.Button deleteStorageButton;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem загрузкаToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem сохранениеToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
}
}

View File

@ -183,13 +183,59 @@ namespace SpeedBoatLab
{
return;
}
var obj = _storage[storagesListBox.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBoats();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (storagesListBox.SelectedIndex == -1)
{
return;
}
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(saveFileDialog.FileName))
{
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.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>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>323, 17</value>
</metadata>
</root>