Compare commits

...

25 Commits

Author SHA1 Message Date
642e19f10d готовая 8 лаб работа 2024-05-20 13:12:41 +04:00
e8b3ec816b изменения 2024-05-14 14:29:17 +04:00
0e3a9a94a8 Лабораторная работа 8 2024-05-14 14:27:41 +04:00
b63e7a1c12 изменения 2024-05-07 19:28:47 +04:00
65771b774b изменения 2024-05-07 19:27:21 +04:00
c60abd65d7 Лабороторная работа 7 2024-05-06 14:07:43 +04:00
6b8ef29396 лабораторная работа 6 2024-05-05 16:18:45 +04:00
37a08bafc8 Лабораторная работа 5 2024-04-22 14:04:34 +04:00
95921980a6 готовая 4 лабораторная работа 2024-04-08 13:06:55 +04:00
b95fc3e7cd компании 2024-03-25 15:33:02 +04:00
343844e578 половина лабы 3 2024-03-23 17:23:26 +04:00
c49c341692 удаление папки с плохим проектом 2024-03-23 16:27:34 +04:00
1a26bf133a начало 2024-03-22 18:25:32 +04:00
89bdff531b начало лаб работы 2024-03-22 18:22:55 +04:00
626b613b39 готовая лаб работа 2 2024-03-12 12:14:52 +04:00
40448cbf4f изменения 2024-03-11 21:28:37 +04:00
5bcdc587bd изменения 2024-03-11 21:23:21 +04:00
47dfbb8244 изменения 2024-03-11 19:10:31 +04:00
e3268bf2a9 еще изменения 2024-03-11 16:22:33 +04:00
a30f2a037c изменения в лабе 2 2024-03-11 13:16:46 +04:00
7f9117622a половина 2 лабы 2024-03-10 16:16:18 +04:00
9bdf486696 Lab Work 01 2024-03-10 12:31:33 +04:00
5a2601f0fa изменения 2024-03-10 12:07:45 +04:00
ae1b6816f6 Лабораторная работа №1 2024-02-27 12:12:54 +04:00
03272f2f77 lab1 2024-02-12 16:11:02 +04:00
53 changed files with 4369 additions and 69 deletions

View File

@ -0,0 +1,155 @@
using ProjectGasMachine.Exceptions;
using ProjectGasMachine.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 280;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 80;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectionGenericObjects<DrawningMachine>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
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<DrawningMachine> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="machine">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningMachine machine)
{
try
{
return company._collection.Insert(machine, 0, new DrawningMachineEqutables());
}
catch (ObjectAlreadyInCollectionException)
{
return -1;
}
catch (CollectionOverflowException)
{
return -1;
}
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningMachine? operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningMachine? GetRandomObject()
{
Random rnd = new();
try
{
return _collection?.Get(rnd.Next(GetMaxCount));
}
catch (ObjectNotFoundException)
{
return null;
}
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningMachine? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningMachine?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackground(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,70 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.CollectionGenericObjects;
public class Autopark : AbstractCompany
{
public Autopark(int picWidth, int picHeight, ICollectionGenericObjects<DrawningMachine> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 2);
Pen Pen2 = new(Color.Black, 3);
for (int i = 0; i < _pictureHeight / _placeSizeHeight; i++)
{
int y = _placeSizeHeight;
y *= i;
for (int j = 0; j <= _pictureWidth / _placeSizeWidth; j++)
{
int x = _placeSizeWidth;
x *= j;
g.DrawLine(Pen2, x, y, x + _placeSizeWidth / 2, y);
g.DrawLine(Pen2, x, y + _placeSizeHeight - 10, x + _placeSizeWidth / 2, y + _placeSizeHeight - 10);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight - 10);
}
}
}
protected override void SetObjectsPosition()
{
int n = 0;
int m = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
{
if (_collection?.Get(i) != null)
{
int x = 5 + _placeSizeWidth * n;
int y = (-3 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m;
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
}
if (n < _pictureWidth / _placeSizeWidth)
n++;
else
{
n = 0;
m++;
}
}
catch (ObjectNotFoundException)
{
break;
}
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,74 @@
using ProjectGasMachine.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.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>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</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,120 @@

using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using System.Linq;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyInCollectionException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если выход за границы списка
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyInCollectionException();
}
}
if (position < 0 || position > Count)
{
throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position > Count)
{
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,177 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using System.Linq;
namespace ProjectGasMachine.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)
{
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
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)
{
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningMachine>).Equals(obj as DrawningMachine, item as DrawningMachine))
{
throw new ObjectAlreadyInCollectionException();
}
}
}
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)
{
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningMachine>).Equals(obj as DrawningMachine, item as DrawningMachine))
{
throw new ObjectAlreadyInCollectionException();
}
}
}
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
T? obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -0,0 +1,232 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningMachine
{
/// <summary>
/// словарь (хранилище) с коллекциями
/// </summary>
private 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="name">название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(CollectionInfo info)
{
if (info == null || _storages.ContainsKey(info))
{
return;
}
if (info.CollectionType == CollectionType.Massive)
{
_storages.Add(info, new MassiveGenericObjects<T>());
}
if (info.CollectionType == CollectionType.List)
{
_storages.Add(info, new ListGenericObjects<T>());
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name"></param>
public void DelCollection(CollectionInfo info)
{
if (info == null || !_storages.ContainsKey(info))
{
return;
}
_storages.Remove(info);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[CollectionInfo info]
{
get
{
if (_storages.ContainsKey(info))
{
return _storages[info];
}
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new StreamWriter(filename))
{
sw.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sw.Write(data);
sw.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new FileFormatException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMachine() is T machine)
{
try
{
if (collection.Insert(machine, new DrawningMachineEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", 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,27 @@
 namespace ProjectGasMachine.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,70 @@
using ProjectGasMachine.Entities;
namespace ProjectGasMachine.Drawnings;
/// <summary>
///
/// </summary>
public class DrawningGasMachine : DrawningMachine
{
/// <summary>
/// конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес машины</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gas">Признак наличия бака для бензина</param>
/// <param name="beacon">Признак наличия маяка</param>
public DrawningGasMachine(int speed, double weight, Color bodyColor, Color additionalColor, bool gas, bool beacon) : base(115, 70)
{
EntityGas = new EntityMachine(speed, weight, bodyColor, additionalColor, gas, beacon);
}
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="gasmachine"></param>
public DrawningGasMachine(EntityGas? gasmachine) : base(gasmachine)
{
EntityGas = gasmachine;
}
public override void DrawTransport(Graphics g)
{
if (EntityGas == null || EntityGas is not EntityMachine gasmachine || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(gasmachine.AdditionalColor);
//маяк сигнальный
if (gasmachine.Beacon)
{
g.DrawRectangle(pen, _startPosX.Value + 95, _startPosY.Value, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 95, _startPosY.Value, 10, 10);
}
//бак с газом
if (gasmachine.Gas)
{
g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 10, 80, 30);
g.FillEllipse(additionalBrush, _startPosX.Value, _startPosY.Value + 10, 80, 30);
}
_startPosX += 5;
base.DrawTransport(g);
_startPosX -= 5;
}
}

View File

@ -0,0 +1,258 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
public class DrawningMachine
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityGas? EntityGas { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки газ автомобиля
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки газ автомобиля
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки газ автомобиля
/// </summary>
private readonly int _drawningMachineWidth = 110;
/// <summary>
/// Высота прорисовки газ автомобиля
/// </summary>
private readonly int _drawningMachineHeight = 70;
/// <summary>
/// координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// ширина объекта
/// </summary>
public int GetWidth => _drawningMachineWidth;
/// <summary>
/// высота объекта
/// </summary>
public int GetHeight => _drawningMachineHeight;
/// <summary>
/// пустой конструктор
/// </summary>
private DrawningMachine()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес машины</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningMachine(int speed, double weight, Color bodyColor) : this()
{
EntityGas = new EntityGas(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningMachineWidth">Ширина прорисовки газ автомобиля</param>
/// <param name="drawningMachineHeight">Высота прорисовки газ автомобиля</param>
protected DrawningMachine(int drawningMachineWidth, int drawningMachineHeight) : this()
{
_drawningMachineWidth = drawningMachineWidth;
_pictureHeight = drawningMachineHeight;
}
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="machine"></param>
public DrawningMachine(EntityGas? machine) : this()
{
EntityGas = machine;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих границах</returns>
public bool SetPictureSize(int width, int height)
{
if (EntityGas == null)
{
return false;
}
if (width >= _drawningMachineWidth && height >= _drawningMachineHeight)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningMachineWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningMachineWidth;
}
if (_startPosY + _drawningMachineHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningMachineHeight;
}
}
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if (x < 0)
{
_startPosX = 0;
}
if (y < 0)
{
_startPosY = 0;
}
if (x + _drawningMachineWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningMachineWidth;
}
if (y + _drawningMachineHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningMachineHeight;
}
}
public bool MoveTransport(DirectionType direction)
{
if (EntityGas == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityGas.Step > 0)
{
_startPosX -= (int)EntityGas.Step;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityGas.Step > 0)
{
_startPosY -= (int)EntityGas.Step;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + EntityGas.Step + _drawningMachineWidth < _pictureWidth)
{
_startPosX += (int)EntityGas.Step;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + EntityGas.Step + _drawningMachineHeight < _pictureHeight)
{
_startPosY += (int)EntityGas.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityGas == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
//границы автомобиля
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 40, 110, 10);
g.DrawRectangle(pen, _startPosX.Value + 76, _startPosY.Value + 10, 30, 30);
//кузов
Brush br = new SolidBrush(EntityGas.BodyColor);
g.FillRectangle(br, _startPosX.Value, _startPosY.Value + 40, 110, 10);
//кабина
g.FillRectangle(br, _startPosX.Value + 76, _startPosY.Value + 10, 30, 30);
//колеса
g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 50, 20, 20);
g.FillEllipse(br, _startPosX.Value + 10, _startPosY.Value + 50, 20, 20);
g.DrawEllipse(pen, _startPosX.Value + 85, _startPosY.Value + 50, 20, 20);
g.FillEllipse(br, _startPosX.Value + 85, _startPosY.Value + 50, 20, 20);
}
}

View File

@ -0,0 +1,48 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningMachineCompareByColor : IComparer<DrawningMachine?>
{
public int Compare(DrawningMachine? x, DrawningMachine? y)
{
if (x == null || x.EntityGas == null)
{
return 1;
}
if (y == null || y.EntityGas == null)
{
return -1;
}
var bodyColorCompare = y.EntityGas.BodyColor.Name.CompareTo(x.EntityGas.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x is DrawningGasMachine && y is DrawningGasMachine)
{
var additionalColorCompare = (y.EntityGas as EntityMachine).AdditionalColor.Name.CompareTo(
(x.EntityGas as EntityMachine).AdditionalColor.Name);
if (additionalColorCompare != 0)
{
return additionalColorCompare;
}
}
var speedCompare = y.EntityGas.Speed.CompareTo(x.EntityGas.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityGas.Weight.CompareTo(x.EntityGas.Weight);
}
}

View File

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

View File

@ -0,0 +1,68 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningMachineEqutables : IEqualityComparer<DrawningMachine?>
{
public bool Equals(DrawningMachine? x, DrawningMachine? y)
{
if (x == null || x.EntityGas == null)
{
return false;
}
if (y == null || y.EntityGas == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityGas.Speed != y.EntityGas.Speed)
{
return false;
}
if (x.EntityGas.Weight != y.EntityGas.Weight)
{
return false;
}
if (x.EntityGas.BodyColor != y.EntityGas.BodyColor)
{
return false;
}
if (x is DrawningGasMachine && y is DrawningGasMachine)
{
// TODO доделать логику сравнения дополнительных параметров
if ((x.EntityGas as EntityMachine)?.AdditionalColor !=
(y.EntityGas as EntityMachine)?.AdditionalColor)
{
return false;
}
if ((x.EntityGas as EntityMachine)?.Gas !=
(y.EntityGas as EntityMachine)?.Gas)
{
return false;
}
if ((x.EntityGas as EntityMachine)?.Beacon !=
(y.EntityGas as EntityMachine)?.Beacon)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningMachine? obj)
{
return obj.GetHashCode();
}
}

View File

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

View File

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Entities;
/// <summary>
/// Класс-сущность "машина для перевозки газа"
/// </summary>
public class EntityGas
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения машины
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес машины</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityGas(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Смена основного цвета
/// </summary>
/// <param name="newColor"></param>
public void BodyColorChange(Color newColor)
{
BodyColor = newColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityGas), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityGas? CreateEntityGas(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityGas))
{
return null;
}
return new EntityGas(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -0,0 +1,69 @@
namespace ProjectGasMachine.Entities;
/// <summary>
/// Класс-сущность "бензовоз"
/// </summary>
public class EntityMachine : EntityGas
{
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия бака для бензина
/// </summary>
public bool Gas { get; private set; }
/// <summary>
/// Признак (опция) наличия маяка
/// </summary>
public bool Beacon { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gas">Признак наличия бака для бензина</param>
/// <param name="beacon">Признак наличия маяка</param>
public EntityMachine(int speed, double weight, Color bodyColor, Color additionalColor, bool gas, bool beacon) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Gas = gas;
Beacon = beacon;
}
/// <summary>
/// Смена дополнительного цвета
/// </summary>
/// <param name="newColor"></param>
public void AdditionalColorChange(Color newColor)
{
AdditionalColor = newColor;
}
public override string[] GetStringRepresentation()
{
return new[]
{
nameof(EntityMachine),
Speed.ToString(),
Weight.ToString(),
BodyColor.Name,
AdditionalColor.Name,
Gas.ToString(),
Beacon.ToString(),
};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMachine? CreateEntityMachine(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityMachine))
{
return null;
}
return new EntityMachine(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public 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,20 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int count) : base("Такой объект уже присутствует в коллекции. Позиция " + count) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[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,22 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[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

@ -1,45 +0,0 @@
namespace ProjectCar
{
partial class Form1
{
/// <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()
{
SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(750, 209);
Name = "Form1";
Text = "Form1";
ResumeLayout(false);
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace ProjectCar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,145 @@
namespace ProjectGasMachine
{
partial class FormGasMachine
{
/// <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()
{
buttonLeft = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
pictureBoxGasMachine = new PictureBox();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxGasMachine).BeginInit();
SuspendLayout();
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.влево;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(862, 481);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.вправо;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(944, 481);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 3;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.вверх;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(903, 440);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 4;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.вниз;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(903, 481);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// pictureBoxGasMachine
//
pictureBoxGasMachine.Dock = DockStyle.Fill;
pictureBoxGasMachine.Location = new Point(0, 0);
pictureBoxGasMachine.Name = "pictureBoxGasMachine";
pictureBoxGasMachine.Size = new Size(988, 528);
pictureBoxGasMachine.TabIndex = 0;
pictureBoxGasMachine.TabStop = false;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(858, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(901, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormGasMachine
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(988, 528);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxGasMachine);
Name = "FormGasMachine";
Text = "Газовоз";
((System.ComponentModel.ISupportInitialize)pictureBoxGasMachine).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private PictureBox pictureBoxGasMachine;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,137 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.MovementStrategy;
namespace ProjectGasMachine;
public partial class FormGasMachine : Form
{
/// <summary>
/// поле-объект для прорисовки объекта
/// </summary>
private DrawningMachine? _drawningMachine;
/// <summary>
/// стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
public DrawningMachine SetMachine
{
set
{
_drawningMachine = value;
_drawningMachine.SetPictureSize(pictureBoxGasMachine.Height, pictureBoxGasMachine.Width);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// конструктор формы
/// </summary>
public FormGasMachine()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// метод прорисовки машины
/// </summary>
private void Draw()
{
if (_drawningMachine == null)
{
return;
}
Bitmap bmp = new(pictureBoxGasMachine.Width, pictureBoxGasMachine.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningMachine.DrawTransport(gr);
pictureBoxGasMachine.Image = bmp;
}
/// <summary>
/// перемещение объекта по форме
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningMachine == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningMachine.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningMachine.MoveTransport(DirectionType.Down);
break;
case "buttonRight":
result = _drawningMachine.MoveTransport(DirectionType.Right);
break;
case "buttonLeft":
result = _drawningMachine.MoveTransport(DirectionType.Left);
break;
}
if (result)
{
Draw();
}
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningMachine == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableMachine(_drawningMachine), pictureBoxGasMachine.Width, pictureBoxGasMachine.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

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,374 @@
namespace ProjectGasMachine
{
partial class FormGasMachineCollection
{
/// <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();
buttonAddMachine = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
buttonRemoveMachine = new Button();
buttonGoToCheck = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
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(780, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(196, 557);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(ButtonSortByColor);
panelCompanyTools.Controls.Add(ButtonSortByType);
panelCompanyTools.Controls.Add(buttonAddMachine);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveMachine);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 292);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(190, 262);
panelCompanyTools.TabIndex = 9;
//
// buttonAddMachine
//
buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMachine.Location = new Point(10, 3);
buttonAddMachine.Name = "buttonAddMachine";
buttonAddMachine.Size = new Size(174, 33);
buttonAddMachine.TabIndex = 2;
buttonAddMachine.Text = "Добавление грузовика";
buttonAddMachine.UseVisualStyleBackColor = true;
buttonAddMachine.Click += ButtonAddMachine_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 42);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(184, 23);
maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(10, 144);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(174, 32);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonRemoveMachine
//
buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMachine.Location = new Point(10, 71);
buttonRemoveMachine.Name = "buttonRemoveMachine";
buttonRemoveMachine.Size = new Size(174, 32);
buttonRemoveMachine.TabIndex = 5;
buttonRemoveMachine.Text = "Удалить газовоз";
buttonRemoveMachine.UseVisualStyleBackColor = true;
buttonRemoveMachine.Click += ButtonRemoveMachine_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(10, 109);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(174, 29);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 263);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(184, 23);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(190, 209);
panelStorage.TabIndex = 8;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 176);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(184, 23);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 106);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(184, 64);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 77);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(184, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(115, 52);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(16, 52);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 18);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(184, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(34, 0);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 234);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(184, 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(780, 557);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(976, 24);
menuStrip.TabIndex = 4;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByColor
//
ButtonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonSortByColor.Location = new Point(10, 217);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(174, 32);
ButtonSortByColor.TabIndex = 9;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonSortByType.Location = new Point(10, 182);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(174, 29);
ButtonSortByType.TabIndex = 8;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// FormGasMachineCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(976, 581);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormGasMachineCollection";
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 buttonAddMachine;
private Button buttonRemoveMachine;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Panel panelStorage;
private Label labelCollectionName;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -0,0 +1,374 @@
using Microsoft.Extensions.Logging;
using ProjectGasMachine.CollectionGenericObjects;
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectGasMachine
{
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormGasMachineCollection : Form
{
/// <summary>
/// хранение коллекций
/// </summary>
private readonly StorageCollection<DrawningMachine> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// конструктор
/// </summary>
public FormGasMachineCollection(ILogger<FormGasMachineCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление газовоза в коллекцию
/// </summary>
/// <param name="machine"></param>
private void SetMachine(DrawningMachine? machine)
{
if (_company == null || machine == null)
{
return;
}
try
{
if (_company + machine != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {machine.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
/// добавление грузовика
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddMachine_Click(object sender, EventArgs e)
{
FormGasConfig form = new();
// TODO передать метод +
form.AddEvent(SetMachine);
form.Show();
}
/// <summary>
/// удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveMachine_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningMachine? machine = null;
int counter = 100;
while (machine == null)
{
machine = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (machine == null)
{
return;
}
FormGasMachine form = new()
{
SetMachine = machine
};
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);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RerfreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Вы уверены, что хотите удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningMachine>? collection = _storageCollection[collectionInfo];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Autopark(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
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("Ошибка: {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);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из фала: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", 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)
{
CompareMachines(new DrawningMachineCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareMachines(new DrawningMachineCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareMachines(IComparer<DrawningMachine?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}

View File

@ -0,0 +1,132 @@
<?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>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -0,0 +1,136 @@
namespace ProjectGasMachine.MovementStrategy;
/// <summary>
/// класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// перемещаемый объект
/// </summary>
private IMoveableObjects? _moveableObject;
/// <summary>
/// статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// установка данных
/// </summary>
/// <param name="moveableObject">перемещаемый объект</param>
/// <param name="width">ширина</param>
/// <param name="height">высота</param>
public void SetData(IMoveableObjects moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestination();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,24 @@
namespace ProjectGasMachine.MovementStrategy;
/// <summary>
/// интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObjects
{
/// <summary>
/// получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction"></param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,52 @@
namespace ProjectGasMachine.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта к краю
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder - GetStep() <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder - GetStep() <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,48 @@
namespace ProjectGasMachine.MovementStrategy;
internal class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,70 @@
using ProjectGasMachine.Drawnings;
using System.Reflection.PortableExecutable;
namespace ProjectGasMachine.MovementStrategy;
/// <summary>
/// класс-реализация IMoveableObjects с использованием DrawningMachine
/// </summary>
public class MoveableMachine : IMoveableObjects
{
/// <summary>
/// поле-объект класса DrawningMachine или его наследника
/// </summary>
private readonly DrawningMachine? _machine = null;
/// <summary>
/// конструктор
/// </summary>
/// <param name="machine">объект класса DrawningMachine</param>
public MoveableMachine(DrawningMachine machine)
{
_machine = machine;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_machine == null || _machine.EntityGas == null || !_machine.GetPosX.HasValue || !_machine.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_machine.GetPosX.Value, _machine.GetPosY.Value, _machine.GetWidth, _machine.GetHeight);
}
}
public int GetStep => (int)(_machine?.EntityGas?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_machine == null || _machine.EntityGas == null)
{
return false;
}
return _machine.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,21 @@
namespace ProjectGasMachine.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,72 @@
namespace ProjectGasMachine.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// координата x
/// </summary>
private readonly int _x;
/// <summary>
/// координата y
/// </summary>
private readonly int _y;
/// <summary>
/// ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width/2;
/// <summary>
/// середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// конструктор
/// </summary>
/// <param name="x">координата x</param>
/// <param name="y">координата y</param>
/// <param name="width">ширина объекта</param>
/// <param name="height">высота объекта</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -0,0 +1,22 @@
namespace ProjectGasMachine.MovementStrategy;
/// <summary>
/// статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// все готово к началу
/// </summary>
NotInit,
/// <summary>
/// выполняется
/// </summary>
InProgress,
/// <summary>
/// завершено
/// </summary>
Finish
}

View File

@ -1,4 +1,9 @@
namespace ProjectCar
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasMachine
{
internal static class Program
{
@ -11,7 +16,26 @@ namespace ProjectCar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormGasMachineCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services
.AddSingleton<FormGasMachineCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}
}

View File

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Include="ProjectGasMachine.csproj" />
<None Include="ProjectGasMachine.csproj.user" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,113 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectGasMachine.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectGasMachine.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap free_icon_left_arrow_10696518 {
get {
object obj = ResourceManager.GetObject("free-icon-left-arrow-10696518", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap вверх {
get {
object obj = ResourceManager.GetObject("вверх", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap влево {
get {
object obj = ResourceManager.GetObject("влево", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap вниз {
get {
object obj = ResourceManager.GetObject("вниз", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap вправо {
get {
object obj = ResourceManager.GetObject("вправо", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,136 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="free-icon-left-arrow-10696518" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\free-icon-left-arrow-10696518.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="вверх" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\вверх.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="влево" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\влево.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="вниз" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\вниз.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="вправо" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\вправо.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,25 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Пользователи\\artem\\OneDrive\\Рабочий стол\\уник\\ООП\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34309.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectCar", "ProjectCar\ProjectCar.csproj", "{0BAD5252-A074-4558-8F3E-7CDB84331644}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectGasMachine", "ProjectCar\ProjectGasMachine.csproj", "{0BAD5252-A074-4558-8F3E-7CDB84331644}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution