ISEbd-12 Khaliullov LabWork06 Simple #7

Closed
rakhaliullov wants to merge 2 commits from LabWork6 into LabWork5
13 changed files with 431 additions and 16 deletions
Showing only changes of commit ed25e277ef - Show all commits

View File

@ -49,7 +49,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>

View File

@ -11,16 +11,19 @@ where T : class
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
@ -28,16 +31,29 @@ where T : class
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -22,7 +22,11 @@ where T : class
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@ -75,5 +79,12 @@ where T : class
return null;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -13,8 +13,14 @@ where T : class
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount {
public int MaxCount {
get
{
return _collection.Length;
}
set
{
if (value > 0) {
@ -30,6 +36,8 @@ where T : class
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -101,4 +109,12 @@ where T : class
_collection[position] = null;
return DrawningAircraft;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using Stormtrooper.CollectionGenericObjects;
using Stormtrooper.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
@ -12,16 +13,32 @@ namespace Stormtrooper.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningAircraft
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -76,5 +93,125 @@ where T : class
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
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 StreamReader(filename))// открываем файла на чтение
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningAircraft() is T aircraft)
{
if (collection.Insert(aircraft) == -1)
return false;
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -49,7 +49,7 @@ public class DrawningAircraft
/// </summary>
public int GetHeight => _drawningAircraftHeight;
// Пустой конструктор
/// Пустой конструктор
private DrawningAircraft()
{
_pictureWidth = null;
@ -77,6 +77,15 @@ public class DrawningAircraft
_pictureHeight = drawningAircraftHeight;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="aircraft"></param>
public DrawningAircraft(EntityAircraft aircraft) : this()
{
EntityAircraft = new EntityAircraft(aircraft.Speed, aircraft.Weight, aircraft.BodyColor);
}
/// Прорисовка объекта
/// <param name="g"></param>
/// // Установка границ поля

View File

@ -27,6 +27,15 @@ public class DrawningStormtrooper : DrawningAircraft
}
public DrawningStormtrooper(EntityAircraft? entityAircraft) : base(140, 70)
{
if (entityAircraft != null)
{
EntityAircraft = entityAircraft;
}
}
public override void DrawTransport(Graphics g)
{
if (EntityAircraft == null || EntityAircraft is not EntityStormtrooper entityStormtrooper|| !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -0,0 +1,59 @@
using Stormtrooper.Drawnings;
using Stormtrooper.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningAircraft
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningAircraft? CreateDrawningAircraft(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityAircraft? aircraft = EntityStormtrooper.CreateEntityStormtrooper(strs);
if (aircraft != null)
{
return new DrawningStormtrooper(aircraft);
}
aircraft = EntityAircraft.CreateEntityAicraft(strs);
if (aircraft != null)
{
return new DrawningAircraft(aircraft);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningAircraft drawningAircraft)
{
string[]? array = drawningAircraft?.EntityAircraft?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -33,6 +33,28 @@ public class EntityAircraft
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAircraft? CreateEntityAicraft(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityAircraft))
{
return null;
}
return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -38,4 +38,28 @@ public class EntityStormtrooper : EntityAircraft
Rocket = rocket;
Bomb = bomb;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityStormtrooper), Speed.ToString(), Weight.ToString(),
BodyColor.Name, AdditionalColor.Name, Rocket.ToString(), Bomb.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAircraft? CreateEntityStormtrooper(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityStormtrooper))
{
return null;
}
return new EntityStormtrooper(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(980, 0);
groupBoxTools.Location = new Point(980, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(264, 677);
groupBoxTools.Size = new Size(264, 649);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Tag = "";
@ -77,7 +84,7 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 391);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(258, 286);
panelCompanyTools.Size = new Size(258, 262);
panelCompanyTools.TabIndex = 9;
//
// buttonAddAiracft
@ -94,7 +101,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 224);
buttonRefresh.Location = new Point(0, 207);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(252, 41);
buttonRefresh.TabIndex = 6;
@ -105,7 +112,7 @@
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(3, 97);
maskedTextBox.Location = new Point(0, 80);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(252, 27);
@ -115,7 +122,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 177);
buttonGoToCheck.Location = new Point(0, 160);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(252, 41);
buttonGoToCheck.TabIndex = 5;
@ -126,7 +133,7 @@
// buttonRemoveAircraft
//
buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveAircraft.Location = new Point(3, 130);
buttonRemoveAircraft.Location = new Point(0, 113);
buttonRemoveAircraft.Name = "buttonRemoveAircraft";
buttonRemoveAircraft.Size = new Size(252, 41);
buttonRemoveAircraft.TabIndex = 4;
@ -241,12 +248,53 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(980, 677);
pictureBox.Size = new Size(980, 649);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// 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(1244, 28);
menuStrip.TabIndex = 2;
menuStrip.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.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormAircraftCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -254,6 +302,8 @@
ClientSize = new Size(1244, 677);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormAircraftCollection";
Text = "Коллекция самолетов";
groupBoxTools.ResumeLayout(false);
@ -262,7 +312,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -285,5 +338,11 @@
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -234,4 +234,45 @@ public partial class FormAircraftCollection : Form
}
}
}
/// <summary>
/// Обработка нажатия "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.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 (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -117,4 +117,16 @@
<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, 1</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 1</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 1</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>