8 Commits

Author SHA1 Message Date
Kankistodor
ce9c88e5bb lab8-ready 2024-04-25 02:31:55 +04:00
Kankistodor
c50ddb14a2 Lab7-ready 2024-04-24 23:26:19 +04:00
Kankistodor
4cab399d4b lab6-ready 2024-04-21 13:18:45 +04:00
bca0b7ff6e part6lab 2024-04-10 21:03:23 +04:00
25e8f077f6 lab5-ready 2024-04-10 19:18:28 +04:00
d6180bbeb8 lab4 ready 2024-03-28 00:10:11 +04:00
be8ee033b2 fix 2024-03-14 09:42:38 +04:00
fe90aefffa lab3 ready 2024-03-13 19:49:07 +04:00
48 changed files with 3115 additions and 114 deletions

13
.idea/.idea.BoykoSolution/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,13 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/projectSettingsUpdater.xml
/.idea.BoykoSolution.iml
/modules.xml
/contentModel.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

1
.idea/.idea.BoykoSolution/.idea/.name generated Normal file
View File

@@ -0,0 +1 @@
BoykoSolution

View File

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

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

6
.idea/.idea.BoykoSolution/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,137 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 80;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция поездов
/// </summary>
protected ICollectionGenericObjects<DrawingTrans>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
// private int GetMaxCount => (_pictureWidth * _pictureHeight) / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция поездов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingTrans trans)
{
return company._collection?.Insert(trans, new DrawingTransEquitables()) ??
throw new DrawingEquitablesException();
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawingTrans? operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawingTrans?> comparer) =>
_collection?.CollectionSort(comparer);
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawingTrans? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawingTrans? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@@ -0,0 +1,82 @@
namespace ProjectElectroTrans.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 bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

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

View File

@@ -0,0 +1,66 @@
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

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

View File

@@ -0,0 +1,164 @@
using ProjectElectroTrans.Exceptions;
using System.Collections.Generic;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
{
get { return _collection.Length; }
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> lst = [.._collection];
lst.Sort(comparer.Compare);
for (int i = 0; i < _collection.Length; ++i)
{
_collection[i] = lst[i];
}
}
}

View File

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

View File

@@ -0,0 +1,71 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.Entities;
using System;
using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - аренда поезда
/// </summary>
public class TransDepoService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection) : base(
picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
}
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
}
protected override void SetObjectsPosition()
{
int n = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
try
{
DrawingTrans? drawingTrans = _collection?.Get(n);
if (drawingTrans != null)
{
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
n++;
}
}
}
}

View File

@@ -1,4 +1,4 @@
namespace ProjectSportCar.Drawnings; namespace ProjectElectroTrans.Drawnings;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения

View File

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

View File

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

View File

@@ -0,0 +1,35 @@
namespace ProjectElectroTrans.Drawnings;
public class DrawingTransCompareByColor : IComparer<DrawingTrans?>
{
public int Compare(DrawingTrans? x, DrawingTrans? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityTrans == null)
{
return 1;
}
if (y == null || y.EntityTrans == null)
{
return -1;
}
if (ToHex(x.EntityTrans.BodyColor) != ToHex(y.EntityTrans.BodyColor))
{
return String.Compare(ToHex(x.EntityTrans.BodyColor), ToHex(y.EntityTrans.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityTrans.Speed.CompareTo(y.EntityTrans.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrans.Weight.CompareTo(y.EntityTrans.Weight);
}
private static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@@ -0,0 +1,31 @@
namespace ProjectElectroTrans.Drawnings;
public class DrawingTransCompareByType : IComparer<DrawingTrans?>
{
public int Compare(DrawingTrans? x, DrawingTrans? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityTrans == null)
{
return 1;
}
if (y == null || y.EntityTrans == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTrans.Speed.CompareTo(y.EntityTrans.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrans.Weight.CompareTo(y.EntityTrans.Weight);
}
}

View File

@@ -0,0 +1,59 @@
using System.Diagnostics.CodeAnalysis;
using ProjectElectroTrans.Entities;
namespace ProjectElectroTrans.Drawnings;
public class DrawingTransEquitables : IEqualityComparer<DrawingTrans?>
{
public bool Equals(DrawingTrans? x, DrawingTrans? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrans != null && y.EntityTrans != null && x.EntityTrans.Speed != y.EntityTrans.Speed)
{
return false;
}
if (x.EntityTrans.Weight != y.EntityTrans.Weight)
{
return false;
}
if (x.EntityTrans.BodyColor != y.EntityTrans.BodyColor)
{
return false;
}
if (x is DrawingElectroTrans && y is DrawingElectroTrans)
{
if (((EntityElectroTrans)x.EntityTrans).AdditionalColor !=
((EntityElectroTrans)y.EntityTrans).AdditionalColor)
{
return false;
}
if (((EntityElectroTrans)x.EntityTrans).Battery!=
((EntityElectroTrans)y.EntityTrans).Battery)
{
return false;
}
if (((EntityElectroTrans)x.EntityTrans).Horns!=
((EntityElectroTrans)y.EntityTrans).Horns)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingTrans obj)
{
return obj.GetHashCode();
}
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
using ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectElectroTrans.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception) { }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class CollectionInfoException : Exception
{
public CollectionInfoException() : base() { }
public CollectionInfoException(string message) : base(message) { }
public CollectionInfoException(string message, Exception exception) :
base(message, exception) { }
protected CollectionInfoException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,15 @@
using System.Runtime.Serialization;
using ProjectElectroTrans.Drawnings;
namespace ProjectElectroTrans.Exceptions;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception) { }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,31 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions
{
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count)
{
}
public CollectionOverflowException() : base()
{
}
public CollectionOverflowException(string message) : base(message)
{
}
public CollectionOverflowException(string message, Exception exception) :
base(message, exception)
{
}
protected CollectionOverflowException(SerializationInfo info,
StreamingContext contex) : base(info, contex)
{
}
}
}

View File

@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
using ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectElectroTrans.Exceptions;
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :
base(message, exception) { }
protected CollectionTypeException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class DrawingEquitablesException : Exception
{
public DrawingEquitablesException() : base("Объекты прорисовки одинаковые") { }
public DrawingEquitablesException(string message) : base(message) { }
public DrawingEquitablesException(string message, Exception exception) :
base(message, exception) { }
protected DrawingEquitablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception) { }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class EmptyStorageException : Exception
{
public EmptyStorageException() : base() { }
public EmptyStorageException(string message) : base(message) { }
public EmptyStorageException(string message, Exception exception) :
base(message, exception) { }
protected EmptyStorageException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class FileFormatException : Exception
{
public FileFormatException() : base() { }
public FileFormatException(string message) : base(message) { }
public FileFormatException(string name, Exception exception) :
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception) { }
protected FileFormatException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class FileNotFoundException : Exception
{
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
public FileNotFoundException() : base() { }
public FileNotFoundException(string name, string message) : base(message) { }
public FileNotFoundException(string name, string message, Exception exception) :
base(message, exception) { }
protected FileNotFoundException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,15 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) :
base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,27 @@
using System.Runtime.Serialization;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i)
{
}
public PositionOutOfCollectionException() : base()
{
}
public PositionOutOfCollectionException(string message) : base(message)
{
}
public PositionOutOfCollectionException(string message, Exception
exception) : base(message, exception)
{
}
protected PositionOutOfCollectionException(SerializationInfo info,
StreamingContext contex) : base(info, contex)
{
}
}

View File

@@ -7,9 +7,9 @@ namespace ProjectElectroTrans
partial class FormElectroTrans partial class FormElectroTrans
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
@@ -33,12 +33,10 @@ namespace ProjectElectroTrans
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxElectroTrans = new PictureBox(); pictureBoxElectroTrans = new PictureBox();
buttonCreateElectroTrans = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateCar = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).BeginInit();
@@ -53,17 +51,6 @@ namespace ProjectElectroTrans
pictureBoxElectroTrans.TabIndex = 0; pictureBoxElectroTrans.TabIndex = 0;
pictureBoxElectroTrans.TabStop = false; pictureBoxElectroTrans.TabStop = false;
// //
// buttonCreateElectroTrans
//
buttonCreateElectroTrans.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateElectroTrans.Location = new Point(12, 562);
buttonCreateElectroTrans.Name = "buttonCreateElectroTrans";
buttonCreateElectroTrans.Size = new Size(223, 23);
buttonCreateElectroTrans.TabIndex = 1;
buttonCreateElectroTrans.Text = "Создать электропоезд";
buttonCreateElectroTrans.UseVisualStyleBackColor = true;
buttonCreateElectroTrans.Click += ButtonCreateElectroTrans_Click;
//
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@@ -112,17 +99,6 @@ namespace ProjectElectroTrans
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreateCar
//
buttonCreateCar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateCar.Location = new Point(250, 562);
buttonCreateCar.Name = "buttonCreateTrans";
buttonCreateCar.Size = new Size(223, 23);
buttonCreateCar.TabIndex = 6;
buttonCreateCar.Text = "Создать поезд";
buttonCreateCar.UseVisualStyleBackColor = true;
buttonCreateCar.Click += ButtonCreateTrans_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@@ -143,22 +119,21 @@ namespace ProjectElectroTrans
buttonStrategyStep.UseVisualStyleBackColor = true; buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click; buttonStrategyStep.Click += ButtonStrategyStep_Click;
// //
// FormElectroTrans // Form
//
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 597); ClientSize = new Size(923, 597);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCar);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreateElectroTrans);
Controls.Add(pictureBoxElectroTrans); Controls.Add(pictureBoxElectroTrans);
Name = "FormElectroTrans"; Name = "FormElectroTrans";
Text = "Электропоезд"; Text = "Электровоз";
((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
@@ -166,12 +141,10 @@ namespace ProjectElectroTrans
#endregion #endregion
private PictureBox pictureBoxElectroTrans; private PictureBox pictureBoxElectroTrans;
private Button buttonCreateElectroTrans;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateCar;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@@ -1,22 +1,42 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.MovementStrategy; using ProjectElectroTrans.MovementStrategy;
using ProjectSportCar.Drawnings; using ProjectElectroTrans.Drawnings;
using ProjectSportCar.MovementStrategy;
namespace ProjectElectroTrans; namespace ProjectElectroTrans;
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"
/// </summary>
public partial class FormElectroTrans : Form public partial class FormElectroTrans : Form
{ {
/// <summary> /// <summary>
/// <20><><EFBFBD><EFBFBD>-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> /// <20><><EFBFBD><EFBFBD>-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary> /// </summary>
private DrawingTrans? _drawingTrans; private DrawingTrans? _drawningTrans;
/// <summary> /// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> /// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public DrawingTrans SetTrans
{
set
{
_drawningTrans = value;
_drawningTrans.SetPictureSize(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public FormElectroTrans() public FormElectroTrans()
{ {
InitializeComponent(); InitializeComponent();
@@ -28,62 +48,25 @@ public partial class FormElectroTrans : Form
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawingTrans == null) if (_drawningTrans == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height); Bitmap bmp = new(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawingTrans.DrawTransport(gr); _drawningTrans.DrawTransport(gr);
pictureBoxElectroTrans.Image = bmp; pictureBoxElectroTrans.Image = bmp;
} }
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawingTrans):
_drawingTrans = new DrawingTrans(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawingElectroTrans):
_drawingTrans = new DrawingElectroTrans(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)));
break;
default:
return;
}
_drawingTrans.SetPictureSize(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
_drawingTrans.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary> /// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>" /// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreateElectroTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingElectroTrans)); private void ButtonMove_Click(object sender, EventArgs e)
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingTrans));
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawingTrans == null) if (_drawningTrans == null)
{ {
return; return;
} }
@@ -93,16 +76,16 @@ public partial class FormElectroTrans : Form
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawingTrans.MoveTransport(DirectionType.Up); result = _drawningTrans.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawingTrans.MoveTransport(DirectionType.Down); result = _drawningTrans.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawingTrans.MoveTransport(DirectionType.Left); result = _drawningTrans.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawingTrans.MoveTransport(DirectionType.Right); result = _drawningTrans.MoveTransport(DirectionType.Right);
break; break;
} }
@@ -111,14 +94,15 @@ public partial class FormElectroTrans : Form
Draw(); Draw();
} }
} }
/// <summary> /// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD>" /// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD>"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e) private void ButtonStrategyStep_Click(object sender, EventArgs e)
{ {
if (_drawingTrans == null) if (_drawningTrans == null)
{ {
return; return;
} }
@@ -135,7 +119,7 @@ public partial class FormElectroTrans : Form
{ {
return; return;
} }
_strategy.SetData(new MoveableTrans(_drawingTrans), pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height); _strategy.SetData(new MoveableTrans(_drawningTrans), pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
} }
if (_strategy == null) if (_strategy == null)

View File

@@ -0,0 +1,378 @@
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
using System.Xml.Linq;
namespace ProjectElectroTrans
{
partial class FormTransCollection
{
/// <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()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddCar = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
buttonRemoveCar = new Button();
buttonGoToCheck = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(783, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(179, 657);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddCar);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveCar);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 355);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(173, 299);
panelCompanyTools.TabIndex = 9;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 250);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(167, 40);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 210);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(167, 40);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonAddCar
//
buttonAddCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddCar.Location = new Point(3, 3);
buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(167, 40);
buttonAddCar.TabIndex = 1;
buttonAddCar.Text = "Добавление поезда";
buttonAddCar.UseVisualStyleBackColor = true;
buttonAddCar.Click += ButtonAddTrans_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 49);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(167, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 164);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(167, 40);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonRemoveCar
//
buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveCar.Location = new Point(3, 78);
buttonRemoveCar.Name = "buttonRemoveCar";
buttonRemoveCar.Size = new Size(167, 40);
buttonRemoveCar.TabIndex = 4;
buttonRemoveCar.Text = "Удалить поезд";
buttonRemoveCar.UseVisualStyleBackColor = true;
buttonRemoveCar.Click += ButtonRemoveTrans_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 124);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(167, 40);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 320);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(167, 23);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(173, 266);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 227);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(167, 23);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 112);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(167, 109);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 83);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(167, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(98, 58);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(16, 58);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 29);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(167, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(26, 11);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 291);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(167, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(783, 657);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(962, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormCarCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(962, 681);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTransCollection";
Text = "Коллекция электропоездов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddCar;
private Button buttonRemoveCar;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonGoToCheck;
private Button buttonRefresh;
private Panel panelStorage;
private Label labelCollectionName;
private TextBox textBoxCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCollectionAdd;
private ListBox listBoxCollection;
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -0,0 +1,373 @@
using ProjectElectroTrans.CollectionGenericObjects;
using ProjectElectroTrans.Drawnings;
using Microsoft.Extensions.Logging;
using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormTransCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawingTrans> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTransCollection(ILogger<FormTransCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TransDepoService(pictureBox.Width, pictureBox.Height,
new MassiveGenericObjects<DrawingTrans>());
break;
}
}
private void ButtonAddTrans_Click(object sender, EventArgs e)
{
FormTransConfig form = new();
form.Show();
form.AddEvent(SetTrans);
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void SetTrans(DrawingTrans? drawingTrans)
{
if (_company == null || drawingTrans == null)
{
return;
}
try
{
var res = _company + drawingTrans;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTrans_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawingTrans? car = null;
int counter = 100;
while (car == null)
{
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (car == null)
{
return;
}
FormElectroTrans form = new()
{
SetTrans = car
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ"));
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
CollectionInfo? col = _storageCollection.Keys?[i];
if (!col!.IsEmpty())
{
listBoxCollection.Items.Add(col);
}
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawingTrans>? collection =
_storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TransDepoService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}",
saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawingTransCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawingTransCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareCars(IComparer<DrawingTrans?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

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

View File

@@ -0,0 +1,397 @@
namespace ProjectElectroTrans
{
partial class FormTransConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
panel2 = new Panel();
pictureBox1 = new PictureBox();
panel1 = new Panel();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxBulldozerDump = new CheckBox();
checkBoxSupport = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
panelObject = new Panel();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
labelAdditionalColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(panel2);
groupBoxConfig.Controls.Add(panel1);
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxBulldozerDump);
groupBoxConfig.Controls.Add(checkBoxSupport);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(571, 251);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// panel2
//
panel2.Controls.Add(pictureBox1);
panel2.Location = new Point(578, 10);
panel2.Name = "panel2";
panel2.Size = new Size(250, 125);
panel2.TabIndex = 1;
//
// pictureBox1
//
pictureBox1.Location = new Point(59, 48);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(125, 62);
pictureBox1.TabIndex = 0;
pictureBox1.TabStop = false;
//
// panel1
//
panel1.Location = new Point(594, 12);
panel1.Name = "panel1";
panel1.Size = new Size(226, 144);
panel1.TabIndex = 1;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(316, 21);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(256, 125);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(189, 81);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(35, 33);
panelPurple.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(189, 36);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(35, 33);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(130, 81);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(35, 33);
panelBlack.TabIndex = 6;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(130, 36);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(35, 33);
panelBlue.TabIndex = 2;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(74, 81);
panelGray.Name = "panelGray";
panelGray.Size = new Size(35, 33);
panelGray.TabIndex = 5;
//
// panelGreen
//
panelGreen.BackColor = Color.FromArgb(0, 192, 0);
panelGreen.Location = new Point(74, 36);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(35, 33);
panelGreen.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(23, 81);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(35, 33);
panelWhite.TabIndex = 4;
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.AutoSize = true;
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(23, 36);
panelRed.Name = "panelRed";
panelRed.Size = new Size(35, 33);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxBulldozerDump
//
checkBoxBulldozerDump.AutoSize = true;
checkBoxBulldozerDump.Location = new Point(13, 162);
checkBoxBulldozerDump.Name = "checkBoxBulldozerDump";
checkBoxBulldozerDump.Size = new Size(315, 24);
checkBoxBulldozerDump.TabIndex = 8;
checkBoxBulldozerDump.Text = "Признак наличие рогов";
checkBoxBulldozerDump.UseVisualStyleBackColor = true;
//
// checkBoxSupport
//
checkBoxSupport.AutoSize = true;
checkBoxSupport.Location = new Point(12, 132);
checkBoxSupport.Name = "checkBoxSupport";
checkBoxSupport.Size = new Size(209, 24);
checkBoxSupport.TabIndex = 7;
checkBoxSupport.Text = "Признак наличие батарей ";
checkBoxSupport.UseVisualStyleBackColor = true;
//
// checkBoxBucket
//
numericUpDownWeight.Location = new Point(91, 54);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(150, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(91, 21);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(150, 27);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 61);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(33, 20);
labelWeight.TabIndex = 3;
labelWeight.Text = "Вес";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 23);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(73, 20);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(161, 201);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(113, 25);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(33, 201);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(98, 25);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Location = new Point(575, 7);
panelObject.Name = "panelObject";
panelObject.Size = new Size(250, 197);
panelObject.TabIndex = 1;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.AutoSize = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(31, 19);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(44, 22);
labelBodyColor.TabIndex = 1;
labelBodyColor.Text = "Цвет";
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(19, 44);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(216, 150);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.AutoSize = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(158, 19);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(77, 22);
labelAdditionalColor.TabIndex = 2;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(578, 210);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(716, 210);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormExcavatorConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(822, 251);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormExcavatorConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
groupBoxColors.ResumeLayout(false);
groupBoxColors.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
panelObject.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxBulldozerDump;
private CheckBox checkBoxSupport;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Panel panel1;
private Panel panel2;
private PictureBox pictureBox1;
private Panel panelObject;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

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

View File

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

View File

@@ -1,6 +1,4 @@
using ProjectElectroTrans.MovementStrategy; namespace ProjectElectroTrans.MovementStrategy;
namespace ProjectSportCar.MovementStrategy;
public class MoveToBorder : AbstractStrategy public class MoveToBorder : AbstractStrategy
{ {

View File

@@ -1,5 +1,4 @@
using ProjectElectroTrans.Drawnings; using ProjectElectroTrans.Drawnings;
using ProjectSportCar.Drawnings;
namespace ProjectElectroTrans.MovementStrategy; namespace ProjectElectroTrans.MovementStrategy;

View File

@@ -1,17 +1,45 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectElectroTrans namespace ProjectElectroTrans
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormElectroTrans()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTransCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTransCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework> <TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
@@ -23,4 +23,14 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0-preview.3.24172.9" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0-preview.3.24172.9" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0-preview.3.24172.9" />
<PackageReference Include="Serilog" Version="4.0.0-dev-02160" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10389" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1-dev-00582" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00972" />
</ItemGroup>
</Project> </Project>

View File

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

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}, {"Name": "Console"}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotives"
}
}
}