pibd-12 Tangatarov.I.A. LabWork06 Base #21

Closed
sqdselo wants to merge 33 commits from LabWork06 into LabWork05
18 changed files with 944 additions and 467 deletions

View File

@ -1,55 +1,78 @@
using HoistingCrane.Drawning; using HoistingCrane.CollectionGenericObjects;
namespace HoistingCrane.CollectionGenericObjects using HoistingCrane.Drawning;
{
public abstract class AbstractCompany public abstract class AbstractCompany
{ {
/// <summary> /// <summary>
/// Ширина ячейки гаража /// Размер места (ширина)
/// </summary> /// </summary>
protected readonly int _placeSizeWidth = 150; protected readonly int _placeSizeWidth = 180;
/// <summary> /// <summary>
/// Высота ячейки гаража /// Размер места (высота)
/// </summary> /// </summary>
protected readonly int _placeSizeHeight = 90; protected readonly int _placeSizeHeight = 100;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
protected readonly int pictureWidth; protected readonly int _pictureWidth;
/// <summary> /// <summary>
/// Высота окна /// Высота окна
/// </summary> /// </summary>
protected readonly int pictureHeight; protected readonly int _pictureHeight;
/// <summary> /// <summary>
/// Коллекция автомобилей /// Коллекция военных кораблей
/// </summary> /// </summary>
protected ICollectionGenericObjects<DrawningTrackedVehicle>? arr = null; protected ICollectionGenericObjects<DrawningTrackedVehicle>? _collection = null;
/// <summary> /// <summary>
/// Максимальное количество гаражей /// Вычисление максимального количества элементов, которые можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция военных кораблей</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> collection)
{ {
get _pictureWidth = picWidth;
{ _pictureHeight = picHeight;
return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-3; _collection = collection;
} _collection.MaxCount = GetMaxCount;
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array)
{
pictureWidth = picWidth;
pictureHeight = picHeight;
arr = array;
arr.SetMaxCount = GetMaxCount;
} }
public static int operator +(AbstractCompany company, DrawningTrackedVehicle car) /// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="warship">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedVehicle crane)
{ {
return company.arr?.Insert(car) ?? -1; return company._collection.Insert(crane);
} }
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
{ {
return company.arr?.Remove(position); return company._collection.Remove(position);
} }
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTrackedVehicle? GetRandomObject() public DrawningTrackedVehicle? GetRandomObject()
{ {
Random rnd = new(); Random rnd = new();
@ -65,15 +88,19 @@ namespace HoistingCrane.CollectionGenericObjects
Bitmap bitmap = new(pictureWidth, pictureHeight); Bitmap bitmap = new(pictureWidth, pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackgound(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (arr?.Count ?? 0); i++) for (int i = 0; i < (arr?.Count ?? 0); ++i)
{
try
{ {
DrawningTrackedVehicle? obj = arr?.Get(i); DrawningTrackedVehicle? obj = arr?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>
@ -85,4 +112,3 @@ namespace HoistingCrane.CollectionGenericObjects
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
} }
}

View File

@ -1,5 +1,4 @@
using System; namespace HoistingCrane.CollectionGenericObjects
namespace HoistingCrane.CollectionGenericObjects
{ {
public enum CollectionType public enum CollectionType
{ {

View File

@ -8,8 +8,8 @@ namespace HoistingCrane.CollectionGenericObjects
} }
protected override void DrawBackgound(Graphics g) protected override void DrawBackgound(Graphics g)
{ {
int width = pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 3); Pen pen = new(Color.Black, 3);
for (int i = 0; i < width; i++) for (int i = 0; i < width; i++)
{ {
@ -22,18 +22,18 @@ namespace HoistingCrane.CollectionGenericObjects
} }
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
{ {
int countWidth = pictureWidth / _placeSizeWidth; int countWidth = _pictureWidth / _placeSizeWidth;
int countHeight = pictureHeight / _placeSizeHeight; int countHeight = _pictureHeight / _placeSizeHeight;
int currentPosWidth = countWidth - 1; int currentPosWidth = countWidth - 1;
int currentPosHeight = countHeight - 1; int currentPosHeight = countHeight - 1;
for (int i = 0; i < (arr?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (arr?.Get(i) != null) if (_collection?.Get(i) != null)
{ {
arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); _collection?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15);
} }
if (currentPosWidth > 0) if (currentPosWidth > 0)
@ -47,7 +47,6 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
break; break;
} }
} }
} }

View File

@ -1,40 +1,55 @@
namespace HoistingCrane.CollectionGenericObjects using HoistingCrane.CollectionGenericObjects;
{
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Кол-во объектов в коллекции /// Количество объектов в коллекции
/// </summary> /// </summary>
int Count { get; } int Count { get; }
/// <summary> /// <summary>
/// Максимальное количество элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление элемента в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj">Добавляемый объект</param>
/// <returns></returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj);
/// <summary> /// <summary>
/// Добавление элемента в коллекцию на определенную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position"></param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position);
/// <summary> /// <summary>
/// Удаление элемента из коллекции по его позиции /// Удаление объекта из коллекции с конкретной позиции
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position); T? Remove(int position);
/// <summary> /// <summary>
/// Получение объекта коллекции /// Получение объекта по позиции
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
}
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
} }

View File

@ -1,32 +1,28 @@
using System; using HoistingCrane.Drawning;
using System.CodeDom.Compiler; using HoistingCrane.Exceptions;
using System.Windows.Forms.VisualStyles; namespace HoistingCrane.CollectionGenericObjects;
namespace HoistingCrane.CollectionGenericObjects
{
public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class
{ {
/// <summary> /// <summary>
/// Список объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
readonly List<T> list; private readonly List<T?> _collection;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
list = new List<T>();
}
/// <summary> /// <summary>
/// Максимально допустимое число объектов в списке /// Максимально допустимое число объектов в списке
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public int Count
public int Count => _collection.Count;
public int MaxCount
{ {
get { return list.Count; } get
{
return Count;
} }
public int SetMaxCount
{
set set
{ {
if (value > 0) if (value > 0)
@ -36,39 +32,55 @@ namespace HoistingCrane.CollectionGenericObjects
} }
} }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position) public T? Get(int position)
{ {
if (position >= Count || position < 0) return null; // Проверка позиции
return list[position]; if (position >= Count || position < 0)
{
return null;
} }
return _collection[position];
}
public int Insert(T obj) public int Insert(T obj)
{ {
// Проверка, что не превышено максимальное количество элементов
if (Count == _maxCount) if (Count == _maxCount)
{ {
return -1; return -1;
} }
list.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
list.Insert(position, obj);
return position;
}
public T? Remove(int position) public T? Remove(int position)
{ {
if(position >= 0 && position < list.Count) if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position);
{
T? temp = list[position]; T? temp = list[position];
list.RemoveAt(position); list.RemoveAt(position);
return temp; return temp;
} }
return null;
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

@ -1,7 +1,7 @@
using System; namespace HoistingCrane.CollectionGenericObjects;
namespace HoistingCrane.CollectionGenericObjects
{ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public class MassivGenericObjects<T> : ICollectionGenericObjects<T> where T : class where T : class
{ {
private T?[] arr; private T?[] arr;
public MassivGenericObjects() public MassivGenericObjects()
@ -12,78 +12,143 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
get { return arr.Length; } get { return arr.Length; }
} }
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
{ {
if (arr.Length > 0) if (_collection.Length > 0)
{ {
Array.Resize(ref arr, value); Array.Resize(ref _collection, value);
} }
else else
{ {
arr = new T?[value]; _collection = new T?[value];
}
}
}
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];
=========
>>>>>>>>> Temporary merge branch 2
}
}
public void CollectionSort(IComparer<T> comparer)
{
T[] notNullArr = arr.OfType<T>().ToArray();
Array.Sort(notNullArr, comparer);
Array.Copy(notNullArr, 0, arr, 0, notNullArr.Length);
}
}
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < arr.Length) // Проверка позиции
if (position < 0 || position >= Count)
{ {
return arr[position];
}
return null; return null;
} }
return _collection[position];
}
public int Insert(T obj) public int Insert(T obj)
{ {
// Вставка в свободное место набора
return Insert(obj, 0); return Insert(obj, 0);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// Проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return -1; return -1;
} }
// Проверка, что элемент массива по этой позиции пустой
int copyPos = position - 1; if (_collection[position] == null)
while (position < Count)
{ {
if (arr[position] == null) _collection[position] = obj;
{
arr[position] = obj;
return position; return position;
} }
position++; //Свободное место после этой позиции
} for (int i = position + 1; i < Count; i++)
while (copyPos > 0)
{ {
if (arr[copyPos] == null) if (_collection[i] == null)
{ {
arr[copyPos] = obj; _collection[i] = obj;
return copyPos; return i;
}
}
//Свободное место до этой позиции
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
} }
copyPos--;
} }
return -1; return -1;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= 0 && position < Count) // Проверка позиции и наличия объекта
if (position < 0 || position >= Count || _collection[position] == null)
{ {
T? temp = arr[position];
arr[position] = null;
return temp;
}
return null; return null;
} }
// Удаление объекта из массива
T? obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
} }
} }

View File

@ -1,48 +1,75 @@
using System; using HoistingCrane.Drawning;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects;
{
public class StorageCollection<T> where T : class public class StorageCollection<T>
where T : DrawningTrackedVehicle
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> dict; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => dict.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
dict = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">Тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (dict.ContainsKey(name)) return; // Проверка, что name не пустой и нет в словаре записи с таким ключом
if (collectionType == CollectionType.None) return; if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None)
else if (collectionType == CollectionType.Massive) {
dict[name] = new MassivGenericObjects<T>(); return;
else if (collectionType == CollectionType.List)
dict[name] = new ListGenericObjects<T>();
} }
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
}
if (collectionType == CollectionType.List)
{
_storages[name] = new ListGenericObjects<T>();
}
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (Keys.Contains(name)) if (_storages.ContainsKey(name))
{ {
dict.Remove(name); _storages.Remove(name);
} }
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
/// </summary> /// </summary>
@ -52,11 +79,140 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
get get
{ {
if (dict.ContainsKey(name)) if (_storages.ContainsKey(name))
return dict[name]; {
return _storages[name];
}
else
{
return null; return null;
} }
} }
}
/// <summary>
/// Сохранение информации по военным кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
} }
} }
}
return true;
}
/// <summary>
/// Загрузка информации по военным кораблям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader read = File.OpenText(filename))
{
string str = read.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = read.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedVehicle() is T warship)
{
if (collection.Insert(warship) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -1,5 +1,6 @@
using HoistingCrane.Entities; using HoistingCrane.Entities;
using System.Configuration; using System.Configuration;
using System.Reflection.PortableExecutable;
namespace HoistingCrane.Drawning; namespace HoistingCrane.Drawning;
@ -39,6 +40,15 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle
EntityTrackedVehicle = new EntityHoistingCrane(speed, weight, bodyColor, additionalColor, counterweight, platform); 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>
/// Метод отрисовки объекта /// Метод отрисовки объекта
/// </summary> /// </summary>
@ -49,7 +59,6 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle
{ {
return; return;
} }
base.DrawTransport(gr); base.DrawTransport(gr);
Brush b = new SolidBrush(EntityHoistingCrane.AdditionalColor); Brush b = new SolidBrush(EntityHoistingCrane.AdditionalColor);
Pen pen = new Pen(EntityHoistingCrane.AdditionalColor); Pen pen = new Pen(EntityHoistingCrane.AdditionalColor);

View File

@ -1,4 +1,5 @@
using HoistingCrane.Entities; using HoistingCrane.Entities;
using System.Reflection.PortableExecutable;
namespace HoistingCrane.Drawning namespace HoistingCrane.Drawning
{ {
@ -80,6 +81,15 @@ namespace HoistingCrane.Drawning
_startPosY = 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>
/// Метод отрисовки игрового поля /// Метод отрисовки игрового поля

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

@ -30,7 +30,7 @@ public class EntityHoistingCrane : EntityTrackedVehicle
// Äîïîëíÿåò íåäîñòîþùèå ýëåìåíòû èç ðîä. êëàññà // Äîïîëíÿåò íåäîñòîþùèå ýëåìåíòû èç ðîä. êëàññà
public EntityHoistingCrane(int Speed, int Weight, Color BodyColor, Color AdditionalColor, bool Counterweight, bool Platform) : base(Speed, Weight, BodyColor) public EntityHoistingCrane(int Speed, double Weight, Color BodyColor, Color AdditionalColor, bool Counterweight, bool Platform) : base(Speed, Weight, BodyColor)
{ {
this.AdditionalColor = AdditionalColor; this.AdditionalColor = AdditionalColor;
this.Counterweight = Counterweight; this.Counterweight = Counterweight;
@ -42,4 +42,27 @@ public class EntityHoistingCrane : EntityTrackedVehicle
{ {
AdditionalColor = 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

@ -49,5 +49,28 @@
BodyColor = 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

@ -29,6 +29,12 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTool = new Panel();
buttonCreateHoistingCrane = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
buttonGoToChek = new Button();
buttonDeleteCar = new Button();
buttonCreateCompany = new Button(); buttonCreateCompany = new Button();
panelStorage = new Panel(); panelStorage = new Panel();
buttonDeleteCollection = new Button(); buttonDeleteCollection = new Button();
@ -38,18 +44,21 @@
radioButtonMassive = new RadioButton(); radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
buttonGoToChek = new Button();
buttonRefresh = new Button();
buttonDeleteCar = new Button();
maskedTextBox = new MaskedTextBox();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
buttonCreateHoistingCrane = new Button();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
panelCompanyTool = new Panel(); 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(); groupBoxTools.SuspendLayout();
panelCompanyTool.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTool.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -59,16 +68,84 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(763, 0); groupBoxTools.Location = new Point(763, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(210, 509); groupBoxTools.Size = new Size(210, 524);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; 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
// //
buttonCreateCompany.Location = new Point(12, 295); buttonCreateCompany.Location = new Point(12, 267);
buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(192, 23); buttonCreateCompany.Size = new Size(192, 23);
buttonCreateCompany.TabIndex = 7; buttonCreateCompany.TabIndex = 7;
@ -88,12 +165,12 @@
panelStorage.Dock = DockStyle.Top; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19); panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(204, 229); panelStorage.Size = new Size(204, 216);
panelStorage.TabIndex = 7; panelStorage.TabIndex = 7;
// //
// buttonDeleteCollection // buttonDeleteCollection
// //
buttonDeleteCollection.Location = new Point(9, 199); buttonDeleteCollection.Location = new Point(9, 186);
buttonDeleteCollection.Name = "buttonDeleteCollection"; buttonDeleteCollection.Name = "buttonDeleteCollection";
buttonDeleteCollection.Size = new Size(192, 27); buttonDeleteCollection.Size = new Size(192, 27);
buttonDeleteCollection.TabIndex = 6; buttonDeleteCollection.TabIndex = 6;
@ -105,14 +182,14 @@
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15; listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(9, 118); listBoxCollection.Location = new Point(9, 101);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(192, 79); listBoxCollection.Size = new Size(192, 79);
listBoxCollection.TabIndex = 5; listBoxCollection.TabIndex = 5;
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(9, 81); buttonCollectionAdd.Location = new Point(9, 72);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(192, 23); buttonCollectionAdd.Size = new Size(192, 23);
buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.TabIndex = 4;
@ -123,9 +200,9 @@
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(128, 56); radioButtonList.Location = new Point(128, 47);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(67, 19); radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3; radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true; radioButtonList.TabStop = true;
radioButtonList.Text = "Список"; radioButtonList.Text = "Список";
@ -134,9 +211,9 @@
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(18, 56); radioButtonMassive.Location = new Point(12, 47);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(69, 19); radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2; radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
@ -154,113 +231,92 @@
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(35, 0); labelCollectionName.Location = new Point(35, 0);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(135, 15); labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:"; labelCollectionName.Text = "Название коллекции:";
// //
// buttonGoToChek
//
buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToChek.Location = new Point(9, 99);
buttonGoToChek.Name = "buttonGoToChek";
buttonGoToChek.Size = new Size(192, 24);
buttonGoToChek.TabIndex = 6;
buttonGoToChek.Text = "Передать на тесты";
buttonGoToChek.UseVisualStyleBackColor = true;
buttonGoToChek.Click += buttonGoToChek_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(9, 129);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(192, 27);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonDeleteCar
//
buttonDeleteCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDeleteCar.Location = new Point(9, 70);
buttonDeleteCar.Name = "buttonDeleteCar";
buttonDeleteCar.Size = new Size(192, 23);
buttonDeleteCar.TabIndex = 4;
buttonDeleteCar.Text = "Удалить автомобиль";
buttonDeleteCar.UseVisualStyleBackColor = true;
buttonDeleteCar.Click += buttonDeleteCar_Click;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(9, 41);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(192, 23);
maskedTextBox.TabIndex = 3;
//
// comboBoxSelectorCompany // comboBoxSelectorCompany
// //
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(12, 266); comboBoxSelectorCompany.Location = new Point(12, 238);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(192, 23); comboBoxSelectorCompany.Size = new Size(192, 23);
comboBoxSelectorCompany.TabIndex = 2; comboBoxSelectorCompany.TabIndex = 2;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged; comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
// //
// buttonCreateHoistingCrane
//
buttonCreateHoistingCrane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateHoistingCrane.Location = new Point(9, 13);
buttonCreateHoistingCrane.Name = "buttonCreateHoistingCrane";
buttonCreateHoistingCrane.Size = new Size(192, 22);
buttonCreateHoistingCrane.TabIndex = 0;
buttonCreateHoistingCrane.Text = "Добавить транспорт";
buttonCreateHoistingCrane.UseVisualStyleBackColor = true;
buttonCreateHoistingCrane.Click += buttonCreateHoistingCrane_Click;
//
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(763, 509); pictureBox.Size = new Size(763, 524);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// panelCompanyTool // menuStrip
// //
panelCompanyTool.Anchor = AnchorStyles.None; menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
panelCompanyTool.Controls.Add(buttonCreateHoistingCrane); menuStrip.Location = new Point(0, 0);
panelCompanyTool.Controls.Add(maskedTextBox); menuStrip.Name = "menuStrip";
panelCompanyTool.Controls.Add(buttonRefresh); menuStrip.Size = new Size(973, 24);
panelCompanyTool.Controls.Add(buttonGoToChek); menuStrip.TabIndex = 2;
panelCompanyTool.Controls.Add(buttonDeleteCar); menuStrip.Text = "menuStrip1";
panelCompanyTool.Location = new Point(6, 324); //
panelCompanyTool.Name = "panelCompanyTool"; // файлToolStripMenuItem
panelCompanyTool.Size = new Size(204, 185); //
panelCompanyTool.TabIndex = 8; файл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";
// //
// FormCarCollection // FormCarCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(973, 509); ClientSize = new Size(973, 548);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCarCollection"; Name = "FormCarCollection";
Text = "FormCarCollections"; Text = "FormCarCollections";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
panelCompanyTool.ResumeLayout(false);
panelCompanyTool.PerformLayout();
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
panelCompanyTool.ResumeLayout(false); menuStrip.ResumeLayout(false);
panelCompanyTool.PerformLayout(); menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -283,5 +339,13 @@
private ListBox listBoxCollection; private ListBox listBoxCollection;
private Button buttonCollectionAdd; private Button buttonCollectionAdd;
private Panel panelCompanyTool; 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

@ -1,15 +1,6 @@
using HoistingCrane.CollectionGenericObjects; using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System; using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HoistingCrane namespace HoistingCrane
{ {
public partial class FormCarCollection : Form public partial class FormCarCollection : Form
@ -17,6 +8,10 @@ namespace HoistingCrane
private AbstractCompany? _company; private AbstractCompany? _company;
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection; private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger logger;
public FormCarCollection() public FormCarCollection()
{ {
InitializeComponent(); InitializeComponent();
@ -27,55 +22,15 @@ namespace HoistingCrane
{ {
panelCompanyTool.Enabled = false; panelCompanyTool.Enabled = false;
} }
private void CreateObject(string type)
{
DrawningTrackedVehicle drawning;
if (_company == null) return;
Random rand = new();
switch (type)
{
case nameof(DrawningHoistingCrane):
drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand), GetColor(rand), true, true);
break;
case nameof(DrawningTrackedVehicle):
drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand));
break;
default:
return;
}
if ((_company + drawning) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void buttonCreateHoistingCrane_Click(object sender, EventArgs e) private void buttonCreateHoistingCrane_Click(object sender, EventArgs e)
{ {
FormCarConfig form = new(); FormCarConfig form = new();
form.Show(); form.Show();
form.AddEvent(SetCar); form.AddEvent(SetCrane);
} }
private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle)
{ {
if (_company == null || drawningTrackedVehicle == null) if (_company == null || drawningTrackedVehicle == null) return;
{
return;
}
if (_company + drawningTrackedVehicle != -1) if (_company + drawningTrackedVehicle != -1)
{ {
@ -90,7 +45,6 @@ namespace HoistingCrane
private void buttonDeleteCar_Click(object sender, EventArgs e) private void buttonDeleteCar_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
return; return;
@ -109,6 +63,7 @@ namespace HoistingCrane
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
private void buttonRefresh_Click(object sender, EventArgs e) private void buttonRefresh_Click(object sender, EventArgs e)
{ {
@ -153,8 +108,7 @@ namespace HoistingCrane
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
@ -166,9 +120,7 @@ namespace HoistingCrane
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RerfreshListBoxItems();
collectionType);
RerfreshListBoxItems();
} }
private void buttonDeleteCollection_Click(object sender, EventArgs e) private void buttonDeleteCollection_Click(object sender, EventArgs e)
{ {
@ -181,9 +133,11 @@ namespace HoistingCrane
return; return;
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
@ -194,7 +148,7 @@ namespace HoistingCrane
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} };
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
@ -204,6 +158,50 @@ namespace HoistingCrane
panelCompanyTool.Enabled = true; panelCompanyTool.Enabled = true;
RerfreshListBoxItems(); 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);
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <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);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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> </root>

View File

@ -31,6 +31,7 @@ namespace HoistingCrane
panelColorPurple.MouseDown += panel_MouseDown; panelColorPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close(); buttonCancel.Click += (sender, e) => Close();
} }
/// <summary> /// <summary>
/// Привязка метода к событию /// Привязка метода к событию
/// </summary> /// </summary>

View File

@ -12,6 +12,18 @@
<None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" /> <None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" />
</ItemGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -1,5 +1,5 @@
namespace HoistingCrane namespace HoistingCrane;
{
internal static class Program internal static class Program
{ {
/// <summary> /// <summary>
@ -12,7 +12,5 @@ namespace HoistingCrane
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormCarCollection()); Application.Run(new FormCarCollection());
}
} }
} }