лаба6_1 комит

This commit is contained in:
Nastya_Kozlova 2023-11-29 18:27:48 +04:00
parent b2db3f35e3
commit 7c43414e62
6 changed files with 258 additions and 9 deletions

View File

@ -29,6 +29,9 @@ namespace AirFighter.Generics
// Набор объектов
private readonly SetGeneric<T> _collection;
// Получение объектов коллекции
public IEnumerable<T?> GetAirplanes => _collection.GetAirplanes();
// Конструктор
public AirplanesGenericCollection(int picWidth, int picHeight)
{

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirFighter.DrawningObjects;
using AirFighter.Drawnings;
using AirFighter.Generics;
using AirFighter.MovementStrategy;
@ -26,6 +27,15 @@ namespace AirFighter.Generics
// Высота окна отрисовки
private readonly int _pictureHeight;
// Разделитель для записи ключа и значения элемента словаря
private static readonly char _separatorForKeyValue = '|';
// Разделитель для записей коллекции данных в файл
private readonly char _separatorRecords = ';';
// Разделитель для записи информации по объекту в файл
private static readonly char _separatorForObject = ':';
// Конструктор
public AirplanesGenericStorage(int pictureWidth, int pictureHeight)
{
@ -61,5 +71,79 @@ namespace AirFighter.Generics
return null;
}
}
// Сохранение информации по самолетам в хранилище в файл
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>>
record in _AirplaneStorages)
{
StringBuilder records = new();
foreach (DrawningAirplane? elem in record.Value.GetAirplanes)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using StreamWriter sw = new(filename);
sw.Write($"AirplaneStorage{Environment.NewLine}{data}");
return true;
}
// Загрузка информации по автомобилям в хранилище из файла
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith("AirplaneStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_AirplaneStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set.Reverse())
{
DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if (airplane != null)
{
if (collection + airplane == -1)
{
return false;
}
}
}
_AirplaneStorages.Add(record[0], collection);
}
}
return true;
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirFighter.DrawningObject;
using AirFighter.DrawningObjects;
using AirFighter.Entities;
namespace AirFighter.Drawnings
{
public static class ExtentionDrawningAirplane
{
// Создание объекта из строки
public static DrawningAirplane? CreateDrawningAirplane(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirplane(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningAirFighter(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;
}
// Получение данных для сохранения в файл
public static string GetDataForSave(this DrawningAirplane drawningAirplane,
char separatorForObject)
{
var airplane = drawningAirplane.EntityAirplane;
if (airplane == null)
{
return string.Empty;
}
var str =
$"{airplane.Speed}{separatorForObject}{airplane.Weight}{separatorForObject}{airplane.BodyColor.Name}";
if (airplane is not EntityAirFighter sportCar)
{
return str;
}
return
$"{str}{separatorForObject}{sportCar.AdditionalColor.Name}{separatorForObject}{sportCar.Rockets}" +
$"{separatorForObject}{sportCar.Wings}";
}
}
}

View File

@ -31,6 +31,7 @@
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
panelSets = new Panel();
textBoxStorageName = new TextBox();
ButtonRemoveObject = new Button();
listBoxStorage = new ListBox();
ButtonAddObject = new Button();
@ -40,15 +41,21 @@
buttonRemoveAirplane = new Button();
maskedTextBoxNumber = new MaskedTextBox();
labelTools = new Label();
textBoxStorageName = new TextBox();
menuStrip1 = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
panelSets.SuspendLayout();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(1, 0);
pictureBoxCollection.Location = new Point(1, 47);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(778, 591);
pictureBoxCollection.TabIndex = 0;
@ -64,7 +71,7 @@
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Location = new Point(577, 12);
panelTools.Name = "panelTools";
panelTools.Size = new Size(202, 579);
panelTools.Size = new Size(202, 619);
panelTools.TabIndex = 1;
//
// panelSets
@ -79,6 +86,13 @@
panelSets.Size = new Size(178, 296);
panelSets.TabIndex = 8;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(10, 43);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(157, 27);
textBoxStorageName.TabIndex = 5;
//
// ButtonRemoveObject
//
ButtonRemoveObject.Location = new Point(10, 254);
@ -165,21 +179,56 @@
labelTools.TabIndex = 2;
labelTools.Text = "Инструменты";
//
// textBoxStorageName
// menuStrip1
//
textBoxStorageName.Location = new Point(10, 43);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(157, 27);
textBoxStorageName.TabIndex = 5;
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(789, 28);
menuStrip1.TabIndex = 3;
menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(59, 24);
fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(224, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new Size(224, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormAirPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(789, 597);
ClientSize = new Size(789, 643);
Controls.Add(labelTools);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormAirPlaneCollection";
Text = "FormAirPlaneCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
@ -187,6 +236,8 @@
panelTools.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -206,5 +257,11 @@
private Button ButtonRemoveObject;
private ListBox listBoxStorage;
private TextBox textBoxStorageName;
private MenuStrip menuStrip1;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -149,7 +149,9 @@ namespace AirFighter
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
@ -164,5 +166,40 @@ namespace AirFighter
}
pictureBoxCollection.Image = obj.ShowAirplanes();
}
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);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
}
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>315, 17</value>
</metadata>
</root>