Compare commits

...

74 Commits

Author SHA1 Message Date
sqdselo
64eed84f85 Готовая лаба 7 2024-06-06 10:55:54 +04:00
sqdselo
54cf6efad5 Merge branch 'LabWork07' of http://student.git.athene.tech/sqdselo/pibd-12_Tangatarov.I.A._Base into LabWork07 2024-06-06 10:52:03 +04:00
sqdselo
0412610b10 laba 7 2024-06-06 10:51:58 +04:00
sqdselo
9fa0365307 Merge branch 'LabWork07' of http://student.git.athene.tech/sqdselo/pibd-12_Tangatarov.I.A._Base into LabWork07 2024-06-06 10:48:56 +04:00
sqdselo
6a1f539b10 Борьба с конфликтами 2024-06-06 10:48:49 +04:00
sqdselo
d31c6e4617 Борьба с конфликтами 2024-06-06 10:44:54 +04:00
sqdselo
021c5ee399 борьба с конфликтами завершена 2024-06-06 10:43:19 +04:00
sqdselo
bb32f6d69e борьба с конфликтами завершена 2024-06-06 10:12:34 +04:00
sqdselo
919febed18 Готовая лаба 7 2024-06-06 00:55:16 +04:00
sqdselo
0d5ea4481f Готовая лабораторная работа 8 2024-06-05 23:04:37 +04:00
e4d751e638 Готовая лабораторная работа 7 2024-05-13 13:58:20 +04:00
sqdselo
84b3e6f21e допкаГотовая лабораторная работа 7 2024-05-13 13:58:12 +04:00
f655c6b4bb доделаю 2024-05-13 13:29:40 +04:00
sqdselo
ea555cc897 Готовая лабораторная работа 7 2024-05-09 11:11:26 +04:00
sqdselo
170e4abff0 Убрал лишние юзинги, сделал исключения на операции (добавить, удалить, получить) и сделал исключения на загрузку и выгрузку файлов 2024-05-06 17:35:33 +04:00
sqdselo
c4ee67ab56 Разрешены конфликты 2024-05-05 14:09:36 +04:00
sqdselo
c4546990f8 борюсь с конфликтами 2024-05-05 13:53:24 +04:00
sqdselo
8d7324d52e Разрешены конфликты 2024-05-05 13:23:10 +04:00
sqdselo
f51c2c348f Борюсь с конфликтами 2024-05-05 13:08:21 +04:00
sqdselo
08c1734614 Готовая лаба 4 2024-05-05 00:20:13 +04:00
sqdselo
ad565c92f3 Готовая лаба3 2024-05-04 20:15:42 +04:00
sqdselo
21e126ef09 Готовая лабораторная работа 6 2024-05-04 16:09:17 +04:00
sqdselo
58d5e959c7 Готовая лабораторная работа 6 2024-05-04 16:01:40 +04:00
sqdselo
f6f705c9f2 Готовая лабораторная работа 5 2024-05-04 16:00:29 +04:00
sqdselo
7f4d7dfdce Готовая лабораторная работа 4 2024-05-04 15:59:20 +04:00
sqdselo
2015e638fe 1 2024-05-04 15:57:24 +04:00
0b15e5c7d0 Готовая лабораторная работа 6 2024-04-29 13:26:18 +04:00
04c45def82 Готовая лабораторная работа 5 2024-04-29 12:19:14 +04:00
592fd5bea5 Готовая лабораторная работа 4 2024-04-29 12:00:25 +04:00
f520564545 доделаю 2024-04-29 11:38:35 +04:00
5ae896d09f в процессе 2024-04-29 11:30:11 +04:00
sqdselo
d7cbb73567 Лабораторная работа 7 2024-04-29 01:40:45 +04:00
sqdselo
4fc0549d2e доделаю 2024-04-29 00:51:57 +04:00
sqdselo
3cae6dc2f4 Лабораторная работа 7 (все кроме логирования) 2024-04-28 23:17:48 +04:00
sqdselo
d83972988a Готовая лабораторная работа 6 2024-04-28 13:04:05 +04:00
sqdselo
77a1def62e Осталось доработать 2024-04-28 11:50:50 +04:00
sqdselo
ccc5ae5227 Готовая лабораторная 5 2024-04-28 10:26:52 +04:00
sqdselo
21f4acf2d5 Готовая лабораторная 4 2024-04-28 10:26:11 +04:00
sqdselo
242fad7ac8 Готовая лабораторная работа 5 2024-04-28 01:09:39 +04:00
sqdselo
0a9f5bcbb6 Готовая лабораторная работа 3 2024-04-28 00:31:52 +04:00
sqdselo
68f321a652 Доделаю 2024-04-28 00:24:18 +04:00
sqdselo
052b9929c1 Готовая 4 лабораторная работа 2024-04-28 00:20:54 +04:00
sqdselo
4de1bca002 Лабораторная 3 финал 2024-04-22 19:48:41 +04:00
sqdselo
f57496c459 доделать 2024-04-22 19:10:26 +04:00
ff1e1066b6 доделаю 2024-04-15 14:25:51 +04:00
5f5f61f51b лабораторная 3 2024-04-15 12:30:38 +04:00
1cd23e10d7 / 2024-04-15 11:44:04 +04:00
ea6a49ba00 почтии 2024-04-15 11:28:15 +04:00
sqdselo
d1ad010777 маленькие изменения 2024-04-14 21:47:16 +04:00
sqdselo
50146d6d1b Лаба4 2024-04-14 21:43:46 +04:00
sqdselo
a50b38a592 доделаю 2024-04-14 20:01:01 +04:00
sqdselo
d4ccb9c74a доделаю 2024-04-14 13:50:37 +04:00
sqdselo
52b3bc2a87 Merge branch 'LabWork04' of http://student.git.athene.tech/sqdselo/pibd-12_Tangatarov.I.A._Base into LabWork04 2024-04-07 15:46:01 +04:00
sqdselo
486da066a1 Готово+- 2024-04-07 15:45:51 +04:00
sqdselo
46fb3ca9d8 доделаю 2024-04-04 15:14:16 +04:00
sqdselo
92f30977af Merge branch 'LabWork03' of http://student.git.athene.tech/sqdselo/pibd-12_Tangatarov.I.A._Base into LabWork03 2024-04-04 14:54:22 +04:00
sqdselo
feea0da22b Лабораторная работa 3 2024-04-04 14:53:50 +04:00
sqdselo
948209a130 доделать 2024-04-01 20:44:55 +04:00
4eeaacde4b Удалить 'Безымянный.png' 2024-04-01 18:39:17 +04:00
0b56d30241 Удалить "Безымянный png" 2024-04-01 18:38:51 +04:00
sqdselo
051ef5f863 доделаю 2024-04-01 18:36:14 +04:00
sqdselo
681e60fbd6 Лабораторная работка #3 2024-04-01 18:26:17 +04:00
dc01587054 Итоговая лабораторная работа 3 2024-04-01 14:05:34 +04:00
sqdselo
5c08bba55b прописать логику удаления элемента из коллекции 2024-04-01 02:15:50 +04:00
sqdselo
95a176686a не прописан функционал кнопок формы. допишу 2024-04-01 02:01:34 +04:00
sqdselo
b967200792 Теперь точно всё готово. Лабораторная работа 3 2024-04-01 01:15:33 +04:00
sqdselo
0be2471e88 Лабораторная работа №3 2024-03-31 22:08:27 +04:00
sqdselo
7fe1682f7b Коллекции объектов 2024-03-17 23:37:52 +04:00
sqdselo
b32311652f Лабораторная работа №2 2024-03-04 19:24:17 +04:00
b386a86150 Лабораторная работа №2 2024-03-04 13:07:36 +04:00
a1dab73b6d Лабораторная работа №2 2024-03-04 13:07:10 +04:00
sqdselo
534f994111 Добавление родителей и ввод конструкторов 2024-03-02 21:31:53 +04:00
83216e0433 Лабораторная работа №1 2024-02-19 13:55:12 +04:00
sqdselo
0455a1fe3f Лабораторная работа №1 2024-02-17 23:43:01 +04:00
51 changed files with 4009 additions and 56 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.7.34221.43 VisualStudioVersion = 17.7.34221.43
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HoistingCrane", "HoistingCrane\HoistingCrane.csproj", "{915BDF62-D64D-4AB9-BA2D-8E228E803B7F}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HoistingCrane", "HoistingCrane\HoistingCrane.csproj", "{915BDF62-D64D-4AB9-BA2D-8E228E803B7F}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -0,0 +1,100 @@
using HoistingCrane.Drawning;
namespace HoistingCrane.CollectionGenericObjects
{
public abstract class AbstractCompany
{
/// <summary>
/// Ширина ячейки гаража
/// </summary>
protected readonly int _placeSizeWidth = 150;
/// <summary>
/// Высота ячейки гаража
/// </summary>
protected readonly int _placeSizeHeight = 90;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectionGenericObjects<DrawningTrackedVehicle>? arr = null;
/// <summary>
/// Максимальное количество гаражей
/// </summary>
private int GetMaxCount
{
get
{
return (pictureWidth / _placeSizeWidth) * (pictureHeight * _placeSizeHeight);
}
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array)
{
pictureWidth = picWidth;
pictureHeight = picHeight;
arr = array;
arr.MaxCount = GetMaxCount;
}
public static int operator +(AbstractCompany company, DrawningTrackedVehicle car)
{
return company.arr.Insert(car, new DrawningCraneEqutables());
}
public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
{
return company.arr?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTrackedVehicle? GetRandomObject()
{
Random rnd = new();
return arr?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(pictureWidth, pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (arr?.Count ?? 0); ++i)
{
try
{
DrawningTrackedVehicle? obj = arr?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<DrawningTrackedVehicle> comparer) => arr?.CollectionSort(comparer);
}
}

View File

@ -0,0 +1,66 @@
using System.Diagnostics.CodeAnalysis;
namespace HoistingCrane.CollectionGenericObjects
{
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType collectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string description { get; private set; }
/// <summary>
/// Разделитель
/// </summary>
public 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)
{
this.name = name;
this.collectionType = collectionType;
this.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)
{
if (other == null) return false;
if (name != other.name) return false;
return true;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return name.GetHashCode();
}
}
}

View File

@ -0,0 +1,7 @@
namespace HoistingCrane.CollectionGenericObjects
{
public enum CollectionType
{
None = 0, Massive = 1, List = 2
}
}

View File

@ -0,0 +1,54 @@
using HoistingCrane.Drawning;
namespace HoistingCrane.CollectionGenericObjects
{
public class Garage : AbstractCompany
{
public Garage(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array) : base(picWidth, picHeight, array)
{
}
protected override void DrawBackgound(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 3);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth + 15, j * _placeSizeHeight, i * _placeSizeWidth + 15 + _placeSizeWidth - 55, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth + 15, j * _placeSizeHeight, i * _placeSizeWidth + 15, j * _placeSizeHeight - _placeSizeHeight);
}
}
}
protected override void SetObjectsPosition()
{
int countWidth = _pictureWidth / _placeSizeWidth;
int countHeight = _pictureHeight / _placeSizeHeight;
int currentPosWidth = countWidth - 1;
int currentPosHeight = countHeight - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15);
}
if (currentPosWidth > 0)
currentPosWidth--;
else
{
currentPosWidth = countWidth - 1;
currentPosHeight--;
}
if (currentPosHeight < 0)
{
break;
}
}
}
}
}

View File

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

View File

@ -0,0 +1,107 @@
using HoistingCrane.Drawning;
using HoistingCrane.Exceptions;
namespace HoistingCrane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
readonly List<T> list;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
list = new List<T>();
}
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count
{
get { return list.Count; }
}
public int MaxCount
{
get
{
return list.Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public T? Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return list[position];
}
public int Insert(T obj, IEqualityComparer<T>? comparer = null)
{
try
{
if (list.Contains(obj, comparer)) throw new ObjectIsPresentInTheCollectionException(Count);
if (Count == _maxCount) throw new CollectionOverflowException(Count);
list.Add(obj);
return Count - 1;
}
catch (ObjectIsPresentInTheCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
}
public int Insert(T obj, int position, IEqualityComparer<T>? comparer = null)
{
try
{
if (comparer != null && list.Contains(obj, comparer))
{
throw new ObjectIsPresentInTheCollectionException(Count);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
list.Insert(position, obj);
return position;
}
catch (ObjectIsPresentInTheCollectionException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
}
public T? Remove(int position)
{
if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position);
T? temp = list[position];
list.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < list.Count; i++)
{
yield return list[i];
}
}
public void CollectionSort(IComparer<T> comparer)
{
list.Sort(comparer);
}
}

View File

@ -0,0 +1,148 @@
using HoistingCrane.Drawning;
using HoistingCrane.Exceptions;
using System.Linq;
namespace HoistingCrane.CollectionGenericObjects;
public class MassivGenericObjects<T> : ICollectionGenericObjects<T> where T : DrawningTrackedVehicle
{
private T?[] arr;
public MassivGenericObjects()
{
arr = Array.Empty<T?>();
}
public int Count
{
get { return arr.Length; }
}
public int MaxCount
{
get
{
return arr.Length;
}
set
{
if (value > 0)
{
if (arr.Length > 0)
{
Array.Resize(ref arr, value);
}
else
{
arr = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
public T? Get(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
return arr[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
try
{
if (arr.Contains(obj, comparer))
{
throw new ObjectIsPresentInTheCollectionException();
}
for (int i = 0; i < Count; ++i)
{
if (arr[i] == null)
{
arr[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
catch (ObjectIsPresentInTheCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
try
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(arr[i], obj))
{
throw new ObjectIsPresentInTheCollectionException();
}
}
}
if (arr[position] == null)
{
arr[position] = obj;
return position;
}
else
{
for (int i = 1; i < Count; ++i)
{
if (arr[position + i] == null)
{
arr[position + i] = obj;
return position + i;
}
for (i = position - 1; i >= 0; i--)
{
if (arr[i] == null)
{
arr[i] = obj;
return i;
}
}
}
}
throw new CollectionOverflowException(Count);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
catch (ObjectIsPresentInTheCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
}
public T? Remove(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (arr[position] == null) throw new ObjectNotFoundException(position);
T? temp = arr[position];
arr[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < arr.Length; i++)
{
yield return arr[i];
}
}
public void CollectionSort(IComparer<T> comparer)
{
T[] notNullArr = arr.OfType<T>().ToArray();
Array.Sort(notNullArr, comparer);
Array.Copy(notNullArr, 0, arr, 0, notNullArr.Length);
}
}

View File

@ -0,0 +1,200 @@
using HoistingCrane.Drawning;
using HoistingCrane.Exceptions;
using System.Text;
namespace HoistingCrane.CollectionGenericObjects;
public class StorageCollection<T> where T : DrawningTrackedVehicle
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> dict;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => dict.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
dict = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
var collectionInfo = new CollectionInfo(name, collectionType, " ");
if (!string.IsNullOrEmpty(name) && !Keys.Contains(collectionInfo))
{
if (collectionType == CollectionType.Massive)
{
dict.Add(collectionInfo, new MassivGenericObjects<T>());
}
if (collectionType == CollectionType.List)
{
dict.Add(collectionInfo, new ListGenericObjects<T>());
}
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
var key = dict.Keys.FirstOrDefault(k => k.name == name);
if (key != null)
{
dict.Remove(key);
}
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
var key = dict.Keys.FirstOrDefault(k => k.name == name);
if (key == null) { return null; }
return dict[key];
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (dict.Count == 0)
{
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in dict)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по грузовикам в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <exception cref="Exception"></exception>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new InvalidOperationException("В файле не присутствуют данные");
}
if (!str.StartsWith(_collectionKey))
{
throw new FormatException("В файле неверные данные");
}
dict.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new InvalidOperationException("Не удалось определить информацию о коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.collectionType) ?? throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedVehicle() is T crane)
{
try
{
if (collection.Insert(crane) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[2]);
}
}
catch(CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
dict.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassivGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
}

View File

@ -0,0 +1,27 @@
namespace HoistingCrane.Drawning;
public enum DirectionType //Создали не класс(class), а перечисление (enum)
{
//Перечислим основные траектории движния нашего автомобиля. Сразу же зададим значения.
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down,
/// <summary>
/// Влево
/// </summary>
Left,
/// <summary>
/// Вправо
/// </summary>
Right
}

View File

@ -0,0 +1,18 @@
namespace HoistingCrane.Drawning
{
public class DrawningCraneCompareByColor : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null) return -1;
if (y == null || y.EntityTrackedVehicle == null) return 1;
if (x.EntityTrackedVehicle.BodyColor.Name != y.EntityTrackedVehicle.BodyColor.Name)
return x.EntityTrackedVehicle.BodyColor.Name.CompareTo(y.EntityTrackedVehicle.BodyColor.Name);
var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed);
if (speedCompare != 0) return speedCompare;
return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight);
}
}
}

View File

@ -0,0 +1,21 @@
namespace HoistingCrane.Drawning
{
public class DrawningCraneCompareByType : IComparer<DrawningTrackedVehicle?>
{
/// <summary>
/// Сравнение по типу, скорости и весу
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null) return -1;
if (y == null || y.EntityTrackedVehicle == null) return 1;
if (x.GetType().Name != y.GetType().Name) return x.GetType().Name.CompareTo(y.GetType().Name);
var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed);
if(speedCompare != 0) return speedCompare;
return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight);
}
}
}

View File

@ -0,0 +1,32 @@
using HoistingCrane.Entities;
using System.Diagnostics.CodeAnalysis;
namespace HoistingCrane.Drawning
{
public class DrawningCraneEqutables : IEqualityComparer<DrawningTrackedVehicle>
{
public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null) return false;
if (y == null || y.EntityTrackedVehicle == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed) return false;
if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight) return false;
if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor) return false;
if ((x.EntityTrackedVehicle as EntityHoistingCrane)!= null && (y.EntityTrackedVehicle as EntityHoistingCrane)!=null)
{
var newX = x.EntityTrackedVehicle as EntityHoistingCrane;
var newY = y.EntityTrackedVehicle as EntityHoistingCrane;
if (newX?.AdditionalColor != newY?.AdditionalColor) return false;
if (newX?.Platform != newY?.Platform) return false;
if (newX?.Counterweight != newY?.Counterweight) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrackedVehicle obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,93 @@
using HoistingCrane.Entities;
using System.Configuration;
using System.Reflection.PortableExecutable;
namespace HoistingCrane.Drawning;
//В данном классе мы будем думать над полем игры, размерами персонажа, размерами объектов и т.д.
public class DrawningHoistingCrane : DrawningTrackedVehicle
{
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawingCarWidth = 115;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawingCarHeight = 63;
/// <summary>
/// конструктор класса отрисовки крана
/// </summary>
/// <param name="AdditionalColor">Дополнительный цвет</param>
/// <param name="Counterweight">Противовес</param>
/// <param name="Platform">Платформа</param>
public DrawningHoistingCrane(int speed, int weight, Color bodyColor, Color additionalColor, bool counterweight, bool platform) : base(115, 63)
{
EntityTrackedVehicle = new EntityHoistingCrane(speed, weight, bodyColor, additionalColor, counterweight, platform);
}
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="entityHoistingCrane"></param>
public DrawningHoistingCrane(EntityHoistingCrane entityHoistingCrane) : base(115, 63)
{
EntityTrackedVehicle = new EntityHoistingCrane(entityHoistingCrane.Speed, entityHoistingCrane.Weight, entityHoistingCrane.BodyColor, entityHoistingCrane.AdditionalColor, entityHoistingCrane.Counterweight, entityHoistingCrane.Platform);
}
/// <summary>
/// Метод отрисовки объекта
/// </summary>
/// <param name="gr"></param>
public override void DrawTransport(Graphics gr)
{
if (EntityTrackedVehicle == null || EntityTrackedVehicle is not EntityHoistingCrane EntityHoistingCrane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
base.DrawTransport(gr);
Brush b = new SolidBrush(EntityHoistingCrane.AdditionalColor);
Pen pen = new Pen(EntityHoistingCrane.AdditionalColor);
Pen penBase = new Pen(EntityHoistingCrane.BodyColor);
if (EntityHoistingCrane.Counterweight)
{
//противовес
gr.DrawRectangle(pen, _startPosX.Value + 69, _startPosY.Value + 3, 10, 10);
gr.DrawLine(pen, _startPosX.Value + 68, _startPosY.Value + 3, _startPosX.Value + 78, _startPosY.Value + 12);
gr.DrawLine(pen, _startPosX.Value + 68, _startPosY.Value + 7, _startPosX.Value + 78, _startPosY.Value + 3);
}
if (EntityHoistingCrane.Platform) {
//Наличие спусковой платформы
gr.FillRectangle(b, _startPosX.Value + 101, _startPosY.Value + 40, 15, 5);
gr.FillRectangle(b, _startPosX.Value + 116, _startPosY.Value + 35, 4, 5);
gr.FillRectangle(b, _startPosX.Value + 97, _startPosY.Value + 35, 4, 5);
}
//Отрисовка крана, на котором держится платформа и противовес
gr.FillRectangle(b, _startPosX.Value + 65, _startPosY.Value, 5, 26);
gr.FillRectangle(b, _startPosX.Value + 65, _startPosY.Value, 50, 4);
gr.DrawLine(penBase, _startPosX.Value + 115, _startPosY.Value + 4, _startPosX.Value + 108, _startPosY.Value + 40);
}
}

View File

@ -0,0 +1,273 @@
using HoistingCrane.Entities;
using System.Reflection.PortableExecutable;
namespace HoistingCrane.Drawning
{
//В данном классе мы будем думать над полем игры, размерами персонажа, размерами объектов и т.д.
public class DrawningTrackedVehicle
{
/// <summary>
/// Класс - сущность
/// </summary>
public EntityTrackedVehicle? EntityTrackedVehicle { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Стартовая позиция по х
/// </summary>
protected int? _startPosX;
/// <summary>
/// Стартовая позиция по у
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawingCarWidth = 83;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawingCarHeight = 63;
public int? GetPosX => _startPosX;
public int? GetPosY => _startPosY;
public int GetWidth => _drawingCarWidth;
public int GetHeight => _drawingCarHeight;
/// <summary>
/// Конструктор класса, который принимает параметры автомобиля(скорость, вес и цвет) и создает объект класса с данными параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет</param>
public DrawningTrackedVehicle(int speed, double weight, Color bodyColor) : this()
{
EntityTrackedVehicle = new EntityTrackedVehicle(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор, при вызове которого можем менять границы транспорта
/// </summary>
/// <param name="_drawingCarWidth">Ширина прорисовки автомобиля</param>
/// <param name="_drawingCarHeight">Высота прорисовки автомобиля</param>
protected DrawningTrackedVehicle(int _drawingCarWidth, int _drawingCarHeight) : this()
{
this._drawingCarWidth = _drawingCarWidth;
this._drawingCarHeight = _drawingCarHeight;
}
/// <summary>
/// Приватный конструктор, который делает значения границ окна = null и стартовую позицию = null
/// </summary>
private DrawningTrackedVehicle()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="drawningTrackedVehicle"></param>
public DrawningTrackedVehicle(EntityTrackedVehicle entityTrackedVehicle) : this()
{
EntityTrackedVehicle = new EntityTrackedVehicle(entityTrackedVehicle.Speed, entityTrackedVehicle.Weight, entityTrackedVehicle.BodyColor);
}
/// <summary>
/// Метод отрисовки игрового поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns></returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена ✔
if (_drawingCarHeight > height || _drawingCarWidth > width)
{
return false;
}
_pictureHeight = height;
_pictureWidth = width;
if (_startPosX.HasValue && _startPosX.Value + _drawingCarWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawingCarWidth;
}
if (_startPosY.HasValue && _startPosY.Value + _drawingCarHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawingCarHeight;
}
return true;
}
/// <summary>
/// Установим позицию игрока
/// </summary>
/// <param name="x">Координата по Х</param>
/// <param name="y">Координата по У</param>
public void SetPosition(int x, int y)
{
//Если размеры были заданы, то присваиваем х и у, иначе выходим из метода
if (x < 0)
x = -x;
if (y < 0)
y = -y;
if (x + _drawingCarWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawingCarWidth;
}
else
{
_startPosX = x;
}
if (y + _drawingCarHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawingCarHeight;
}
else
{
_startPosY = y;
}
}
/// <summary>
/// Перемещение машины
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public bool MoveTransport(DirectionType direction) //Подключили модив\фикатор virtual для переопределения в дочернем классе
{
if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityTrackedVehicle.Step > 0)
{
_startPosX -= (int)EntityTrackedVehicle.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityTrackedVehicle.Step > 0)
{
_startPosY -= (int)EntityTrackedVehicle.Step;
}
return true;
//вправо
case DirectionType.Right:
if (_startPosX.Value + EntityTrackedVehicle.Step + _drawingCarWidth < _pictureWidth)
{
_startPosX += (int)EntityTrackedVehicle.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityTrackedVehicle.Step + _drawingCarHeight < _pictureHeight)
{
_startPosY += (int)EntityTrackedVehicle.Step;
}
return true;
default: return false;
}
}
/// <summary>
/// Метод отрисовки объекта
/// </summary>
/// <param name="gr"></param>
public virtual void DrawTransport(Graphics gr)
{
if (EntityTrackedVehicle == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new Pen(Color.Black);
//границы
gr.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 25, 75, 20);
gr.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 25, 25);
gr.DrawRectangle(pen, _startPosX.Value + 4, _startPosY.Value + 4, 17, 17);
gr.DrawRectangle(pen, _startPosX.Value + 52, _startPosY.Value + 7, 6, 18);
gr.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 45, 20, 20);
gr.DrawEllipse(pen, _startPosX.Value + 63, _startPosY.Value + 45, 20, 20);
gr.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 45, 68, 20);
gr.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 46, 18, 18);
gr.DrawEllipse(pen, _startPosX.Value + 62, _startPosY.Value + 46, 18, 18);
gr.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 53, 10, 10);
gr.DrawEllipse(pen, _startPosX.Value + 35, _startPosY.Value + 53, 10, 10);
gr.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 53, 10, 10);
gr.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value + 45, 4, 6);
gr.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 45, 4, 6);
//корпус
Brush br = new SolidBrush(EntityTrackedVehicle.BodyColor);
gr.FillRectangle(br, _startPosX.Value, _startPosY.Value + 25, 75, 25);
gr.FillRectangle(br, _startPosX.Value, _startPosY.Value, 25, 25);
//окно
Brush brq = new SolidBrush(Color.AliceBlue);
gr.FillRectangle(brq, _startPosX.Value + 4, _startPosY.Value + 4, 17, 17);
//выхлопная труба
Brush brBlack = new SolidBrush(Color.Black);
gr.FillRectangle(brBlack, _startPosX.Value + 52, _startPosY.Value + 7, 6, 18);
//гусеница
Brush brDarkGray = new SolidBrush(Color.DarkGray);
gr.FillEllipse(brDarkGray, _startPosX.Value - 5, _startPosY.Value + 45, 20, 20);
gr.FillEllipse(brDarkGray, _startPosX.Value + 63, _startPosY.Value + 45, 20, 20);
gr.FillRectangle(brDarkGray, _startPosX.Value + 5, _startPosY.Value + 45, 68, 20);
gr.FillEllipse(brq, _startPosX.Value - 1, _startPosY.Value + 46, 18, 18);
gr.FillEllipse(brq, _startPosX.Value + 62, _startPosY.Value + 46, 18, 18);
gr.FillEllipse(brq, _startPosX.Value + 20, _startPosY.Value + 53, 10, 10);
gr.FillEllipse(brq, _startPosX.Value + 35, _startPosY.Value + 53, 10, 10);
gr.FillEllipse(brq, _startPosX.Value + 50, _startPosY.Value + 53, 10, 10);
gr.FillRectangle(brq, _startPosX.Value + 30, _startPosY.Value + 45, 4, 6);
gr.FillRectangle(brq, _startPosX.Value + 45, _startPosY.Value + 45, 4, 6);
}
}
}

View File

@ -0,0 +1,55 @@
using HoistingCrane.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HoistingCrane.Drawning
{
public static class ExtentionDrawningCrane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrackedVehicle? CreateDrawningTrackedVehicle(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrackedVehicle? trackedVehicle = EntityHoistingCrane.CreateEntityHoistingCrane(strs);
if (trackedVehicle != null)
{
return new DrawningHoistingCrane((EntityHoistingCrane)trackedVehicle);
}
trackedVehicle = EntityTrackedVehicle.CreateEntityTrackedVehicle(strs);
if (trackedVehicle != null)
{
return new DrawningTrackedVehicle(trackedVehicle);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTrackedMachine">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrackedVehicle drawningTrackedVehicle)
{
string[]? array = drawningTrackedVehicle?.EntityTrackedVehicle?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HoistingCrane.Drawning
{
internal class StorageEqutables
{
}
}

View File

@ -0,0 +1,68 @@
namespace HoistingCrane.Entities;
/// <summary>
/// Êëàññ-ñóùíîñòü (Ïîäúåìíûé êðàí) Êëàññ íàñëåäíèê
/// </summary>
public class EntityHoistingCrane : EntityTrackedVehicle
{
/// <summary>
/// Äîïîëíèòåëüíûé öâåò îáúåêòà
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Íàëè÷èå ïðîòèâîâåñà
/// </summary>
public bool Counterweight { get; private set; }
/// <summary>
/// Íàëè÷èå ïëàòôîðìû
/// </summary>
public bool Platform { get; private set; }
/// <summary>
/// Ìåòîä çàäà÷è ïàðàìåòðîâ
/// </summary>
/// <param name="AdditionalColor">Äîï. öâåò</param>
/// <param name="Counterweight">Ãðóç äëÿ ðàâíîâåñèÿ</param>
/// <param name="Platform">Ïëàòôîðìà íà âåðåâêå</param>
// Äîïîëíÿåò íåäîñòîþùèå ýëåìåíòû èç ðîä. êëàññà
public EntityHoistingCrane(int Speed, double Weight, Color BodyColor, Color AdditionalColor, bool Counterweight, bool Platform) : base(Speed, Weight, BodyColor)
{
this.AdditionalColor = AdditionalColor;
this.Counterweight = Counterweight;
this.Platform = Platform;
}
public void SetAdditionalColor(Color newColor)
{
AdditionalColor = newColor;
}
/// <summary>
/// Ïîëó÷óåèí ñòðîê ñî çíà÷åíèÿìè ñâîéñòâ îáúåêòà êëàññà-ñóùíîñòè
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityHoistingCrane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Counterweight.ToString(), Platform.ToString()};
}
/// <summary>
/// Ñîçäàíèå îáúåêòà èç ìàññèâà ñòðîê
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityHoistingCrane? CreateEntityHoistingCrane(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityHoistingCrane))
{
return null;
}
return new EntityHoistingCrane(Convert.ToInt32(strs[1]), Convert.ToInt32(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -0,0 +1,76 @@
namespace HoistingCrane.Entities
{
/// <summary>
/// Класс-сущность (Гусеничная машина) Родительский класс
/// </summary>
public class EntityTrackedVehicle
{
/// <summary>
/// Скорость, которой обладает объект
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес, которым обладает объект
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет объекта
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг движения
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="Speed">Скорость</param>
/// <param name="Weight">Вес</param>
/// <param name="BodyColor">Основной цвет</param>
public EntityTrackedVehicle(int Speed, double Weight, Color BodyColor)
{
this.Speed = Speed;
this.Weight = Weight;
this.BodyColor = BodyColor;
}
public void SetBodyColor(Color newBodyColor)
{
BodyColor = newBodyColor;
}
/// <summary>
/// Получуеин строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrackedVehicle), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrackedVehicle? CreateEntityTrackedVehicle(string[] strs)
{
if(strs.Length != 4 || strs[0] != nameof(EntityTrackedVehicle))
{
return null;
}
return new EntityTrackedVehicle(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}
}

View File

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

View File

@ -0,0 +1,12 @@
using System.Runtime.Serialization;
namespace HoistingCrane.Exceptions
{
[Serializable]
public class ObjectIsPresentInTheCollectionException : ApplicationException
{
public ObjectIsPresentInTheCollectionException(int objName) : base("В коллекции уже присустствует объект " + objName) { }
public ObjectIsPresentInTheCollectionException() : base() { }
public ObjectIsPresentInTheCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsPresentInTheCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

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

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace HoistingCrane.Exceptions
{
[Serializable]
public 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,39 +0,0 @@
namespace HoistingCrane
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

@ -0,0 +1,373 @@
namespace HoistingCrane
{
partial class FormCarCollection
{
/// <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();
panelCompanyTool = new Panel();
buttonCreateHoistingCrane = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
buttonGoToChek = new Button();
buttonDeleteCar = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonDeleteCollection = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTool.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTool);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(763, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(210, 524);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTool
//
panelCompanyTool.Anchor = AnchorStyles.None;
panelCompanyTool.Controls.Add(buttonSortByColor);
panelCompanyTool.Controls.Add(buttonSortByType);
panelCompanyTool.Controls.Add(buttonCreateHoistingCrane);
panelCompanyTool.Controls.Add(maskedTextBox);
panelCompanyTool.Controls.Add(buttonRefresh);
panelCompanyTool.Controls.Add(buttonGoToChek);
panelCompanyTool.Controls.Add(buttonDeleteCar);
panelCompanyTool.Location = new Point(6, 296);
panelCompanyTool.Name = "panelCompanyTool";
panelCompanyTool.Size = new Size(204, 221);
panelCompanyTool.TabIndex = 8;
//
// buttonCreateHoistingCrane
//
buttonCreateHoistingCrane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateHoistingCrane.Location = new Point(6, 3);
buttonCreateHoistingCrane.Name = "buttonCreateHoistingCrane";
buttonCreateHoistingCrane.Size = new Size(192, 22);
buttonCreateHoistingCrane.TabIndex = 0;
buttonCreateHoistingCrane.Text = "Добавить транспорт";
buttonCreateHoistingCrane.UseVisualStyleBackColor = true;
buttonCreateHoistingCrane.Click += buttonCreateHoistingCrane_Click;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(6, 31);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(192, 23);
maskedTextBox.TabIndex = 3;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 119);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(192, 27);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonGoToChek
//
buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToChek.Location = new Point(6, 89);
buttonGoToChek.Name = "buttonGoToChek";
buttonGoToChek.Size = new Size(192, 24);
buttonGoToChek.TabIndex = 6;
buttonGoToChek.Text = "Передать на тесты";
buttonGoToChek.UseVisualStyleBackColor = true;
buttonGoToChek.Click += buttonGoToChek_Click;
//
// buttonDeleteCar
//
buttonDeleteCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDeleteCar.Location = new Point(6, 60);
buttonDeleteCar.Name = "buttonDeleteCar";
buttonDeleteCar.Size = new Size(192, 23);
buttonDeleteCar.TabIndex = 4;
buttonDeleteCar.Text = "Удалить автомобиль";
buttonDeleteCar.UseVisualStyleBackColor = true;
buttonDeleteCar.Click += buttonDeleteCar_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(12, 267);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(192, 23);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonDeleteCollection);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(204, 216);
panelStorage.TabIndex = 7;
//
// buttonDeleteCollection
//
buttonDeleteCollection.Location = new Point(9, 186);
buttonDeleteCollection.Name = "buttonDeleteCollection";
buttonDeleteCollection.Size = new Size(192, 27);
buttonDeleteCollection.TabIndex = 6;
buttonDeleteCollection.Text = "Удалить коллекцию";
buttonDeleteCollection.UseVisualStyleBackColor = true;
buttonDeleteCollection.Click += buttonDeleteCollection_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(9, 101);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(192, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(9, 72);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(192, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(128, 47);
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(12, 47);
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(9, 18);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(192, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(35, 0);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(12, 238);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(192, 23);
comboBoxSelectorCompany.TabIndex = 2;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(763, 524);
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(973, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(6, 152);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(192, 27);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(6, 185);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(192, 27);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormCarCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(973, 548);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCarCollection";
Text = "FormCarCollections";
groupBoxTools.ResumeLayout(false);
panelCompanyTool.ResumeLayout(false);
panelCompanyTool.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private Button buttonCreateHoistingCrane;
private ComboBox comboBoxSelectorCompany;
private Button buttonRefresh;
private Button buttonDeleteCar;
private MaskedTextBox maskedTextBox;
private PictureBox pictureBox;
private Button buttonGoToChek;
private Panel panelStorage;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private Button buttonCreateCompany;
private Button buttonDeleteCollection;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Panel panelCompanyTool;
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,260 @@
using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning;
using HoistingCrane.Exceptions;
using Microsoft.Extensions.Logging;
namespace HoistingCrane;
public partial class FormCarCollection : Form
{
private AbstractCompany? _company;
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger logger;
public FormCarCollection(ILogger<FormCarCollection> logger)
{
InitializeComponent();
_storageCollection = new();
panelCompanyTool.Enabled = false;
this.logger = logger;
}
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTool.Enabled = false;
}
private void buttonCreateHoistingCrane_Click(object sender, EventArgs e)
{
FormCarConfig form = new();
form.Show();
form.AddEvent(SetCrane);
}
private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle)
{
if (_company == null || drawningTrackedVehicle == null) return;
try
{
if (_company + drawningTrackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name);
}
else
{
MessageBox.Show("Не удалось добавить объект");
logger.LogInformation("Не удалось добавить кран {crane} в коллекцию", drawningTrackedVehicle.GetType().Name);
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Ошибка переполнения коллекции");
logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void buttonDeleteCar_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBox.Text);
if ((_company - pos) != null)
{
MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show();
logger.LogInformation("Удаление авто по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
logger.LogInformation("Не удалось удалить авто из коллекции по индексу {pos}", pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (_company == null) return;
pictureBox.Image = _company.Show();
}
private void buttonGoToChek_Click(object sender, EventArgs e)
{
if (_company == null) return;
DrawningTrackedVehicle? car = null;
int count = 100;
while (car == null)
{
car = _company.GetRandomObject();
count--;
if (count <= 0) break;
}
if (car == null) return;
FormHoistingCrane form = new()
{
SetCar = car
};
form.ShowDialog();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
private void buttonDeleteCollection_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
return;
if (listBoxCollection.SelectedItem != null)
{
logger.LogInformation("Коллекция '{name}' успешно удалена", listBoxCollection.SelectedItem.ToString());
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
};
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Garage(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTool.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName.ToString());
}
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);
RerfreshListBoxItems();
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);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
compareCars(new DrawningCraneCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
compareCars(new DrawningCraneCompareByColor());
}
private void compareCars(IComparer<DrawningTrackedVehicle?> 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, 5</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>130, 5</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>270, 5</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -0,0 +1,358 @@
namespace HoistingCrane
{
partial class FormCarConfig
{
/// <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();
panelColorPurple = new Panel();
panelColorYellow = new Panel();
panelColorGray = new Panel();
panelColorGreen = new Panel();
panelColorWhite = new Panel();
panelColorBlue = new Panel();
panelColorBlack = new Panel();
panelColorRed = new Panel();
checkBoxPlatform = new CheckBox();
checkBoxCounterweight = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
panel = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxPlatform);
groupBoxConfig.Controls.Add(checkBoxCounterweight);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(514, 207);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelColorPurple);
groupBoxColors.Controls.Add(panelColorYellow);
groupBoxColors.Controls.Add(panelColorGray);
groupBoxColors.Controls.Add(panelColorGreen);
groupBoxColors.Controls.Add(panelColorWhite);
groupBoxColors.Controls.Add(panelColorBlue);
groupBoxColors.Controls.Add(panelColorBlack);
groupBoxColors.Controls.Add(panelColorRed);
groupBoxColors.Location = new Point(283, 26);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(210, 114);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвет";
//
// panelColorPurple
//
panelColorPurple.BackColor = Color.Purple;
panelColorPurple.Location = new Point(168, 68);
panelColorPurple.Name = "panelColorPurple";
panelColorPurple.Size = new Size(36, 35);
panelColorPurple.TabIndex = 7;
//
// panelColorYellow
//
panelColorYellow.BackColor = Color.Yellow;
panelColorYellow.Location = new Point(168, 22);
panelColorYellow.Name = "panelColorYellow";
panelColorYellow.Size = new Size(36, 35);
panelColorYellow.TabIndex = 3;
//
// panelColorGray
//
panelColorGray.BackColor = Color.Gray;
panelColorGray.Location = new Point(114, 68);
panelColorGray.Name = "panelColorGray";
panelColorGray.Size = new Size(36, 35);
panelColorGray.TabIndex = 6;
//
// panelColorGreen
//
panelColorGreen.BackColor = Color.Green;
panelColorGreen.Location = new Point(114, 22);
panelColorGreen.Name = "panelColorGreen";
panelColorGreen.Size = new Size(36, 35);
panelColorGreen.TabIndex = 2;
//
// panelColorWhite
//
panelColorWhite.BackColor = Color.White;
panelColorWhite.Location = new Point(61, 68);
panelColorWhite.Name = "panelColorWhite";
panelColorWhite.Size = new Size(36, 35);
panelColorWhite.TabIndex = 5;
//
// panelColorBlue
//
panelColorBlue.BackColor = Color.Blue;
panelColorBlue.Location = new Point(61, 22);
panelColorBlue.Name = "panelColorBlue";
panelColorBlue.Size = new Size(36, 35);
panelColorBlue.TabIndex = 1;
//
// panelColorBlack
//
panelColorBlack.BackColor = Color.Black;
panelColorBlack.Location = new Point(6, 68);
panelColorBlack.Name = "panelColorBlack";
panelColorBlack.Size = new Size(36, 35);
panelColorBlack.TabIndex = 4;
//
// panelColorRed
//
panelColorRed.BackColor = Color.Red;
panelColorRed.Location = new Point(6, 22);
panelColorRed.Name = "panelColorRed";
panelColorRed.Size = new Size(36, 35);
panelColorRed.TabIndex = 0;
panelColorRed.MouseDown += panel_MouseDown;
//
// checkBoxPlatform
//
checkBoxPlatform.AutoSize = true;
checkBoxPlatform.Location = new Point(6, 135);
checkBoxPlatform.Name = "checkBoxPlatform";
checkBoxPlatform.Size = new Size(144, 19);
checkBoxPlatform.TabIndex = 7;
checkBoxPlatform.Text = "Наличие платформы";
checkBoxPlatform.UseVisualStyleBackColor = true;
//
// checkBoxCounterweight
//
checkBoxCounterweight.AutoSize = true;
checkBoxCounterweight.Location = new Point(6, 110);
checkBoxCounterweight.Name = "checkBoxCounterweight";
checkBoxCounterweight.Size = new Size(148, 19);
checkBoxCounterweight.TabIndex = 6;
checkBoxCounterweight.Text = "Наличие противовеса";
checkBoxCounterweight.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(72, 66);
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(120, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(72, 31);
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(120, 23);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 68);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(26, 15);
labelWeight.TabIndex = 3;
labelWeight.Text = "Вес";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 33);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(59, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(139, 173);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(114, 31);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(6, 172);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(114, 31);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// panel
//
panel.AllowDrop = true;
panel.Controls.Add(labelAdditionalColor);
panel.Controls.Add(labelBodyColor);
panel.Controls.Add(pictureBoxObject);
panel.Location = new Point(545, 0);
panel.Name = "panel";
panel.Size = new Size(216, 167);
panel.TabIndex = 1;
panel.DragDrop += panel_DragDrop;
panel.DragEnter += panel_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(116, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(97, 31);
labelAdditionalColor.TabIndex = 10;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(3, 9);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(97, 31);
labelBodyColor.TabIndex = 9;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 43);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(210, 121);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(545, 172);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(91, 34);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(670, 173);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(91, 35);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormCarConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(777, 207);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panel);
Controls.Add(groupBoxConfig);
Name = "FormCarConfig";
Text = "FormCarConfig";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxPlatform;
private CheckBox checkBoxCounterweight;
private GroupBox groupBoxColors;
private Panel panelColorPurple;
private Panel panelColorYellow;
private Panel panelColorGray;
private Panel panelColorGreen;
private Panel panelColorWhite;
private Panel panelColorBlue;
private Panel panelColorBlack;
private Panel panelColorRed;
private Panel panel;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@ -0,0 +1,185 @@
using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning;
using HoistingCrane.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;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace HoistingCrane
{
public partial class FormCarConfig : Form
{
private DrawningTrackedVehicle? drawningTrackedVehicle;
private event Action<DrawningTrackedVehicle>? _carDelegate;
public FormCarConfig()
{
InitializeComponent();
panelColorRed.MouseDown += panel_MouseDown;
panelColorBlue.MouseDown += panel_MouseDown;
panelColorGreen.MouseDown += panel_MouseDown;
panelColorYellow.MouseDown += panel_MouseDown;
panelColorBlack.MouseDown += panel_MouseDown;
panelColorWhite.MouseDown += panel_MouseDown;
panelColorGray.MouseDown += panel_MouseDown;
panelColorPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка метода к событию
/// </summary>
/// <param name="carDelegate"></param>
public void AddEvent(Action<DrawningTrackedVehicle> carDelegate)
{
if (carDelegate == null)
{
_carDelegate = carDelegate;
}
else
{
_carDelegate += carDelegate;
}
}
/// <summary>
/// Отрисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
drawningTrackedVehicle?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
drawningTrackedVehicle?.SetPosition(25, 25);
drawningTrackedVehicle?.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 panel_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 panel_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
drawningTrackedVehicle = new DrawningTrackedVehicle((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
drawningTrackedVehicle = new DrawningHoistingCrane((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxCounterweight.Checked,
checkBoxPlatform.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 ?? Color.White, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (drawningTrackedVehicle != null)
{
_carDelegate?.Invoke(drawningTrackedVehicle);
Close();
}
}
/// <summary>
/// Прорисовка основным цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (drawningTrackedVehicle == null)
return;
drawningTrackedVehicle.EntityTrackedVehicle?.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
/// <summary>
/// Передача основного цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Прорисовка основным цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (drawningTrackedVehicle?.EntityTrackedVehicle is EntityHoistingCrane entityHoistingCrane)
{
entityHoistingCrane.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача дополнительного цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (drawningTrackedVehicle is DrawningHoistingCrane)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}
}

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,138 @@
using Microsoft.VisualBasic.ApplicationServices;
using System.ComponentModel.Design;
using System.Resources;
namespace HoistingCrane
{
partial class FormHoistingCrane
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
pictureBoxHoistingCrane = new PictureBox();
ButtonLeft = new Button();
ButtonRight = new Button();
ButtonUp = new Button();
ButtonDown = new Button();
comboStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxHoistingCrane).BeginInit();
SuspendLayout();
//
// pictureBoxHoistingCrane
//
pictureBoxHoistingCrane.Dock = DockStyle.Fill;
pictureBoxHoistingCrane.Location = new Point(0, 0);
pictureBoxHoistingCrane.Name = "pictureBoxHoistingCrane";
pictureBoxHoistingCrane.Size = new Size(818, 515);
pictureBoxHoistingCrane.TabIndex = 0;
pictureBoxHoistingCrane.TabStop = false;
//
// ButtonLeft
//
ButtonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonLeft.BackgroundImage = Properties.Resources.left_arrow;
ButtonLeft.BackgroundImageLayout = ImageLayout.Stretch;
ButtonLeft.Location = new Point(642, 475);
ButtonLeft.Name = "ButtonLeft";
ButtonLeft.Size = new Size(40, 40);
ButtonLeft.TabIndex = 2;
ButtonLeft.UseVisualStyleBackColor = true;
ButtonLeft.Click += ButtonMove_Click;
//
// ButtonRight
//
ButtonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonRight.BackgroundImage = Properties.Resources.right_arrow;
ButtonRight.BackgroundImageLayout = ImageLayout.Stretch;
ButtonRight.Location = new Point(734, 475);
ButtonRight.Name = "ButtonRight";
ButtonRight.Size = new Size(40, 40);
ButtonRight.TabIndex = 3;
ButtonRight.UseVisualStyleBackColor = true;
ButtonRight.Click += ButtonMove_Click;
//
// ButtonUp
//
ButtonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonUp.BackgroundImage = Properties.Resources.up_arrow;
ButtonUp.BackgroundImageLayout = ImageLayout.Stretch;
ButtonUp.Location = new Point(688, 429);
ButtonUp.Name = "ButtonUp";
ButtonUp.Size = new Size(40, 40);
ButtonUp.TabIndex = 4;
ButtonUp.UseVisualStyleBackColor = true;
ButtonUp.Click += ButtonMove_Click;
//
// ButtonDown
//
ButtonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonDown.BackgroundImage = Properties.Resources.arrow_down_sign_to_navigate;
ButtonDown.BackgroundImageLayout = ImageLayout.Stretch;
ButtonDown.Location = new Point(688, 475);
ButtonDown.Name = "ButtonDown";
ButtonDown.Size = new Size(40, 40);
ButtonDown.TabIndex = 5;
ButtonDown.UseVisualStyleBackColor = true;
ButtonDown.Click += ButtonMove_Click;
//
// comboStrategy
//
comboStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboStrategy.FormattingEnabled = true;
comboStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboStrategy.Location = new Point(697, 42);
comboStrategy.Name = "comboStrategy";
comboStrategy.Size = new Size(121, 23);
comboStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(743, 71);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormHoistingCrane
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(818, 515);
Controls.Add(buttonStrategyStep);
Controls.Add(comboStrategy);
Controls.Add(ButtonDown);
Controls.Add(ButtonUp);
Controls.Add(ButtonRight);
Controls.Add(ButtonLeft);
Controls.Add(pictureBoxHoistingCrane);
Name = "FormHoistingCrane";
Text = "Подъемный кран";
((System.ComponentModel.ISupportInitialize)pictureBoxHoistingCrane).EndInit();
ResumeLayout(false);
}
// #endregion
private PictureBox pictureBoxHoistingCrane;
private Button ButtonLeft;
private Button ButtonRight;
private Button ButtonUp;
private Button ButtonDown;
private ComboBox comboStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,102 @@
using HoistingCrane.Drawning;
using HoistingCrane.MovementStrategy;
namespace HoistingCrane
{
public partial class FormHoistingCrane : Form
{
private DrawningTrackedVehicle? _drawning;
private AbstractStrategy? _abstractStrategy;
public FormHoistingCrane()
{
InitializeComponent();
_abstractStrategy = null;
}
public DrawningTrackedVehicle? SetCar
{
set
{
_drawning = value;
_drawning?.SetPictureSize(pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
comboStrategy.Enabled = true;
Draw();
}
}
private void Draw()
{
Bitmap bmp = new(pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawning?.DrawTransport(gr);
pictureBoxHoistingCrane.Image = bmp;
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawning == null) { return; }
String name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "ButtonUp":
result = _drawning.MoveTransport(DirectionType.Up);
break;
case "ButtonDown":
result = _drawning.MoveTransport(DirectionType.Down);
break;
case "ButtonRight":
result = _drawning.MoveTransport(DirectionType.Right);
break;
case "ButtonLeft":
result = _drawning.MoveTransport(DirectionType.Left);
break;
}
if (result)
{
Draw();
}
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawning == null)
{
return;
}
if (comboStrategy.Enabled)
{
_abstractStrategy = comboStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new MoveableCar(_drawning), pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == StrategyStatus.Finish)
{
comboStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

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

View File

@ -8,4 +8,35 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" 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="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project> </Project>

View File

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

View File

@ -0,0 +1,24 @@
namespace HoistingCrane.MovementStrategy
{
public interface IMoveableObjects
{
/// <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,52 @@
using System.Configuration;
namespace HoistingCrane.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())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,52 @@
namespace HoistingCrane.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,62 @@
using HoistingCrane.Drawning;
namespace HoistingCrane.MovementStrategy
{
public class MoveableCar : IMoveableObjects
{
/// <summary>
/// Поле-объект класса DrawningAirplane или его наследника
/// </summary>
private readonly DrawningTrackedVehicle? drawningTrackedVehicle = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="airplane">Объект класса DrawningAirplane</param>
public MoveableCar(DrawningTrackedVehicle drawningTrackedVehicle)
{
this.drawningTrackedVehicle = drawningTrackedVehicle;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (drawningTrackedVehicle == null || drawningTrackedVehicle.EntityTrackedVehicle == null || !drawningTrackedVehicle.GetPosX.HasValue || !drawningTrackedVehicle.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(drawningTrackedVehicle.GetPosX.Value, drawningTrackedVehicle.GetPosY.Value, drawningTrackedVehicle.GetWidth, drawningTrackedVehicle.GetHeight);
}
}
public int GetStep => (int)(drawningTrackedVehicle?.EntityTrackedVehicle?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (drawningTrackedVehicle == null || drawningTrackedVehicle.EntityTrackedVehicle == null)
{
return false;
}
return drawningTrackedVehicle.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}
}

View File

@ -0,0 +1,24 @@
namespace HoistingCrane.MovementStrategy
{
public enum MovementDirection
{
//Перечислим основные траектории движния нашего автомобиля. Сразу же зададим значения.
/// <summary>
/// Вверх1
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,70 @@
namespace HoistingCrane.MovementStrategy
{
public class ObjectParameters
{
/// <summary>
/// Начальная координата х
/// </summary>
private readonly int _x;
/// <summary>
/// Начальная координата y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <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">Координата по х</param>
/// <param name="_y">Координата по у</param>
/// <param name="_width">Ширина объекта</param>
/// <param name="_height">Высота объекта</param>
public ObjectParameters(int _x, int _y, int _width, int _height)
{
this._x = _x;
this._y = _y;
this._width = _width;
this._height = _height;
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HoistingCrane.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("HoistingCrane.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 arrow_down_sign_to_navigate {
get {
object obj = ResourceManager.GetObject("arrow-down-sign-to-navigate", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left_arrow {
get {
object obj = ResourceManager.GetObject("left-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right_arrow {
get {
object obj = ResourceManager.GetObject("right-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up_arrow {
get {
object obj = ResourceManager.GetObject("up-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,17 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.log"
}
}
],
"Properties": {
"Application": "Sample"
}
}
}