This commit is contained in:
Дима 2024-08-30 00:45:20 +04:00
parent acd1b0cce2
commit 18228eeafd
17 changed files with 469 additions and 90 deletions

View File

@ -57,11 +57,11 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// Перегрузка оператора сложения для класса /// Перегрузка оператора сложения для класса
/// </summary> /// </summary>
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="сruiser">Добавляемый объект</param> /// <param name="locomotive">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningLocomotive сruiser) public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{ {
return company._collection.Insert(сruiser); return company._collection.Insert(locomotive, new DrawiningLocomotiveEqutables());
} }
/// <summary> /// <summary>
@ -110,6 +110,13 @@ namespace ProjectLocomotive.CollectionGenericObjects
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -0,0 +1,75 @@
namespace ProjectLocomotive.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,4 +1,7 @@
namespace ProjectLocomotive.CollectionGenericObjects using ProjectLocomotive.Drawnings;
using ProjectLocomotive.CollectionGenericObjects;
namespace ProjectLocomotive.CollectionGenericObjects
{ {
/// <summary> /// <summary>
/// Интерфейс описания действий для набора хранимых объектов /// Интерфейс описания действий для набора хранимых объектов
@ -11,29 +14,35 @@
/// Количество объектов в коллекции /// Количество объектов в коллекции
/// </summary> /// </summary>
int Count { get; } int Count { get; }
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int MaxCount { get; set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// </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>
/// Получение объекта по позиции /// Получение объекта по позиции
/// </summary> /// </summary>
@ -51,6 +60,12 @@
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }
} }

View File

@ -1,4 +1,7 @@
using ProjectLocomotive.Exceptions; using ProjectLocomotive.Drawnings;
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Exceptions;
namespace ProjectLocomotive.CollectionGenericObjects namespace ProjectLocomotive.CollectionGenericObjects
{ {
@ -47,23 +50,38 @@ namespace ProjectLocomotive.CollectionGenericObjects
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение // TODO выбром позиций, если переполнение
// TODO выброc позиций, если такой объект есть в коллекции
// TODO вставка в конец набора // TODO вставка в конец набора
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции // TODO проверка позиции
// TODO вставка по позиции // TODO вставка по позиции
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -72,9 +90,10 @@ namespace ProjectLocomotive.CollectionGenericObjects
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из списка
// TODO выбром позиций, если выход за границы массива // TODO выбром позиций, если выход за границы массива
// TODO удаление объекта из списка
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
@ -87,5 +106,10 @@ namespace ProjectLocomotive.CollectionGenericObjects
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }
} }

View File

@ -1,4 +1,7 @@
using ProjectLocomotive.Exceptions; using ProjectLocomotive.Drawnings;
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Exceptions;
namespace ProjectLocomotive.CollectionGenericObjects namespace ProjectLocomotive.CollectionGenericObjects
{ {
@ -55,34 +58,44 @@ namespace ProjectLocomotive.CollectionGenericObjects
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{ {
// TODO вставка в свободное место набора // TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение // TODO выброc позиций, если переполнение
int index = 0; // TODO выброc позиций, если такой объект есть в коллекции
while (index < Count && _collection[index] != null) for (int i = 0; i < Count; i++)
{ {
index++; if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
} }
if (index < Count) for (int i = 0; i < Count; i++)
{ {
_collection[index] = obj; if (_collection[i] == null)
return index; {
_collection[i] = obj;
return i;
}
} }
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{ {
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции // TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то // TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до // если нет после, ищем до
// TODO вставка
// TODO выбром позиций, если переполнение // TODO выбром позиций, если переполнение
// TODO выбром позиций, если выход за границы массива // TODO вставка
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null) if (_collection[position] != null)
@ -143,5 +156,10 @@ namespace ProjectLocomotive.CollectionGenericObjects
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }
} }

View File

@ -1,5 +1,7 @@
using ProjectLocomotive.Drawnings; using ProjectLocomotive.Drawnings;
using ProjectLocomotive.Exceptions; using ProjectLocomotive.Exceptions;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Exceptions;
using System.Text; using System.Text;
namespace ProjectLocomotive.CollectionGenericObjects namespace ProjectLocomotive.CollectionGenericObjects
@ -13,12 +15,12 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -40,7 +42,7 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -48,29 +50,40 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(CollectionInfo name)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления // TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return; if (name == null || _storages.ContainsKey(name))
{
return;
}
if (collectionType == CollectionType.None) return; if (name.CollectionType == CollectionType.Massive)
else if (collectionType == CollectionType.Massive) {
_storages[name] = new MassiveGenericObjects<T>(); _storages.Add(name, new MassiveGenericObjects<T>());
else if (collectionType == CollectionType.List) }
_storages[name] = new ListGenericObjects<T>();
if (name.CollectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(CollectionInfo name)
{ {
// TODO Прописать логику для удаления коллекции // TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name)) if (name == null || !_storages.ContainsKey(name))
_storages.Remove(name); {
return;
}
_storages.Remove(name);
} }
/// <summary> /// <summary>
@ -78,13 +91,16 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[CollectionInfo name]
{ {
get get
{ {
// TODO Продумать логику получения объекта // TODO Продумать логику получения объекта
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
{
return _storages[name]; return _storages[name];
}
return null; return null;
} }
} }
@ -111,7 +127,7 @@ namespace ProjectLocomotive.CollectionGenericObjects
using StreamWriter streamWriter = new StreamWriter(fs); using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey); streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
streamWriter.Write(Environment.NewLine); streamWriter.Write(Environment.NewLine);
@ -122,8 +138,6 @@ namespace ProjectLocomotive.CollectionGenericObjects
streamWriter.Write(value.Key); streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount); streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
@ -164,27 +178,25 @@ namespace ProjectLocomotive.CollectionGenericObjects
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
string[] record = str.Split(_separatorForKeyValue); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningLocomotive() is T aircraft) if (elem?.CreateDrawningLocomotive() is T locomotive)
{ {
try try
{ {
if (collection.Insert(aircraft) == -1) if (collection.Insert(locomotive, new DrawiningLocomotiveEqutables()) == -1)
{ {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
} }
@ -193,9 +205,13 @@ namespace ProjectLocomotive.CollectionGenericObjects
{ {
throw new CollectionOverflowException("Коллекция переполнена", ex); throw new CollectionOverflowException("Коллекция переполнена", ex);
} }
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }

View File

@ -0,0 +1,54 @@
using System.Diagnostics.CodeAnalysis;
namespace ProjectLocomotive.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningLocomotiveEqutables : IEqualityComparer<DrawningLocomotive?>
{
public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return false;
}
if (y == null || y.EntityLocomotive == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed)
{
return false;
}
if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight)
{
return false;
}
if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor)
{
return false;
}
if (x is DrawningTLocomotive && y is DrawningTLocomotive)
{
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLocomotive obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,34 @@
using ProjectLocomotive.Entities;
namespace ProjectLocomotive.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByColor : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityLocomotive == null)
{
return 1;
}
if (y == null || y.EntityLocomotive == null)
{
return -1;
}
var bodycolorCompare = x.EntityLocomotive.BodyColor.Name.CompareTo(y.EntityLocomotive.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return 1;
}
if (y == null || y.EntityLocomotive == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive.Exceptions;
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -48,6 +48,7 @@
pictureBoxLocomotive.SizeMode = PictureBoxSizeMode.AutoSize; pictureBoxLocomotive.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxLocomotive.TabIndex = 0; pictureBoxLocomotive.TabIndex = 0;
pictureBoxLocomotive.TabStop = false; pictureBoxLocomotive.TabStop = false;
pictureBoxLocomotive.Click += pictureBoxLocomotive_Click;
// //
// buttonUp // buttonUp
// //

View File

@ -135,5 +135,9 @@ namespace ProjectLocomotive
} }
} }
private void pictureBoxLocomotive_Click(object sender, EventArgs e)
{
}
} }
} }

View File

@ -167,9 +167,9 @@
checkBoxHeadlight.AutoSize = true; checkBoxHeadlight.AutoSize = true;
checkBoxHeadlight.Location = new Point(6, 217); checkBoxHeadlight.Location = new Point(6, 217);
checkBoxHeadlight.Name = "checkBoxHeadlight"; checkBoxHeadlight.Name = "checkBoxHeadlight";
checkBoxHeadlight.Size = new Size(193, 24); checkBoxHeadlight.Size = new Size(211, 24);
checkBoxHeadlight.TabIndex = 8; checkBoxHeadlight.TabIndex = 8;
checkBoxHeadlight.Text = "Признак наличие люка"; checkBoxHeadlight.Text = "Признак наличие фонаря";
checkBoxHeadlight.UseVisualStyleBackColor = true; checkBoxHeadlight.UseVisualStyleBackColor = true;
// //
// checkBoxFueltank // checkBoxFueltank
@ -177,21 +177,21 @@
checkBoxFueltank.AutoSize = true; checkBoxFueltank.AutoSize = true;
checkBoxFueltank.Location = new Point(6, 169); checkBoxFueltank.Location = new Point(6, 169);
checkBoxFueltank.Name = "checkBoxFueltank"; checkBoxFueltank.Name = "checkBoxFueltank";
checkBoxFueltank.Size = new Size(297, 24); checkBoxFueltank.Size = new Size(276, 24);
checkBoxFueltank.TabIndex = 7; checkBoxFueltank.TabIndex = 7;
checkBoxFueltank.Text = "Признак наличие ракетной установки"; checkBoxFueltank.Text = "Признак наличие топливного бака";
checkBoxFueltank.UseVisualStyleBackColor = true; checkBoxFueltank.UseVisualStyleBackColor = true;
checkBoxFueltank.CheckedChanged += checkBoxFueltank_CheckedChanged;
// //
// checkBoxPipe // checkBoxPipe
// //
checkBoxPipe.AutoSize = true; checkBoxPipe.AutoSize = true;
checkBoxPipe.Location = new Point(6, 123); checkBoxPipe.Location = new Point(6, 123);
checkBoxPipe.Name = "checkBoxPipe"; checkBoxPipe.Name = "checkBoxPipe";
checkBoxPipe.Size = new Size(189, 24); checkBoxPipe.Size = new Size(200, 24);
checkBoxPipe.TabIndex = 6; checkBoxPipe.TabIndex = 6;
checkBoxPipe.Text = "Признак наличие дула"; checkBoxPipe.Text = "Признак наличие трубы";
checkBoxPipe.UseVisualStyleBackColor = true; checkBoxPipe.UseVisualStyleBackColor = true;
checkBoxPipe.CheckedChanged += checkBoxPipe_CheckedChanged;
// //
// numericUpDownWeight // numericUpDownWeight
// //
@ -260,6 +260,7 @@
pictureBoxObject.Size = new Size(183, 125); pictureBoxObject.Size = new Size(183, 125);
pictureBoxObject.TabIndex = 1; pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false; pictureBoxObject.TabStop = false;
pictureBoxObject.Click += pictureBoxObject_Click;
// //
// buttonAdd // buttonAdd
// //

View File

@ -173,7 +173,12 @@ namespace ProjectLocomotive
} }
} }
private void checkBoxFueltank_CheckedChanged(object sender, EventArgs e) private void pictureBoxObject_Click(object sender, EventArgs e)
{
}
private void checkBoxPipe_CheckedChanged(object sender, EventArgs e)
{ {
} }

View File

@ -40,6 +40,8 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
ButtonAddLocomotive = new Button(); ButtonAddLocomotive = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
ButtonRemoveLocomotive = new Button(); ButtonRemoveLocomotive = new Button();
@ -66,9 +68,9 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(631, 28); groupBoxTools.Location = new Point(631, 30);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(222, 651); groupBoxTools.Size = new Size(222, 658);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты"; groupBoxTools.Text = "инструменты";
@ -177,6 +179,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(ButtonAddLocomotive); panelCompanyTools.Controls.Add(ButtonAddLocomotive);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ButtonRemoveLocomotive); panelCompanyTools.Controls.Add(ButtonRemoveLocomotive);
@ -185,27 +189,49 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 379); panelCompanyTools.Location = new Point(3, 379);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(216, 274); panelCompanyTools.Size = new Size(216, 275);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSortByColor.Location = new Point(19, 241);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(186, 31);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Right;
buttonSortByType.Location = new Point(19, 199);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(186, 37);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// ButtonAddLocomotive // ButtonAddLocomotive
// //
ButtonAddLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; ButtonAddLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddLocomotive.BackgroundImageLayout = ImageLayout.Center; ButtonAddLocomotive.BackgroundImageLayout = ImageLayout.Center;
ButtonAddLocomotive.Location = new Point(18, 3); ButtonAddLocomotive.Location = new Point(18, 3);
ButtonAddLocomotive.Name = "ButtonAddLocomotive"; ButtonAddLocomotive.Name = "ButtonAddLocomotive";
ButtonAddLocomotive.Size = new Size(186, 40); ButtonAddLocomotive.Size = new Size(186, 52);
ButtonAddLocomotive.TabIndex = 1; ButtonAddLocomotive.TabIndex = 1;
ButtonAddLocomotive.Text = "добваление установки"; ButtonAddLocomotive.Text = "добваление поезда";
ButtonAddLocomotive.UseVisualStyleBackColor = true; ButtonAddLocomotive.UseVisualStyleBackColor = true;
ButtonAddLocomotive.Click += ButtonAddLocomotive_Click; ButtonAddLocomotive.Click += ButtonAddLocomotive_Click;
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(18, 227); buttonRefresh.Location = new Point(19, 164);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(186, 41); buttonRefresh.Size = new Size(186, 29);
buttonRefresh.TabIndex = 5; buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить"; buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -214,17 +240,17 @@
// ButtonRemoveLocomotive // ButtonRemoveLocomotive
// //
ButtonRemoveLocomotive.Anchor = AnchorStyles.Right; ButtonRemoveLocomotive.Anchor = AnchorStyles.Right;
ButtonRemoveLocomotive.Location = new Point(18, 138); ButtonRemoveLocomotive.Location = new Point(19, 99);
ButtonRemoveLocomotive.Name = "ButtonRemoveLocomotive"; ButtonRemoveLocomotive.Name = "ButtonRemoveLocomotive";
ButtonRemoveLocomotive.Size = new Size(186, 40); ButtonRemoveLocomotive.Size = new Size(186, 28);
ButtonRemoveLocomotive.TabIndex = 3; ButtonRemoveLocomotive.TabIndex = 3;
ButtonRemoveLocomotive.Text = "удалить установку"; ButtonRemoveLocomotive.Text = "удалить поезд";
ButtonRemoveLocomotive.UseVisualStyleBackColor = true; ButtonRemoveLocomotive.UseVisualStyleBackColor = true;
ButtonRemoveLocomotive.Click += ButtonRemoveLocomotive_Click; ButtonRemoveLocomotive.Click += ButtonRemoveLocomotive_Click;
// //
// maskedTextBoxPosision // maskedTextBoxPosision
// //
maskedTextBoxPosision.Location = new Point(17, 105); maskedTextBoxPosision.Location = new Point(18, 60);
maskedTextBoxPosision.Mask = "00"; maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision"; maskedTextBoxPosision.Name = "maskedTextBoxPosision";
maskedTextBoxPosision.Size = new Size(187, 27); maskedTextBoxPosision.Size = new Size(187, 27);
@ -234,9 +260,9 @@
// buttonGetToTest // buttonGetToTest
// //
buttonGetToTest.Anchor = AnchorStyles.Right; buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(18, 184); buttonGetToTest.Location = new Point(18, 132);
buttonGetToTest.Name = "buttonGetToTest"; buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(186, 40); buttonGetToTest.Size = new Size(186, 27);
buttonGetToTest.TabIndex = 4; buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты"; buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true; buttonGetToTest.UseVisualStyleBackColor = true;
@ -245,9 +271,9 @@
// pictureBoxLocomotive // pictureBoxLocomotive
// //
pictureBoxLocomotive.Dock = DockStyle.Fill; pictureBoxLocomotive.Dock = DockStyle.Fill;
pictureBoxLocomotive.Location = new Point(0, 28); pictureBoxLocomotive.Location = new Point(0, 30);
pictureBoxLocomotive.Name = "pictureBoxLocomotive"; pictureBoxLocomotive.Name = "pictureBoxLocomotive";
pictureBoxLocomotive.Size = new Size(631, 651); pictureBoxLocomotive.Size = new Size(631, 658);
pictureBoxLocomotive.TabIndex = 1; pictureBoxLocomotive.TabIndex = 1;
pictureBoxLocomotive.TabStop = false; pictureBoxLocomotive.TabStop = false;
pictureBoxLocomotive.Click += pictureBoxLocomotive_Click; pictureBoxLocomotive.Click += pictureBoxLocomotive_Click;
@ -258,7 +284,8 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(853, 28); menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(853, 30);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@ -297,13 +324,14 @@
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(853, 679); ClientSize = new Size(853, 688);
Controls.Add(pictureBoxLocomotive); Controls.Add(pictureBoxLocomotive);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Name = "FormLocomotivesCollection"; Name = "FormLocomotivesCollection";
Text = "FormLocomotivesCollection"; Text = "FormLocomotivesCollection";
Load += FormLocomotivesCollection_Load;
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
@ -342,5 +370,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ProjectLocomotive.CollectionGenericObjects; using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Drawnings; using ProjectLocomotive.Drawnings;
using System.Windows.Forms;
namespace ProjectLocomotive namespace ProjectLocomotive
{ {
@ -174,17 +175,11 @@ namespace ProjectLocomotive
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
try CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(collectionInfo);
_logger.LogInformation("Добавление коллекции"); _logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems(); RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -203,7 +198,10 @@ namespace ProjectLocomotive
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation("Коллекция удалена"); _logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -216,7 +214,7 @@ namespace ProjectLocomotive
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -237,8 +235,8 @@ namespace ProjectLocomotive
return; return;
} }
ICollectionGenericObjects<DrawningLocomotive>? collection = CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawningLocomotive>? collection = _storageCollection[collectionInfo];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
@ -253,6 +251,7 @@ namespace ProjectLocomotive
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
} }
@ -303,6 +302,45 @@ namespace ProjectLocomotive
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareLocomotives(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBoxLocomotive.Image = _company.Show();
}
private void FormLocomotivesCollection_Load(object sender, EventArgs e)
{
}
private void pictureBoxLocomotive_Click(object sender, EventArgs e) private void pictureBoxLocomotive_Click(object sender, EventArgs e)
{ {