4 Commits

16 changed files with 1534 additions and 149 deletions

View File

@@ -0,0 +1,15 @@
using ProjectSportCar.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSportCar;
/// <summary>
/// Делегат передачи обьекта - класса-прорисовки
/// </summary>
/// <param name="car"></param>
public delegate void CarDelegate(DrawningCar car);

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSportCar.CollectionGenericObjects;
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// список
/// </summary>
List = 2
}

View File

@@ -6,17 +6,20 @@ using System.Threading.Tasks;
namespace ProjectSportCar.CollectionGenericObjects; namespace ProjectSportCar.CollectionGenericObjects;
public interface ICollectionGenericObjects <T> public interface ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Количество объектов в коллекции /// Количество объектов в коллекции
/// </summary> /// </summary>
int Count { get; } int Count { get; }
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
@@ -42,4 +45,17 @@ bool Remove(int position);
/// <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,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSportCar.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 SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
// TODO проверка позиции
return _collection[position];
}
public bool Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
return true;
}
public bool Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
return true;
}
public bool Remove(int position)
{
// TODO проверка позиции
// TODO удаление обьекта из списка
return true;
}
}

View File

@@ -23,8 +23,21 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
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)
{
_collection = new T?[value]; }
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -57,4 +70,12 @@ return false;
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
return true; return true;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -0,0 +1,226 @@
using ProjectSportCar.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSportCar.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningCar
{
///<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)
{
// TODO Проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Проприсать логику для добалвения
}
public void DelCollection(string name)
{
// Прописать логику для удаления коллекции
}
/// <summary>
/// Доступ к коллекци
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
//TODO Продумать логику получения обьекта
return null;
}
}
}
/// <summary>
/// Cохранение информации по автомобилям в хранилище в файл
/// </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);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach(KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
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);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по автомобиоям вы хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.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?.CreateDrawningCar() is T car)
{
if (!collection.Insert(car))
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
private static ICollectionGenericObjects<T>? CreateeCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
=> null,
};
}
}

View File

@@ -9,6 +9,13 @@ namespace ProjectSportCar.Drawnings;
public class DrawningSportCar : DrawningCar public class DrawningSportCar : DrawningCar
{ {
private EntityCar car;
public DrawningSportCar(EntityCar car)
{
this.car = car;
}
/// <summary> /// <summary>
/// конструктор /// конструктор
/// </summary> /// </summary>

View File

@@ -0,0 +1,63 @@
using ProjectSportCar.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSportCar.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningCar
{
/// <summary>
/// Разделитель для записи информации по обьекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание обьекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания обьекта</param>
/// <returns>Обьект</returns>
public static DrawningCar? CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityCar? car = EntitySportCar.CreateEntitySportCar(strs);
if (car != null)
{
return new DrawningSportCar(car);
}
car = EntityCar.CreateEntityCar(strs);
if (car != null)
{
return new DrawningCar(car);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый обьект</param>
/// <returns>Строка с данными по обьекту</returns>
public static string GetDataForSave(this DrawningCar drawningCar)
{
string[]? array = drawningCar?.EntityCar?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -37,11 +37,45 @@ namespace ProjectSportCar.Entities
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param> /// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
// Через конструктор заносить данные по изменению цветов в FormCarConfig
public EntityCar(int speed, double weight, Color bodyColor) public EntityCar(int speed, double weight, Color bodyColor)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк с значениями свойств обьекта класса - сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityCar), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание обьекта из строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityCar? CreateEntityCar(string[] strs)
{
if (strs.Length == 4 || strs[0] != nameof(EntityCar)) // что не равно 4 нас не интерисует
{
return null;
}
return new EntityCar(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }
} }

View File

@@ -33,9 +33,14 @@ public class EntitySportCar : EntityCar
/// </summary> /// </summary>
public double Step => Speed * 100 / Weight; public double Step => Speed * 100 / Weight;
internal static EntityCar? CreateEntitySportCar(string[] strs)
{
throw new NotImplementedException();
}
/// ПЕРЕПИСАТЬ КОНСТРУКТОР!!!! /// ПЕРЕПИСАТЬ КОНСТРУКТОР!!!!
/// <summary> /// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля /// Инициализация полей объекта-класса спортивного автомобиля
/// </summary> /// </summary>

View File

@@ -29,98 +29,207 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonRefresh = new Button(); panelCompanyTools = new Panel();
buttonGoToCheck = new Button();
buttonRemoveCar = new Button();
maskedTextBox = new MaskedTextBox();
buttonAddSportCar = new Button();
buttonAddCar = new Button(); buttonAddCar = new Button();
maskedTextBox = 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();
comboBoxSelectionCompany = new ComboBox(); comboBoxSelectionCompany = 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(maskedTextBox);
groupBoxTools.Controls.Add(buttonAddSportCar);
groupBoxTools.Controls.Add(buttonAddCar);
groupBoxTools.Controls.Add(comboBoxSelectionCompany); groupBoxTools.Controls.Add(comboBoxSelectionCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(746, 0); groupBoxTools.Location = new Point(794, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(182, 518); groupBoxTools.Size = new Size(182, 611);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddCar);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveCar);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 353);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(182, 282);
panelCompanyTools.TabIndex = 8;
//
// buttonAddCar
//
buttonAddCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddCar.Location = new Point(10, 12);
buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(166, 43);
buttonAddCar.TabIndex = 1;
buttonAddCar.Text = "Добавление автомобиля";
buttonAddCar.UseVisualStyleBackColor = true;
buttonAddCar.Click += ButtonAddCar_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 112);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(164, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.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(12, 443); buttonRefresh.Location = new Point(12, 249);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(164, 49); buttonRefresh.Size = new Size(146, 21);
buttonRefresh.TabIndex = 5; buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click; buttonRefresh.Click += ButtonRefresh_Click;
// //
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(12, 370);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(164, 49);
buttonGoToCheck.TabIndex = 4;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemoveCar // buttonRemoveCar
// //
buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveCar.Location = new Point(12, 298); buttonRemoveCar.Location = new Point(12, 164);
buttonRemoveCar.Name = "buttonRemoveCar"; buttonRemoveCar.Name = "buttonRemoveCar";
buttonRemoveCar.Size = new Size(164, 49); buttonRemoveCar.Size = new Size(146, 22);
buttonRemoveCar.TabIndex = 3; buttonRemoveCar.TabIndex = 3;
buttonRemoveCar.Text = "Удалить автомобиль"; buttonRemoveCar.Text = "Удалить автомобиль";
buttonRemoveCar.UseVisualStyleBackColor = true; buttonRemoveCar.UseVisualStyleBackColor = true;
buttonRemoveCar.Click += ButtonRemoveCar_Click; buttonRemoveCar.Click += ButtonRemoveCar_Click;
// //
// maskedTextBox // buttonGoToCheck
// //
maskedTextBox.Location = new Point(6, 237); buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Mask = "00"; buttonGoToCheck.Location = new Point(12, 207);
maskedTextBox.Name = "maskedTextBox"; buttonGoToCheck.Name = "buttonGoToCheck";
maskedTextBox.Size = new Size(170, 23); buttonGoToCheck.Size = new Size(146, 23);
maskedTextBox.TabIndex = 3; buttonGoToCheck.TabIndex = 4;
maskedTextBox.ValidatingType = typeof(int); buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
// //
// buttonAddSportCar // buttonCreateCompany
// //
buttonAddSportCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonCreateCompany.Location = new Point(3, 276);
buttonAddSportCar.Location = new Point(12, 138); buttonCreateCompany.Name = "buttonCreateCompany";
buttonAddSportCar.Name = "buttonAddSportCar"; buttonCreateCompany.Size = new Size(173, 29);
buttonAddSportCar.Size = new Size(164, 49); buttonCreateCompany.TabIndex = 7;
buttonAddSportCar.TabIndex = 2; buttonCreateCompany.Text = "Создать компанию";
buttonAddSportCar.Text = "Добавление спортивного автомобиля"; buttonCreateCompany.UseVisualStyleBackColor = true;
buttonAddSportCar.UseVisualStyleBackColor = true; buttonCreateCompany.Click += ButtonCreateCompany_Click;
buttonAddSportCar.Click += ButtonAddSportCar_Click;
// //
// buttonAddCar // panelStorage
// //
buttonAddCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; panelStorage.Controls.Add(buttonCollectionDel);
buttonAddCar.Location = new Point(12, 71); panelStorage.Controls.Add(listBoxCollection);
buttonAddCar.Name = "buttonAddCar"; panelStorage.Controls.Add(buttonCollectionAdd);
buttonAddCar.Size = new Size(164, 49); panelStorage.Controls.Add(radioButtonList);
buttonAddCar.TabIndex = 1; panelStorage.Controls.Add(radioButtonMassive);
buttonAddCar.Text = "Добавление автомобиля"; panelStorage.Controls.Add(textBoxCollectionName);
buttonAddCar.UseVisualStyleBackColor = true; panelStorage.Controls.Add(labelCollectionName);
buttonAddCar.Click += ButtonAddCar_Click; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(176, 251);
panelStorage.TabIndex = 6;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(0, 214);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(173, 21);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 114);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(170, 94);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 87);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(173, 21);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(101, 62);
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(9, 62);
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(9, 33);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(158, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(28, 15);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
// //
// comboBoxSelectionCompany // comboBoxSelectionCompany
// //
@@ -128,48 +237,111 @@
comboBoxSelectionCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectionCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectionCompany.FormattingEnabled = true; comboBoxSelectionCompany.FormattingEnabled = true;
comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectionCompany.Location = new Point(6, 22); comboBoxSelectionCompany.Location = new Point(6, 324);
comboBoxSelectionCompany.Name = "comboBoxSelectionCompany"; comboBoxSelectionCompany.Name = "comboBoxSelectionCompany";
comboBoxSelectionCompany.Size = new Size(170, 23); comboBoxSelectionCompany.Size = new Size(170, 23);
comboBoxSelectionCompany.TabIndex = 0; comboBoxSelectionCompany.TabIndex = 0;
comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectionCompany_SelectedIndexChanged; comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
comboBoxSelectionCompany.Validating += comboBoxSelectionCompany_Validating; comboBoxSelectionCompany.Validating += comboBoxSelectionCompany_Validating;
// //
// 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(746, 518); pictureBox.Size = new Size(794, 611);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
pictureBox.Click += pictureBox_Click; pictureBox.Click += pictureBox_Click;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(976, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(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(928, 518); ClientSize = new Size(976, 635);
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 comboBoxSelectionCompany; private ComboBox comboBoxSelectionCompany;
private Button buttonAddSportCar;
private Button buttonAddCar; private Button buttonAddCar;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonRemoveCar; private Button buttonRemoveCar;
private MaskedTextBox maskedTextBox; private MaskedTextBox maskedTextBox;
private Button buttonRefresh; private Button buttonRefresh;
private Button buttonGoToCheck; private Button buttonGoToCheck;
private Panel panelStorage;
private Label labelCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -20,7 +20,12 @@ public partial class FormCarCollection : Form
{ {
/// <summary> /// <summary>
/// /// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningCar> _storageCollection;
/// <summary>
/// Компания
/// </summary> /// </summary>
@@ -33,62 +38,27 @@ public partial class FormCarCollection : Form
public FormCarCollection() public FormCarCollection()
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new();
} }
private void ButtonAddCar_Click(object sender, EventArgs e)
private void comboBoxSelectionCompany_Validating(object sender, CancelEventArgs e)
{ {
FormCarConfig form = new();
// TODO передать метод
form.Show();
} }
private void pictureBox_Click(object sender, EventArgs e)
{
}
/// <summary> /// <summary>
/// /// Добавление автомобиля в коллекцию
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="car"></param>
/// <param name="e"></param>
private void ComboBoxSelectionCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text) //ИСПРАВИТЬ ОШИБКУ 3 практ раб 20 минута (или ранее на минуту)
{
case "Хранилище":
_company = new CarSharingService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningCar>());
break;
}
}
private void CreateObject(string type) private void SetCar(DrawningCar car)
{ {
if (_company == null) if (_company == null || car == null)
{ {
return; return;
} }
if (_company + car)
Random random = new();
DrawningCar drawningCar;
switch (type)
{
case nameof(DrawningCar):
drawningCar = new DrawningCar(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningSportCar):
drawningCar = new DrawningSportCar(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningCar)
{ {
MessageBox.Show("Обьект добавлен"); MessageBox.Show("Обьект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
@@ -100,48 +70,14 @@ public partial class FormCarCollection : 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;
}
private void ButtonAddCar_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningCar));
private void ButtonAddSportCar_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSportCar));
private void ButtonRemoveCar_Click(object sender, EventArgs e) private void ButtonRemoveCar_Click(object sender, EventArgs e)
{ {
if (_company == null)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
return; return;
} }
if (MessageBox.Show("Удалить обьект?", "удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить обьект?", "удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !== DialogResult.Yes) ;
{ {
return; return;
} }
@@ -182,7 +118,7 @@ public partial class FormCarCollection : Form
if (car == null) if (car == null)
{ {
return; return;
} }
FormSportCar form = new() FormSportCar form = new()
{ {
@@ -192,6 +128,36 @@ public partial class FormCarCollection : Form
} }
private void comboBoxSelectionCompany_Validating(object sender, CancelEventArgs e)
{
}
private void pictureBox_Click(object sender, EventArgs e)
{
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e) private void ButtonRefresh_Click(object sender, EventArgs e)
{ {
if (_company == null) if (_company == null)
@@ -204,5 +170,131 @@ public partial class FormCarCollection : Form
} }
/// <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);
RefreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
//TODO Прописать логику удаления элемента из коллекции
// нужно убедиться что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RefreshListBoxItems()
{
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<DrawningCar>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализированна");
return;
}
switch (comboBoxSelectorCompany.Text) //ИСПРАВИТЬ ОШИБКУ 3 практ раб 20 минута (или ранее на минуту)
{
case "Хранилище":
_company = new CarSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO продумать логику
}
} }

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,364 @@
namespace ProjectSportCar
{
partial class FormCarConfig
{
/// <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();
panelYellow = new Panel();
panelBlack = new Panel();
panelGrey = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxSportLine = new CheckBox();
checkBoxWing = new CheckBox();
checkBoxBodyKit = 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(checkBoxSportLine);
groupBoxConfig.Controls.Add(checkBoxWing);
groupBoxConfig.Controls.Add(checkBoxBodyKit);
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(594, 176);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGrey);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(275, 0);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(249, 115);
groupBoxColors.TabIndex = 1;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(212, 78);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(31, 31);
panelPurple.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(212, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(31, 31);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(140, 78);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(31, 31);
panelBlack.TabIndex = 6;
//
// panelGrey
//
panelGrey.BackColor = Color.Gray;
panelGrey.Location = new Point(72, 78);
panelGrey.Name = "panelGrey";
panelGrey.Size = new Size(31, 31);
panelGrey.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(140, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(31, 31);
panelBlue.TabIndex = 2;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(6, 78);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(31, 31);
panelWhite.TabIndex = 4;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(72, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(31, 31);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(31, 31);
panelRed.TabIndex = 0;
//
// checkBoxSportLine
//
checkBoxSportLine.AutoSize = true;
checkBoxSportLine.Location = new Point(12, 146);
checkBoxSportLine.Name = "checkBoxSportLine";
checkBoxSportLine.Size = new Size(226, 19);
checkBoxSportLine.TabIndex = 8;
checkBoxSportLine.Text = "Признак наличия гоночной полосы";
checkBoxSportLine.UseVisualStyleBackColor = true;
//
// checkBoxWing
//
checkBoxWing.AutoSize = true;
checkBoxWing.Location = new Point(12, 121);
checkBoxWing.Name = "checkBoxWing";
checkBoxWing.Size = new Size(198, 19);
checkBoxWing.TabIndex = 7;
checkBoxWing.Text = "Признак наличия антитикрыла";
checkBoxWing.UseVisualStyleBackColor = true;
//
// checkBoxBodyKit
//
checkBoxBodyKit.AutoSize = true;
checkBoxBodyKit.Location = new Point(12, 96);
checkBoxBodyKit.Name = "checkBoxBodyKit";
checkBoxBodyKit.Size = new Size(164, 19);
checkBoxBodyKit.TabIndex = 6;
checkBoxBodyKit.Text = "Признак наличия обвеса";
checkBoxBodyKit.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(80, 64);
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(96, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 66);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(80, 29);
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(96, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 29);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(418, 130);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(100, 36);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(281, 130);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 36);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(12, 44);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(210, 91);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(672, 146);
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(753, 146);
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(638, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(235, 140);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(139, 5);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(72, 36);
labelAdditionalColor.TabIndex = 10;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
//
// labelBodyColor
//
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(22, 5);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(72, 36);
labelBodyColor.TabIndex = 9;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
//
// FormCarConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(885, 176);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormCarConfig";
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 CheckBox checkBoxBodyKit;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxSportLine;
private CheckBox checkBoxWing;
private GroupBox groupBoxColors;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGrey;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,148 @@
using ProjectSportCar.Drawnings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectSportCar;
/// <summary>
/// Форма конфигурации обьекта
/// </summary>
public partial class FormCarConfig : Form
{
/// <summary>
/// Обьект прорисовка автомобиля
/// </summary>
private DrawningCar? _car;
/// <summary>
/// Событие для передачи обьекта
/// </summary>
private event CarDelegate? CarDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormCarConfig()
{
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGrey.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
// TODO buttonCancel.Click with привязать анонимный метод через lambda с закрытием формы
InitializeComponent();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="carDelegate"></param>
public void AddEvent(CarDelegate carDelegate)
{
CarDelegate += carDelegate;
}
/// <summary>
/// Прорисовка обьекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_car?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_car?.SetPosition(5, 5); //установка позиции
_car?.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":
_car = new DrawningCar((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_car = new DrawningSportCar((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxBodyKit.Checked, checkBoxWing.Checked, checkBoxSportLine.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
}
//TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого обьекта)
/// <summary>
/// Передача обьекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_car != null)
{
CarDelegate?.Invoke(_car);
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>