10 Commits

46 changed files with 4127 additions and 80 deletions

View File

@@ -0,0 +1,12 @@

using ProjectDoubleDeckerBus.Drawnings;
namespace ProjectDoubleDeckerBus;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="bus"></param>
public delegate void BusDelegate(DrawningBus bus);

View File

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

View File

@@ -0,0 +1,76 @@
using ProjectDoubleDeckerBus.Drawnings;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
public class BusSharingServies : AbstractCompany
{
public BusSharingServies(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBus> collection) : base(picWidth, picHeight, collection)
{
}
// Отрисовка сетки фона
protected override void DrawBackgound(Graphics g)
{
// Определение количества ячеек по горизонтали и вертикали
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
// Создание пера чёрного цвета толщиной 1 пиксель
Pen pen = new(Color.Black, 1);
// Цикл отрисовки линий сетки
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
// Горизонтальная линия внутри ячейки
g.DrawLine(pen, i * _placeSizeWidth + 5, j * _placeSizeHeight, i * _placeSizeWidth + 5 + _placeSizeWidth - 107, j * _placeSizeHeight);
// Вертикальная линия от верхней до нижней границы ячейки
g.DrawLine(pen, i * _placeSizeWidth + 5, j * _placeSizeHeight, i * _placeSizeWidth + 5, j * _placeSizeHeight - _placeSizeHeight);
}
}
}
// Установка позиций объектов на сетке
protected override void SetObjectsPosition()
{
// Расчёт количества ячеек по ширине и высоте
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int boatWidth = 0;
int boatHeight = 0;
// Проход по всем объектам в коллекции
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
{
// Установка размеров области отображения
_collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
// Установка позиции объекта в ячейке с небольшим смещением
_collection.Get(i)?.SetPosition(_placeSizeWidth * boatWidth + 8, boatHeight * _placeSizeHeight + 13);
}
// Переход к следующей ячейке
if (boatWidth < width - 1)
boatWidth++;
else
{
boatWidth = 0;
boatHeight++;
}
// Выход, если превышено количество строк
if (boatHeight > height)
{
return;
}
}
}
}

View File

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

View File

@@ -0,0 +1,64 @@
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary>
/// Интерфейс опмсания действия для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добовляемый объект</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась </returns>
bool Insert(T obj);
/// <summary>
/// Добавление объекта на конкретную позицию
/// </summary>
/// <param name="obj">Добовляемый объект</param>
/// <param name="position">Добовляемый объект</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась </returns>
bool Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошла успешно, false - удаление не удалась </returns>
bool 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();
}

View File

@@ -0,0 +1,99 @@
using ProjectDoubleDeckerBus.Exceptions;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = 14;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
// Проверяем, что позиция в допустимых границах коллекции
if (!(position >= 0 && position < _collection.Count)) throw new PositionOutOfCollectionException(position);
// Проверяем, что в данной позиции не хранится null (если допустимы nullable объект
if (_collection[position] == null) throw new ObjectNotFoundException(position);
// Возвращаем объект
return _collection[position];
}
public bool Insert(T obj)
{
// Проверяем, что коллекция ещё не достигла максимального размера
if (_collection.Count >= _maxCount) throw new CollectionOverflowException(_maxCount);
// Добавляем объект в конец
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position)
{
// Проверяем переполнение коллекции
if (_collection.Count >= _maxCount) throw new CollectionOverflowException(_maxCount);
// Проверяем, что позиция корректна (от 0 до Count - 1)
if (!(position >= 0 && position < _collection.Count)) throw new PositionOutOfCollectionException(position);
// Вставляем объект по указанной позиции
_collection.Insert(position, obj);
return true;
}
public bool Remove(int position)
{
// Проверяем, что позиция находится в пределах коллекции
if (!(position >= 0 && position < _collection.Count)) throw new PositionOutOfCollectionException(position);
// Удаляем объект по указанной позиции
_collection.RemoveAt(position);
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -0,0 +1,152 @@
using ProjectDoubleDeckerBus.Exceptions;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => 14;
public int MaxCount
{
get => _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;
private bool checkposition(int pos) => pos >= 0 && pos < Count;
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
//Проверка на то , можно ли вставить объект в позицию
private bool InsertCheck(T obj, int pos)
{
if (_collection[pos] == null)
{
_collection[pos] = obj;
return true;
}
return false;
}
// Получение элемента по указанной позиции
public T? Get(int position)
{
// Проходим по всей коллекции
for (int i = 0; i < _collection.Length; i++)
{
// Если текущий индекс совпадает с запрошенной позицией
if (i == position)
{
// Возвращаем элемент из этой позиции
return _collection[position];
}
}
// Если позиция не найдена (на практике сюда попасть сложно при корректных входных данных)
return default;
}
// Вставка элемента на первое доступное свободное место
public bool Insert(T obj)
{
// Проходим по всей коллекции
for (int i = 0; i < Count; i++)
{
// Если найдено свободное место (null)
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
// Если нет свободного места, выбрасываем исключение
throw new CollectionOverflowException(Count);
}
// Вставка элемента в указанную позицию, либо в ближайшую свободную
public bool Insert(T obj, int position)
{
// Проверяем валидность позиции
if (!checkposition(position)) throw new PositionOutOfCollectionException(position);
// Если в указанной позиции свободно — вставляем
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
}
// Ищем ближайшее свободное место после указанной позиции
for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
// Если не нашли — ищем в начале до позиции
for (int i = 0; i < position; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
// Если не нашли вообще — коллекция переполнена
throw new CollectionOverflowException(Count);
}
// Удаление элемента по указанной позиции
public bool Remove(int position)
{
// Проверяем валидность позиции
if (!checkposition(position)) throw new PositionOutOfCollectionException(position);
// Проверяем наличие объекта
if (_collection[position] == null) throw new ObjectNotFoundException(position);
// Удаляем (обнуляем)
_collection[position] = null;
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -0,0 +1,228 @@
using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Exceptions;
using System.Text;
using Serilog;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningBus
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// Проверка: если имя null или уже существует в словаре — ничего не делаем
if (name == null || _storages.ContainsKey(name))
{ return; }
// В зависимости от типа коллекции, создаётся соответствующий объект и добавляется в словарь
switch (collectionType)
{
case CollectionType.None:
// Тип None — ничего не делаем
return;
case CollectionType.Massive:
// Добавление массива в качестве коллекции
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
// Добавление списка в качестве коллекции
_storages[name] = new ListGenericObjects<T>();
return;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// Удаление коллекции, если она существует
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
//Получения объекта
if (name == null || !_storages.ContainsKey(name))
{ return null; }
return _storages[name];
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0) throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
if (File.Exists(filename))
{
File.Delete(filename);
}
StreamWriter writer = new StreamWriter(filename);
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<String, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new StringBuilder();
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data)) continue;
sb.Append(data);
sb.Append(_separatorItems);
}
writer.WriteLine(sb.ToString());
}
writer.Close();
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (FileStream fs = new(filename, FileMode.Open))
{
using StreamReader streamReader = new StreamReader(fs);
string firstString = streamReader.ReadLine();
if (firstString == null || firstString.Length == 0)
{
throw new ArgumentException("В файле нет данных");
}
if (!firstString.Equals(_collectionKey))
{
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
while (!streamReader.EndOfStream)
{
string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
if (record.Length != 4)
{
continue;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ;
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingBus() is T loko)
{
try
{
if (!collection.Insert(loko))
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException e)
{
throw new CollectionOverflowException("Коллекция переполнена", e);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -0,0 +1,29 @@
namespace ProjectDoubleDeckerBus.Drawnings;
/// <summary>
/// Напрваление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@@ -0,0 +1,261 @@
using ProjectDoubleDeckerBus.Entities;
namespace ProjectDoubleDeckerBus.Drawnings;
public class DrawningBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; }
private EntityBus bus;
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки двухэтажного автобуса
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки двухэтажного автобуса
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина отрисовки автобуса
/// </summary>
private readonly int _drawningBusWidth = 110;
/// <summary>
/// Высота отрисовки автобуса
/// </summary>
private readonly int _drawningBusHeight = 70;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBusWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningBusHeight;
/// <summary>
/// Пустой Конструктор
/// </summary>
private DrawningBus()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет</param>
public DrawningBus (int speed, double weight, Color bodyColor) : this()
{
EntityBus = new EntityBus(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningBusWidth">Ширина отрисовки автобуса</param>
/// <param name="drawningBusHeight">Высота отрисовки автобуса</param>
protected DrawningBus(int drawningBusWidth, int drawningBusHeight) : this()
{
_drawningBusWidth = drawningBusWidth;
_pictureHeight = drawningBusHeight;
}
public DrawningBus(EntityBus bus)
{
EntityBus = bus;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true границы заданы, false проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if (_drawningBusWidth < width && _drawningBusHeight < height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x > 0 && y > 0 && x + _drawningBusWidth < _pictureWidth
&& y + _drawningBusHeight < _pictureHeight)
{
_startPosX = x;
_startPosY = y;
}
else
{
Random rnd = new();
_startPosX = rnd.Next(0, _pictureWidth.Value -
_drawningBusWidth);
_startPosY = rnd.Next(0, _pictureHeight.Value -
_drawningBusHeight);
}
}
public bool MoveTransport(DirectionType direction)
{
if (EntityBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//Влево
case DirectionType.Left:
if (_startPosX.Value - EntityBus.Step > 0)
{
_startPosX -= (int)EntityBus.Step;
}
return true;
//Вверх
case DirectionType.Up:
if (_startPosY.Value - EntityBus.Step > 0)
{
_startPosY -= (int)EntityBus.Step;
}
return true;
//Вправо
case DirectionType.Right:
if (_startPosX.Value + EntityBus.Step < _pictureWidth - 110)
{
_startPosX += (int)EntityBus.Step;
}
return true;
//Вниз
case DirectionType.Down:
if (_startPosY.Value + EntityBus.Step < _pictureHeight - 70)
{
_startPosY += (int)EntityBus.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush brBlack = new SolidBrush(Color.Black);
Brush brGray = new SolidBrush(Color.Gray);
Brush brDarkGray = new SolidBrush(Color.DarkGray);
Brush brLightBlue = new SolidBrush(Color.LightBlue);
// Границы первого этажа двухэтажного автобуса с черной обводкой
Brush brBodyColor = new SolidBrush(EntityBus.BodyColor);
g.FillRectangle(brBodyColor, _startPosX.Value, _startPosY.Value + 30, 100, 30);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 30, 100, 30);
// Дверь с черной обводкой
g.FillRectangle(brDarkGray, _startPosX.Value + 30, _startPosY.Value + 40, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value + 40, 10, 20);
// Колеса с черной обводкой
g.DrawEllipse(pen, _startPosX.Value + 7, _startPosY.Value + 55, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 77, _startPosY.Value + 55, 10, 10);
g.FillEllipse(brDarkGray, _startPosX.Value + 7, _startPosY.Value + 55, 10, 10);
g.FillEllipse(brDarkGray, _startPosX.Value + 77, _startPosY.Value + 55, 10, 10);
// Окна с черной обводкой
g.FillEllipse(brLightBlue, _startPosX.Value + 3, _startPosY.Value + 35, 10, 15);
g.DrawEllipse(pen, _startPosX.Value + 3, _startPosY.Value + 35, 10, 15);
g.FillEllipse(brLightBlue, _startPosX.Value + 17, _startPosY.Value + 35, 10, 15);
g.DrawEllipse(pen, _startPosX.Value + 17, _startPosY.Value + 35, 10, 15);
g.FillEllipse(brLightBlue, _startPosX.Value + 43, _startPosY.Value + 35, 10, 15);
g.DrawEllipse(pen, _startPosX.Value + 43, _startPosY.Value + 35, 10, 15);
g.FillEllipse(brLightBlue, _startPosX.Value + 57, _startPosY.Value + 35, 10, 15);
g.DrawEllipse(pen, _startPosX.Value + 57, _startPosY.Value + 35, 10, 15);
g.FillEllipse(brLightBlue, _startPosX.Value + 72, _startPosY.Value + 35, 10, 15);
g.DrawEllipse(pen, _startPosX.Value + 72, _startPosY.Value + 35, 10, 15);
g.FillEllipse(brLightBlue, _startPosX.Value + 87, _startPosY.Value + 35, 10, 15);
g.DrawEllipse(pen, _startPosX.Value + 87, _startPosY.Value + 35, 10, 15);
}
}

View File

@@ -0,0 +1,116 @@
using ProjectDoubleDeckerBus.Entities;
namespace ProjectDoubleDeckerBus.Drawnings;
/// <summary>
/// Класс,отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningDoubleDeckerBus : DrawningBus
{
public DrawningDoubleDeckerBus(EntityBus bus) : base(bus)
{
EntityBus = bus;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет</param>
/// <param name="additionalColor">Доп цвет</param>
/// <param name="secondFloor">Второй этаж</param>
/// <param name="ladder">Лестница на второй этаж</param>
/// <param name="section">Раздел для багажа</param>
public DrawningDoubleDeckerBus(int speed, double weight, Color bodyColor, Color additionalColor,bool secondFloor, bool ladder, bool section) : base(110, 70)
{
EntityBus = new EntityDoubleDeckerBus(speed, weight, bodyColor, additionalColor, secondFloor, ladder, section);
}
public override void DrawTransport(Graphics g)
{
if (EntityBus == null || EntityBus is not EntityDoubleDeckerBus doubleDeckerBus || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush brBodyColor = new SolidBrush(doubleDeckerBus.BodyColor);
Brush brAdditionaColor = new SolidBrush(doubleDeckerBus.AdditionalColor);
Brush brBlue = new SolidBrush(Color.Blue);
Brush brBlack = new SolidBrush(Color.Black);
Brush brGray = new SolidBrush(Color.Gray);
Brush brDarkGray = new SolidBrush(Color.DarkGray);
// второй этаж
if (doubleDeckerBus.SecondFloor)
{
// Границы второго этажа автобуса с черной обводкой
g.FillRectangle(brAdditionaColor, _startPosX.Value, _startPosY.Value, 100, 30);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 100, 30);
// Окна второго этажа
g.FillRectangle(new SolidBrush(Color.LightBlue), _startPosX.Value, _startPosY.Value + 7, 100, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 100, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 15, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 30, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 40, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 55, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 69, 16);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 7, 84, 16);
}
base.DrawTransport(g);
// Лестница на второй этаж
if (doubleDeckerBus.Ladder)
{
// Добавление лестницы только на двухэтажный автобус
if (doubleDeckerBus.SecondFloor == true)
{
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 55, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 50, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 45, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 40, 5, 5);
}
}
// Раздел для багажа
if (doubleDeckerBus.Section)
{
// Добавление раздела для багажа только на двухэтажный автобус
if (doubleDeckerBus.SecondFloor == true)
{
g.FillRectangle(brAdditionaColor, _startPosX.Value + 45, _startPosY.Value + 54, 27, 6);
g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 54, 27, 6);
g.FillRectangle(brAdditionaColor, _startPosX.Value + 48, _startPosY.Value + 56, 21, 2);
g.DrawRectangle(pen, _startPosX.Value + 48, _startPosY.Value + 56, 21, 2);
}
}
}
}

View File

@@ -0,0 +1,53 @@

using ProjectDoubleDeckerBus.Entities;
namespace ProjectDoubleDeckerBus.Drawnings;
public static class ExtentionDrawningBus
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawingBus(this string info)
{
string[] str = info.Split(_separatorForObject);
EntityBus? bus = EntityDoubleDeckerBus.CreateEntityDoubleDeckerBus(str);
if (bus != null)
{
return new DrawningDoubleDeckerBus(bus);
}
bus = EntityBus.CreateEntityBus(str);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -0,0 +1,79 @@
namespace ProjectDoubleDeckerBus.Entities;
/// <summary>
/// Класс-сущность "Автобус"
/// </summary>
public class EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Установка основного цвета автобуса
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color bodyColor)
{
BodyColor = bodyColor;
}
/// <summary>
/// Шаг перемещения автобуса
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет</param>
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
//TODO Прописать метод
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return [nameof(EntityBus), Speed.ToString(), Weight.ToString(), BodyColor.Name];
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBus? CreateEntityBus(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityBus))
{
return null;
}
return new EntityBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -0,0 +1,78 @@
using System.Net.NetworkInformation;
namespace ProjectDoubleDeckerBus.Entities;
/// <summary>
/// Двухэтажный автобус
/// </summary>
public class EntityDoubleDeckerBus : EntityBus
{
/// <summary>
/// Доп цвет
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Второй этаж
/// </summary>
public bool SecondFloor { get; private set; }
/// <summary>
/// Лестница на второй этаж
/// </summary>
public bool Ladder { get; private set; }
/// <summary>
/// Раздел для багажа
/// </summary>
public bool Section { get; private set; }
/// <summary>
/// Установка дополнительно цвета автобуса
/// </summary>
/// <param name="additionalColor"></param>
public void SetAdditionalColor(Color additionalColor)
{
AdditionalColor = additionalColor;
}
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет</param>
/// <param name="additionalColor">Доп цвет</param>
/// <param name="secondFloor">Второй этаж</param>
/// <param name="ladder">Лестница на второй этаж</param>
/// <param name="section">Раздел для багажа</param>
public EntityDoubleDeckerBus (int speed, double weight, Color bodyColor, Color additionalColor,
bool secondFloor, bool ladder, bool section) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
SecondFloor = secondFloor;
Ladder = ladder;
Section = section;
}
public override string[] GetStringRepresentation()
{
return new string[] { nameof(EntityDoubleDeckerBus), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, SecondFloor.ToString(), Ladder.ToString(), Section.ToString() };
}
public static EntityDoubleDeckerBus? CreateEntityDoubleDeckerBus(string[] str)
{
if (str.Length == 0 || str[0] != nameof(EntityDoubleDeckerBus)) return null;
return new EntityDoubleDeckerBus(
Convert.ToInt32(str[1]),
Convert.ToDouble(str[2]),
Color.FromName(str[3]),
Color.FromName(str[4]),
Convert.ToBoolean(str[5]),
Convert.ToBoolean(str[6]),
Convert.ToBoolean(str[7])
);
}
}

View File

@@ -0,0 +1,21 @@

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

View File

@@ -0,0 +1,19 @@

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

View File

@@ -0,0 +1,19 @@

using System.Runtime.Serialization;
namespace ProjectDoubleDeckerBus.Exceptions;
[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 ProjectDoubleDeckerBus
{
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 ProjectDoubleDeckerBus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@@ -0,0 +1,345 @@
namespace ProjectDoubleDeckerBus;
partial class FormBusCollection
{
/// <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();
buttonAddBus = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheck = new Button();
buttonRemoveBus = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(608, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(173, 604);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveBus);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 310);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(167, 291);
panelCompanyTools.TabIndex = 9;
//
// buttonAddBus
//
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBus.Location = new Point(3, 10);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(161, 44);
buttonAddBus.TabIndex = 1;
buttonAddBus.Text = "Добавление автобуса";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 239);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(161, 44);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(5, 110);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(153, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 189);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(161, 44);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveBus
//
buttonRemoveBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveBus.Location = new Point(3, 139);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(161, 44);
buttonRemoveBus.TabIndex = 4;
buttonRemoveBus.Text = "Удалить автобус";
buttonRemoveBus.UseVisualStyleBackColor = true;
buttonRemoveBus.Click += ButtonRemoveBus_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 284);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(161, 23);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(167, 238);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 210);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(161, 23);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 110);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(161, 94);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 81);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(161, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(98, 56);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(3, 56);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 27);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(161, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(20, 9);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 258);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(161, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(608, 604);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(781, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(173, 22);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(173, 22);
loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(781, 628);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBusCollection";
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 Button buttonAddBus;
private ComboBox comboBoxSelectorCompany;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRemoveBus;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Panel panelStorage;
private Label labelCollectionName;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}

View File

@@ -0,0 +1,334 @@
using Microsoft.Extensions.Logging;
using ProjectDoubleDeckerBus.CollectionGenericObjects;
using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Exceptions;
using System.Windows.Forms;
namespace ProjectDoubleDeckerBus;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormBusCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawningBus> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Логгер
/// </summary>
public FormBusCollection(ILogger<FormBusCollection> logger)
{
InitializeComponent();
_storageCollection = new();
panelCompanyTools.Enabled = false;
_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 ButtonAddBus_Click(object sender, EventArgs e)
{
FormBusConfig form = new();
form.AddEvent(SetBus);
form.Show();
}
/// <summary>
/// Добавление автобуса в коллекцию
/// </summary>
/// <param name="bus"></param>
private void SetBus(DrawningBus bus)
{
if (_company == null)
{
MessageBox.Show("_company == null");
return;
}
if (bus == null)
{
MessageBox.Show("bus == null");
return;
}
try
{
bool addingObject = (_company + bus);
MessageBox.Show("объект добавлен");
_logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
catch (Exception e)
{
_logger.LogError($"Не удалось добавить объект: {e.Message}");
MessageBox.Show(e.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveBus_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
Object decrementObject = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален по позиции {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
_logger.LogError($"Удаление объекта в позиции {pos} ");
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningBus? bus = null;
int counter = 100;
while (bus == null)
{
bus = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (bus == null)
{
return;
}
FormDoubleDeckerBus form = new()
{
SetBus = bus
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не заполненная коллекция");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RefreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItems.Count == 0)
{
MessageBox.Show("Нет выбранных элементов");
_logger.LogWarning("Удаление невыбранной коллекции");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Подтвердите удаление коллекции" + listBoxCollection.SelectedItem?.ToString(), "", MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString());
_logger.LogInformation($"Удалена коллекция: {name}");
RefreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании c невыбранной коллекции");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
ICollectionGenericObjects<DrawningBus>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new BusSharingServies(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обрвботка нажатие "Cохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатие "Загрузить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RefreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

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>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,368 @@
namespace ProjectDoubleDeckerBus
{
partial class FormBusConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelYellow = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxSection = new CheckBox();
checkBoxLadder = new CheckBox();
checkBoxSecondFloor = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxSection);
groupBoxConfig.Controls.Add(checkBoxLadder);
groupBoxConfig.Controls.Add(checkBoxSecondFloor);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(433, 198);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(235, 17);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(147, 89);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(111, 52);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(29, 30);
panelPurple.TabIndex = 13;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(76, 52);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(29, 30);
panelBlack.TabIndex = 12;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(111, 16);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(29, 30);
panelYellow.TabIndex = 3;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(41, 52);
panelGray.Name = "panelGray";
panelGray.Size = new Size(29, 30);
panelGray.TabIndex = 11;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(76, 16);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(29, 30);
panelBlue.TabIndex = 2;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(6, 52);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(29, 30);
panelWhite.TabIndex = 10;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(41, 16);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(29, 30);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 16);
panelRed.Name = "panelRed";
panelRed.Size = new Size(29, 30);
panelRed.TabIndex = 0;
//
// checkBoxSection
//
checkBoxSection.AutoSize = true;
checkBoxSection.Location = new Point(12, 157);
checkBoxSection.Name = "checkBoxSection";
checkBoxSection.Size = new Size(127, 19);
checkBoxSection.TabIndex = 8;
checkBoxSection.Text = "Раздел для багажа";
checkBoxSection.UseVisualStyleBackColor = true;
//
// checkBoxLadder
//
checkBoxLadder.AutoSize = true;
checkBoxLadder.Location = new Point(12, 122);
checkBoxLadder.Name = "checkBoxLadder";
checkBoxLadder.Size = new Size(165, 19);
checkBoxLadder.TabIndex = 7;
checkBoxLadder.Text = "Лестница на второй этаж";
checkBoxLadder.UseVisualStyleBackColor = true;
//
// checkBoxSecondFloor
//
checkBoxSecondFloor.AutoSize = true;
checkBoxSecondFloor.Location = new Point(12, 87);
checkBoxSecondFloor.Name = "checkBoxSecondFloor";
checkBoxSecondFloor.Size = new Size(98, 19);
checkBoxSecondFloor.TabIndex = 6;
checkBoxSecondFloor.Text = "Второй этаж ";
checkBoxSecondFloor.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(80, 46);
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(97, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 48);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(80, 17);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(97, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 19);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(327, 163);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(100, 29);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(221, 163);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 29);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(15, 45);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(151, 87);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(449, 163);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(555, 163);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 29);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(451, 9);
panelObject.Name = "panelObject";
panelObject.Size = new Size(179, 148);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(104, 10);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(58, 29);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(15, 10);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(58, 29);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormBusConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(642, 198);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormBusConfig";
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 labelSimpleObject;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private Label labelModifiedObject;
private CheckBox checkBoxSecondFloor;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxLadder;
private CheckBox checkBoxSection;
private GroupBox groupBoxColors;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Panel panelYellow;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,237 @@
using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Entities;
using System;
namespace ProjectDoubleDeckerBus;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormBusConfig : Form
{
/// <summary>
/// Объект - прорисовка автобуса
/// </summary>
private DrawningBus? _bus;
/// <summary>
/// Событие дял передачи объекта
/// </summary>
private event BusDelegate? BusDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormBusConfig()
{
InitializeComponent();
labelBodyColor.AllowDrop = true;
labelAdditionalColor.AllowDrop = true;
buttonCancel.Click += (sender, e) => Close();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="busDelegate"></param>
public void AddEvent(BusDelegate busDelegate)
{
BusDelegate += busDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_bus?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_bus?.SetPosition(15, 15);
_bus?.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":
_bus = new DrawningBus((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_bus = new DrawningDoubleDeckerBus((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxSecondFloor.Checked, checkBoxLadder.Checked, checkBoxSection.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатие на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
// Обработчик события MouseDown для панели
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
// Преобразуем sender к типу Control и проверяем, что он не равен null
// Затем инициируем операцию DragDrop, передавая в качестве данных цвет фона (BackColor)
// Эффекты: разрешено как копирование, так и перемещение
// Используем цвет фона элемента как переносимые данные
// Разрешаем перемещение и копирование
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor!, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
// Обработчик события DragEnter для labelBodyColor
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
// Проверяем, содержит ли переносимые данные объект типа Color
if (e.Data != null && e.Data.GetDataPresent(typeof(Color)))
// Разрешаем копирование
e.Effect = DragDropEffects.Copy;
else
// Иначе запрещаем перетаскивание
e.Effect = DragDropEffects.None;
}
// Обработчик события DragDrop для labelBodyColor
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
// Проверяем, что объект _bus и отправитель события не равны null
if (_bus == null || sender == null)
{
return;
}
// Пытаемся получить объект типа Color из данных перетаскивания
if (!(e.Data?.GetData(typeof(Color)) is Color color))
{
return;
}
// Приводим sender к типу Label
Label label = (Label)sender;
// В зависимости от имени метки устанавливаем соответствующий цвет
switch (label.Name)
{
case "labelBodyColor":
// Устанавливаем основной цвет
_bus.EntityBus?.SetBodyColor(color);
break;
case "labelAdditionalColor":
// Устанавливаем дополнительный цвет
(_bus.EntityBus as EntityDoubleDeckerBus)?.SetAdditionalColor(color);
break;
}
// Перерисовываем объект
DrawObject();
}
// Обработчик события DragEnter для labelAdditionalColor
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
// Проверяем, что _bus не равен null и является двухэтажным автобусом
if (_bus == null || !(_bus is DrawningDoubleDeckerBus))
{
// Запрещаем перетаскивание
e.Effect = DragDropEffects.None;
return;
}
// Если переносимые данные содержат цвет, разрешаем копирование
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
// Обработчик события DragDrop для labelAdditionalColor
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
// Проверяем, что _bus является объектом DrawningDoubleDeckerBus
if (!(_bus is DrawningDoubleDeckerBus drawingBus))
{
return;
}
// Получаем EntityDoubleDeckerBus и цвет из данных
if (drawingBus.EntityBus is EntityDoubleDeckerBus sailboat &&
e.Data.GetData(typeof(Color)) is Color color)
{
// Устанавливаем дополнительный цвет и перерисовываем
sailboat.SetAdditionalColor(color);
DrawObject();
}
}
// Обработчик клика по кнопке "Добавить"
private void ButtonAdd_Click(object sender, EventArgs e)
{
// Если _bus задан, вызываем делегат и закрываем форму
if (_bus != null)
{
BusDelegate?.Invoke(_bus);
Close();
}
}
}

View File

@@ -0,0 +1,147 @@
namespace ProjectDoubleDeckerBus
{
partial class FormDoubleDeckerBus
{
/// <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()
{
pictureBoxDoubleDeckerBus = new PictureBox();
buttonLeft = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxDoubleDeckerBus).BeginInit();
SuspendLayout();
//
// pictureBoxDoubleDeckerBus
//
pictureBoxDoubleDeckerBus.Dock = DockStyle.Fill;
pictureBoxDoubleDeckerBus.Location = new Point(0, 0);
pictureBoxDoubleDeckerBus.Name = "pictureBoxDoubleDeckerBus";
pictureBoxDoubleDeckerBus.Size = new Size(800, 425);
pictureBoxDoubleDeckerBus.TabIndex = 0;
pictureBoxDoubleDeckerBus.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(671, 378);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(753, 378);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 3;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(712, 337);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 4;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(712, 378);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(667, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(713, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormDoubleDeckerBus
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 425);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxDoubleDeckerBus);
Name = "FormDoubleDeckerBus";
Text = "Автобус";
Load += FormDoubleDeckerBus_Load;
((System.ComponentModel.ISupportInitialize)pictureBoxDoubleDeckerBus).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxDoubleDeckerBus;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@@ -0,0 +1,147 @@
using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.MovementStrategy;
namespace ProjectDoubleDeckerBus
/// <summary>
/// Форма работы с объектом "Двухэтажный автобус"
/// </summary>
{
public partial class FormDoubleDeckerBus : Form
{
/// <summary>
/// Поле-объект дял прорисовки объекта
/// </summary>
private DrawningBus? _drawningBus;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningBus SetBus
{
set
{
_drawningBus = value;
_drawningBus.SetPictureSize(pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Конструктор формы
/// </summary>
public FormDoubleDeckerBus()
{
InitializeComponent();
_strategy = null;
}
public void Draw()
{
if (_drawningBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningBus.DrawTransport(gr);
pictureBoxDoubleDeckerBus.Image = bmp;
}
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningBus == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningBus.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 (_drawningBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableBus(_drawningBus), pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void FormDoubleDeckerBus_Load(object sender, EventArgs e)
{
}
}
}

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,139 @@
namespace ProjectDoubleDeckerBus.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
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>
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 (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true удалось переместиться, false неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true удалось переместиться, false неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestination();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true удалось переместиться, false неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@@ -0,0 +1,25 @@

namespace ProjectDoubleDeckerBus.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 перемещение невозможно.
bool TryMoveObject(MovementDirection direction);
}

View File

@@ -0,0 +1,63 @@
namespace ProjectDoubleDeckerBus.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в правый нижний край экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
int? step = GetStep();
if (objParams == null || step == null)
return false;
bool atHorizontalEdge = objParams.LeftBorder <= step || objParams.RightBorder >= FieldWidth - step;
bool atVerticalEdge = objParams.TopBorder <= step || objParams.DownBorder >= FieldHeight - step;
return atHorizontalEdge && atVerticalEdge;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
int? step = GetStep();
if (objParams == null || step == null)
{
return;
}
// Горизонтальное направление
if (objParams.ObjectMiddleHorizontal < FieldWidth / 2)
{
if (objParams.LeftBorder > step)
{
MoveLeft();
}
}
else
{
if (objParams.RightBorder < FieldWidth - step)
{
MoveRight();
}
}
// Вертикальное направление
if (objParams.ObjectMiddleVertical < FieldHeight / 2)
{
if (objParams.TopBorder > step)
{
MoveUp();
}
}
else
{
if (objParams.DownBorder < FieldHeight - step)
{
MoveDown();
}
}
}
}

View File

@@ -0,0 +1,57 @@
namespace ProjectDoubleDeckerBus.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth ||
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();
}
return;
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@@ -0,0 +1,63 @@
using ProjectDoubleDeckerBus.Drawnings;
namespace ProjectDoubleDeckerBus.MovementStrategy;
/// <summary>
/// Класс реализация IMoveableObject с использованием DrawningShip
/// </summary>
public class MoveableBus : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningBus или его наследника
/// </summary>
private readonly DrawningBus? _bus = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="bus"></param>
public MoveableBus(DrawningBus bus)
{
_bus = bus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_bus == null || _bus.EntityBus == null || !_bus.GetPosX.HasValue || !_bus.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_bus.GetPosX.Value, _bus.GetPosY.Value, _bus.GetWidth, _bus.GetHeight);
}
}
public int GetStep => (int)(_bus?.EntityBus?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_bus == null || _bus.EntityBus == null)
{
return false;
}
return _bus.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

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

View File

@@ -0,0 +1,72 @@
namespace ProjectDoubleDeckerBus.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 DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина объекта</param>
/// <param name="height">Высота объекта</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@@ -0,0 +1,19 @@
namespace ProjectDoubleDeckerBus.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectDoubleDeckerBus namespace ProjectDoubleDeckerBus
{ {
internal static class Program internal static class Program
@@ -8,10 +16,51 @@ namespace ProjectDoubleDeckerBus
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, try
// see https://aka.ms/applicationconfiguration. {
ConfigureLogging();
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
using var serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
}
catch (Exception ex)
{
// <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
MessageBox.Show($"<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: {ex.Message}", "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Fatal(ex, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureLogging()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("serilog.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormBusCollection>();
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders(); // <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
loggingBuilder.SetMinimumLevel(LogLevel.Information);
loggingBuilder.AddSerilog();
});
} }
} }
} }

View File

@@ -8,4 +8,41 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.6" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.5.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="System.IO" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectDoubleDeckerBus.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("ProjectDoubleDeckerBus.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 Down {
get {
object obj = ResourceManager.GetObject("Down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Left {
get {
object obj = ResourceManager.GetObject("Left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Right {
get {
object obj = ResourceManager.GetObject("Right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Up {
get {
object obj = ResourceManager.GetObject("Up", 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="Down" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Down.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Left" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Left.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Right" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Right.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Up" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Up.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: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 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>

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Lokolog-.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithThreadId" ],
"Properties": {
"Application": "PrLaba1"
}
}
}