9 Commits

31 changed files with 2733 additions and 308 deletions

View File

@@ -0,0 +1,10 @@
using ProjectAccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus;
public delegate void BusDelegate(DrawningBus bus);

View File

@@ -0,0 +1,69 @@
using ProjectAccordionBus.Drawnings;
using ProjectAccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects;
public abstract class AbstractCompany
{
protected readonly int _placeSizeWidth = 240;
protected readonly int _placeSizeHeight = 60;
protected readonly int _pictureWidth;
protected readonly int _pictureHeight;
protected ICollectionGenericObjects<DrawningBus?> _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawningBus> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeigth;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
public static int operator +(AbstractCompany company, DrawningBus bus)
{
return company._collection.Insert(bus);
}
public static DrawningBus operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
public DrawningBus? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics);
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
DrawningBus? obj = _collection?.Get(i);
SetObjectPosition(i, _collection?.Count ?? 0, obj);
obj?.DrawTransport(graphics);
}
return bitmap;
}
protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus);
}

View File

@@ -0,0 +1,56 @@
using ProjectAccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects;
public class BusSharingService : AbstractCompany
{
public BusSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBus> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i <= _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
protected override void SetObjectPosition(int position, int MaxPos, DrawningBus? bus)
{
int n = 0;
int m = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
{
int x = 5 + _placeSizeWidth * n;
int y = (10 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m;
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
}
if (n < _pictureWidth / _placeSizeWidth)
n++;
else
{
n = 0;
m++;
}
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
private readonly List<T> _collection;
private int _maxCount;
public int MaxCount => _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public ListGenericObjects()
{
_collection = new();
}
public T Get(int position)
{
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null;
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount)
{
return -1;
}
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position)
{
if (Count == _maxCount || position < 0 || position > Count)
{
return -1;
}
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
if (_collection == null || position < 0 || position >= _collection.Count) return null;
T? obj = _collection[position];
_collection[position] = null;
return obj;
}
}

View File

@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects;
/// <summary>
/// Параметризированный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position >= _collection.Length || position < 0)
{
return null;
}
return _collection[position];
}
public int Insert(T obj)
{
int index = 0;
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
}
return -1;
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0)
return -1;
if (_collection[position] != null)
{
// проверка, что после вставляемого элемента в массиве есть пустой элемент
int nullIndex = -1;
for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{
nullIndex = i;
break;
}
}
// Если пустого элемента нет, то выходим
if (nullIndex < 0)
{
return -1;
}
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
int j = nullIndex - 1;
while (j >= position)
{
_collection[j + 1] = _collection[j];
j--;
}
}
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0)
{
return null;
}
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
}

View File

@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects;
public class StorageCollection<T>
where T : class
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name) || name == "") return;
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
}
else
{
_storages[name] = new ListGenericObjects<T>();
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
_storages.Remove(name);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
if (name == "")
{
return null;
}
return _storages[name];
}
}
}

View File

@@ -1,206 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus;
public class DrawningAccordionBus
{
public EntityAccordionBus? EntityAccordionBus { get; private set; }
private int? _pictureWidth;
private int? _pictureHeight;
private int? _startPosX;
private int? _startPosY;
private int _drawningAccordionBusWidth = 60;
private readonly int _drawningAccordionBusHeight = 50;
public void Init(EntityAccordionBus entity)
{
EntityAccordionBus = entity;
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
public bool SetPictureSize(int width, int height)
{
if (_drawningAccordionBusWidth <= width && _drawningAccordionBusHeight <= height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningAccordionBusWidth > width)
{
_startPosX = width - _drawningAccordionBusWidth;
}
if (_startPosY + _drawningAccordionBusHeight > height)
{
_startPosY = height - _drawningAccordionBusHeight;
}
}
return true;
}
return false;
}
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if (x < 0)
{
_startPosX = 0;
}
if (y < 0)
{
_startPosY = 0;
}
if (x + _drawningAccordionBusWidth > _pictureWidth) {
_startPosX = _pictureWidth - _drawningAccordionBusWidth;
}
if (y + _drawningAccordionBusHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningAccordionBusHeight;
}
}
public bool MoveTransport(DirectionType direction)
{
if (EntityAccordionBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityAccordionBus.Step > 0)
{
_startPosX -= (int)EntityAccordionBus.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityAccordionBus.Step > 0)
{
_startPosY -= (int)EntityAccordionBus.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningAccordionBusWidth + EntityAccordionBus.Step < _pictureWidth.Value)
{
_startPosX += (int)EntityAccordionBus.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawningAccordionBusHeight + EntityAccordionBus.Step < _pictureHeight.Value)
{
_startPosY += (int)EntityAccordionBus.Step;
}
return true;
default:
return false;
}
}
public void DrawTransport(Graphics g)
{
if (EntityAccordionBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityAccordionBus.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityAccordionBus.BodyColor);
// границы автобуса
g.FillRectangle(bodyBrush, _startPosX.Value + 10, _startPosY.Value + 10, 50, 30);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 10, 50, 30);
// окна
Brush brushBlue = new SolidBrush(Color.Blue);
g.FillEllipse(brushBlue, _startPosX.Value + 15, _startPosY.Value + 15, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 50, _startPosY.Value + 15, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 40, _startPosY.Value + 15, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 15, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 15, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 15, 5, 10);
// крылья
if (EntityAccordionBus.Compartment)
{
_drawningAccordionBusWidth = 130;
// отсек
g.FillRectangle(bodyBrush, _startPosX.Value + 70, _startPosY.Value + 10, 50, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value + 15, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 70, _startPosY.Value + 10, 50, 30);
g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value + 15, 10, 20);
// колеса
g.FillEllipse(additionalBrush, _startPosX.Value + 75, _startPosY.Value + 35, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 105, _startPosY.Value + 35, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 75, _startPosY.Value + 35, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 105, _startPosY.Value + 35, 10, 10);
if (EntityAccordionBus.Entrance)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 88, _startPosY.Value + 20, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 88, _startPosY.Value + 20, 10, 20);
}
if (EntityAccordionBus.Windows)
{
g.FillEllipse(brushBlue, _startPosX.Value + 75, _startPosY.Value + 15, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 110, _startPosY.Value + 15, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 100, _startPosY.Value + 15, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 75, _startPosY.Value + 15, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 15, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 15, 5, 10);
}
}
// двери
g.FillRectangle(additionalBrush, _startPosX.Value + 28, _startPosY.Value + 20, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 28, _startPosY.Value + 20, 10, 20);
// колеса
g.FillEllipse(additionalBrush, _startPosX.Value + 15, _startPosY.Value + 35, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 35, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 35, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 45, _startPosY.Value + 35, 10, 10);
}
}

View File

@@ -4,13 +4,18 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus;
namespace ProjectAccordionBus.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@@ -0,0 +1,65 @@
using ProjectAccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectAccordionBus.Drawnings;
public class DrawningAccordionBus : DrawningBus
{
public DrawningAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool compartment, bool entrance, bool windows) : base(110, 40)
{
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, compartment, entrance, windows);
}
public override void DrawTransport(Graphics g)
{
if (EntityBus == null || EntityBus is not EntityAccordionBus accordionBus || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(accordionBus.AdditionalColor);
base.DrawTransport(g);
Brush brushBlue = new SolidBrush(Color.Blue);
// отсек
if (accordionBus.Compartment)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value, 50, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value, 50, 30);
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20);
// колеса
g.FillEllipse(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10);
g.FillEllipse(additionalBrush, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10);
if (accordionBus.Entrance)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20);
}
if (accordionBus.Windows)
{
g.FillEllipse(brushBlue, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10);
}
}
}
}

View File

@@ -0,0 +1,217 @@
using ProjectAccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.Drawnings;
public class DrawningBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { 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 _drawningBusWidth = 50;
/// <summary>
/// Высота прорисовки транспорта
/// </summary>
private readonly int _drawningBusHeight = 35;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBusWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHight => _drawningBusHeight;
// Пустой конструктор
private DrawningBus()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
// Конструктор
public DrawningBus(int speed, double weight, Color bodyColor) : this()
{
EntityBus = new EntityBus(speed, weight, bodyColor);
}
// Конструктор
protected DrawningBus(int drawningBusWidth, int drawningBusHeight) : this()
{
_drawningBusWidth = drawningBusWidth;
_drawningBusHeight = drawningBusHeight;
}
public bool SetPictureSize(int width, int height)
{
if (_drawningBusWidth <= width && _drawningBusHeight <= height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningBusWidth > width)
{
_startPosX = width - _drawningBusWidth;
}
if (_startPosY + _drawningBusHeight > height)
{
_startPosY = height - _drawningBusHeight;
}
}
return true;
}
return false;
}
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if (x < 0)
{
_startPosX = 0;
}
if (y < 0)
{
_startPosY = 0;
}
if (x + _drawningBusWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningBusWidth;
}
if (y + _drawningBusHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningBusHeight;
}
}
public bool MoveTransport(DirectionType direction)
{
if (EntityBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityBus.Step > 0)
{
_startPosX -= (int)EntityBus.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityBus.Step > 0)
{
_startPosY -= (int)EntityBus.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningBusWidth + EntityBus.Step < _pictureWidth.Value)
{
_startPosX += (int)EntityBus.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawningBusHeight + EntityBus.Step < _pictureHeight.Value)
{
_startPosY += (int)EntityBus.Step;
}
return true;
default:
return false;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyBrush = new SolidBrush(EntityBus.BodyColor);
// границы автобуса
g.FillRectangle(bodyBrush, _startPosX.Value, _startPosY.Value, 50, 30);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 50, 30);
// окна
Brush brushBlue = new SolidBrush(Color.Blue);
g.FillEllipse(brushBlue, _startPosX.Value + 5, _startPosY.Value + 5, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 40, _startPosY.Value + 5, 5, 10);
g.FillEllipse(brushBlue, _startPosX.Value + 30, _startPosY.Value + 5, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 5, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 5, 5, 10);
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 5, 5, 10);
// двери
g.FillRectangle(bodyBrush, _startPosX.Value + 18, _startPosY.Value + 10, 10, 20);
g.DrawRectangle(pen, _startPosX.Value + 18, _startPosY.Value + 10, 10, 20);
// колеса
g.FillEllipse(bodyBrush, _startPosX.Value + 5, _startPosY.Value + 25, 10, 10);
g.FillEllipse(bodyBrush, _startPosX.Value + 35, _startPosY.Value + 25, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 25, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 35, _startPosY.Value + 25, 10, 10);
}
}

View File

@@ -4,19 +4,13 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus;
namespace ProjectAccordionBus.Entities;
public class EntityAccordionBus
public class EntityAccordionBus : EntityBus
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public Color AdditionalColor { get; private set; }
public double Step => Speed * 50 / Weight;
public void SetAdditionalColor(Color color) => AdditionalColor = color;
public bool Compartment { get; private set; }
@@ -25,24 +19,18 @@ public class EntityAccordionBus
public bool Windows { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// Инициализация полей объекта-класса accordion bus
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="compartment">Признак наличия доп. отсека с гармошкой</param>
/// <param name="entrance">Признак наличия входа у доп. отсека</param>
/// <param name="windows">Признак наличия окон у доп. отсека</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool compartment, bool entrance, bool windows)
public EntityAccordionBus(int Speed, double Weight, Color bodyColor, Color additionalColor, bool compartment, bool entrance, bool windows) : base(Speed, Weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Compartment = compartment; // отсек
Entrance = entrance; // крылья
Entrance = entrance;
Windows = windows;
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectAccordionBus.Entities;
public class EntityBus
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public void SetBodyColor(Color color) => BodyColor = color;
public double Step => Speed * 50 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@@ -30,11 +30,12 @@
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAccordionBus));
pictureBoxAccordionBus = new PictureBox();
buttonCreate = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonUp = new Button();
buttonRight = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
SuspendLayout();
//
@@ -48,17 +49,6 @@
pictureBoxAccordionBus.TabStop = false;
pictureBoxAccordionBus.Click += pictureBoxAccordionBus_Click;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 351);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@@ -107,16 +97,37 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(595, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(641, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormAccordionBus
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(728, 386);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxAccordionBus);
Name = "FormAccordionBus";
Text = "Сочленённый автобус";
@@ -132,10 +143,11 @@
#endregion
private PictureBox pictureBoxAccordionBus;
private Button buttonCreate;
private Button buttonLeft;
private Button buttonDown;
private Button buttonUp;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@@ -1,4 +1,7 @@
using System;
using ProjectAccordionBus.Drawnings;
using ProjectAccordionBus.Entities;
using ProjectAccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -10,78 +13,112 @@ using System.Windows.Forms;
namespace ProjectAccordionBus;
public partial class FormAccordionBus : Form
{
private DrawningBus? _drawningBus;
private AbstractStrategy? _strategy;
public DrawningBus SetBus
{
private DrawningAccordionBus? _drawningAccordionBus;
private EntityAccordionBus? _entity;
public FormAccordionBus()
set
{
InitializeComponent();
}
private void Draw()
{
if (_drawningAccordionBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAccordionBus.DrawTransport(gr);
pictureBoxAccordionBus.Image = bmp;
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAccordionBus = new DrawningAccordionBus();
_entity = new EntityAccordionBus();
_entity.Init(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningAccordionBus.Init(_entity);
_drawningAccordionBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
_drawningAccordionBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
_drawningBus = value;
_drawningBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningAccordionBus == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningAccordionBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningAccordionBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningAccordionBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningAccordionBus.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
}
public FormAccordionBus()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningBus.DrawTransport(gr);
pictureBoxAccordionBus.Image = bmp;
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningBus == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningBus.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableBus(_drawningBus), pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

@@ -0,0 +1,292 @@
namespace ProjectAccordionBus
{
partial class FormBusCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonDeleteBus = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonAddBus = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
buttonCreateCompany = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
comboBoxSelectorCompany = new ComboBox();
labelCollectionName = new Label();
pictureBox = new PictureBox();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(625, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(175, 510);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonDeleteBus);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 316);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(169, 191);
panelCompanyTools.TabIndex = 10;
//
// buttonDeleteBus
//
buttonDeleteBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDeleteBus.Location = new Point(6, 109);
buttonDeleteBus.Name = "buttonDeleteBus";
buttonDeleteBus.Size = new Size(160, 23);
buttonDeleteBus.TabIndex = 5;
buttonDeleteBus.Text = "Удаление автобуса";
buttonDeleteBus.UseVisualStyleBackColor = true;
buttonDeleteBus.Click += buttonDeleteBus_Click;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(6, 80);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(160, 23);
maskedTextBox.TabIndex = 5;
maskedTextBox.ValidatingType = typeof(int);
maskedTextBox.MaskInputRejected += maskedTextBox_MaskInputRejected;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 167);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(160, 21);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 138);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(160, 23);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonAddBus
//
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBus.Location = new Point(6, 17);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(160, 37);
buttonAddBus.TabIndex = 2;
buttonAddBus.Text = "Добавление автобуса";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += buttonAddBus_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(buttonCreateCompany);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(comboBoxSelectorCompany);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(169, 291);
panelStorage.TabIndex = 8;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(6, 198);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(160, 23);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += buttonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(6, 113);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(160, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 81);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(163, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateCompany.Location = new Point(6, 256);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(160, 23);
buttonCreateCompany.TabIndex = 9;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(93, 56);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(6, 56);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(6, 27);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(160, 23);
textBoxCollectionName.TabIndex = 1;
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 227);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(160, 23);
comboBoxSelectorCompany.TabIndex = 1;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(24, 9);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(122, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
labelCollectionName.Click += labelCollectionName_Click;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(625, 510);
pictureBox.TabIndex = 4;
pictureBox.TabStop = false;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 510);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormBusCollection";
Text = "Коллекция автобусов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddBus;
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonDeleteBus;
private MaskedTextBox maskedTextBox;
private Panel panelStorage;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private ListBox listBoxCollection;
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
}
}

View File

@@ -0,0 +1,272 @@
using ProjectAccordionBus.CollectionGenericObjects;
using ProjectAccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectAccordionBus;
/// <summary>
///
/// </summary>
public partial class FormBusCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawningBus> _storageCollection;
/// <summary>
///
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormBusCollection()
{
InitializeComponent();
_storageCollection = new();
}
/// <summary>
/// Добавление улучшенного троллейбуса
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAccordionBus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAccordionBus));
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создания объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningBus drawningBus;
switch (type)
{
case nameof(DrawningBus):
drawningBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningAccordionBus):
drawningBus = new DrawningAccordionBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningBus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Выбор цвета
/// </summary>
/// <param name="random"></param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void buttonAddBus_Click(object sender, EventArgs e)
{
FormBusConfig form = new();
form.Show();
form.AddEvent(SetBus);
}
private void SetBus(DrawningBus bus)
{
if (_company == null || bus == null) return;
bus.SetPictureSize(pictureBox.Width, pictureBox.Height);
if (_company + bus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Объект не удалось добавить");
}
}
private void buttonDeleteBus_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удалён");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void buttonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null) return;
DrawningBus? bus = null;
int counter = 100;
while (bus == null || counter > 0)
{
bus = _company.GetRandomObject();
counter--;
}
if (bus == null) return;
FormAccordionBus form = new()
{
SetBus = bus
};
form.ShowDialog();
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void maskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void labelCollectionName_Click(object sender, EventArgs e)
{
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
RefreshListBoxItems();
}
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null) return;
if (MessageBox.Show("Вы действительно хотите удалить выбранный элемент?",
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
MessageBox.Show("Компания удалена");
}
else
{
MessageBox.Show("Не удалось удалить компанию");
}
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Компания не выбрана");
return;
}
ICollectionGenericObjects<DrawningBus?> collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Компания не инициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new BusSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
}

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,382 @@
namespace ProjectAccordionBus
{
partial class FormBusConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelGray = new Panel();
panelRed = new Panel();
checkBoxWindows = new CheckBox();
checkBoxEntrance = new CheckBox();
checkBoxCompartment = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObjects = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObjects.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxWindows);
groupBoxConfig.Controls.Add(checkBoxEntrance);
groupBoxConfig.Controls.Add(checkBoxCompartment);
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(479, 208);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(211, 22);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(239, 130);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(180, 73);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(38, 38);
panelPurple.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(123, 73);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(38, 38);
panelBlack.TabIndex = 1;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(180, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(38, 38);
panelYellow.TabIndex = 1;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(123, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(38, 38);
panelBlue.TabIndex = 1;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(69, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(38, 38);
panelGreen.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(13, 73);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(38, 38);
panelWhite.TabIndex = 1;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(69, 73);
panelGray.Name = "panelGray";
panelGray.Size = new Size(38, 38);
panelGray.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(13, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(38, 38);
panelRed.TabIndex = 0;
//
// checkBoxWindows
//
checkBoxWindows.AutoSize = true;
checkBoxWindows.Location = new Point(6, 155);
checkBoxWindows.Name = "checkBoxWindows";
checkBoxWindows.Size = new Size(153, 19);
checkBoxWindows.TabIndex = 8;
checkBoxWindows.Text = "Признак наличие окон";
checkBoxWindows.UseVisualStyleBackColor = true;
//
// checkBoxEntrance
//
checkBoxEntrance.AutoSize = true;
checkBoxEntrance.Location = new Point(6, 120);
checkBoxEntrance.Name = "checkBoxEntrance";
checkBoxEntrance.Size = new Size(158, 19);
checkBoxEntrance.TabIndex = 7;
checkBoxEntrance.Text = "Признак наличие двери";
checkBoxEntrance.UseVisualStyleBackColor = true;
//
// checkBoxCompartment
//
checkBoxCompartment.AutoSize = true;
checkBoxCompartment.Location = new Point(6, 86);
checkBoxCompartment.Name = "checkBoxCompartment";
checkBoxCompartment.Size = new Size(188, 19);
checkBoxCompartment.TabIndex = 6;
checkBoxCompartment.Text = "Признак наличие доп. отсека";
checkBoxCompartment.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(74, 46);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(120, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(74, 17);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(120, 23);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 48);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 3;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 19);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.AllowDrop = true;
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(350, 165);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(100, 31);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.Click += buttonAdd_Click;
labelModifiedObject.DragDrop += panelObject_DragDrop;
labelModifiedObject.DragEnter += panelObjects_DragEnter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.AllowDrop = true;
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(224, 164);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 32);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.Click += buttonAdd_Click;
labelSimpleObject.DragDrop += panelObject_DragDrop;
labelSimpleObject.DragEnter += panelObjects_DragEnter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(19, 57);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(173, 95);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
pictureBoxObject.DragDrop += panelObject_DragDrop;
pictureBoxObject.DragEnter += panelObjects_DragEnter;
pictureBoxObject.MouseDown += panel_MouseDown;
//
// buttonAdd
//
buttonAdd.Location = new Point(504, 173);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 23);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(602, 173);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObjects
//
panelObjects.AllowDrop = true;
panelObjects.Controls.Add(labelAdditionalColor);
panelObjects.Controls.Add(labelBodyColor);
panelObjects.Controls.Add(pictureBoxObject);
panelObjects.Location = new Point(485, 0);
panelObjects.Name = "panelObjects";
panelObjects.Size = new Size(204, 167);
panelObjects.TabIndex = 4;
panelObjects.DragDrop += panelObject_DragDrop;
panelObjects.DragEnter += panelObjects_DragEnter;
panelObjects.MouseDown += panel_MouseDown;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(117, 10);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(75, 32);
labelAdditionalColor.TabIndex = 3;
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(19, 10);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(75, 32);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// FormBusConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(689, 208);
Controls.Add(panelObjects);
Controls.Add(buttonAdd);
Controls.Add(buttonCancel);
Controls.Add(groupBoxConfig);
Name = "FormBusConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObjects.ResumeLayout(false);
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 checkBoxCompartment;
private CheckBox checkBoxEntrance;
private CheckBox checkBoxWindows;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelGray;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObjects;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,164 @@
using ProjectAccordionBus.Drawnings;
using ProjectAccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectAccordionBus;
public partial class FormBusConfig : Form
{
/// <summary>
/// Объект прорисовки класса
/// </summary>
private DrawningBus? _bus = null;
private event Action<DrawningAccordionBus>? BusDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormBusConfig()
{
InitializeComponent();
panelRed.MouseDown += panel_MouseDown;
panelGreen.MouseDown += panel_MouseDown;
panelBlue.MouseDown += panel_MouseDown;
panelWhite.MouseDown += panel_MouseDown;
panelBlack.MouseDown += panel_MouseDown;
panelGray.MouseDown += panel_MouseDown;
panelPurple.MouseDown += panel_MouseDown;
panelYellow.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
public void AddEvent(Action<DrawningAccordionBus> busDelegate)
{
BusDelegate += busDelegate;
}
// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_bus?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_bus?.SetPosition(15, 15);
_bus?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObjects_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_bus = new DrawningBus((int)numericUpDownSpeed.Value,
(double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_bus = new DrawningAccordionBus((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value,
Color.White,
Color.Black, checkBoxCompartment.Checked,
checkBoxEntrance.Checked, checkBoxWindows.Checked);
break;
}
labelBodyColor.BackColor = Color.Empty;
labelAdditionalColor.BackColor = Color.Empty;
DrawObject();
}
private void panel_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor ?? Color.Black, DragDropEffects.Move | DragDropEffects.Copy);
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_bus != null)
{
BusDelegate?.Invoke((DrawningAccordionBus)_bus);
Close();
}
}
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus != null)
{
_bus.EntityBus.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_bus is DrawningBus)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus?.EntityBus is EntityAccordionBus _accordionBus)
{
_accordionBus.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
}

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

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public interface IMoveableObject
{
/// <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,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
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,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.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,61 @@
using ProjectAccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public class MoveableBus : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningBus или его наследника
/// </summary>
private readonly DrawningBus? _bus = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="bus">Объект класса DrawningBus</param>
public MoveableBus(DrawningBus bus)
{
_bus = bus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_bus == null || _bus.EntityBus == null || !_bus.GetPosX.HasValue || !_bus.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_bus.GetPosX.Value, _bus.GetPosY.Value, _bus.GetWidth, _bus.GetHight);
}
}
public int GetStep => (int)(_bus?.EntityBus?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_bus == null || _bus.EntityBus == null)
{
return false;
}
return _bus.MoveTransport(GetDirectionType(direction));
}
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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// Координата x
/// </summary>
private readonly int _x;
/// <summary>
/// Координата y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@@ -11,7 +11,7 @@ namespace ProjectAccordionBus
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAccordionBus());
Application.Run(new FormBusCollection());
}
}
}