4 Commits

Author SHA1 Message Date
Kankistodor
4cab399d4b lab6-ready 2024-04-21 13:18:45 +04:00
bca0b7ff6e part6lab 2024-04-10 21:03:23 +04:00
25e8f077f6 lab5-ready 2024-04-10 19:18:28 +04:00
d6180bbeb8 lab4 ready 2024-03-28 00:10:11 +04:00
20 changed files with 1775 additions and 252 deletions

View File

@@ -1,4 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" /> <component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise">
<file url="file://$PROJECT_DIR$/ProjectElectroTrans/FormElectroTrans.cs" charset="windows-1251" />
<file url="PROJECT" charset="windows-1251" />
</component>
</project> </project>

View File

@@ -48,7 +48,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>

View File

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

View File

@@ -1,6 +1,4 @@
using ProjectElectroTrans.Drawnings; namespace ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary> /// <summary>
/// Интерфейс описания действий для набора хранимых объектов /// Интерфейс описания действий для набора хранимых объектов
@@ -17,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@@ -39,7 +37,7 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns> /// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position); T Remove(int position);
/// <summary> /// <summary>
/// Получение объекта по позиции /// Получение объекта по позиции
@@ -47,4 +45,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,80 @@
namespace ProjectElectroTrans.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 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 >= Count || position < 0) return null;
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount) return -1;
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
if (position >= _collection.Count || position < 0) 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,6 +1,4 @@
using System.Runtime.Remoting; 
using ProjectElectroTrans.Drawnings;
namespace ProjectElectroTrans.CollectionGenericObjects; namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary> /// <summary>
@@ -17,8 +15,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -35,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -130,4 +134,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null; _collection[position] = null;
return temp; return temp;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -0,0 +1,218 @@
using ProjectElectroTrans.Drawnings;
using System.Text;
using ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawingTrans
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly 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 (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
_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 writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrans() is T ship)
{
if (collection.Insert(ship) == -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

@@ -22,6 +22,15 @@ public class DrawingElectroTrans : DrawingTrans
{ {
EntityTrans = new EntityElectroTrans(speed, weight, bodyColor, additionalColor, horns, battery); EntityTrans = new EntityElectroTrans(speed, weight, bodyColor, additionalColor, horns, battery);
} }
public DrawingElectroTrans(EntityTrans trans) : base(110, 60)
{
if (trans != null && trans is EntityElectroTrans electroTrans)
{
EntityTrans = new EntityElectroTrans(electroTrans.Speed, electroTrans.Weight, electroTrans.BodyColor, electroTrans.AdditionalColor, electroTrans.Horns, electroTrans.Battery);
}
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityTrans == null || EntityTrans is not EntityElectroTrans electroTrans || if (EntityTrans == null || EntityTrans is not EntityElectroTrans electroTrans ||

View File

@@ -76,15 +76,29 @@ public class DrawingTrans
{ {
EntityTrans = new EntityTrans(speed, weight, bodyColor); EntityTrans = new EntityTrans(speed, weight, bodyColor);
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="car">Класс-сущность</param>
public DrawingTrans(EntityTrans trans) : this()
{
if (trans != null)
{
EntityTrans = new EntityTrans(trans.Speed, trans.Weight, trans.BodyColor);
}
}
/// <summary> /// <summary>
/// Конструктор для наследников /// Конструктор для наследников
/// </summary> /// </summary>
/// <param name="drawningCarWidth">Ширина прорисовки автомобиля</param> /// <param name="drawning
/// <param name="drawningCarHeight">Высота прорисовки автомобиля</param> /// Width">Ширина прорисовки автомобиля</param>
protected DrawingTrans(int drawningCarWidth, int drawningCarHeight) : this() /// <param name="drawningTransHeight">Высота прорисовки автомобиля</param>
protected DrawingTrans(int drawningTransWidth, int drawningTransHeight) : this()
{ {
_drawningTransWidth = drawningCarWidth; _drawningTransWidth = drawningTransWidth;
_pictureHeight = drawningCarHeight; _pictureHeight = drawningTransHeight;
} }
/// <summary> /// <summary>

View File

@@ -0,0 +1,53 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.Entities;
namespace ProjectElectroTrans;
public static class ExtentionDrawningTrans
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingTrans? CreateDrawningTrans(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrans? airplan = EntityElectroTrans.CreateEntityElectroTrans(strs);
if (airplan != null)
{
return new DrawingElectroTrans((EntityElectroTrans)airplan);
}
airplan = EntityTrans.CreateEntityTrans(strs);
if (airplan != null)
{
return new DrawingTrans(airplan);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="DrawingTrans">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingTrans DrawingTrans)
{
string[]? array = DrawingTrans?.EntityTrans?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -13,6 +13,15 @@ internal class EntityElectroTrans : EntityTrans
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
/// <summary>
/// установка доп. цвета
/// </summary>
/// <param name="color"></param>
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
/// <summary> /// <summary>
/// Признак (опция) подняты ли рога /// Признак (опция) подняты ли рога
/// </summary> /// </summary>
@@ -22,6 +31,7 @@ internal class EntityElectroTrans : EntityTrans
/// Признак (опция) налиция батерей /// Признак (опция) налиция батерей
/// </summary> /// </summary>
public bool Battery { get; private set; } public bool Battery { get; private set; }
/// <summary> /// <summary>
/// Конструктор сущности /// Конструктор сущности
/// </summary> /// </summary>
@@ -38,4 +48,34 @@ internal class EntityElectroTrans : EntityTrans
Horns = horns; Horns = horns;
Battery = battery; Battery = battery;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[]
{
nameof(EntityElectroTrans), Speed.ToString(),
Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Horns.ToString(), Battery.ToString()
};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrans? CreateEntityElectroTrans(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityElectroTrans))
{
return null;
}
return new EntityElectroTrans(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[5]));
}
} }

View File

@@ -20,6 +20,16 @@ public class EntityTrans
/// <summary> /// <summary>
/// Шаг перемещения автомобиля /// Шаг перемещения автомобиля
/// </summary> /// </summary>
/// <summary>
/// Основной цвет
/// </summary>
/// <param name="color"></param>
public void setBodyColor(Color color)
{
BodyColor = color;
}
public double Step => Speed * 100 / Weight; public double Step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// Конструктор сущности /// Конструктор сущности
@@ -34,4 +44,29 @@ public class EntityTrans
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrans), Speed.ToString(),
Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrans? CreateEntityTrans(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrans))
{
return null;
}
return new EntityTrans(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@@ -119,7 +119,8 @@ namespace ProjectElectroTrans
buttonStrategyStep.UseVisualStyleBackColor = true; buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click; buttonStrategyStep.Click += ButtonStrategyStep_Click;
// //
// FormSportCar // Form
//
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;

View File

@@ -21,7 +21,8 @@ public partial class FormElectroTrans : Form
/// <summary> /// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> /// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary> /// </summary>
public DrawingTrans SetCar public DrawingTrans SetTrans
{ {
set set
{ {

View File

@@ -33,39 +33,88 @@ namespace ProjectElectroTrans
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonRefresh = new Button(); panelCompanyTools = new Panel();
buttonGoToCheck = new Button();
buttonRemoveCar = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddSportCar = new Button();
buttonAddCar = new Button(); buttonAddCar = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
buttonRemoveCar = 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();
файлToolStripMenuItem = 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(buttonRemoveCar); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddSportCar);
groupBoxTools.Controls.Add(buttonAddCar);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(783, 0); groupBoxTools.Location = new Point(783, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(179, 616); groupBoxTools.Size = new Size(179, 608);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddCar);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveCar);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 352);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(173, 253);
panelCompanyTools.TabIndex = 9;
//
// buttonAddCar
//
buttonAddCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddCar.Location = new Point(3, 3);
buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(167, 40);
buttonAddCar.TabIndex = 1;
buttonAddCar.Text = "Добавление автомобиля";
buttonAddCar.UseVisualStyleBackColor = true;
buttonAddCar.Click += ButtonAddTrans_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 95);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(167, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 499); buttonRefresh.Location = new Point(3, 210);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(167, 40); buttonRefresh.Size = new Size(167, 40);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@@ -73,10 +122,21 @@ namespace ProjectElectroTrans
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click; buttonRefresh.Click += ButtonRefresh_Click;
// //
// buttonRemoveCar
//
buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveCar.Location = new Point(3, 124);
buttonRemoveCar.Name = "buttonRemoveCar";
buttonRemoveCar.Size = new Size(167, 40);
buttonRemoveCar.TabIndex = 4;
buttonRemoveCar.Text = "Удалить автомобиль";
buttonRemoveCar.UseVisualStyleBackColor = true;
buttonRemoveCar.Click += ButtonRemoveTrans_Click;
//
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 361); buttonGoToCheck.Location = new Point(3, 170);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(167, 40); buttonGoToCheck.Size = new Size(167, 40);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@@ -84,47 +144,97 @@ namespace ProjectElectroTrans
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click; buttonGoToCheck.Click += ButtonGoToCheck_Click;
// //
// buttonRemoveCar // buttonCreateCompany
// //
buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonCreateCompany.Location = new Point(6, 320);
buttonRemoveCar.Location = new Point(6, 251); buttonCreateCompany.Name = "buttonCreateCompany";
buttonRemoveCar.Name = "buttonRemoveTrans"; buttonCreateCompany.Size = new Size(167, 23);
buttonRemoveCar.Size = new Size(167, 40); buttonCreateCompany.TabIndex = 8;
buttonRemoveCar.TabIndex = 4; buttonCreateCompany.Text = "Создать компанию";
buttonRemoveCar.Text = "Удалить поезд"; buttonCreateCompany.UseVisualStyleBackColor = true;
buttonRemoveCar.UseVisualStyleBackColor = true; buttonCreateCompany.Click += ButtonCreateCompany_Click;
buttonRemoveCar.Click += ButtonRemoveTrans_Click;
// //
// maskedTextBoxPosition // panelStorage
// //
maskedTextBoxPosition.Location = new Point(6, 222); panelStorage.Controls.Add(buttonCollectionDel);
maskedTextBoxPosition.Mask = "00"; panelStorage.Controls.Add(listBoxCollection);
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; panelStorage.Controls.Add(buttonCollectionAdd);
maskedTextBoxPosition.Size = new Size(167, 23); panelStorage.Controls.Add(radioButtonList);
maskedTextBoxPosition.TabIndex = 3; panelStorage.Controls.Add(radioButtonMassive);
maskedTextBoxPosition.ValidatingType = typeof(int); 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(173, 266);
panelStorage.TabIndex = 7;
// //
// buttonAddSportCar // buttonCollectionDel
// //
buttonAddSportCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonCollectionDel.Location = new Point(3, 227);
buttonAddSportCar.Location = new Point(6, 137); buttonCollectionDel.Name = "buttonCollectionDel";
buttonAddSportCar.Name = "buttonAddSportCar"; buttonCollectionDel.Size = new Size(167, 23);
buttonAddSportCar.Size = new Size(167, 40); buttonCollectionDel.TabIndex = 6;
buttonAddSportCar.TabIndex = 2; buttonCollectionDel.Text = "Удалить коллекцию";
buttonAddSportCar.Text = "Добавление электропоезда"; buttonCollectionDel.UseVisualStyleBackColor = true;
buttonAddSportCar.UseVisualStyleBackColor = true; buttonCollectionDel.Click += ButtonCollectionDel_Click;
buttonAddSportCar.Click += ButtonAddElectroTrans_Click;
// //
// buttonAddCar // listBoxCollection
// //
buttonAddCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; listBoxCollection.FormattingEnabled = true;
buttonAddCar.Location = new Point(6, 91); listBoxCollection.ItemHeight = 15;
buttonAddCar.Name = "buttonAddCar"; listBoxCollection.Location = new Point(3, 112);
buttonAddCar.Size = new Size(167, 40); listBoxCollection.Name = "listBoxCollection";
buttonAddCar.TabIndex = 1; listBoxCollection.Size = new Size(167, 109);
buttonAddCar.Text = "Добавление поезда"; listBoxCollection.TabIndex = 5;
buttonAddCar.UseVisualStyleBackColor = true; //
buttonAddCar.Click += ButtonAddTrans_Click; // buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 83);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(167, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(98, 58);
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, 58);
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, 29);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(167, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(26, 11);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
// //
// comboBoxSelectorCompany // comboBoxSelectorCompany
// //
@@ -132,7 +242,7 @@ namespace ProjectElectroTrans
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, 291);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(167, 23); comboBoxSelectorCompany.Size = new Size(167, 23);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
@@ -141,37 +251,100 @@ namespace ProjectElectroTrans
// 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(783, 616); pictureBox.Size = new Size(783, 608);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(962, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файл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(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";
//
// FormCarCollection // FormCarCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(962, 616); ClientSize = new Size(962, 632);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCarCollection"; Name = "FormCarCollection";
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
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonAddSportCar;
private Button buttonAddCar; private Button buttonAddCar;
private Button buttonRemoveCar; private Button buttonRemoveCar;
private MaskedTextBox maskedTextBoxPosition; private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonGoToCheck; private Button buttonGoToCheck;
private Button buttonRefresh; private Button buttonRefresh;
private Panel panelStorage;
private Label labelCollectionName;
private TextBox textBoxCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCollectionAdd;
private ListBox listBoxCollection;
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -9,6 +9,11 @@ namespace ProjectElectroTrans;
/// </summary> /// </summary>
public partial class FormTransCollection : Form public partial class FormTransCollection : Form
{ {
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawingTrans> _storageCollection;
/// <summary> /// <summary>
/// Компания /// Компания
/// </summary> /// </summary>
@@ -20,6 +25,7 @@ public partial class FormTransCollection : Form
public FormTransCollection() public FormTransCollection()
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new();
} }
/// <summary> /// <summary>
@@ -32,54 +38,31 @@ public partial class FormTransCollection : Form
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new TransDepoService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawingTrans>()); _company = new TransDepoService(pictureBox.Width, pictureBox.Height,
new MassiveGenericObjects<DrawingTrans>());
break; break;
} }
} }
/// <summary> private void ButtonAddTrans_Click(object sender, EventArgs e)
/// Добавление обычного автомобиля {
/// </summary> FormTransConfig form = new();
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingTrans));
/// <summary> form.Show();
/// Добавление спортивного автомобиля form.AddEvent(SetTrans);
/// </summary> }
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddElectroTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingElectroTrans));
/// <summary> /// <summary>
/// Создание объекта класса-перемещения /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="type">Тип создаваемого объекта</param> /// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type) private void SetTrans(DrawingTrans? drawingTrans)
{ {
if (_company == null) if (_company == null || drawingTrans == null)
{ {
return; return;
} }
Random random = new();
DrawingTrans drawingTrans;
switch (type)
{
case nameof(DrawingTrans):
drawingTrans = new DrawingTrans(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawingElectroTrans):
// вызов диалогового окна для выбора цвета
drawingTrans = new DrawingElectroTrans(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 + drawingTrans != -1) if (_company + drawingTrans != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
@@ -91,23 +74,6 @@ public partial class FormTransCollection : Form
} }
} }
/// <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>
/// Удаление объекта /// Удаление объекта
/// </summary> /// </summary>
@@ -120,7 +86,8 @@ public partial class FormTransCollection : Form
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{ {
return; return;
} }
@@ -168,7 +135,7 @@ public partial class FormTransCollection : Form
FormElectroTrans form = new() FormElectroTrans form = new()
{ {
SetCar = car SetTrans = car
}; };
form.ShowDialog(); form.ShowDialog();
} }
@@ -187,4 +154,148 @@ public partial class FormTransCollection : Form
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<DrawingTrans>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TransDepoService(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

@@ -0,0 +1,400 @@
namespace ProjectElectroTrans
{
partial class FormTransConfig
{
/// <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();
panel2 = new Panel();
pictureBox1 = new PictureBox();
panel1 = new Panel();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxBulldozerDump = new CheckBox();
checkBoxSupport = new CheckBox();
checkBoxBucket = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
panelObject = new Panel();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
labelAdditionalColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(panel2);
groupBoxConfig.Controls.Add(panel1);
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxBulldozerDump);
groupBoxConfig.Controls.Add(checkBoxSupport);
groupBoxConfig.Controls.Add(checkBoxBucket);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
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(571, 251);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// panel2
//
panel2.Controls.Add(pictureBox1);
panel2.Location = new Point(578, 10);
panel2.Name = "panel2";
panel2.Size = new Size(250, 125);
panel2.TabIndex = 1;
//
// pictureBox1
//
pictureBox1.Location = new Point(59, 48);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(125, 62);
pictureBox1.TabIndex = 0;
pictureBox1.TabStop = false;
//
// panel1
//
panel1.Location = new Point(594, 12);
panel1.Name = "panel1";
panel1.Size = new Size(226, 144);
panel1.TabIndex = 1;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(316, 21);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(256, 125);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(189, 81);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(35, 33);
panelPurple.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(189, 36);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(35, 33);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(130, 81);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(35, 33);
panelBlack.TabIndex = 6;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(130, 36);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(35, 33);
panelBlue.TabIndex = 2;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(74, 81);
panelGray.Name = "panelGray";
panelGray.Size = new Size(35, 33);
panelGray.TabIndex = 5;
//
// panelGreen
//
panelGreen.BackColor = Color.FromArgb(0, 192, 0);
panelGreen.Location = new Point(74, 36);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(35, 33);
panelGreen.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(23, 81);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(35, 33);
panelWhite.TabIndex = 4;
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.AutoSize = true;
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(23, 36);
panelRed.Name = "panelRed";
panelRed.Size = new Size(35, 33);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxBulldozerDump
//
checkBoxBulldozerDump.AutoSize = true;
checkBoxBulldozerDump.Location = new Point(13, 162);
checkBoxBulldozerDump.Name = "checkBoxBulldozerDump";
checkBoxBulldozerDump.Size = new Size(315, 24);
checkBoxBulldozerDump.TabIndex = 8;
checkBoxBulldozerDump.Text = "Признак наличие рогов";
checkBoxBulldozerDump.UseVisualStyleBackColor = true;
//
// checkBoxSupport
//
checkBoxSupport.AutoSize = true;
checkBoxSupport.Location = new Point(12, 132);
checkBoxSupport.Name = "checkBoxSupport";
checkBoxSupport.Size = new Size(209, 24);
checkBoxSupport.TabIndex = 7;
checkBoxSupport.Text = "Признак наличие батарей ";
checkBoxSupport.UseVisualStyleBackColor = true;
//
// checkBoxBucket
//
numericUpDownWeight.Location = new Point(91, 54);
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(150, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(91, 21);
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(150, 27);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 61);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(33, 20);
labelWeight.TabIndex = 3;
labelWeight.Text = "Вес";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 23);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(73, 20);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(161, 201);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(113, 25);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(33, 201);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(98, 25);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Location = new Point(575, 7);
panelObject.Name = "panelObject";
panelObject.Size = new Size(250, 197);
panelObject.TabIndex = 1;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.AutoSize = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(31, 19);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(44, 22);
labelBodyColor.TabIndex = 1;
labelBodyColor.Text = "Цвет";
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(19, 44);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(216, 150);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.AutoSize = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(158, 19);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(77, 22);
labelAdditionalColor.TabIndex = 2;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(578, 210);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(716, 210);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormExcavatorConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(822, 251);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormExcavatorConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
groupBoxColors.ResumeLayout(false);
groupBoxColors.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
panelObject.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxBulldozerDump;
private CheckBox checkBoxSupport;
private CheckBox checkBoxBucket;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Panel panel1;
private Panel panel2;
private PictureBox pictureBox1;
private Panel panelObject;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,214 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.Entities;
namespace ProjectElectroTrans
{
/// <summary>
/// форма конфигурации объекта
/// </summary>
public partial class FormTransConfig : Form
{
private DrawingTrans? _trans;
/// <summary>
/// событие для передачи объекта
/// </summary>
private event Action<DrawingTrans>? ElectroTransDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormTransConfig()
{
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>
/// <param name="carDelegate"></param>
public void AddEvent(Action<DrawingTrans> excavatorDelegate)
{
ElectroTransDelegate += excavatorDelegate;
}
/// <summary>
/// Отрисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_trans?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_trans?.SetPosition(15, 15);
_trans?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Labe
/// </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)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = 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":
_trans = new DrawingTrans((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_trans = new DrawingElectroTrans((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value,
Color.White,
Color.Black, checkBoxBucket.Checked,
checkBoxSupport.Checked);
break;
}
labelBodyColor.BackColor = Color.Empty;
labelAdditionalColor.BackColor = Color.Empty;
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации по основному цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// действия при приеме перетаскиваемого основного цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_trans != null)
{
_trans.EntityTrans.setBodyColor((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)
{
if (_trans is DrawingElectroTrans)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
/// <summary>
/// действия при перетаскивании доп. цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_trans.EntityTrans is EntityElectroTrans _excavator)
{
_excavator.setAdditionalColor((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 (_trans != null)
{
ElectroTransDelegate?.Invoke(_trans);
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

@@ -0,0 +1,9 @@
using ProjectElectroTrans.Drawnings;
namespace ProjectElectroTrans;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="car"></param>
public delegate void TransDelegate(DrawingTrans car);