Compare commits

...

16 Commits
main ... Lab08

Author SHA1 Message Date
ee08b19d17 Merge branch 'Lab07' into Lab08 2024-05-23 18:17:48 +04:00
369bfdae70 изменил сообщение логера 2024-05-21 13:30:40 +04:00
d5e19301a4 лабораторная работа №8 2024-05-18 16:26:55 +04:00
5d47765f02 лабораторная работа №7 2024-05-17 14:10:29 +04:00
744a9cec65 Удалил не использующийся делегат 2024-05-02 10:50:18 +04:00
5821b6d346 Лабораторная работа №6 2024-04-26 00:30:31 +04:00
d8b3fa6554 Убрал опечатки 2024-04-26 00:21:40 +04:00
2508ad1f12 Лабораторная работа №5 2024-04-24 19:34:58 +04:00
6e23967d26 Переделал установку максимального значения 2024-04-23 12:17:25 +04:00
66e147bd3a 4 лабораторная работа 2024-04-18 15:27:34 +04:00
578ac2e424 Переделал методы из требования №5 2024-03-27 18:41:43 +04:00
a22085ac83 Лабораторная работа №3 2024-03-27 01:48:45 +04:00
b869ca4747 Лабораторная работа №2 2024-03-27 01:29:09 +04:00
42aa45de02 Добавление проверки выхода за верхнюю и левую границы 2024-03-12 12:44:07 +04:00
070132467e Добавление комментария к коду 2024-03-12 11:54:13 +04:00
03f4e8d73a Лабораторная работа №1 2024-03-11 15:09:34 +04:00
62 changed files with 4739 additions and 57 deletions

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,82 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System.Linq;
namespace ProjectMonorail.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 = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
_collection.Add(obj);
return Count + 1;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
_collection.Insert(position, obj);
return Count + 1;
}
public T Remove(int position)
{
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
T tmp = _collection[position];
_collection.RemoveAt(position);
return tmp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -0,0 +1,118 @@
using ProjectMonorail.CollectionGenericObjects;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObject;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection[position] == null) { throw new ObjectNotFoundException(); }
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException();
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException();
}
public T Remove(int position)
{
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection == null) { throw new ObjectNotFoundException(); }
T tmp = _collection[position];
_collection[position] = null;
return tmp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -0,0 +1,218 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System.Collections;
namespace ProjectMonorail.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawingTrain
{
/// <summary>
/// Словарь (хранилище) коллекций
/// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">Тип коллекции</param>
public void AddCollection(String name, CollectionType collectionType)
{
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo)) { return; }
switch (collectionInfo.CollectionType)
{
case CollectionType.None:
break;
case CollectionType.Massive:
_storages.Add(collectionInfo, new MassiveGenericObjects<T>());
break;
case CollectionType.List:
_storages.Add(collectionInfo, new ListGenericObjects<T>());
break;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(String name)
{
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (collectionInfo.Name == null || !_storages.ContainsKey(collectionInfo)) { return; }
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[String collectionName]
{
get
{
CollectionInfo collectionInfo = new CollectionInfo(collectionName, CollectionType.None, "");
if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
}
}
/// <summary>
/// Сохранение информации по поездам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
//Не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
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 != _collectionKey || 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);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingTrain() is T train)
{
try
{
if (collection.Insert(train) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -0,0 +1,60 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.CollectionGenericObjects;
public class TrainSharingService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public TrainSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrain> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
int posX = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
int posY = 0;
g.DrawLine(pen, posX, posY, posX, posY + _placeSizeHeight * (_pictureHeight / _placeSizeHeight));
for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, posX, posY, posX + _placeSizeWidth - 30, posY);
posY += _placeSizeHeight;
}
posX += _placeSizeWidth;
}
}
protected override void SetObjectsPosition()
{
int counter = 0;
int valPlaceY = _pictureHeight / _placeSizeHeight;
for (int y = ((valPlaceY - 1) * _placeSizeHeight) + 30; y >= 0; y -= _placeSizeHeight)
{
for (int x = 10; x + _placeSizeWidth < _pictureWidth; x += _placeSizeWidth)
{
try
{
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(counter)?.SetPosition(x, y);
counter++;
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException) { }
}
}
}
}

View File

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

View File

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectMonorail.Entities;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingMonorail : DrawingTrain
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="wheels">Количество колёс</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rail">Признак наличия магнитного рельса</param>
/// <param name="secondCarriage">Признак наличия второго вагона</param>
public DrawingMonorail(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) : base(40, 150)
{
EntityTrain = new EntityMonorail(speed, (int)weight, wheels, mainColor, additionalColor, rail, secondCarriage);
}
public DrawingMonorail(EntityTrain? entityTrain)
{
if (entityTrain != null)
{
EntityTrain = entityTrain;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityTrain == null || EntityTrain is not EntityMonorail monoRail || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
base.DrawTransport(g);
Brush additionalBrush = new SolidBrush(monoRail.AdditionalColor);
Pen pen = new(Color.Black);
Brush brBlue = new SolidBrush(Color.LightBlue);
Brush brWhite = new SolidBrush(Color.White);
Brush brBlack = new SolidBrush(Color.Black);
//магнитная рельса
if (monoRail.Rail)
{
if (monoRail.SecondСarriage)
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 150, 3);
}
else
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3);
}
}
//Второй вагон
if (monoRail.SecondСarriage)
{
//кузов
g.DrawRectangle(pen, _startPosX.Value + 95, _startPosY.Value, 55, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 96, _startPosY.Value + 1, 54, 29);
//сцепка
g.FillRectangle(brBlack, _startPosX.Value + 85, _startPosY.Value + 5, 10, 23);
//Окно
g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 35, 10);
g.FillRectangle(brBlue, _startPosX.Value + 106, _startPosY.Value + 6, 34, 9);
//Дверь
g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 10, 23);
g.FillRectangle(brWhite, _startPosX.Value + 106, _startPosY.Value + 16, 9, 12);
//Колёса
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 130, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 140, _startPosY.Value + 30, 10, 10);
}
switch (monoRail.Wheels)
{
case 3:
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
break;
case 4:
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10);
break;
}
}
}

View File

@ -0,0 +1,309 @@
using ProjectMonorail.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary>
public class DrawingTrain
{
/// <summary>
/// Класс-сущность "монорельс"
/// </summary>
public EntityTrain? EntityTrain { get; protected set; }
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Левая координата прорисовки монорельса
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки монорельса
/// </summary>
protected int? _startPosY;
/// <summary>
/// Высота прорисовки монорельса
/// </summary>
private readonly int _drawingMonorailHeight = 40;
/// <summary>
/// Ширина прорисовки монорельса
/// </summary>
private readonly int _drawingMonorailWidth = 95;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawingMonorailWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingMonorailHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawingTrain()
{
_pictureHeight = null;
_pictureWidth = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
public DrawingTrain(int speed, double weight, Color mainColor) : this()
{
EntityTrain = new EntityTrain(speed, weight, mainColor);
}
public DrawingTrain(EntityTrain? entityTrain)
{
if (entityTrain != null)
{
EntityTrain = entityTrain;
}
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawingMonorailHeight">Высота</param>
/// <param name="drawingMonorailWidth">Ширина</param>
protected DrawingTrain(int drawingMonorailHeight, int drawingMonorailWidth) : this()
{
_drawingMonorailHeight = drawingMonorailHeight;
_drawingMonorailWidth = drawingMonorailWidth;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns></returns>
public bool SetPictureSize(int width, int height)
{
if (_drawingMonorailWidth <= width && _drawingMonorailHeight <= height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawingMonorailWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawingMonorailWidth;
}
if (_startPosY + _drawingMonorailHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawingMonorailHeight;
}
}
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата x</param>
/// <param name="y">Координата y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x < 0)
{
x = 0;
}
if (x + _drawingMonorailWidth > _pictureWidth.Value)
{
x = _pictureWidth.Value - _drawingMonorailWidth;
}
if (y < 0)
{
y = 0;
}
if (y + _drawingMonorailHeight > _pictureHeight.Value)
{
y = _pictureHeight.Value - _drawingMonorailHeight;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещение выполнено; false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//Перемещение влево
case DirectionType.Left:
if (_startPosX.Value - EntityTrain.Step > 0)
{
_startPosX -= (int)EntityTrain.Step;
}
return true;
//Перемещение вправо
case DirectionType.Right:
if (_startPosX.Value + _drawingMonorailWidth + EntityTrain.Step < _pictureWidth)
{
_startPosX += (int)EntityTrain.Step;
}
return true;
//Перемещение вверх
case DirectionType.Up:
if (_startPosY.Value - EntityTrain.Step > 0)
{
_startPosY -= (int)EntityTrain.Step;
}
return true;
//Перемещение вниз
case DirectionType.Down:
if (_startPosY.Value + _drawingMonorailHeight + EntityTrain.Step < _pictureHeight)
{
_startPosY += (int)EntityTrain.Step;
}
return true;
default: return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush mainBrush = new SolidBrush(EntityTrain.MainColor);
Brush brBlue = new SolidBrush(Color.LightBlue);
Brush brWhite = new SolidBrush(Color.White);
Brush brBlack = new SolidBrush(Color.Black);
//Границы монорельса
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 15, 80, 15);
Point[] points1 = {
new Point(_startPosX.Value + 10, _startPosY.Value),
new Point(_startPosX.Value + 85, _startPosY.Value),
new Point(_startPosX.Value + 85, _startPosY.Value + 15),
new Point(_startPosX.Value + 5, _startPosY.Value + 15)
};
g.DrawPolygon(pen, points1);
g.FillRectangle(mainBrush, _startPosX.Value + 6, _startPosY.Value + 16, 79, 14);
Point[] points2 = {
new Point(_startPosX.Value + 10, _startPosY.Value + 1),
new Point(_startPosX.Value + 85, _startPosY.Value + 1),
new Point(_startPosX.Value + 85, _startPosY.Value + 15),
new Point(_startPosX.Value + 5, _startPosY.Value + 15)
};
g.FillPolygon(mainBrush, points2);
//Держатель 1
Point[] points_cart1 = {
new Point(_startPosX.Value, _startPosY.Value + 35),
new Point(_startPosX.Value + 15, _startPosY.Value + 35),
new Point(_startPosX.Value + 15, _startPosY.Value + 30),
new Point(_startPosX.Value + 5, _startPosY.Value + 30)
};
g.DrawPolygon(pen, points_cart1);
g.FillPolygon(brBlack, points_cart1);
//Держатель 2
Point[] points_cart2 = {
new Point(_startPosX.Value + 20, _startPosY.Value + 30),
new Point(_startPosX.Value + 25, _startPosY.Value + 35),
new Point(_startPosX.Value + 30, _startPosY.Value + 35),
new Point(_startPosX.Value + 35, _startPosY.Value + 30)
};
g.DrawPolygon(pen, points_cart2);
g.FillPolygon(brBlack, points_cart2);
//Держатель 3
Point[] points_cart3 = {
new Point(_startPosX.Value + 55, _startPosY.Value + 30),
new Point(_startPosX.Value + 60, _startPosY.Value + 35),
new Point(_startPosX.Value + 65, _startPosY.Value + 35),
new Point(_startPosX.Value + 70, _startPosY.Value + 30)
};
g.DrawPolygon(pen, points_cart3);
g.FillPolygon(brBlack, points_cart3);
//Держатель 4
Point[] points_cart4 = {
new Point(_startPosX.Value + 70, _startPosY.Value + 30),
new Point(_startPosX.Value + 75, _startPosY.Value + 35),
new Point(_startPosX.Value + 90, _startPosY.Value + 35),
new Point(_startPosX.Value + 85, _startPosY.Value + 30)
};
g.DrawPolygon(pen, points_cart4);
g.FillPolygon(brBlack, points_cart4);
//Окна монорельса
g.DrawRectangle(pen, _startPosX.Value + 17, _startPosY.Value + 5, 17, 7);
g.FillRectangle(brBlue, _startPosX.Value + 18, _startPosY.Value + 6, 16, 6);
g.DrawRectangle(pen, _startPosX.Value + 55, _startPosY.Value + 5, 27, 7);
g.FillRectangle(brBlue, _startPosX.Value + 56, _startPosY.Value + 6, 26, 6);
//Дверь монорельса
g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 7, 10, 21);
g.FillRectangle(brWhite, _startPosX.Value + 41, _startPosY.Value + 8, 9, 20);
//колёса
//1, 4 колесо
g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 15, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 65, _startPosY.Value + 30, 10, 10);
}
}

View File

@ -0,0 +1,29 @@
namespace ProjectMonorail.Drawings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawingTrainCompareByColor : IComparer<DrawingTrain?>
{
public int Compare(DrawingTrain? x, DrawingTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return -1;
}
if (y == null || y.EntityTrain == null)
{
return 1;
}
if (x.EntityTrain.MainColor.Name != y.EntityTrain.MainColor.Name)
{
return x.EntityTrain.MainColor.Name.CompareTo(y.EntityTrain.MainColor.Name);
}
var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight);
}
}

View File

@ -0,0 +1,29 @@
namespace ProjectMonorail.Drawings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawingTrainCompareByType : IComparer<DrawingTrain?>
{
public int Compare(DrawingTrain? x, DrawingTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return -1;
}
if (y == null || y.EntityTrain == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight);
}
}

View File

@ -0,0 +1,65 @@
using ProjectMonorail.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawingTrainEqutables : IEqualityComparer<DrawingTrain?>
{
public bool Equals(DrawingTrain? x, DrawingTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return false;
}
if (y == null || y.EntityTrain == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrain.Speed != y.EntityTrain.Speed)
{
return false;
}
if (x.EntityTrain.Weight != y.EntityTrain.Weight)
{
return false;
}
if (x.EntityTrain.MainColor != y.EntityTrain.MainColor)
{
return false;
}
if (x is DrawingMonorail && y is DrawingMonorail)
{
EntityMonorail newX = (EntityMonorail)x.EntityTrain;
EntityMonorail newY = (EntityMonorail)y.EntityTrain;
if (newX.AdditionalColor != newY.AdditionalColor)
{
return false;
}
if (newX.Wheels != newY.Wheels)
{
return false;
}
if (newX.Rail != newY.Rail)
{
return false;
}
if (newX.SecondСarriage != newY.SecondСarriage)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingTrain? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,56 @@
using ProjectMonorail.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawingTrain
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingTrain? CreateDrawingTrain(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrain? train = EntityMonorail.CreateEntityMonorail(strs);
if (train != null)
{
return new DrawingMonorail(train);
}
train = EntityTrain.CreateEntityTrain(strs);
if (train != null)
{
return new DrawingTrain(train);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingTrain">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingTrain drawingTrain)
{
string[]? array = drawingTrain?.EntityTrain?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Entities;
/// <summary>
/// Класс-сущность "Монорельс"
/// </summary>
public class EntityMonorail : EntityTrain
{
/// <summary>
/// Количество колёс
/// </summary>
public int Wheels { get; private set; }
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак наличия магнитного рельса
/// </summary>
public bool Rail { get; private set; }
/// <summary>
/// Признак наличия второго вагона
/// </summary>
public bool SecondСarriage { get; private set; }
/// <summary>
/// Метод для задания дополнительного цвета
/// </summary>
/// <param name="color"></param>
public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="wheels">Количество колёс</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rail">Признак наличия магнитного рельса</param>
/// <param name="secondCarriage">Признак наличия второго вагона</param>
public EntityMonorail(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) : base(speed, weight, mainColor)
{
Wheels = wheels;
AdditionalColor = additionalColor;
Rail = rail;
SecondСarriage = secondCarriage;
}
/// <summary>
/// Получние строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityMonorail), Speed.ToString(), Weight.ToString(), Wheels.ToString(),
MainColor.Name, AdditionalColor.Name, Rail.ToString(), SecondСarriage.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMonorail? CreateEntityMonorail(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityMonorail))
{
return null;
}
return new EntityMonorail(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Convert.ToInt32(strs[3]),
Color.FromName(strs[4]), Color.FromName(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}

View File

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

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превыщено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку добавления уже существующего объекта
/// </summary>
[Serializable]
public class ObjectExistsException : ApplicationException
{
public ObjectExistsException() : base("Данный объект уже существует") { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -1,45 +0,0 @@
namespace ProjectMonorail
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(801, 450);
Name = "Form1";
Text = "Form1";
ResumeLayout(false);
}
#endregion
}
}

View File

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

146
ProjectMonorail/FormMonorail.Designer.cs generated Normal file
View File

@ -0,0 +1,146 @@
namespace ProjectMonorail
{
partial class FormMonorail
{
/// <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()
{
pictureBoxMonorail = new PictureBox();
buttonDown = new Button();
buttonRight = new Button();
buttonLeft = new Button();
buttonUp = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit();
SuspendLayout();
//
// pictureBoxMonorail
//
pictureBoxMonorail.Dock = DockStyle.Fill;
pictureBoxMonorail.Location = new Point(0, 0);
pictureBoxMonorail.Name = "pictureBoxMonorail";
pictureBoxMonorail.Size = new Size(1206, 616);
pictureBoxMonorail.TabIndex = 5;
pictureBoxMonorail.TabStop = false;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.icons8_стрелка_50вниз;
buttonDown.Location = new Point(1088, 554);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(50, 50);
buttonDown.TabIndex = 10;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.icons8_стрелка_50__1_;
buttonRight.Location = new Point(1144, 554);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(50, 50);
buttonRight.TabIndex = 9;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.icons8_стрелка_50влево;
buttonLeft.Location = new Point(1032, 554);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(50, 50);
buttonLeft.TabIndex = 8;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.icons8_стрелка_50вверх;
buttonUp.Location = new Point(1088, 498);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(50, 50);
buttonUp.TabIndex = 7;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(1064, 9);
comboBoxStrategy.Margin = new Padding(3, 2, 3, 2);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(133, 23);
comboBoxStrategy.TabIndex = 12;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(1113, 34);
buttonStrategyStep.Margin = new Padding(3, 2, 3, 2);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(82, 22);
buttonStrategyStep.TabIndex = 13;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormMonorail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1206, 616);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(pictureBoxMonorail);
Name = "FormMonorail";
Text = "FormMonorail";
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxMonorail;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private Button buttonUp;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectMonorail.Drawings;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail
{
/// <summary>
/// Форма работы с объектом "Монорельс"
/// </summary>
public partial class FormMonorail : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingTrain? _drawingTrain;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawingTrain SetTrain
{
set
{
_drawingTrain = value;
_drawingTrain.SetPictureSize(pictureBoxMonorail.Width, pictureBoxMonorail.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Конструктор формы
/// </summary>
public FormMonorail()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки
/// </summary>
private void Draw()
{
if (_drawingTrain == null)
{
return;
}
Bitmap bmp = new(pictureBoxMonorail.Width, pictureBoxMonorail.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingTrain.DrawTransport(gr);
pictureBoxMonorail.Image = bmp;
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingTrain == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawingTrain.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawingTrain.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawingTrain.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawingTrain.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingTrain == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTrain(_drawingTrain), pictureBoxMonorail.Width, pictureBoxMonorail.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,389 @@
namespace ProjectMonorail
{
partial class FormTrainCollection
{
/// <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();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveTrain = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddTrain = 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();
label1 = 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();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1006, 24);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(200, 642);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveTrain);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonAddTrain);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 370);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 270);
panelCompanyTools.TabIndex = 8;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 153);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(185, 34);
buttonRefresh.TabIndex = 12;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 115);
buttonGoToCheck.Margin = new Padding(3, 2, 3, 2);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(185, 34);
buttonGoToCheck.TabIndex = 11;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveTrain
//
buttonRemoveTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTrain.Location = new Point(3, 77);
buttonRemoveTrain.Margin = new Padding(3, 2, 3, 2);
buttonRemoveTrain.Name = "buttonRemoveTrain";
buttonRemoveTrain.Size = new Size(185, 34);
buttonRemoveTrain.TabIndex = 10;
buttonRemoveTrain.Text = "Удалить объект";
buttonRemoveTrain.UseVisualStyleBackColor = true;
buttonRemoveTrain.Click += ButtonRemoveTrain_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(5, 50);
maskedTextBoxPosition.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(185, 23);
maskedTextBoxPosition.TabIndex = 9;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddTrain
//
buttonAddTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTrain.Location = new Point(5, 12);
buttonAddTrain.Margin = new Padding(3, 2, 3, 2);
buttonAddTrain.Name = "buttonAddTrain";
buttonAddTrain.Size = new Size(185, 34);
buttonAddTrain.TabIndex = 7;
buttonAddTrain.Text = "Добавление поезда";
buttonAddTrain.UseVisualStyleBackColor = true;
buttonAddTrain.Click += ButtonAddTrain_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateCompany.Location = new Point(6, 332);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(185, 34);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создание компании";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(label1);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 18);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(194, 282);
panelStorage.TabIndex = 2;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 245);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(185, 34);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 122);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(188, 109);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 82);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(185, 34);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(76, 57);
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, 57);
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, 28);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(188, 23);
textBoxCollectionName.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(34, 10);
label1.Name = "label1";
label1.Size = new Size(125, 15);
label1.TabIndex = 0;
label1.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, 305);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(185, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Margin = new Padding(3, 2, 3, 2);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1006, 642);
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(1206, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 229);
buttonSortByColor.Margin = new Padding(3, 2, 3, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(185, 34);
buttonSortByColor.TabIndex = 14;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 191);
buttonSortByType.Margin = new Padding(3, 2, 3, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(185, 34);
buttonSortByType.TabIndex = 13;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormTrainCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1206, 666);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormTrainCollection";
Text = "Коллекция поездов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private PictureBox pictureBox;
private Panel panelStorage;
private Label label1;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRemoveTrain;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddTrain;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -0,0 +1,359 @@
using Microsoft.Extensions.Logging;
using ProjectMonorail.CollectionGenericObjects;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System.Windows.Forms;
namespace ProjectMonorail;
/// <summary>
/// Форма работы с компанией и её коллекцией
/// </summary>
public partial class FormTrainCollection : Form
{
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawingTrain> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTrainCollection(ILogger<FormTrainCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление поезда
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
FormTrainConfig form = new();
form.AddEvent(SetTrain);
form.Show();
}
/// <summary>
/// Добавление поезда в коллекцию
/// </summary>
/// <param name="train"></param>
private void SetTrain(DrawingTrain train)
{
if (_company == null || train == null)
{
return;
}
try
{
var set = _company + train;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект: {train.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Коллекция переполнена");
_logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Данный объект уже существует");
_logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление объекта по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект из коллекции по индексу {pos}", pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawingTrain? train = null;
int counter = 100;
while (train == null)
{
try
{
train = _company.GetRandomObject();
}
catch (ObjectNotFoundException)
{
counter--;
if (counter <= 0)
{
break;
}
}
}
if (train == null)
{
return;
}
FormMonorail form = new()
{
SetTrain = train
};
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;
}
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.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление компании, не выбрав коллекцию");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция {name}");
RefreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; i++)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании, не выбрав коллекцию");
return;
}
CollectionGenericObject.ICollectionGenericObjects<DrawingTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не далось иницализировать коллекцию");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception 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(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareTrains(new DrawingTrainCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareTrains(new DrawingTrainCompareByColor());
}
private void CompareTrains(IComparer<DrawingTrain?> comparer)
{
if (_company == null) { return; }
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

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

View File

@ -0,0 +1,384 @@
namespace ProjectMonorail
{
partial class FormTrainConfig
{
/// <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();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
numericUpDownWheels = new NumericUpDown();
labelWheels = new Label();
checkBoxSecondСarriage = new CheckBox();
checkBoxRail = 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();
labelMainColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWheels).BeginInit();
((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(numericUpDownWheels);
groupBoxConfig.Controls.Add(labelWheels);
groupBoxConfig.Controls.Add(checkBoxSecondСarriage);
groupBoxConfig.Controls.Add(checkBoxRail);
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(599, 272);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(298, 30);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(274, 137);
groupBoxColors.TabIndex = 11;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(215, 80);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(42, 42);
panelPurple.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(215, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(42, 42);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(149, 80);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(42, 42);
panelBlack.TabIndex = 6;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(149, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(42, 42);
panelBlue.TabIndex = 2;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(83, 80);
panelGray.Name = "panelGray";
panelGray.Size = new Size(42, 42);
panelGray.TabIndex = 5;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(83, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(42, 42);
panelGreen.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(23, 80);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(42, 42);
panelWhite.TabIndex = 4;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(23, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(42, 42);
panelRed.TabIndex = 0;
//
// numericUpDownWheels
//
numericUpDownWheels.Location = new Point(128, 110);
numericUpDownWheels.Maximum = new decimal(new int[] { 4, 0, 0, 0 });
numericUpDownWheels.Minimum = new decimal(new int[] { 2, 0, 0, 0 });
numericUpDownWheels.Name = "numericUpDownWheels";
numericUpDownWheels.Size = new Size(87, 23);
numericUpDownWheels.TabIndex = 10;
numericUpDownWheels.Value = new decimal(new int[] { 2, 0, 0, 0 });
//
// labelWheels
//
labelWheels.AutoSize = true;
labelWheels.Location = new Point(12, 118);
labelWheels.Name = "labelWheels";
labelWheels.Size = new Size(110, 15);
labelWheels.TabIndex = 9;
labelWheels.Text = "Количество колёс:";
//
// checkBoxSecondСarriage
//
checkBoxSecondСarriage.AutoSize = true;
checkBoxSecondСarriage.Location = new Point(12, 201);
checkBoxSecondСarriage.Name = "checkBoxSecondСarriage";
checkBoxSecondСarriage.Size = new Size(213, 19);
checkBoxSecondСarriage.TabIndex = 8;
checkBoxSecondСarriage.Text = "Признак наличия второго вагона ";
checkBoxSecondСarriage.UseVisualStyleBackColor = true;
//
// checkBoxRail
//
checkBoxRail.AutoSize = true;
checkBoxRail.Location = new Point(12, 159);
checkBoxRail.Name = "checkBoxRail";
checkBoxRail.Size = new Size(232, 19);
checkBoxRail.TabIndex = 7;
checkBoxRail.Text = "Признак наличия магнитного рельса";
checkBoxRail.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(128, 70);
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(87, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 78);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(128, 30);
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(87, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 38);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(65, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость: ";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(298, 192);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(125, 40);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(447, 192);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(125, 40);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 52);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(250, 150);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(605, 226);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(100, 30);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(761, 226);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(100, 30);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelMainColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(605, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(256, 220);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(153, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(100, 30);
labelAdditionalColor.TabIndex = 12;
labelAdditionalColor.Text = "Доп. Цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelColor_DragDrop;
labelAdditionalColor.DragEnter += LabelColor_DragEnter;
//
// labelMainColor
//
labelMainColor.AllowDrop = true;
labelMainColor.BorderStyle = BorderStyle.FixedSingle;
labelMainColor.Location = new Point(3, 9);
labelMainColor.Name = "labelMainColor";
labelMainColor.Size = new Size(100, 30);
labelMainColor.TabIndex = 13;
labelMainColor.Text = "Цвет";
labelMainColor.TextAlign = ContentAlignment.MiddleCenter;
labelMainColor.DragDrop += LabelColor_DragDrop;
labelMainColor.DragEnter += LabelColor_DragEnter;
//
// FormTrainConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(873, 272);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormTrainConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWheels).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxSecondСarriage;
private CheckBox checkBoxRail;
private NumericUpDown numericUpDownWheels;
private Label labelWheels;
private GroupBox groupBoxColors;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
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 labelMainColor;
private Label labelAdditionalColor;
}
}

View File

@ -0,0 +1,171 @@
using ProjectMonorail.Drawings;
using ProjectMonorail.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectMonorail;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormTrainConfig : Form
{
/// <summary>
/// Объект - прорисовка поезда
/// </summary>
private DrawingTrain? _train;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawingTrain>? TrainDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormTrainConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="trainDelegate"></param>
public void AddEvent(Action<DrawingTrain> trainDelegate)
{
TrainDelegate += trainDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_train?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_train?.SetPosition(20, 50);
_train?.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":
_train = new DrawingTrain((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_train = new DrawingMonorail((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, (int)numericUpDownWheels.Value, Color.White,
Color.Black, checkBoxRail.Checked, checkBoxSecondСarriage.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragEnter(object? sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragDrop(object? sender, DragEventArgs e)
{
if (_train == null || sender == null) { return; }
Label colorof = (Label)sender;
Color color = (Color)e.Data?.GetData(typeof(Color));
switch (colorof?.Name)
{
case "labelMainColor":
_train.EntityTrain?.SetMainColor(color);
DrawObject();
break;
case "labelAdditionalColor":
if (_train is DrawingMonorail)
{
(_train.EntityTrain as EntityMonorail).SetAdditionalColor(color);
DrawObject();
}
break;
}
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object? sender, EventArgs e)
{
if (_train != null)
{
TrainDelegate?.Invoke(_train);
Close();
}
}
}

View File

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

View File

@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMovableObjects? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
/// <returns></returns>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="movableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMovableObjects movableObject, int width, int height)
{
if (movableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = movableObject;
FieldHeight = height;
FieldWidth = width;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Шаг влево
/// </summary>
/// <returns></returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Шаг вверх
/// </summary>
/// <returns></returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Шаг вправо
/// </summary>
/// <returns></returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Шаг вниз
/// </summary>
/// <returns></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();
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public interface IMovableObjects
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в заданном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffx = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffx) > GetStep())
{
MoveRight();
}
int diffy = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffy) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
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 / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffx = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffx) > GetStep())
{
if (diffx > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffy = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffy) > GetStep())
{
if (diffy > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,63 @@
using ProjectMonorail.Drawings;
namespace ProjectMonorail.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawingTrain
/// </summary>
public class MoveableTrain : IMovableObjects
{
/// <summary>
/// Поле-объект класса DrawingTrain или его наследника
/// </summary>
private readonly DrawingTrain? _train = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="train">Объект класса DrawingTrain</param>
public MoveableTrain(DrawingTrain train)
{
_train = train;
}
public ObjectParameters? GetObjectPosition
{
get
{
if(_train == null || _train.EntityTrain == null || !_train.GetPosX.HasValue || !_train.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_train.GetPosX.Value, _train.GetPosY.Value, _train.GetWidth, _train.GetHeight);
}
}
public int GetStep => (int)(_train?.EntityTrain?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_train == null || _train.EntityTrain == null)
{
return false;
}
return _train.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.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
_ => DirectionType.Unknown,
};
}
}

View File

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

View File

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TobBorder => _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="height">Высота</param>
/// <param name="width">Ширина</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_height = height;
_width = width;
}
}

View File

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

View File

@ -1,4 +1,10 @@
namespace ProjectMonorail
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ProjectMonorail;
using Serilog;
namespace ProjectAirFighter
{
internal static class Program
{
@ -10,8 +16,30 @@ namespace ProjectMonorail
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ServiceCollection serviceCollection = new();
ConfigureService(serviceCollection);
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTrainCollection>());
}
private static void ConfigureService(ServiceCollection services)
{
services.AddSingleton<FormTrainCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appSettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -8,4 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

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

View File

@ -0,0 +1,139 @@
<?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="icons8-стрелка-50вниз" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\icons8-стрелка-50вниз.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="icons8-стрелка-50вверх" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\icons8-стрелка-50вверх.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="icons8-стрелка-50влево" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\icons8-стрелка-50влево.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>
<data name="up1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\up1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="icons8-стрелка-50 (1)" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\icons8-стрелка-50 (1).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: 326 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

View File

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

View File

@ -0,0 +1,5 @@
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

40
WindowsFormsApp1/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,40 @@
namespace WindowsFormsApp1
{
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </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
}
}

20
WindowsFormsApp1/Form1.cs Normal file
View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
internal static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанных со сборкой.
[assembly: AssemblyTitle("WindowsFormsApp1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsFormsApp1")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, следует установить атрибут ComVisible в TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("63aecd52-fcbb-4900-a5fd-57b61edd33d0")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программным средством.
// Версия среды выполнения: 4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
// код создан повторно.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1.Properties
{
/// <summary>
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
/// </summary>
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
// класс с помощью таких средств, как ResGen или Visual Studio.
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
// с параметром /str или заново постройте свой VS-проект.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp1.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;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?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.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: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" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</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" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</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=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{63AECD52-FCBB-4900-A5FD-57B61EDD33D0}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>WindowsFormsApp1</RootNamespace>
<AssemblyName>WindowsFormsApp1</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsFormsApp1", "WindowsFormsApp1.csproj", "{63AECD52-FCBB-4900-A5FD-57B61EDD33D0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{63AECD52-FCBB-4900-A5FD-57B61EDD33D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63AECD52-FCBB-4900-A5FD-57B61EDD33D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63AECD52-FCBB-4900-A5FD-57B61EDD33D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63AECD52-FCBB-4900-A5FD-57B61EDD33D0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E2E350C5-D465-419E-9B2D-7DF5DF76814C}
EndGlobalSection
EndGlobal