4 Commits

Author SHA1 Message Date
95cdc05c76 изменения 2024-05-07 19:24:38 +04:00
6b8ef29396 лабораторная работа 6 2024-05-05 16:18:45 +04:00
37a08bafc8 Лабораторная работа 5 2024-04-22 14:04:34 +04:00
95921980a6 готовая 4 лабораторная работа 2024-04-08 13:06:55 +04:00
18 changed files with 1612 additions and 122 deletions

View File

@@ -53,7 +53,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -64,7 +64,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningMachine machine) public static int operator +(AbstractCompany company, DrawningMachine machine)
{ {
return company._collection.Insert(machine); return company._collection.Insert(machine, 0);
} }
/// <summary> /// <summary>

View File

@@ -0,0 +1,21 @@
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// неопределено
/// </summary>
None = 0,
/// <summary>
/// массив
/// </summary>
Massive = 1,
/// <summary>
/// список
/// </summary>
List = 2
}

View File

@@ -1,4 +1,5 @@
using System; using ProjectGasMachine.CollectionGenericObjects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -21,7 +22,7 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@@ -51,4 +52,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
} }

View File

@@ -0,0 +1,88 @@

namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount)
{
return -1;
}
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position)
{
if (Count == _maxCount || position < 0 || position > Count)
{
return -1;
}
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
if (position < 0 || position > Count)
{
return null;
}
T? obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,5 @@
namespace ProjectGasMachine.CollectionGenericObjects; 
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@@ -15,7 +16,30 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length; 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>
/// конструктор /// конструктор
@@ -94,4 +118,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -0,0 +1,229 @@
using ProjectGasMachine.Drawnings;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningMachine
{
/// <summary>
/// словарь (хранилище) с коллекциями
/// </summary>
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>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
/// добваление коллекции в хранилище
/// </summary>
/// <param name="name">название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name))
{
return;
}
if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name"></param>
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name))
{
return;
}
_storages.Remove(name);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
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 sw = new StreamWriter(filename))
{
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sw.Write(data);
sw.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(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
return false;
}
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
{
string[] record = line.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?.CreateDrawningMachine() is T machine)
{
if (collection.Insert(machine) == -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

@@ -23,6 +23,15 @@ public class DrawningGasMachine : DrawningMachine
EntityGas = new EntityMachine(speed, weight, bodyColor, additionalColor, gas, beacon); EntityGas = new EntityMachine(speed, weight, bodyColor, additionalColor, gas, beacon);
} }
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="gasmachine"></param>
public DrawningGasMachine(EntityGas? gasmachine) : base(gasmachine)
{
EntityGas = gasmachine;
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@@ -97,6 +97,18 @@ public class DrawningMachine
_drawningMachineWidth = drawningMachineWidth; _drawningMachineWidth = drawningMachineWidth;
_pictureHeight = drawningMachineHeight; _pictureHeight = drawningMachineHeight;
} }
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="machine"></param>
public DrawningMachine(EntityGas? machine) : this()
{
EntityGas = machine;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>

View File

@@ -0,0 +1,56 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
public static class ExtentionDrawningGas
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningMachine? CreateDrawningMachine(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityGas? machine = EntityMachine.CreateEntityMachine(strs);
if (machine != null)
{
return new DrawningGasMachine(machine);
}
machine = EntityGas.CreateEntityGas(strs);
if (machine != null)
{
return new DrawningMachine(machine);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningMachine">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningMachine drawningMachine)
{
string[]? array = drawningMachine?.EntityGas?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

@@ -27,4 +27,43 @@ public class EntityMachine : EntityGas
Gas = gas; Gas = gas;
Beacon = beacon; Beacon = beacon;
} }
/// <summary>
/// Смена дополнительного цвета
/// </summary>
/// <param name="newColor"></param>
public void AdditionalColorChange(Color newColor)
{
AdditionalColor = newColor;
}
public override string[] GetStringRepresentation()
{
return new[]
{
nameof(EntityMachine),
Speed.ToString(),
Weight.ToString(),
BodyColor.Name,
AdditionalColor.Name,
Gas.ToString(),
Beacon.ToString(),
};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMachine? CreateEntityMachine(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityMachine))
{
return null;
}
return new EntityMachine(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

@@ -0,0 +1,365 @@
namespace ProjectGasMachine
{
partial class FormGasConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxBeacon = new CheckBox();
checkBoxGas = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxBeacon);
groupBoxConfig.Controls.Add(checkBoxGas);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(464, 208);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(249, 12);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(209, 98);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(168, 64);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(30, 28);
panelPurple.TabIndex = 1;
panelPurple.MouseDown += Panel_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(118, 64);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(30, 28);
panelBlack.TabIndex = 1;
panelBlack.MouseDown += Panel_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(62, 64);
panelGray.Name = "panelGray";
panelGray.Size = new Size(30, 28);
panelGray.TabIndex = 1;
panelGray.MouseDown += Panel_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(11, 64);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(30, 28);
panelWhite.TabIndex = 2;
panelWhite.MouseDown += Panel_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(168, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(30, 28);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += Panel_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(118, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(30, 28);
panelBlue.TabIndex = 1;
panelBlue.MouseDown += Panel_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(62, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(30, 28);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += Panel_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(11, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(30, 28);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxBeacon
//
checkBoxBeacon.AutoSize = true;
checkBoxBeacon.Location = new Point(12, 130);
checkBoxBeacon.Name = "checkBoxBeacon";
checkBoxBeacon.Size = new Size(159, 19);
checkBoxBeacon.TabIndex = 7;
checkBoxBeacon.Text = "Признак наличия маяка";
checkBoxBeacon.UseVisualStyleBackColor = true;
//
// checkBoxGas
//
checkBoxGas.AutoSize = true;
checkBoxGas.Location = new Point(12, 99);
checkBoxGas.Name = "checkBoxGas";
checkBoxGas.Size = new Size(221, 19);
checkBoxGas.TabIndex = 6;
checkBoxGas.Text = "Признак наличия бака для бензина";
checkBoxGas.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(80, 52);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(104, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 54);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(80, 17);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(104, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 19);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(357, 127);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(101, 32);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(250, 127);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(101, 32);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой ";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(12, 42);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(177, 91);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(482, 173);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 23);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(584, 173);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(470, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(199, 147);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(105, 7);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(84, 26);
labelAdditionalColor.TabIndex = 10;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(12, 7);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(85, 26);
labelBodyColor.TabIndex = 9;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormGasConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(671, 208);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormGasConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxGas;
private CheckBox checkBoxBeacon;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,174 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Entities;
namespace ProjectGasMachine;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormGasConfig : Form
{
/// <summary>
/// Объект - прорисовка машины
/// </summary>
private DrawningMachine? _machine;
/// <summary>
/// событие для передачи объекта
/// </summary>
private event Action<DrawningMachine>? MachineDelegate;
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="machineDelegate"></param>
public void AddEvent(Action<DrawningMachine>? machineDelegate)
{
MachineDelegate += machineDelegate;
}
/// <summary>
/// Конструктор
/// </summary>
public FormGasConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_machine?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_machine?.SetPosition(5, 5);
_machine?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label(Объект)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации(Объект) (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации(Объект)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_machine = new DrawningMachine((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_machine = new DrawningGasMachine((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxGas.Checked, checkBoxBeacon.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
// TODO отправка цвета в Drag&Drop +
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor ?? Color.Black, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации(Основной цвет) (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации(Основной цвет)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
_machine?.EntityGas?.BodyColorChange((Color)e.Data?.GetData(typeof(Color)));
DrawObject();
}
/// <summary>
/// Проверка получаемой информации(Доп. цвет) (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации(Доп. цвет)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_machine?.EntityGas is EntityMachine _gasmachine)
{
_gasmachine.AdditionalColorChange((Color)e.Data?.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_machine != null)
{
MachineDelegate?.Invoke(_machine);
Close();
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -29,98 +29,208 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonRefresh = new Button(); panelCompanyTools = new Panel();
buttonGoToCheck = new Button();
buttonRemoveMachine = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddMachine = new Button(); buttonAddMachine = new Button();
buttonAddGasMachine = new Button(); maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
buttonRemoveMachine = new Button();
buttonGoToCheck = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
// //
groupBoxTools.Controls.Add(buttonRefresh); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonGoToCheck); groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(buttonRemoveMachine); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddMachine);
groupBoxTools.Controls.Add(buttonAddGasMachine);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(727, 0); groupBoxTools.Location = new Point(727, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(196, 543); groupBoxTools.Size = new Size(196, 519);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// buttonRefresh // panelCompanyTools
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; panelCompanyTools.Controls.Add(buttonAddMachine);
buttonRefresh.Location = new Point(6, 487); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
buttonRefresh.Name = "buttonRefresh"; panelCompanyTools.Controls.Add(buttonRefresh);
buttonRefresh.Size = new Size(184, 50); panelCompanyTools.Controls.Add(buttonRemoveMachine);
buttonRefresh.TabIndex = 7; panelCompanyTools.Controls.Add(buttonGoToCheck);
buttonRefresh.Text = "Обновить"; panelCompanyTools.Dock = DockStyle.Bottom;
buttonRefresh.UseVisualStyleBackColor = true; panelCompanyTools.Enabled = false;
buttonRefresh.Click += ButtonRefresh_Click; panelCompanyTools.Location = new Point(3, 323);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(190, 193);
panelCompanyTools.TabIndex = 9;
// //
// buttonGoToCheck // buttonAddMachine
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 365); buttonAddMachine.Location = new Point(10, 3);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonAddMachine.Name = "buttonAddMachine";
buttonGoToCheck.Size = new Size(184, 50); buttonAddMachine.Size = new Size(174, 33);
buttonGoToCheck.TabIndex = 6; buttonAddMachine.TabIndex = 2;
buttonGoToCheck.Text = "Передать на тесты"; buttonAddMachine.Text = "Добавление грузовика";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonAddMachine.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click; buttonAddMachine.Click += ButtonAddMachine_Click;
//
// buttonRemoveMachine
//
buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMachine.Location = new Point(6, 265);
buttonRemoveMachine.Name = "buttonRemoveMachine";
buttonRemoveMachine.Size = new Size(184, 50);
buttonRemoveMachine.TabIndex = 5;
buttonRemoveMachine.Text = "Удалить газовоз";
buttonRemoveMachine.UseVisualStyleBackColor = true;
buttonRemoveMachine.Click += ButtonRemoveMachine_Click;
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(6, 236); maskedTextBoxPosition.Location = new Point(3, 42);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(184, 23); maskedTextBoxPosition.Size = new Size(184, 23);
maskedTextBoxPosition.TabIndex = 4; maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int); maskedTextBoxPosition.ValidatingType = typeof(int);
// //
// buttonAddMachine // buttonRefresh
// //
buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMachine.Location = new Point(6, 140); buttonRefresh.Location = new Point(10, 152);
buttonAddMachine.Name = "buttonAddMachine"; buttonRefresh.Name = "buttonRefresh";
buttonAddMachine.Size = new Size(184, 50); buttonRefresh.Size = new Size(174, 32);
buttonAddMachine.TabIndex = 2; buttonRefresh.TabIndex = 7;
buttonAddMachine.Text = "Добавление грузовика"; buttonRefresh.Text = "Обновить";
buttonAddMachine.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
buttonAddMachine.Click += ButtonAddMachine_Click; buttonRefresh.Click += ButtonRefresh_Click;
// //
// buttonAddGasMachine // buttonRemoveMachine
// //
buttonAddGasMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddGasMachine.Location = new Point(6, 84); buttonRemoveMachine.Location = new Point(10, 71);
buttonAddGasMachine.Name = "buttonAddGasMachine"; buttonRemoveMachine.Name = "buttonRemoveMachine";
buttonAddGasMachine.Size = new Size(184, 50); buttonRemoveMachine.Size = new Size(174, 32);
buttonAddGasMachine.TabIndex = 1; buttonRemoveMachine.TabIndex = 5;
buttonAddGasMachine.Text = "Добавление газовоза"; buttonRemoveMachine.Text = "Удалить газовоз";
buttonAddGasMachine.UseVisualStyleBackColor = true; buttonRemoveMachine.UseVisualStyleBackColor = true;
buttonAddGasMachine.Click += ButtonAddGasMachine_Click; buttonRemoveMachine.Click += ButtonRemoveMachine_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(10, 109);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(174, 29);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 294);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(184, 23);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(190, 239);
panelStorage.TabIndex = 8;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 206);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(184, 23);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 106);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(184, 94);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 77);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(184, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(115, 52);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(16, 52);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 18);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(184, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(34, 0);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
// //
// comboBoxSelectorCompany // comboBoxSelectorCompany
// //
@@ -128,7 +238,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 22); comboBoxSelectorCompany.Location = new Point(6, 265);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(184, 23); comboBoxSelectorCompany.Size = new Size(184, 23);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
@@ -137,12 +247,52 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(727, 543); pictureBox.Size = new Size(727, 519);
pictureBox.TabIndex = 3; pictureBox.TabIndex = 3;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(923, 24);
menuStrip.TabIndex = 4;
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.Filter = "txt file | *.txt";
//
// FormGasMachineCollection // FormGasMachineCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@@ -150,12 +300,20 @@
ClientSize = new Size(923, 543); ClientSize = new Size(923, 543);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormGasMachineCollection"; Name = "FormGasMachineCollection";
Text = "Коллекция газовозов"; Text = "Коллекция газовозов";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout(); panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -163,11 +321,26 @@
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonAddMachine; private Button buttonAddMachine;
private Button buttonAddGasMachine;
private Button buttonRemoveMachine; private Button buttonRemoveMachine;
private MaskedTextBox maskedTextBoxPosition; private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonRefresh; private Button buttonRefresh;
private Button buttonGoToCheck; private Button buttonGoToCheck;
private Panel panelStorage;
private Label labelCollectionName;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -1,5 +1,6 @@
using ProjectGasMachine.CollectionGenericObjects; using ProjectGasMachine.CollectionGenericObjects;
using ProjectGasMachine.Drawnings; using ProjectGasMachine.Drawnings;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectGasMachine namespace ProjectGasMachine
{ {
@@ -8,6 +9,11 @@ namespace ProjectGasMachine
/// </summary> /// </summary>
public partial class FormGasMachineCollection : Form public partial class FormGasMachineCollection : Form
{ {
/// <summary>
/// хранение коллекций
/// </summary>
private readonly StorageCollection<DrawningMachine> _storageCollection;
/// <summary> /// <summary>
/// Компания /// Компания
/// </summary> /// </summary>
@@ -19,6 +25,7 @@ namespace ProjectGasMachine
public FormGasMachineCollection() public FormGasMachineCollection()
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new();
} }
/// <summary> /// <summary>
@@ -28,39 +35,20 @@ namespace ProjectGasMachine
/// <param name="e"></param> /// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
switch (comboBoxSelectorCompany.Text) panelCompanyTools.Enabled = false;
{
case "Хранилище":
_company = new Autopark(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningMachine>());
break;
}
} }
/// <summary> /// <summary>
/// Создание объекта класса-перемещения /// Добавление газовоза в коллекцию
/// </summary> /// </summary>
/// <param name="type"></param> /// <param name="machine"></param>
private void CreateObject(string type) private void SetMachine(DrawningMachine? machine)
{ {
if (_company == null) if (_company == null || machine == null)
{ {
return; return;
} }
Random random = new();
DrawningMachine drawningMachine;
switch (type)
{
case nameof(DrawningMachine):
drawningMachine = new DrawningMachine(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningGasMachine):
drawningMachine = new DrawningGasMachine(random.Next(100, 300), random.Next(1000, 3000), GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningMachine != -1) if (_company + machine != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
@@ -70,36 +58,22 @@ namespace ProjectGasMachine
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} }
/// <summary>
/// Получение цыета
/// </summary>
/// <param name="random">генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// добавление газовоза
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddGasMachine_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningGasMachine));
/// <summary> /// <summary>
/// добавление грузовика /// добавление грузовика
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddMachine_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMachine)); private void ButtonAddMachine_Click(object sender, EventArgs e)
{
FormGasConfig form = new();
// TODO передать метод +
form.AddEvent(SetMachine);
form.Show();
}
/// <summary> /// <summary>
/// удаление объекта /// удаление объекта
@@ -146,17 +120,17 @@ namespace ProjectGasMachine
DrawningMachine? machine = null; DrawningMachine? machine = null;
int counter = 100; int counter = 100;
while (machine == null) while (machine == null)
{ {
machine = _company.GetRandomObject(); machine = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
break; break;
} }
} }
if (machine == null) if (machine == null)
{ {
return; return;
} }
@@ -182,5 +156,140 @@ namespace ProjectGasMachine
pictureBox.Image = _company.Show(); 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)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Вы уверены, что хотите удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
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))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <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<DrawningMachine>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Autopark(pictureBox.Width, pictureBox.Height, 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);
}
}
}
/// <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,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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> </root>

View File

@@ -0,0 +1,8 @@
using ProjectGasMachine.Drawnings;
namespace ProjectGasMachine;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="warship"></param>
public delegate void MachineDelegate(DrawningMachine machine);