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

This commit is contained in:
Vladislav_396ntk 2024-05-20 10:41:58 +04:00
parent 3ee857a83c
commit c0a10c660b
17 changed files with 755 additions and 400 deletions

View File

@ -47,7 +47,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = pictureHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// перегрузка оператора + для класса

View File

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

View File

@ -24,7 +24,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
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>
/// Конструктор
@ -70,4 +76,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -16,7 +16,29 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// конструктор
/// </summary>
@ -87,4 +109,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
return null;
}
private bool InsertingElementCollection(int index, T obj)
{
if (_collection[index] != null) return false;
_collection[index] = obj;
return true;
}
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 LocomativeProject.Drawnings;
using System.Text;
using System.Threading.Tasks;
namespace LocomotiveProject.CollectionGenericObjects
{
@ -11,7 +8,7 @@ namespace LocomotiveProject.CollectionGenericObjects
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningBaseLocomotive
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -23,6 +20,21 @@ namespace LocomotiveProject.CollectionGenericObjects
/// </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>
@ -40,20 +52,23 @@ namespace LocomotiveProject.CollectionGenericObjects
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (name.Length <= 0 || _storages.ContainsKey(name))
if (!_storages.ContainsKey(name))
{
return;
}
switch (collectionType)
{
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
break;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
break;
default:
return;
ICollectionGenericObjects<T> collection;
switch (collectionType)
{
case CollectionType.List:
collection = new ListGenericObjects<T>();
break;
case CollectionType.Massive:
collection = new MassiveGenericObjects<T>();
break;
default:
return;
}
_storages.Add(name, collection);
}
}
@ -64,7 +79,7 @@ namespace LocomotiveProject.CollectionGenericObjects
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (!_storages.ContainsKey(name)) { return; }
_storages.Remove(name);
}
@ -77,10 +92,131 @@ namespace LocomotiveProject.CollectionGenericObjects
{
get
{
// TODO Продумать логику получения объекта
if (!_storages.ContainsKey(name)) { return null; }
return _storages[name];
// TODO Продумать логику получения
if (_storages.TryGetValue(name, out var value)) return value;
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 (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
stringBuilder.Append(value.Key);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.GetCollectionType);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.MaxCount);
stringBuilder.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
stringBuilder.Append(data);
stringBuilder.Append(_separatorItems);
}
writer.Write(stringBuilder);
}
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 streamRader = File.OpenText(filename))
{
string inputString = streamRader.ReadLine();
if (inputString == null || inputString.Length == 0)
{
return false;
}
if (!inputString.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = streamRader.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?.CreateDrawingBaseLocomotive() is T ship)
{
if (collection.Insert(ship) == -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

@ -1,4 +1,5 @@
using LocomativeProject.Entities;
using System.Diagnostics;
namespace LocomativeProject.Drawnings
{
@ -81,6 +82,17 @@ namespace LocomativeProject.Drawnings
{
_EntityBaseLocomotive = new EntityBaseLocomotive(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="entityMonorail"></param>
public DrawningBaseLocomotive(EntityBaseLocomotive entityBaseLocomotive) : this()
{
Debug.WriteLine(entityBaseLocomotive.BodyColor.ToString() + " " + entityBaseLocomotive.Speed + " " + entityBaseLocomotive.Weight);
_EntityBaseLocomotive = new EntityBaseLocomotive(entityBaseLocomotive.Speed, entityBaseLocomotive.Weight, entityBaseLocomotive.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -5,6 +5,15 @@ namespace LocomotiveProject.Drawnings
{
public class DrawningLocomotive : DrawningBaseLocomotive
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="entityModernLocomotive"></param>
public DrawningLocomotive(EntityLocomotive entityLocomotive) : base(120, 60)
{
_EntityBaseLocomotive = new EntityLocomotive(entityLocomotive.Speed, entityLocomotive.Weight, entityLocomotive.BodyColor, entityLocomotive.AdditionalColor, entityLocomotive.FuelCompartment, entityLocomotive.ExehaustPipe);
}
/// <summary>
/// Конструктор
/// </summary>

View File

@ -0,0 +1,47 @@
using LocomativeProject.Drawnings;
using LocomativeProject.Entities;
using LocomotiveProject.Drawnings;
using LocomotiveProject.Entities;
namespace LocomativeProject.Drawnings
{
/// <summary>
/// Расширение для класса EntityMonorail
/// </summary>
public static class ExtentionDrawningMonorail
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
public static DrawningBaseLocomotive? CreateDrawingBaseLocomotive(this string info)
{
string[] args = info.Split(_separatorForObject);
EntityBaseLocomotive? locomotive = EntityLocomotive.CreateEntityLocomotive(args);
if (locomotive != null) return new DrawningLocomotive((EntityLocomotive)locomotive);
locomotive = EntityBaseLocomotive.CreateEntityBaseLocomotive(args);
if (locomotive != null) return new DrawningBaseLocomotive(locomotive);
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingMonorail"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningBaseLocomotive drawningBaseLocomotive)
{
string[]? array = drawningBaseLocomotive?._EntityBaseLocomotive?.GetStringRepresention();
if (array == null)
return string.Empty;
return string.Join(_separatorForObject, array);
}
}
}

View File

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

View File

@ -36,5 +36,26 @@ namespace LocomotiveProject.Entities
ExehaustPipe = exehaustPipe;
FuelCompartment = fuelCompartment;
}
}
/// <summary>
/// Получение строк с значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresention()
{
return new string[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name.ToString(), AdditionalColor.Name.ToString(), FuelCompartment.ToString(), ExehaustPipe.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static EntityLocomotive? CreateEntityLocomotive(string[] args)
{
if (args.Length == 0 || args[0] != nameof(EntityLocomotive)) return null;
return new EntityLocomotive(Convert.ToInt32(args[1]), Convert.ToDouble(args[2]), Color.FromName(args[3]), Color.FromName(args[4]), Convert.ToBoolean(args[5]), Convert.ToBoolean(args[6]));
}
}
}

View File

@ -1,4 +1,4 @@
namespace LocomativeProject
namespace LocomotiveProject
{
partial class FormLocomotiveCollection
{
@ -28,16 +28,16 @@
/// </summary>
private void InitializeComponent()
{
groupBox1 = new GroupBox();
panelCompany = new Panel();
buttonAddLocomotive = new Button();
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddMonorail = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
buttonRemoveLocomotive = new Button();
buttonRemoveMonorail = new Button();
buttonGoToCheck = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
buttonCollectionDelete = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
@ -46,85 +46,96 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
groupBox1.SuspendLayout();
panelCompany.SuspendLayout();
menuStrip = new MenuStrip();
файлToolStripMenuItem = 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();
//
// groupBox1
// groupBoxTools
//
groupBox1.Controls.Add(panelCompany);
groupBox1.Controls.Add(buttonCreateCompany);
groupBox1.Controls.Add(panelStorage);
groupBox1.Controls.Add(comboBoxSelectorCompany);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(912, 0);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(180, 581);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(970, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(241, 638);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompany
// panelCompanyTools
//
panelCompany.Controls.Add(buttonAddLocomotive);
panelCompany.Controls.Add(maskedTextBox);
panelCompany.Controls.Add(buttonRefresh);
panelCompany.Controls.Add(buttonRemoveLocomotive);
panelCompany.Controls.Add(buttonGoToCheck);
panelCompany.Dock = DockStyle.Bottom;
panelCompany.Enabled = false;
panelCompany.Location = new Point(3, 346);
panelCompany.Name = "panelCompany";
panelCompany.Size = new Size(174, 232);
panelCompany.TabIndex = 9;
panelCompanyTools.Controls.Add(buttonAddMonorail);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveMonorail);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 313);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(235, 322);
panelCompanyTools.TabIndex = 8;
//
// buttonAddLocomotive
// buttonAddMonorail
//
buttonAddLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddLocomotive.Location = new Point(15, 6);
buttonAddLocomotive.Name = "buttonAddLocomotive";
buttonAddLocomotive.Size = new Size(150, 26);
buttonAddLocomotive.TabIndex = 1;
buttonAddLocomotive.Text = "Добавление локомотива";
buttonAddLocomotive.UseVisualStyleBackColor = true;
buttonAddLocomotive.Click += ButtonAddLocomotive_Click;
buttonAddMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMonorail.Location = new Point(8, 32);
buttonAddMonorail.Name = "buttonAddMonorail";
buttonAddMonorail.Size = new Size(221, 48);
buttonAddMonorail.TabIndex = 1;
buttonAddMonorail.Text = "Добавление локомотива";
buttonAddMonorail.UseVisualStyleBackColor = true;
buttonAddMonorail.Click += ButtonAddLocomotive_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(15, 87);
maskedTextBox.Location = new Point(5, 130);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(150, 23);
maskedTextBox.Size = new Size(223, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Location = new Point(27, 190);
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(8, 267);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(124, 39);
buttonRefresh.Size = new Size(219, 48);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonRemoveLocomotive
// buttonRemoveMonorail
//
buttonRemoveLocomotive.Location = new Point(15, 116);
buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
buttonRemoveLocomotive.Size = new Size(150, 23);
buttonRemoveLocomotive.TabIndex = 4;
buttonRemoveLocomotive.Text = "Удалить локомотив";
buttonRemoveLocomotive.UseVisualStyleBackColor = true;
buttonRemoveLocomotive.Click += ButtonRemoveLocomotive_Click;
buttonRemoveMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMonorail.Location = new Point(8, 159);
buttonRemoveMonorail.Name = "buttonRemoveMonorail";
buttonRemoveMonorail.Size = new Size(221, 48);
buttonRemoveMonorail.TabIndex = 4;
buttonRemoveMonorail.Text = "Удалить локомотив";
buttonRemoveMonorail.UseVisualStyleBackColor = true;
buttonRemoveMonorail.Click += buttonRemoveLocomotive_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(29, 145);
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(8, 213);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(124, 39);
buttonGoToCheck.Size = new Size(220, 48);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -132,17 +143,18 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(18, 320);
buttonCreateCompany.Location = new Point(6, 291);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(150, 23);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Size = new Size(222, 22);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(buttonCollectionDelete);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
@ -151,34 +163,38 @@
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(174, 266);
panelStorage.Size = new Size(235, 242);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
// buttonCollectionDelete
//
buttonCollectionDel.Location = new Point(15, 218);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(150, 23);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
buttonCollectionDelete.Location = new Point(5, 206);
buttonCollectionDelete.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDelete.Name = "buttonCollectionDelete";
buttonCollectionDelete.Size = new Size(222, 22);
buttonCollectionDelete.TabIndex = 6;
buttonCollectionDelete.Text = "Удалить коллекцию";
buttonCollectionDelete.UseVisualStyleBackColor = true;
buttonCollectionDelete.Click += ButtonCollectionDelete_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(15, 118);
listBoxCollection.Location = new Point(5, 123);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(150, 94);
listBoxCollection.Size = new Size(223, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(15, 89);
buttonCollectionAdd.Location = new Point(5, 97);
buttonCollectionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(150, 23);
buttonCollectionAdd.Size = new Size(222, 22);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
@ -187,7 +203,8 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(99, 64);
radioButtonList.Location = new Point(113, 67);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
@ -198,7 +215,8 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(15, 64);
radioButtonMassive.Location = new Point(20, 67);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
@ -208,19 +226,20 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(15, 35);
textBoxCollectionName.Location = new Point(5, 28);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(150, 23);
textBoxCollectionName.Size = new Size(223, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(29, 17);
labelCollectionName.Location = new Point(47, 10);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(122, 15);
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
@ -228,58 +247,109 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(18, 291);
comboBoxSelectorCompany.Location = new Point(3, 265);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(150, 23);
comboBoxSelectorCompany.Size = new Size(229, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(912, 581);
pictureBox.Size = new Size(970, 638);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1211, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(184, 22);
saveToolStripMenuItem.Text = "Сохранение ";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(184, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1092, 581);
ClientSize = new Size(1211, 662);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormLocomotiveCollection";
Text = "Коллекция Локомотивов";
groupBox1.ResumeLayout(false);
panelCompany.ResumeLayout(false);
panelCompany.PerformLayout();
Text = "Коллекция локомотивов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBox1;
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddLocomotive;
private Button buttonRemoveLocomotive;
private Button buttonRemoveMonorail;
private MaskedTextBox maskedTextBox;
private Button buttonAddMonorail;
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRefresh;
private Panel panelStorage;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private RadioButton radioButtonMassive;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private TextBox textBoxCollectionName;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCollectionDelete;
private ListBox listBoxCollection;
private Button buttonCreateCompany;
private Panel panelCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -1,291 +1,247 @@
using LocomativeProject.Drawnings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LocomotiveProject.CollectionGenericObjects;
using LocomotiveProject.Drawnings;
using LocomotiveProject;
namespace LocomativeProject;
public partial class FormLocomotiveCollection : Form
namespace LocomotiveProject
{
/// <summary>
/// Хранилище коллекций
///
/// </summary>
private readonly StorageCollection<DrawningBaseLocomotive> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Консруктор
/// </summary>
public FormLocomotiveCollection()
public partial class FormLocomotiveCollection : Form
{
InitializeComponent();
_storageCollection = new();
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompany.Enabled = false;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type"> тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningBaseLocomotive> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormLocomotiveCollection()
{
return;
InitializeComponent();
_storageCollection = new StorageCollection<DrawningBaseLocomotive>();
}
Random rnd = new();
DrawningBaseLocomotive drawningBaseLocomotive;
switch (type)
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
case nameof(DrawningBaseLocomotive):
drawningBaseLocomotive = new DrawningBaseLocomotive(rnd.Next(100, 300), rnd.Next(1000, 3000), GetColor(rnd));
break;
case nameof(DrawningLocomotive):
drawningBaseLocomotive = new DrawningLocomotive(rnd.Next(100, 300), rnd.Next(1000, 3000), GetColor(rnd), GetColor(rnd),
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
break;
default:
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new LocomotiveSharingService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningBaseLocomotive>());
break;
}
}
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
FormLocomotiveConfig form = new FormLocomotiveConfig();
form.Show();
form.AddEventListener_Locomotive(SetLocomotive);
}
private void SetLocomotive(DrawningBaseLocomotive Locomotive)
{
if (Locomotive == null || _company == null) return;
if (_company + Locomotive != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
private void buttonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return;
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
int position = Convert.ToInt32(maskedTextBox.Text);
if (_company - position != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null) return;
DrawningBaseLocomotive? Locomotive = null;
int coutner = 100;
while (Locomotive == null && coutner-- > 0)
{
Locomotive = _company.GetRandomObject();
}
if (Locomotive == null) return;
LocomotiveProjectForm form = new LocomotiveProjectForm()
{
SetLocomotive = Locomotive
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null) return;
pictureBox.Image = _company.Show();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_company + drawningBaseLocomotive != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение рандом цвета
/// </summary>
/// <param name="rnd"></param>
/// <returns></returns>
private static Color GetColor(Random rnd)
{
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(255, 256));
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Кнопка добавления крейсера
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
FormLocomotiveConfig form = new FormLocomotiveConfig();
form.Show();
form.AddEvent(setLocomotive);
}
/// <summary>
/// Добавление автомобиля в коллекцию
/// </summary>
/// <param name="Locomotive"></param>
private void setLocomotive(DrawningBaseLocomotive Locomotive)
{
if (_company == null || Locomotive == null)
{
return;
}
if (_company + Locomotive != -1)
{
MessageBox.Show("объект добавлен");
pictureBox.Image= _company.Show();
}
else
{
MessageBox.Show("Не удалось добавлять объект");
}
}
/// <summary>
/// Кнопка удаления Крейсера
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBox.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Кнопка отправить на полигон для испытаний
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningBaseLocomotive BaseLocomotive = null;
int counter = 100;
while (BaseLocomotive == null)
{
BaseLocomotive = _company.GetRandomObject();
counter--;
if (counter <= 0)
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
break;
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
RerfreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDelete_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Коллекция для удаления не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningBaseLocomotive>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new LocomotiveSharingService(pictureBox.Width,
pictureBox.Height, (ICollectionGenericObjects<LocomativeProject.Drawnings.DrawningBaseLocomotive>)collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <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);
}
}
}
if (BaseLocomotive == null)
/// <summary>
/// Обработка нажатия "Загрузки"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
return;
}
LocomotiveProjectForm form = new() { SetLocomotive = BaseLocomotive };
form.ShowDialog();
}
/// <summary>
/// Кнопка обновления компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Коллекция для удаления не выбрана");
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
listBoxCollection.Items.Add(colName);
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningBaseLocomotive>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new LocomotiveStation(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompany.Enabled = true;
RerfreshListBoxItems();
}
}

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="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>
</root>

View File

@ -16,9 +16,13 @@ namespace LocomotiveProject;
/// Форма конфигурации объекта
/// </summary>
public partial class FormLocomotiveConfig : Form
{
{
#region Events & Delegates
private event Action<DrawningBaseLocomotive> OnSendEvent_Locomotive;
#endregion
/// <summary>
/// объект - прорисовка круизера
/// объект - прорисовка локомотива
/// </summary>
private DrawningBaseLocomotive? _BaseLocomotive;
/// <summary>
@ -41,6 +45,12 @@ public partial class FormLocomotiveConfig : Form
panelWhite.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
public void AddEventListener_Locomotive(Action<DrawningBaseLocomotive> method)
{
OnSendEvent_Locomotive += method;
}
/// <summary>
/// привязка метода к событию
/// </summary>
@ -162,6 +172,7 @@ public partial class FormLocomotiveConfig : Form
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_BaseLocomotive != null) { _LocomotiveDelegate?.Invoke(_BaseLocomotive); Close(); }
if (_BaseLocomotive != null) OnSendEvent_Locomotive?.Invoke(_BaseLocomotive);
Close();
}
}

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows7.0</TargetFramework>
<TargetFramework>net8.0-windows7.0</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>