6 лабораторная работа

This commit is contained in:
Ilya Ryabov 2024-04-27 15:13:11 +04:00
parent dbe3954a21
commit 274f3b8dc3
13 changed files with 427 additions and 33 deletions

View File

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

View File

@ -15,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { set; get; }
/// <summary>
/// Добавление объекта в коллекцию
@ -45,4 +45,14 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper.CollectionGenericObjects;
namespace ProjectStormtrooper.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -22,7 +16,22 @@ where T : class
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount {
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@ -75,5 +84,13 @@ where T : class
return null;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using ProjectStormtrooper.Drawnings;
namespace ProjectStormtrooper.CollectionGenericObjects;
/// <summary>
@ -15,8 +16,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -32,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -51,9 +58,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{
// TODO вставка в свободное место набора
int index = 0;
while(index< _collection.Length)
while (index < _collection.Length)
{
if (_collection[index] == null) {
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
@ -107,4 +115,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return temp;
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ProjectStormtrooper.Drawnings;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper.CollectionGenericObjects;
@ -11,7 +8,7 @@ namespace ProjectStormtrooper.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningBaseStormtrooper
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -37,8 +34,8 @@ where T : class
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if(!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)){
if(collectionType== CollectionType.List)
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) {
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
@ -74,5 +71,133 @@ where T : class
return null;
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <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 (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.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 fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
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?.CreateDrawningStormtrooper() is T stormtrooper)
{
if (collection.Insert(stormtrooper) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -19,6 +19,12 @@ public class DrawingStormtrooper : DrawningBaseStormtrooper
{
EntityBaseStormtrooper = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, bombs, rockets);
}
public DrawingStormtrooper(EntityStormtrooper entityBaseStormtrooper) : base(140, 135)
{
EntityBaseStormtrooper = new EntityStormtrooper(entityBaseStormtrooper.Speed, entityBaseStormtrooper.Weight, entityBaseStormtrooper.BodyColor, entityBaseStormtrooper.AdditionalColor, entityBaseStormtrooper.Bombs, entityBaseStormtrooper.Rockets);
}
/// <summary>
/// Прорисовка объекта
/// </summary>

View File

@ -87,6 +87,11 @@ public class DrawningBaseStormtrooper
_drawningStormtrooperWidth= drawningStormtrooperWidth;
}
public DrawningBaseStormtrooper(EntityBaseStormtrooper entityBaseStormtrooper) : this()
{
EntityBaseStormtrooper = new EntityBaseStormtrooper(entityBaseStormtrooper.Speed,entityBaseStormtrooper.Weight,entityBaseStormtrooper.BodyColor);
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -243,5 +248,8 @@ public class DrawningBaseStormtrooper
Nose[2].X = _startPosX.Value + 20; Nose[2].Y = _startPosY.Value + 60;
g.FillPolygon(bodyColorBrush, Nose);
}
}

View File

@ -0,0 +1,48 @@
using ProjectStormtrooper.Entities;
namespace ProjectStormtrooper.Drawnings;
/// <summary>
/// Расширение для класса EntityStormtrooper
/// </summary>
public static class ExtentionDrawningStormtrooper
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBaseStormtrooper? CreateDrawningStormtrooper(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBaseStormtrooper? stormtrooper = EntityStormtrooper.CreateEntityStormtrooper(strs);
if (stormtrooper != null)
{
return new DrawingStormtrooper((EntityStormtrooper)stormtrooper);
}
stormtrooper = EntityBaseStormtrooper.CreateEntityBaseStormtrooper(strs);
if (stormtrooper != null)
{
return new DrawningBaseStormtrooper(stormtrooper);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningStormtrooper">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBaseStormtrooper drawningBaseStormtrooper)
{
string[]? array = drawningBaseStormtrooper?.EntityBaseStormtrooper?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

@ -40,6 +40,29 @@ public class EntityStormtrooper : EntityBaseStormtrooper
Bombs = bombs;
Rockets = rockets;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityStormtrooper), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,Bombs.ToString(),Rockets.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityStormtrooper? 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
@ -58,9 +65,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(898, 0);
groupBoxTools.Location = new Point(935, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(225, 659);
groupBoxTools.Size = new Size(225, 654);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -75,7 +82,7 @@
panelCompanyTools.Controls.Add(buttonRemoveStormtrooper);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 299);
panelCompanyTools.Location = new Point(3, 294);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(219, 357);
panelCompanyTools.TabIndex = 8;
@ -236,19 +243,62 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(898, 659);
pictureBox.Size = new Size(935, 654);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1160, 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.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// FormStormtrooperCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1123, 659);
ClientSize = new Size(1160, 678);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormStormtrooperCollection";
Text = "Коллекция бомбардировщиков";
groupBoxTools.ResumeLayout(false);
@ -257,7 +307,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -280,5 +333,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

@ -33,17 +33,17 @@ public partial class FormStormtrooperCollection : Form
{
panelCompanyTools.Enabled = true;
}
/// <summary>
/// Добавление бомбардировщика в коллекцию
/// </summary>
/// <param name="stormtrooper"></param>
/// <summary>
/// Добавление бомбардировщика в коллекцию
/// </summary>
/// <param name="stormtrooper"></param>
private void SetStormtrooper(DrawningBaseStormtrooper stormtrooper)
{
if (_company == null || stormtrooper == null)
{
return;
}
if (_company + stormtrooper !=-1)
if (_company + stormtrooper != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
@ -59,7 +59,8 @@ public partial class FormStormtrooperCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddBaseStormtrooper_Click(object sender, EventArgs e) {
private void buttonAddBaseStormtrooper_Click(object sender, EventArgs e)
{
FormStormtrooperConfig form = new();
form.Show();
@ -237,6 +238,51 @@ public partial class FormStormtrooperCollection : 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)
{
//TODO продумать логику
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, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>26</value>
</metadata>
</root>