Compare commits

..

17 Commits
main ... Lab8

Author SHA1 Message Date
e711c16adf Лаба 8, готовая. 2024-06-10 12:01:46 +04:00
e89571f599 Лаба 7 готовая. 2024-06-10 01:50:02 +04:00
21ea2ca455 Лаба 6, гготовая. 2024-06-08 20:58:52 +04:00
5e1a479097 Промежуточно лаба 6. 2024-05-21 21:56:57 +04:00
bab2bdbead Лаба 5 всё. 2024-05-21 09:57:44 +04:00
dbcbcb24ea 4 лаба без допов. 2024-05-07 09:12:53 +04:00
c9ce2eac8c Фиксация на всякий случай. 2024-04-23 08:34:01 +04:00
5e7a5b684d Лаба 4 без TODO. 2024-04-22 19:42:45 +04:00
34d5daf3b1 Лаба 3, которая готовая. 2024-04-12 22:54:00 +04:00
614075b569 Лаба 3, перед перенесением доп цвета в крутой бульдозер. 2024-04-12 22:19:35 +04:00
2dd9a71e1f Лаба 3 без TODO 2024-04-09 10:26:55 +04:00
870c31e157 Фиксация третьей лабы на всякий случай 2024-04-06 12:27:28 +04:00
e5b98208f6 Лаба 2 с допом 2 2024-03-26 10:09:54 +04:00
378bceea9b Лаба 2 без допов. 2024-03-26 09:38:42 +04:00
a8c7158463 Более-менее работает 2024-03-24 21:13:20 +04:00
cbf4305be0 Промежуточный коммит 2024-03-13 10:29:32 +04:00
60ab887cca Лаба 1 всё (кроме допов). 2024-03-11 21:54:48 +04:00
51 changed files with 4744 additions and 75 deletions

View File

@ -0,0 +1,128 @@
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллецию автомобилей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 190;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 130;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectoinGenericObjects<DrawningDozer>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (int)(_pictureWidth / _placeSizeWidth) * (int)(_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collectoin">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight, ICollectoinGenericObjects<DrawningDozer> collectoin)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collectoin;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="dozer">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningDozer dozer)
{
return company._collection.Insert(dozer, new DrawningDozerEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningDozer? operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningDozer? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningDozer? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Срвнитель объектов</param>
public void Sort(IComparer<DrawningDozer> 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,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class 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,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

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

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBulldozer.Drawnings;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании
/// </summary>
public class Garage : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collectoin"></param>
public Garage(int picWidth, int picHeight, ICollectoinGenericObjects<DrawningDozer> collectoin) : base(picWidth, picHeight, collectoin)
{
}
/// <summary>
/// отрисовка парковки
/// </summary>
/// <param name="g"></param>
protected override void DrawBackground(Graphics g)
{
int cntVertically = _pictureHeight / _placeSizeHeight; //Колличество мест по вертикали
int cntHorizontally = _pictureWidth / _placeSizeWidth; //Колличество мест по горизонтали
Pen pen = new(Color.FromArgb(185, 140, 0))
{
Width = 3
};
for (int i = 0; i < cntHorizontally; i++)
{
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, cntVertically * _placeSizeHeight);
for (int j = 0; j < cntVertically + 1; j++)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, (i + 1) * _placeSizeWidth - 50, j * _placeSizeHeight);
}
}
}
/// <summary>
/// выбор места на парковке
/// </summary>
protected override void SetObjectsPosition()
{
//Влево, вверх
int width = _pictureWidth / _placeSizeWidth - 1;
int height = _pictureHeight / _placeSizeHeight - 1;
int placeHorizontally = width;
int placeVertically = height;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (placeVertically < 0)
{
return;
}
if (_collection?.Get(i) != null)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * placeHorizontally + 20, _placeSizeHeight * placeVertically + 20);
}
if (placeHorizontally > 0)
{
placeHorizontally--;
}
else
{
placeHorizontally = width;
placeVertically--;
}
}
}
}

View File

@ -0,0 +1,72 @@
using ProjectBulldozer.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectoinGenericObjects<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>
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции на конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns></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,148 @@
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Параметрезированный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectoinGenericObjects<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)
{
// Проверка позиции.
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
// Выброс ошибки, если выход за границы списка
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// Выброс ошибки, если переполнение
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
// Выброс ошибки, если такой объект есть в коллекции
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new NotUniqueObjectException(obj);
}
}
// Вставка в конец набора.
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// Выброс ошибки, если такой объект есть в коллекции
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new NotUniqueObjectException(obj);
}
}
// Выброс ошибки, если переполнение
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
// Выброс ошибки, если выход за границы списка
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
// Вставка по позиции.
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
// Выброс ошибки, если выход за границы списка
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
// Удаление объекта из списка.
T? obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -0,0 +1,200 @@
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.CollectionGenericObjects;
public class MassiveGenericObject<T> : ICollectoinGenericObjects<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 MassiveGenericObject()
{
_collection = Array.Empty<T>();
}
public T? Get(int position)
{
//Проверка позиции
// Выброс ошибки, если выход за границы массива
if (position < 0 || position >= _collection.Length)
{
throw new PositionOutOfCollectionException(position);
}
// Выброс ошибки, если объект пустой
if (position >= _collection.Length && _collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// Выброс ошибки, если такой объект есть в коллекции
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new NotUniqueObjectException(i);
}
}
}
// Вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
// Выброс ошибки, если переполнение
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// Выброс ошибки, если такой объект есть в коллекции
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new NotUniqueObjectException(i);
}
}
}
// Проверка позиции
if ((position < 0) || (position >= Count))
{
return -1;
}
// Выброс ошибки, если переполнение
if (position < 0 || position >= _collection.Length)
{
throw new PositionOutOfCollectionException(position);
}
//Проверка, что элемент массива по этой позиции пустой, если нет, то ищется свободное место после этой
//позиции и идёт вставка туда, если нет после, ищем до
if (_collection[position] == null)
{
//Вставка
_collection[position] = obj;
return position;
}
int temp = position + 1;
while (temp < Count)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
++temp;
}
temp = position - 1;
while (temp >= 0)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
--temp;
}
// Выброс ошибки, если выход за границы массива
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
//Проверка позиции
// Выброс ошибки, если выход за границы массива
if ((position < 0) || (position >= Count))
{
throw new PositionOutOfCollectionException(position);
}
// Выброс ошибки, если объект пустой
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
//Удаление объекта из массива, присвоив элементу массива значение null
T? elem = _collection[position];
_collection[position] = null;
return elem;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}

View File

@ -0,0 +1,244 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
namespace ProjectBulldozer.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningDozer
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<CollectionInfo, ICollectoinGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начианться файл
/// </summary>
private readonly string _collectionKey = "CollectionStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделительдля записи коллекций данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectoinGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
// Проверка, что name не пустой и нет в словаре записи с таким ключом.
if (_storages.ContainsKey(collectionInfo) && name == "")
{
return;
}
// Логика для добавления.
if (collectionType == CollectionType.Massive)
{
_storages[collectionInfo] = new MassiveGenericObject<T>();
}
else
{
_storages[collectionInfo] = new ListGenericObjects<T>();
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
// Логика для удаления коллекции.
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(collectionInfo);
}
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectoinGenericObjects<T>? this[string name]
{
get
{
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
// Логика получения объекта.
if (_storages.ContainsKey(collectionInfo))
{
return _storages[collectionInfo];
}
return null;
}
}
/// <summary>
/// Сохранение информации по бульдозерам в хранилище в файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутсвует коллекция для сохранения!");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder stringBuilder = new();
stringBuilder.Append(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectoinGenericObjects<T>> value in _storages)
{
stringBuilder.Append(Environment.NewLine);
// не сохраняем пустые коллекции.
if (value.Value.Count == 0)
{
continue;
}
stringBuilder.Append(value.Key);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.MaxCount);
stringBuilder.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
stringBuilder.Append(data);
stringBuilder.Append(_separatorItems);
}
}
using FileStream fileStream = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(stringBuilder.ToString());
fileStream.Write(info, 0, info.Length);
}
/// <summary>
/// Загрузка информации по бульдозерам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует!");
}
string bufferTextfromFile = "";
using (FileStream fileStream = new(filename, FileMode.Open))
{
byte[] bytes = new byte[fileStream.Length];
UTF8Encoding temp = new(true);
while (fileStream.Read(bytes, 0, bytes.Length) > 0)
{
bufferTextfromFile += temp.GetString(bytes);
}
}
string[] strs = bufferTextfromFile.Split(new char[] { '\r', '\n'},
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("В файле нет данных!");
}
if (!strs[0].Equals(_collectionKey))
{
throw new Exception("В файле неверные данные!");
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
/* CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);*/
ICollectoinGenericObjects<T>? collectoin = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию!");
collectoin.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningDozer() is T dozer)
{
try
{
if (collectoin.Insert(dozer) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException exception)
{
throw new Exception("Коллекция переполнена!", exception);
}
}
}
_storages.Add(collectionInfo, collectoin);
}
}
private static ICollectoinGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObject<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -0,0 +1,10 @@
using ProjectBulldozer.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer;
public delegate void DozerDelegate(DrawningDozer dozer);

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Drawnings;
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,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Drawnings;
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningBulldozer : DrawningDozer
{
private EntityDozer dozer;
/// <summary>
/// Другой конструктор.
/// </summary>
/// <param name="dozer"></param>
public DrawningBulldozer(EntityDozer? entityDozer) : base(150, 90)
{
if (entityDozer != null)
{
EntityDozer = entityDozer;
}
}
///<summary>
///Конструктор
/// </summary>
/// ///<param name="speed">Скорость</param>
///<param name="weight">Вес</param>
///<param name="bodyColor">Основной цвет</param>
///<param name="additionalColor">Дополнительный цвет</param>
///<param name="blade">Признак наличия отвала</param>
///<param name="caterpillar">Признак наличия гусеницы</param>
public DrawningBulldozer(int speed, double weight, Color bodyColor, Color additionalColor, bool blade, bool caterpillar) : base(150, 90)
{
EntityDozer = new EntityBulldozer(speed, weight, bodyColor, additionalColor, blade, caterpillar);
}
public override void DrawTransport(Graphics g)
{
if (EntityDozer == null || !_startPosX.HasValue || !_startPosY.HasValue || EntityDozer is not EntityBulldozer bulldozer)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyBrush = new SolidBrush(EntityDozer.BodyColor);
Brush additionalBrush = new SolidBrush(bulldozer.AdditionalColor);
//BULDOZER
_startPosX += 0;
_startPosY += 0;
base.DrawTransport(g);
_startPosX -= 0;
_startPosY -= 0;
//caterpillar
if (bulldozer.Caterpillar)
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value, 150, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 150, 15);
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 75, 150, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 75, 150, 15);
}
//blade
if (bulldozer.Blade)
{ //smth like hands?
g.FillRectangle(bodyBrush, _startPosX.Value + 75, _startPosY.Value + 3, 75, 15);
g.DrawRectangle(pen, _startPosX.Value + 75, _startPosY.Value + 3, 75, 15);
g.FillRectangle(bodyBrush, _startPosX.Value + 75, _startPosY.Value + 72, 75, 15);
g.DrawRectangle(pen, _startPosX.Value + 75, _startPosY.Value + 72, 75, 15);
//blade itself
g.FillRectangle(bodyBrush, _startPosX.Value + 125, _startPosY.Value, 25, 90);
g.DrawRectangle(pen, _startPosX.Value + 125, _startPosY.Value, 25, 90);
g.DrawLine(pen, _startPosX.Value + 140, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value + 90);
}
}
}

View File

@ -0,0 +1,285 @@
using ProjectBulldozer.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Drawnings;
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningDozer
{
///<summary>
/// Класс-сущность
/// </summary>
public EntityDozer? EntityDozer { get; protected set; }
///<summary>
///Ширина окна
/// </summary>
private int? _pictureWidth;
///<summary>
///Высота окна
/// </summary>
private int? _pictureHeight;
///<summary>
/// Левая координата прорисовки бульдозера
/// </summary>
protected int? _startPosX;
///<summary>
/// Верхнаяя координата прорисовки бульдозера
/// </summary>
protected int? _startPosY;
private EntityDozer dozer;
///<summary>
///Ширина прорисовки бульдозера
/// </summary>
private readonly int _drawningBulldozerWidth = 150;
///<summary>
///Высота прорисовки бульдозера
/// </summary>
private readonly int _drawningBulldozerHeight = 90;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBulldozerWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningBulldozerHeight;
/// <summary>
/// Пустой конструктор.
/// </summary>
private DrawningDozer()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет(цвет колёс)</param>
public DrawningDozer(int speed, double weight, Color bodyColor) : this()
{
EntityDozer = new EntityDozer(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningBulldozerWidth">Ширина прорисовки бульдозера</param>
/// <param name="drawningBulldozerHeigh">Высота прорисовки бульдозера</param>
protected DrawningDozer (int drawningBulldozerWidth, int drawningBulldozerHeigh) :this()
{
_drawningBulldozerWidth = drawningBulldozerWidth;
_pictureHeight = drawningBulldozerHeigh;
}
/// <summary>
/// Другой конструктор.
/// </summary>
/// <param name="dozer"></param>
public DrawningDozer(EntityDozer? entityDozer)
{
if (entityDozer == null) return;
EntityDozer = entityDozer;
}
///<summary>
///Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
//проверка, что объект "влезает" в размеры поля. Если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена.
if (width < _drawningBulldozerWidth || height < _drawningBulldozerHeight)
{
return false;
}
else
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null || _startPosY != null)
{
if (_startPosX < 0)
{
_startPosX = 0;
}
if (_startPosX + _drawningBulldozerWidth >= _pictureWidth)
{
_startPosX = _pictureWidth - _drawningBulldozerWidth;
}
if (_startPosY < 0)
{
_startPosY = 0;
}
if (_startPosY + _drawningBulldozerHeight >= _pictureHeight)
{
_startPosY = _pictureHeight - _drawningBulldozerHeight;
}
}
}
return true;
}
///<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;
}
//если при установке объекта в эти координаты, он будет выходить за границы формы, то надо изменить координаты,
//чтобы он оставался в этих границах
if (x < 0)
{
_startPosX = 0;
}
else if (x + _drawningBulldozerWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningBulldozerWidth;
}
else
{
_startPosX = x;
}
if (y < 0)
{
_startPosY = 0;
}
else if (y + _drawningBulldozerHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningBulldozerHeight;
}
else
{
_startPosY = y;
}
}
///<summary>
///Изменение направления перемещения
/// </summary>
/// <param name="direction">Направлениие</param>
/// <returns>true - перемещениие выполнено, false - перемещение невозможно</returns>
public virtual bool MoveTransport(DirectionType direction)
{
if (EntityDozer == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
// влево
case DirectionType.Left:
if (_startPosX.Value - EntityDozer.Step > 0)
{
_startPosX -= (int)EntityDozer.Step;
}
return true;
// вверх
case DirectionType.Up:
if (_startPosY.Value - EntityDozer.Step > 0)
{
_startPosY -= (int)EntityDozer.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + EntityDozer.Step + _drawningBulldozerWidth < _pictureWidth)
{
_startPosX += (int)EntityDozer.Step;
}
return true;
// вниз
case DirectionType.Down:
if (_startPosY.Value + EntityDozer.Step + _drawningBulldozerHeight < _pictureHeight)
{
_startPosY += (int)EntityDozer.Step;
}
return true;
default:
return false;
}
}
///<summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityDozer == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyBrush = new SolidBrush(EntityDozer.BodyColor);
Brush wheelstringBuilderrush = new SolidBrush(Color.FromArgb(60, 60, 60));
//BULDOZER
//body
g.FillRectangle(bodyBrush, _startPosX.Value + 10, _startPosY.Value + 15, _drawningBulldozerWidth - 20, _drawningBulldozerHeight - 30);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 15, _drawningBulldozerWidth - 20, _drawningBulldozerHeight - 30);
//wheels
g.FillRectangle(wheelstringBuilderrush, _startPosX.Value, _startPosY.Value + _drawningBulldozerHeight - 15, 50, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + _drawningBulldozerHeight - 15, 50, 15);
g.FillRectangle(wheelstringBuilderrush, _startPosX.Value + _drawningBulldozerWidth - 50, _startPosY.Value + _drawningBulldozerHeight - 15, 50, 15);
g.DrawRectangle(pen, _startPosX.Value + _drawningBulldozerWidth - 50, _startPosY.Value + _drawningBulldozerHeight - 15, 50, 15);
g.FillRectangle(wheelstringBuilderrush, _startPosX.Value, _startPosY.Value, 50, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 50, 15);
g.FillRectangle(wheelstringBuilderrush, _startPosX.Value + _drawningBulldozerWidth - 50, _startPosY.Value, 50, 15);
g.DrawRectangle(pen, _startPosX.Value + _drawningBulldozerWidth - 50, _startPosY.Value, 50, 15);
//strange rectangles
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 25, 3, _drawningBulldozerHeight - 50);
g.DrawRectangle(pen, _startPosX.Value + 13, _startPosY.Value + 25, 20, 4);
g.DrawRectangle(pen, _startPosX.Value + 13, _startPosY.Value + _drawningBulldozerHeight - 29, 20, 4);
g.DrawRectangle(pen, _startPosX.Value + 13, _startPosY.Value + 29, 17, _drawningBulldozerHeight - 58);
//strange circles
g.DrawEllipse(pen, _startPosX.Value + 45, _startPosY.Value + 42, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 45, _startPosY.Value + 30, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 45, _startPosY.Value + 54, 6, 6);
//window
Brush windowBrush = new SolidBrush(Color.FromArgb(170, 170, 215));
g.FillRectangle(windowBrush, _startPosX.Value + 55, _startPosY.Value + 20, _drawningBulldozerWidth - 90, _drawningBulldozerHeight - 40);
g.DrawRectangle(pen, _startPosX.Value + 55, _startPosY.Value + 20, _drawningBulldozerWidth - 90, _drawningBulldozerHeight - 40);
}
}

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningDozerCompareByColor : IComparer<DrawningDozer?>
{
public int Compare(DrawningDozer? x, DrawningDozer? y)
{
// Логика сравения по цвету, скорости, весу
if (x == null || x.EntityDozer == null)
{
return -1;
}
if (y == null || y.EntityDozer == null)
{
return -1;
}
var bodyColorCompare = x.EntityDozer.BodyColor.Name.CompareTo(y.EntityDozer.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
var speedCompare = x.EntityDozer.Speed.CompareTo(y.EntityDozer.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityDozer.Weight.CompareTo(y.EntityDozer.Weight);
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningDozerEqutables : IEqualityComparer<DrawningDozer>
{
public bool Equals(DrawningDozer? x, DrawningDozer? y)
{
if (x == null || x.EntityDozer == null) return false;
if (y == null || y.EntityDozer == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityDozer.Speed != y.EntityDozer.Speed) return false;
if (x.EntityDozer.Weight != y.EntityDozer.Weight) return false;
if (x.EntityDozer.BodyColor != y.EntityDozer.BodyColor) return false;
if (x is DrawningBulldozer && y is DrawningBulldozer)
{
// Логика сравнения доп параметров.
if (((EntityBulldozer)x.EntityDozer).AdditionalColor != ((EntityBulldozer)y.EntityDozer).AdditionalColor)
{
return false;
}
if (((EntityBulldozer)x.EntityDozer).Blade != ((EntityBulldozer)y.EntityDozer).Blade)
{
return false;
}
if (((EntityBulldozer)x.EntityDozer).Caterpillar != ((EntityBulldozer)y.EntityDozer).Caterpillar)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningDozer obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Drawnings;
/// <summary>
/// Расширение для класса EntityDozer
/// </summary>
public static class ExtentionDrawningDozer
{
/// <summary>
/// Разделитель строки для записи информации по объекту.
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки.
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningDozer? CreateDrawningDozer(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityDozer? dozer = EntityBulldozer.CreateEntityBulldozer(strs);
if (dozer != null)
{
return new DrawningBulldozer(dozer);
}
dozer = EntityDozer.CreateEntityDozer(strs);
if (dozer != null)
{
return new DrawningDozer(dozer);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл.
/// </summary>
/// <param name="drawningDozer"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningDozer drawningDozer)
{
string[]? array = drawningDozer?.EntityDozer?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Entities;
/// <summary>
/// Класс-сущность "Бульдозер"
/// </summary>
public class EntityBulldozer : EntityDozer
{
///<summary>
/// Признак (опция) наличие отвала(ковша)
/// </summary>
public bool Blade { get; private set; }
///<summary>
/// Признак (опция) наличие гусеницы
/// </summary>
public bool Caterpillar { get; private set; }
///<summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
///<summary>
///Инициализация полей объекта-класса бульдозера
/// </summary>
///<param name="speed">Скорость</param>
///<param name="weight">Вес</param>
///<param name="bodyColor">Основной цвет</param>
///<param name="additionalColor">Дополнительный цвет</param>
///<param name="blade">Признак наличия отвала</param>
///<param name="caterpillar">Признак наличия гусеницы</param>
public EntityBulldozer(int speed, double weight, Color bodyColor, Color additionalColor, bool blade, bool caterpillar) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Blade = blade;
Caterpillar = caterpillar;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности.
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityBulldozer), Speed.ToString(), Weight.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Blade.ToString(), Caterpillar.ToString() };
}
/// <summary>
/// Создание объекта из массива строк.
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBulldozer? CreateEntityBulldozer(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityBulldozer))
{
return null;
}
return new EntityBulldozer(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,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Entities;
/// <summary>
/// Класс-сущность "Бульдозер"
/// </summary>
public class EntityDozer
{
///<summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
///<summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
///<summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
public void SetBodyColor(Color color)
{
BodyColor = color;
}
///<summary>
/// Шаг перемещения бульдозера
/// </summary>
public double Step => Speed * 100 / Weight;
///<summary>
/// Конструктор
/// </summary>
///<param name="speed">Скорость</param>
///<param name="weight">Вес</param>
///<param name="bodyColor">Основной цвет</param>
public EntityDozer(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности.
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityDozer), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк.
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityDozer? CreateEntityDozer(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityDozer)) return null;
return new EntityDozer(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.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 context) : base(info, context) { }
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Exceptions;
[Serializable]
public class NotUniqueObjectException : ApplicationException
{
public NotUniqueObjectException(object i) : base("В коллекции уже есть такой элемент: " + i) { }
public NotUniqueObjectException() : base() { }
public NotUniqueObjectException(string message) : base(message) { }
public NotUniqueObjectException(string message, Exception exception) : base(message, exception) { }
protected NotUniqueObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.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,39 +0,0 @@
namespace ProjectBulldozer
{
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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

@ -0,0 +1,152 @@
namespace ProjectBulldozer
{
partial class FormBulldozer
{
/// <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()
{
pictureBoxBulldozer = new PictureBox();
buttonRight = new Button();
buttonUp = new Button();
buttonLeft = new Button();
buttonDown = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).BeginInit();
SuspendLayout();
//
// pictureBoxBulldozer
//
pictureBoxBulldozer.Dock = DockStyle.Fill;
pictureBoxBulldozer.Location = new Point(0, 0);
pictureBoxBulldozer.Name = "pictureBoxBulldozer";
pictureBoxBulldozer.Size = new Size(874, 429);
pictureBoxBulldozer.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxBulldozer.TabIndex = 0;
pictureBoxBulldozer.TabStop = false;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.ArrowR;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(832, 387);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 2;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.ArrowU;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(796, 351);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.ArrowL;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(760, 387);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.ArrowD;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(796, 387);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FlatStyle = FlatStyle.System;
comboBoxStrategy.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К левому нижнему краю", "К правому нижнему краю" });
comboBoxStrategy.Location = new Point(620, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(242, 41);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonStrategyStep.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonStrategyStep.Location = new Point(760, 58);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(102, 38);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormBulldozer
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(874, 429);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(pictureBoxBulldozer);
Name = "FormBulldozer";
Text = "FormBulldozer";
((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxBulldozer;
private Button buttonRight;
private Button buttonUp;
private Button buttonLeft;
private Button buttonDown;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.MovementStrategy;
namespace ProjectBulldozer;
/// <summary>
/// Форма работы с объектом "Бульдозер"
/// </summary>
public partial class FormBulldozer : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningDozer? _drawningDozer;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningDozer SetCar
{
set
{
_drawningDozer = value;
_drawningDozer.SetPictureSize(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Конструктор формы
/// </summary>
public FormBulldozer()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки транспорта
/// </summary>
private void Draw()
{
if (_drawningDozer == null)
{
return;
}
Bitmap bmp = new(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningDozer.DrawTransport(gr);
pictureBoxBulldozer.Image = bmp;
}
/*/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningDozer):
_drawningDozer = new DrawningDozer(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(170, 256), random.Next(170, 256), random.Next(30, 140)),
Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120)));
break;
case nameof(DrawningBulldozer):
_drawningDozer = new DrawningBulldozer(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(170, 256), random.Next(170, 256), random.Next(30, 140)),
Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningDozer.SetPictureSize(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
_drawningDozer.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать крутой бульдозер"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateBulldozer_Click(object sender, EventArgs e) =>
CreateObject(nameof(DrawningBulldozer));
/// <summary>
/// Обработка нажатия кнопки "Создать бульдозер"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateDozer_Click(object sender, EventArgs e) =>
CreateObject(nameof(DrawningDozer));
*/
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningDozer == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningDozer.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningDozer.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningDozer.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningDozer.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningDozer == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorderLB(),
2 => new MoveToBorderRB(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableDozer(_drawningDozer), pictureBoxBulldozer.Width,
pictureBoxBulldozer.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

@ -1,17 +1,17 @@
<?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
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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,388 @@
namespace ProjectBulldozer
{
partial class FormBulldozerCollection
{
/// <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();
buttonAddDozer = new Button();
buttonDelBulldozer = new Button();
maskedTextBox = new MaskedTextBox();
buttonGoToCheck = new Button();
buttonRefresh = new Button();
panelStorage = new Panel();
listBoxCollection = new ListBox();
buttonCollectionDel = new Button();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
buttonCreateCompany = new Button();
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(panelStorage);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
groupBoxTools.Location = new Point(1489, 41);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(413, 1114);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddDozer);
panelCompanyTools.Controls.Add(buttonDelBulldozer);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 602);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(406, 512);
panelCompanyTools.TabIndex = 7;
//
// buttonAddDozer
//
buttonAddDozer.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddDozer.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonAddDozer.Location = new Point(13, 14);
buttonAddDozer.Name = "buttonAddDozer";
buttonAddDozer.Size = new Size(383, 66);
buttonAddDozer.TabIndex = 2;
buttonAddDozer.Text = "Добавление бульдозера";
buttonAddDozer.UseVisualStyleBackColor = true;
buttonAddDozer.Click += ButtonAddDozer_Click;
//
// buttonDelBulldozer
//
buttonDelBulldozer.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelBulldozer.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonDelBulldozer.Location = new Point(13, 135);
buttonDelBulldozer.Name = "buttonDelBulldozer";
buttonDelBulldozer.Size = new Size(383, 65);
buttonDelBulldozer.TabIndex = 3;
buttonDelBulldozer.Text = "Удаленить бульдозер";
buttonDelBulldozer.UseVisualStyleBackColor = true;
buttonDelBulldozer.Click += ButtonDelBulldozer_Click;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(13, 87);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(382, 41);
maskedTextBox.TabIndex = 5;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonGoToCheck.Location = new Point(13, 206);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(383, 65);
buttonGoToCheck.TabIndex = 3;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonRefresh.Location = new Point(13, 277);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(383, 65);
buttonRefresh.TabIndex = 3;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// panelStorage
//
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionDel);
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, 37);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(407, 448);
panelStorage.TabIndex = 6;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 33;
listBoxCollection.Location = new Point(13, 209);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(382, 169);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(13, 394);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(383, 47);
buttonCollectionDel.TabIndex = 4;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(13, 144);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(383, 47);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(211, 99);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(129, 37);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(44, 99);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(130, 37);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(13, 48);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(382, 41);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(54, 5);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(263, 33);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(16, 547);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(383, 47);
buttonCreateCompany.TabIndex = 4;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(16, 498);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(382, 41);
comboBoxSelectorCompany.TabIndex = 1;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 41);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1489, 1114);
pictureBox.TabIndex = 4;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
menuStrip.ImageScalingSize = new Size(32, 32);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(7, 2, 0, 2);
menuStrip.Size = new Size(1902, 41);
menuStrip.TabIndex = 5;
menuStrip.Text = "menuStrip";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(93, 37);
fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(369, 44);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(369, 44);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonSortByColor.Location = new Point(12, 435);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(383, 65);
buttonSortByColor.TabIndex = 3;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
buttonSortByType.Location = new Point(12, 364);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(383, 65);
buttonSortByType.TabIndex = 3;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormBulldozerCollection
//
AutoScaleDimensions = new SizeF(15F, 33F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1902, 1155);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
MainMenuStrip = menuStrip;
Name = "FormBulldozerCollection";
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 buttonAddDozer;
private PictureBox pictureBox;
private MaskedTextBox maskedTextBox;
private Button buttonDelBulldozer;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Panel panelStorage;
private Label labelCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Button buttonCollectionAdd;
private ListBox listBoxCollection;
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@ -0,0 +1,492 @@
using Microsoft.Extensions.Logging;
using ProjectBulldozer.CollectionGenericObjects;
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectBulldozer;
/// <summary>
/// Форма работы с компанией и её коллекцией
/// </summary>
public partial class FormBulldozerCollection : Form
{
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningDozer> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBulldozerCollection(ILogger<FormBulldozerCollection> 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="sender"></param>
/// <param name="e"></param>
private void ButtonAddDozer_Click(object sender, EventArgs e)
{
FormBulldozerConfig form = new();
// Передача метода.
form.Show();
form.AddEvent(SetDozer);
}
/// <summary>
/// Добавление бульдозера в коллекцию
/// </summary>
/// <param name="dozer"></param>
private void SetDozer(DrawningDozer? dozer)
{
try
{
if (_company == null || dozer == null)
{
return;
}
if (_company + dozer != -1)
{
MessageBox.Show("Объект добавлен.");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен: " + dozer.GetDataForSave());
}
}
catch (CollectionOverflowException exception)
{
MessageBox.Show(exception.Message);
_logger.LogError("Ошибка: превышено допустимое коллическтво! {Message}", exception);
}
catch (NotUniqueObjectException)
{
MessageBox.Show("Объект уже существует!");
_logger.LogError("Ошибка: объект уже существует {0}", dozer);
}
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningDozer drawningDozer;
switch (type)
{
case nameof(DrawningDozer):
drawningDozer = new DrawningDozer(random.Next(100, 300), random.Next(1000, 3000),
GetBodyColor(random));
break;
case nameof(DrawningBulldozer):
//Вызов диалогового окна для выбора цвета
drawningDozer = new DrawningBulldozer(random.Next(100, 300), random.Next(1000, 3000),
GetBodyColor(random), GetWheelsColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningDozer != -1)
{
MessageBox.Show("Объект добавлен.");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект...");
}
}
/// <summary>
/// Получение цвета корпуса бульдозера
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetBodyColor(Random random)
{
Color color = Color.FromArgb(random.Next(170, 256), random.Next(170, 256), random.Next(30, 140));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Получение цвета гусеницы бульдозера
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetWheelsColor(Random random)
{
Color color = Color.FromArgb(random.Next(30, 120), random.Next(30, 120), random.Next(30, 120));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelBulldozer_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
_logger.LogWarning("Удаление объекта из несуществующей коллекции!");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удалён.");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удалён: " + pos);
}
}
catch (ObjectNotFoundException exception)
{
MessageBox.Show(exception.Message);
_logger.LogWarning("Попытка удалить не найденный объект по позиции: " + pos);
}
catch (PositionOutOfCollectionException)
{
MessageBox.Show("Объект вне коллекции!");
_logger.LogWarning("Попытка удалить объект вне коллекции: " + pos);
}
}
/// <summary>
/// Передача объека в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningDozer? dozer = null;
int counter = 100;
try
{
while (dozer == null)
{
dozer = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (dozer == null)
{
return;
}
FormBulldozer form = new()
{
SetCar = dozer
};
form.ShowDialog();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Прорисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
try
{
pictureBox.Image = _company.Show();
}
catch (PositionOutOfCollectionException) { }
catch (Exception) { }
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
// Логика удаления элемента из коллекции.
// Нужно убедиться, что есть выбранная коллекция
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Коллекция не выбрана!");
return;
}
try
{
// Спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
if (MessageBox.Show("Удалить коллекцию?", "Удаление...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
// Удалить и обновить ListBox
//_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена: " + listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Обновление списка в ListBoxCollection
/// </summary>
private void RefreshListBoxItems()
{
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;
}
ICollectoinGenericObjects<DrawningDozer>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована!");
return;
}
try
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Garage(pictureBox.Width, pictureBox.Height, collection);
break;
}
}
catch (ObjectNotFoundException) { }
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно.", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception exception)
{
MessageBox.Show("Не сохранено!", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", exception.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);
foreach (var collection in _storageCollection.Keys)
{
listBoxCollection.Items.Add(collection);
}
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RefreshListBoxItems();
}
catch (Exception exception)
{
MessageBox.Show("Загрузка не удалась!", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", exception.Message);
}
}
RefreshListBoxItems();
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareDozers(new DrawningDozerCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareDozers(new DrawningDozerCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareDozers(IComparer<DrawningDozer?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -0,0 +1,129 @@
<?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>204, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>447, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,367 @@
namespace ProjectBulldozer
{
partial class FormBulldozerConfig
{
/// <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();
panelBlack = new Panel();
panelOrange = new Panel();
panelSilver = new Panel();
panelRed = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelCadetBlue = new Panel();
panelGold = new Panel();
checkBoxCaterpillar = new CheckBox();
checkBoxBlade = 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();
labelBodyColor = new Label();
labelAdditionalColor = 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(checkBoxCaterpillar);
groupBoxConfig.Controls.Add(checkBoxBlade);
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.Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(851, 261);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelOrange);
groupBoxColors.Controls.Add(panelSilver);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelCadetBlue);
groupBoxColors.Controls.Add(panelGold);
groupBoxColors.Location = new Point(400, 26);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(429, 145);
groupBoxColors.TabIndex = 5;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelBlack
//
panelBlack.AllowDrop = true;
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(324, 89);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(100, 43);
panelBlack.TabIndex = 0;
//
// panelOrange
//
panelOrange.AllowDrop = true;
panelOrange.BackColor = Color.Orange;
panelOrange.Location = new Point(324, 40);
panelOrange.Name = "panelOrange";
panelOrange.Size = new Size(100, 43);
panelOrange.TabIndex = 0;
//
// panelSilver
//
panelSilver.AllowDrop = true;
panelSilver.BackColor = Color.Silver;
panelSilver.Location = new Point(218, 89);
panelSilver.Name = "panelSilver";
panelSilver.Size = new Size(100, 43);
panelSilver.TabIndex = 0;
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(218, 40);
panelRed.Name = "panelRed";
panelRed.Size = new Size(100, 43);
panelRed.TabIndex = 0;
//
// panelWhite
//
panelWhite.AllowDrop = true;
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(112, 89);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(100, 43);
panelWhite.TabIndex = 0;
//
// panelYellow
//
panelYellow.AllowDrop = true;
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(112, 40);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(100, 43);
panelYellow.TabIndex = 0;
//
// panelCadetBlue
//
panelCadetBlue.AllowDrop = true;
panelCadetBlue.BackColor = Color.CadetBlue;
panelCadetBlue.Location = new Point(6, 89);
panelCadetBlue.Name = "panelCadetBlue";
panelCadetBlue.Size = new Size(100, 43);
panelCadetBlue.TabIndex = 0;
//
// panelGold
//
panelGold.AllowDrop = true;
panelGold.BackColor = Color.Gold;
panelGold.Location = new Point(6, 40);
panelGold.Name = "panelGold";
panelGold.Size = new Size(100, 43);
panelGold.TabIndex = 0;
panelGold.MouseDown += LabelObject_MouseDown;
//
// checkBoxCaterpillar
//
checkBoxCaterpillar.AutoSize = true;
checkBoxCaterpillar.Location = new Point(12, 192);
checkBoxCaterpillar.Name = "checkBoxCaterpillar";
checkBoxCaterpillar.Size = new Size(366, 37);
checkBoxCaterpillar.TabIndex = 4;
checkBoxCaterpillar.Text = "Признак наличия гусеницы";
checkBoxCaterpillar.UseVisualStyleBackColor = true;
//
// checkBoxBlade
//
checkBoxBlade.AutoSize = true;
checkBoxBlade.Location = new Point(12, 147);
checkBoxBlade.Name = "checkBoxBlade";
checkBoxBlade.Size = new Size(332, 37);
checkBoxBlade.TabIndex = 4;
checkBoxBlade.Text = "Признак наличия отвала";
checkBoxBlade.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(142, 87);
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(178, 41);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 89);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(62, 33);
labelWeight.TabIndex = 2;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(142, 35);
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(178, 41);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 37);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(124, 33);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(629, 180);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(200, 70);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(400, 180);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(200, 70);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Поростой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(12, 16);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(200, 150);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(869, 207);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(135, 46);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(1028, 207);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(135, 46);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(859, 19);
panelObject.Name = "panelObject";
panelObject.Size = new Size(317, 181);
panelObject.TabIndex = 3;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(218, 16);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(93, 70);
labelBodyColor.TabIndex = 6;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(218, 96);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(93, 70);
labelAdditionalColor.TabIndex = 6;
labelAdditionalColor.Text = "Цвет колёс";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// FormBulldozerConfig
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1182, 261);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormBulldozerConfig";
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 numericUpDownSpeed;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private CheckBox checkBoxBlade;
private CheckBox checkBoxCaterpillar;
private GroupBox groupBoxColors;
private Panel panelGold;
private Panel panelOrange;
private Panel panelRed;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelSilver;
private Panel panelWhite;
private Panel panelCadetBlue;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelBodyColor;
private Label labelAdditionalColor;
}
}

View File

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer;
/// <summary>
/// Форма конигурации объекта
/// </summary>
public partial class FormBulldozerConfig : Form
{
/// <summary>
/// Объект прорисовка бульдозера
/// </summary>
private DrawningDozer? _dozer /*= null*/;
/// <summary>
/// Событие для передачи объекта
/// </summary>
public event Action<DrawningDozer>? _dozerDelegate;
//private event Action<> =
/// <summary>
/// Конструктор
/// </summary>
public FormBulldozerConfig()
{
InitializeComponent();
panelGold.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelRed.MouseDown += Panel_MouseDown;
panelOrange.MouseDown += Panel_MouseDown;
panelCadetBlue.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelSilver.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
// buttonCancel.Click привязка анонимного метода через lambda с закрытием формы.
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="dozerDelegate"></param>
public void AddEvent(Action<DrawningDozer>? dozerDelegate)
{
_dozerDelegate += dozerDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_dozer?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_dozer?.SetPosition(25, 30);
_dozer?.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":
_dozer = new DrawningDozer((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_dozer = new DrawningBulldozer((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value,
Color.White, Color.Black, checkBoxBlade.Checked, checkBoxCaterpillar.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаём информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
// Отправка цвета в Drag&Drop
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
// Реализация логики смены цветов: основного и дополнительного (для смены объекта)
/// <summary>
/// Передача основного цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Закраска основным цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_dozer == null) return;
_dozer.EntityDozer?.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
/// <summary>
/// Передача дополнительного цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_dozer is DrawningBulldozer)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
/// <summary>
/// Расскраска дополнительным цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_dozer == null) return;
if (_dozer?.EntityDozer is EntityBulldozer entityBulldozer)
{
entityBulldozer.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_dozer != null)
{
_dozerDelegate?.Invoke(_dozer);
Close();
}
}
}

View File

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

View File

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _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>
/// <returns></returns>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_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 IsTargetDestinaion();
/// <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,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <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,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
public class MoveToBorderLB : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 && objParams.BottomBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.LeftBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveLeft();
}
int diffY = objParams.BottomBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
public class MoveToBorderRB : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && objParams.LeftBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = objParams.BottomBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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,66 @@
using ProjectBulldozer.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningDozer
/// </summary>
public class MoveableDozer : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningDozer или его наследника
/// </summary>
private readonly DrawningDozer? _dozer = null;
/// <summary>
/// Констректор
/// </summary>
/// <param name="dozer">Объект класса DrawningDozer</param>
public MoveableDozer(DrawningDozer dozer)
{
_dozer = dozer;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_dozer == null || _dozer.EntityDozer == null ||
!_dozer.GetPosX.HasValue || !_dozer.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_dozer.GetPosX.Value, _dozer.GetPosY.Value,
_dozer.GetWidth, _dozer.GetHeight);
}
}
public int GetStep => (int)(_dozer?.EntityDozer?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_dozer == null || _dozer.EntityDozer == null)
{
return false;
}
return _dozer.MoveTransport(GetDirectionType(direction));
}
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,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.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,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
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 BottomBorder => _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,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
namespace ProjectBulldozer
{
internal static class Program
@ -10,8 +15,27 @@ namespace ProjectBulldozer
{
// 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<FormBulldozerCollection>());
}
/// <summary>
/// Êîíôèóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBulldozerCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,4 +8,32 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</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="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CustomToolNamespace> </CustomToolNamespace>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectBulldozer.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("ProjectBulldozer.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 ArrowD {
get {
object obj = ResourceManager.GetObject("ArrowD", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ArrowL {
get {
object obj = ResourceManager.GetObject("ArrowL", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ArrowR {
get {
object obj = ResourceManager.GetObject("ArrowR", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ArrowU {
get {
object obj = ResourceManager.GetObject("ArrowU", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?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="ArrowD" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowD.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ArrowL" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowL.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ArrowR" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowR.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ArrowU" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowU.png;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: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>