Compare commits

..

7 Commits
main ... lab07

39 changed files with 3288 additions and 50 deletions

View File

@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectExcavator.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status 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 = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator
{
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
using ProjectExcavator.MovementStrategy;
namespace ProjectExcavator.DrawingObjects
{
public class DrawingExcavator
{
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectExcavator(this);
/// <summary>
/// Класс-сущность
/// </summary>
public EntityExcavator? EntityExcavator { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
public int _pictureHeight;
/// <summary>
/// /// Левая координата прорисовки экскаватора
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя координата прорисовки экскаватора
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки экскаватора
/// </summary>
protected readonly int _exWidth = 140;
/// <summary>
/// Высота прорисовки экскаватора
/// </summary>
protected readonly int _exHeight = 82;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawingExcavator(int speed, double weight, Color bodyColor, int width, int height)
{
// TODO: Продумать проверки
if (width > _exWidth || height > _exHeight)
{
_pictureWidth = width;
_pictureHeight = height;
EntityExcavator = new EntityExcavator(speed, weight, bodyColor);
}
}
public void bodyColor(Color color)
{
EntityExcavator.BodyColor = color;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="exWidth">Ширина прорисовки автомобиля</param>
/// <param name="exHeight">Высота прорисовки автомобиля</param>
protected DrawingExcavator(int speed, double weight, Color bodyColor, int
width, int height, int exWidth, int exHeight)
{
// TODO: Продумать проверки
if (width > _exWidth || height > _exHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_exWidth = exWidth;
_exHeight = exHeight;
EntityExcavator = new EntityExcavator(speed, weight, bodyColor);
}
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// TODO: Изменение x, y
if (x < 0)
{
x = 0;
}
else if (x > _pictureWidth - _exWidth)
{
x = _pictureWidth - _exWidth;
}
if (y < 0)
{
y = 0;
}
else if (y > _pictureHeight - _exHeight)
{
y = _pictureHeight - _exHeight;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _exWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _exHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityExcavator == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityExcavator.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityExcavator.Step > 0,
// вправо
DirectionType.Right => _startPosX + _exWidth + EntityExcavator.Step <= _pictureWidth,
//влево
DirectionType.Down => _startPosY + _exHeight + EntityExcavator.Step <= _pictureHeight,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityExcavator == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityExcavator.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityExcavator.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityExcavator.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityExcavator.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityExcavator == null)
{
return;
}
//цвета
Pen pen = new(Color.Black);
Brush bodyBrush = new SolidBrush(EntityExcavator.BodyColor);
//отрисовка экскаватора без ковша
g.DrawRectangle(pen, _startPosX + 50, _startPosY + 35, 75, 25);
g.DrawRectangle(pen, _startPosX + 95, _startPosY + 10, 30, 25);
g.DrawRectangle(pen, _startPosX + 60, _startPosY + 15, 10, 20);
g.DrawRectangle(pen, _startPosX + 44, _startPosY + 65, 86, 20);
g.DrawPie(pen, _startPosX + 34, _startPosY + 65, 20, 20, 90, 180);
g.DrawPie(pen, _startPosX + 120, _startPosY + 65, 20, 20, 270, 180);
g.DrawEllipse(pen, _startPosX + 40, _startPosY + 68, 15, 15);
g.DrawEllipse(pen, _startPosX + 120, _startPosY + 68, 15, 15);
g.DrawEllipse(pen, _startPosX + 60, _startPosY + 76, 8, 8);
g.DrawEllipse(pen, _startPosX + 80, _startPosY + 76, 8, 8);
g.DrawEllipse(pen, _startPosX + 100, _startPosY + 76, 8, 8);
g.DrawEllipse(pen, _startPosX + 72, _startPosY + 68, 6, 6);
g.DrawEllipse(pen, _startPosX + 92, _startPosY + 68, 6, 6);
//кабина водителя
g.FillRectangle(bodyBrush, _startPosX + 96, _startPosY + 11, 29, 24);
// кузов
g.FillRectangle(bodyBrush, _startPosX + 51, _startPosY + 36, 74, 24);
// труба
g.FillRectangle(bodyBrush, _startPosX + 61, _startPosY + 16, 9, 19);
//гусеница
g.FillPie(bodyBrush, _startPosX + 34, _startPosY + 65, 20, 20, 90, 180);
g.FillPie(bodyBrush, _startPosX + 120, _startPosY + 65, 20, 20, 270, 180);
g.FillRectangle(bodyBrush, _startPosX + 44, _startPosY + 65, 86, 20);
}
}
}

View File

@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
namespace ProjectExcavator.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingExcavatorKovsh : DrawingExcavator
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="kovsh">Признак наличия ковша</param>
/// <param name="katki">Признак наличия катков</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingExcavatorKovsh(int speed, double weight, Color bodyColor, Color
additionalColor, bool kovsh, bool katki, int width, int height) : base(speed, weight, bodyColor, width, height, 140, 82)
{
if (EntityExcavator != null)
{
EntityExcavator = new EntityExcavatorKovsh(speed, weight, bodyColor,
additionalColor, kovsh, katki);
}
}
public void additionalColor(Color color)
{
(EntityExcavator as EntityExcavatorKovsh).AdditionalColor = color;
}
public override void DrawTransport(Graphics g)
{
if (EntityExcavator is not EntityExcavatorKovsh excavatorKovsh)
{
return;
}
//цвета
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(excavatorKovsh.AdditionalColor);
// ковш
if (excavatorKovsh.Kovsh)
{
g.DrawLine(pen, _startPosX + 50, _startPosY + 35, _startPosX + 10, _startPosY + 10);
g.DrawLine(pen, _startPosX + 58, _startPosY + 35, _startPosX + 12, _startPosY + 5);
g.DrawEllipse(pen, _startPosX + 7, _startPosY + 4, 7, 7);
g.DrawLine(pen, _startPosX + 10, _startPosY + 10, _startPosX + 10, _startPosY + 45);
g.DrawLine(pen, _startPosX + 14, _startPosY + 5, _startPosX + 14, _startPosY + 45);
g.DrawPie(pen, _startPosX, _startPosY + 44, 28, 30, 90, 180);
g.DrawLine(pen, _startPosX + 14, _startPosY + 5, _startPosX + 14, _startPosY);
g.DrawLine(pen, _startPosX + 14, _startPosY, _startPosX + 7, _startPosY + 10);
g.DrawLine(pen, _startPosX + 14, _startPosY, _startPosX + 50, _startPosY + 12);
g.DrawLine(pen, _startPosX + 14, _startPosY, _startPosX + 50, _startPosY + 16);
g.DrawLine(pen, _startPosX + 50, _startPosY + 12, _startPosX + 50, _startPosY + 29);
g.FillEllipse(additionalBrush, _startPosX + 7, _startPosY + 4, 7, 7);
g.FillPie(additionalBrush, _startPosX, _startPosY + 44, 28, 30, 90, 180);
Point point1 = new Point(_startPosX + 50, _startPosY + 35);
Point point2 = new Point(_startPosX + 10, _startPosY + 10);
Point point3 = new Point(_startPosX + 12, _startPosY + 5);
Point point4 = new Point(_startPosX + 58, _startPosY + 35);
Point[] truba_1 = { point1, point2, point3, point4, point1 };
g.FillPolygon(additionalBrush, truba_1);
Point point5 = new Point(_startPosX + 10, _startPosY + 10);
Point point6 = new Point(_startPosX + 10, _startPosY + 45);
Point point7 = new Point(_startPosX + 14, _startPosY + 45);
Point point8 = new Point(_startPosX + 14, _startPosY + 5);
Point[] truba_2 = { point5, point6, point7, point8, point5 };
g.FillPolygon(additionalBrush, truba_2);
Point point9 = new Point(_startPosX + 14, _startPosY + 5);
Point point10 = new Point(_startPosX + 14, _startPosY);
Point point11 = new Point(_startPosX + 7, _startPosY + 10);
Point[] triangle = { point9, point10, point11, point9 };
g.FillPolygon(additionalBrush, triangle);
Point point12 = new Point(_startPosX + 14, _startPosY);
Point point13 = new Point(_startPosX + 50, _startPosY + 12);
Point point14 = new Point(_startPosX + 50, _startPosY + 16);
Point point15 = new Point(_startPosX + 14, _startPosY);
Point[] krepl = { point12, point13, point14, point15, point12 };
g.FillPolygon(additionalBrush, krepl);
}
base.DrawTransport(g);
// катки
if (excavatorKovsh.Katki)
{
g.FillEllipse(additionalBrush, _startPosX + 40, _startPosY + 68, 15, 15);
g.FillEllipse(additionalBrush, _startPosX + 120, _startPosY + 68, 15, 15);
g.FillEllipse(additionalBrush, _startPosX + 60, _startPosY + 76, 8, 8);
g.FillEllipse(additionalBrush, _startPosX + 80, _startPosY + 76, 8, 8);
g.FillEllipse(additionalBrush, _startPosX + 100, _startPosY + 76, 8, 8);
g.FillEllipse(additionalBrush, _startPosX + 72, _startPosY + 68, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 92, _startPosY + 68, 6, 6);
}
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.DrawingObjects;
namespace ProjectExcavator.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningExcavator (паттерн Adapter)
/// </summary>
public class DrawingObjectExcavator : IMoveableObject
{
private readonly DrawingExcavator? _drawingExcavator = null;
public DrawingObjectExcavator(DrawingExcavator drawingExcavator)
{
_drawingExcavator = drawingExcavator;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingExcavator == null || _drawingExcavator.EntityExcavator ==
null)
{
return null;
}
return new ObjectParameters(_drawingExcavator.GetPosX,
_drawingExcavator.GetPosY, _drawingExcavator.GetWidth, _drawingExcavator.GetHeight);
}
}
public int GetStep => (int)(_drawingExcavator?.EntityExcavator?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingExcavator?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingExcavator?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Entities
{
public class EntityExcavator
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения экскаватора
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса экскаватора
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес экскаватора</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityExcavator(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Entities
{
/// <summary>
/// Класс-сущность "Экскаватор Ковш"
/// </summary>
public class EntityExcavatorKovsh : EntityExcavator
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Ковш
/// </summary>
public bool Kovsh { get; private set; }
/// <summary>
/// Катки гусеничные
/// </summary>
public bool Katki { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса экскаватора с ковшом
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес экскаватора</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="kovsh">Признак наличия ковша</param>
/// <param name="katki">Признак наличия катков</param>
public EntityExcavatorKovsh(int speed, double weight, Color bodyColor, Color additionalColor, bool kovsh, bool katki) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Kovsh = kovsh;
Katki = katki;
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.DrawingObjects;
namespace ProjectExcavator.Excavators
{
/// <summary>
/// Делегат для передачи объекта-экскаватора
/// </summary>
/// <param name="car"></param>
public delegate void ExcavatorDelegate(DrawingExcavator excavator);
}

View File

@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.MovementStrategy;
namespace ProjectExcavator.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawingExcavator
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class ExcavatorGenericCollection<T, U>
where T : DrawingExcavator
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 200;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public IEnumerable<T?> GetExcavators => _collection.GetExcavators();
public ExcavatorGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator +(ExcavatorGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(ExcavatorGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowExcavator()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private 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 +
1; ++j)
{//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
// TODO получение объекта
T? excavator = _collection[i];
if (excavator == null)
continue;
excavator._pictureHeight = _pictureHeight;
excavator._pictureWidth = _pictureWidth;
int r = i / width;
int s = width - 1 - (i % width);
// TODO установка позиции
excavator.SetPosition(s * _placeSizeWidth, r * _placeSizeHeight);
// TODO прорисовка объекта
excavator.DrawTransport(g);
}
}
}
}

View File

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.Exceptions;
using ProjectExcavator.Generics;
using ProjectExcavator.MovementStrategy;
namespace ProjectExcavator.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class ExcavatorGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, ExcavatorGenericCollection<DrawingExcavator,
DrawingObjectExcavator>> _excavatorStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _excavatorStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
public ExcavatorGenericStorage(int pictureWidth, int pictureHeight)
{
_excavatorStorages = new Dictionary<string,
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_excavatorStorages.ContainsKey(name))
{
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator> newSet = new ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>(_pictureWidth, _pictureHeight);
_excavatorStorages.Add(name, newSet);
}
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
{
if (_excavatorStorages.ContainsKey(name))
{
_excavatorStorages.Remove(name);
}
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>? this[string ind]
{
get
{
if (_excavatorStorages.ContainsKey(ind))
{
return _excavatorStorages[ind];
}
return null;
}
}
/// <summary>
/// Сохранение информации по экскаваторам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>> record in _excavatorStorages)
{
StringBuilder records = new();
foreach (DrawingExcavator? elem in record.Value.GetExcavators)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new ArgumentException("Нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine("excavatorStorages");
writer.Write(data.ToString());
}
}
/// <summary>
/// Загрузка информации по экскаваторам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string proverkaline = reader.ReadLine();
if (proverkaline == null)
{
throw new ArgumentException("Нет данных для загрузки");
}
if (!proverkaline.StartsWith("excavatorStorages"))
{
throw new InvalidDataException("Неверный формат ввода файла");
}
_excavatorStorages.Clear();
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split('|');
if (parts.Length != 2)
{
continue;
}
string namestorage = parts[0];
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in parts[1].Split(';'))
{
DrawingExcavator? excavator = data?.CreateDrawingExcavator(_separatorForObject, _pictureWidth, _pictureHeight);
if (excavator != null)
{
try { _ = collection + excavator; }
catch (ExcavatorNotFoundException ex)
{
throw ex;
}
catch (StorageOverflowException ex)
{
throw ex;
}
}
}
_excavatorStorages.Add(namestorage, collection);
}
}
}
}
}

View File

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

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
namespace ProjectExcavator.DrawingObjects
{
/// <summary>
/// Расширение для класса EntityEx
/// </summary>
public static class ExtentionDrawingExcavator
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingExcavator? CreateDrawingExcavator(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingExcavator(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingExcavatorKovsh(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingExcavator">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingExcavator drawingExcavator, char separatorForObject)
{
var excavator = drawingExcavator.EntityExcavator;
if (excavator == null)
{
return string.Empty;
}
var str = $"{excavator.Speed}{separatorForObject}{excavator.Weight}{separatorForObject}{excavator.BodyColor.Name}";
if (excavator is not EntityExcavatorKovsh excavatorKovsh)
{
return str;
}
return $"{str}{separatorForObject}{excavatorKovsh.AdditionalColor.Name}{separatorForObject}{excavatorKovsh.Kovsh}{separatorForObject}{excavatorKovsh.Katki}";
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,189 @@
namespace ProjectExcavator
{
partial class FormExcavator
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBoxExcavator = new System.Windows.Forms.PictureBox();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonCreateExKovsh = new System.Windows.Forms.Button();
this.buttonCreateEx = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonSelectExcavator = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxExcavator)).BeginInit();
this.SuspendLayout();
//
// pictureBoxExcavator
//
this.pictureBoxExcavator.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxExcavator.Location = new System.Drawing.Point(0, 0);
this.pictureBoxExcavator.Name = "pictureBoxExcavator";
this.pictureBoxExcavator.Size = new System.Drawing.Size(884, 461);
this.pictureBoxExcavator.TabIndex = 0;
this.pictureBoxExcavator.TabStop = false;
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::ProjectExcavator.Properties.Resources.влево;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(762, 404);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 2;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::ProjectExcavator.Properties.Resources.право;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(842, 404);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 3;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::ProjectExcavator.Properties.Resources.up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(803, 368);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 4;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::ProjectExcavator.Properties.Resources.down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(803, 404);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 5;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonCreateExKovsh
//
this.buttonCreateExKovsh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateExKovsh.Location = new System.Drawing.Point(12, 426);
this.buttonCreateExKovsh.Name = "buttonCreateExKovsh";
this.buttonCreateExKovsh.Size = new System.Drawing.Size(180, 23);
this.buttonCreateExKovsh.TabIndex = 6;
this.buttonCreateExKovsh.Text = "Создать экскаватор с ковшом";
this.buttonCreateExKovsh.UseVisualStyleBackColor = true;
this.buttonCreateExKovsh.Click += new System.EventHandler(this.buttonCreateExKovsh_Click);
//
// buttonCreateEx
//
this.buttonCreateEx.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateEx.Location = new System.Drawing.Point(198, 426);
this.buttonCreateEx.Name = "buttonCreateEx";
this.buttonCreateEx.Size = new System.Drawing.Size(133, 23);
this.buttonCreateEx.TabIndex = 7;
this.buttonCreateEx.Text = "Создать";
this.buttonCreateEx.UseVisualStyleBackColor = true;
this.buttonCreateEx.Click += new System.EventHandler(this.buttonCreateEx_Click);
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(797, 41);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(75, 23);
this.buttonStep.TabIndex = 8;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"0",
"1"});
this.comboBoxStrategy.Location = new System.Drawing.Point(751, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 23);
this.comboBoxStrategy.TabIndex = 9;
//
// buttonSelectExcavator
//
this.buttonSelectExcavator.Location = new System.Drawing.Point(370, 426);
this.buttonSelectExcavator.Name = "buttonSelectExcavator";
this.buttonSelectExcavator.Size = new System.Drawing.Size(105, 23);
this.buttonSelectExcavator.TabIndex = 10;
this.buttonSelectExcavator.Text = "Выбрать обьект";
this.buttonSelectExcavator.UseVisualStyleBackColor = true;
this.buttonSelectExcavator.Click += new System.EventHandler(this.ButtonSelectExcavator_Click);
//
// FormExcavator
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.buttonSelectExcavator);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.buttonCreateEx);
this.Controls.Add(this.buttonCreateExKovsh);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.pictureBoxExcavator);
this.Name = "FormExcavator";
this.Text = "FormExcavator";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxExcavator)).EndInit();
this.ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxExcavator;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private Button buttonCreateExKovsh;
private Button buttonCreateEx;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button buttonSelectExcavator;
}
}

View File

@ -0,0 +1,155 @@
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.MovementStrategy;
using System.Windows.Forms;
namespace ProjectExcavator
{
public partial class FormExcavator : Form
{
private DrawingExcavator? _drawingExcavator;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé ýêñêàâàòîð
/// </summary>
public DrawingExcavator? SelectedExcavator { get; private set; }
public FormExcavator()
{
InitializeComponent();
_abstractStrategy = null;
_drawingExcavator = null;
}
private void Draw()
{
if (_drawingExcavator == null)
{
return;
}
Bitmap bmp = new(pictureBoxExcavator.Width, pictureBoxExcavator.Height);
Graphics g = Graphics.FromImage(bmp);
_drawingExcavator.DrawTransport(g);
pictureBoxExcavator.Image = bmp;
}
private void buttonCreateExKovsh_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð äîïîëíèòåëüíîãî öâåòà
ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK)
{
dopColor = dialog2.Color;
}
_drawingExcavator = new DrawingExcavatorKovsh(random.Next(100, 300), random.Next(1000, 3000),
color, dopColor, Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxExcavator.Width, pictureBoxExcavator.Height);
_drawingExcavator.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateEx_Click(object sender, EventArgs e)
{
Random random = new();
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;
}
_drawingExcavator = new DrawingExcavator(random.Next(100, 300), random.Next(1000, 3000), color,
pictureBoxExcavator.Width, pictureBoxExcavator.Height);
_drawingExcavator.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingExcavator == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingExcavator.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingExcavator.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingExcavator.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingExcavator.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingExcavator == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawingObjectExcavator(_drawingExcavator), pictureBoxExcavator.Width,
pictureBoxExcavator.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
/// <summary>
/// Âûáîð ýêñêàâàòîðà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectExcavator_Click(object sender, EventArgs e)
{
SelectedExcavator = _drawingExcavator;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,242 @@
namespace ProjectExcavator
{
partial class FormExcavatorCollection
{
/// <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()
{
pictureBoxCollection = new PictureBox();
maskedTextBoxNumber = new MaskedTextBox();
buttonAddEx = new Button();
buttonRemoveEx = new Button();
buttonRefreshCollection = new Button();
groupBox1 = new GroupBox();
groupBox2 = new GroupBox();
textBoxStorageName = new TextBox();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
FilemenuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
FilemenuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 24);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(909, 437);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(35, 339);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(100, 23);
maskedTextBoxNumber.TabIndex = 1;
//
// buttonAddEx
//
buttonAddEx.Location = new Point(13, 310);
buttonAddEx.Name = "buttonAddEx";
buttonAddEx.Size = new Size(150, 23);
buttonAddEx.TabIndex = 2;
buttonAddEx.Text = "Добавить экскаватор";
buttonAddEx.UseVisualStyleBackColor = true;
buttonAddEx.Click += ButtonAddEx_Click;
//
// buttonRemoveEx
//
buttonRemoveEx.Location = new Point(13, 368);
buttonRemoveEx.Name = "buttonRemoveEx";
buttonRemoveEx.Size = new Size(150, 23);
buttonRemoveEx.TabIndex = 3;
buttonRemoveEx.Text = "Удалить экскаватор";
buttonRemoveEx.UseVisualStyleBackColor = true;
buttonRemoveEx.Click += ButtonRemoveEx_Click;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(13, 432);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(148, 23);
buttonRefreshCollection.TabIndex = 4;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// groupBox1
//
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(buttonAddEx);
groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonRemoveEx);
groupBox1.Location = new Point(741, 0);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(168, 461);
groupBox1.TabIndex = 5;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// groupBox2
//
groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Controls.Add(buttonDelObject);
groupBox2.Controls.Add(listBoxStorages);
groupBox2.Controls.Add(buttonAddObject);
groupBox2.Location = new Point(13, 28);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(143, 214);
groupBox2.TabIndex = 5;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(15, 30);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(122, 23);
textBoxStorageName.TabIndex = 6;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(15, 185);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(122, 23);
buttonDelObject.TabIndex = 8;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(15, 88);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(122, 79);
listBoxStorages.TabIndex = 6;
listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(15, 59);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(122, 23);
buttonAddObject.TabIndex = 7;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// FilemenuStrip
//
FilemenuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
FilemenuStrip.Location = new Point(0, 0);
FilemenuStrip.Name = "FilemenuStrip";
FilemenuStrip.Size = new Size(909, 24);
FilemenuStrip.TabIndex = 6;
FilemenuStrip.Text = "menuStrip1";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(133, 22);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(133, 22);
LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "\"txt file|*.txt|Все файлы|*.*\".";
//
// saveFileDialog
//
saveFileDialog.Filter = "\"txt file|*.txt|Все файлы|*.*\".";
//
// FormExcavatorCollection
//
ClientSize = new Size(909, 461);
Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection);
Controls.Add(FilemenuStrip);
MainMenuStrip = FilemenuStrip;
Name = "FormExcavatorCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
FilemenuStrip.ResumeLayout(false);
FilemenuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonAddEx;
private Button buttonRemoveEx;
private Button buttonRefreshCollection;
private GroupBox groupBox1;
private GroupBox groupBox2;
private TextBox textBoxStorageName;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private MenuStrip FilemenuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,272 @@
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.Generics;
using ProjectExcavator.Exceptions;
using Microsoft.Extensions.Logging;
using ProjectExcavator.MovementStrategy;
using ProjectExcavator.Excavators;
using System.Linq.Expressions;
using System.Xml.Linq;
namespace ProjectExcavator
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningExcavator
/// </summary>
public partial class FormExcavatorCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ExcavatorGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
{
InitializeComponent();
_storage = new ExcavatorGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowExcavator();
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowExcavator();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddEx_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
FormExcavatorConfig form = new FormExcavatorConfig();
Action<DrawingExcavator> ExcavatorDelegate = new Action<DrawingExcavator>((excavator) =>
{
try
{
bool selectedexcavator = obj + excavator;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowExcavator();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
});
form.AddEvent(ExcavatorDelegate);
form.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveEx_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowExcavator();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (ExcavatorNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowExcavator();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
ReloadObjects();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowExcavator();
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,385 @@
namespace ProjectExcavator
{
partial class FormExcavatorConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxParam = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBox_Katki = new System.Windows.Forms.CheckBox();
this.checkBox_Kovsh = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelweight = new System.Windows.Forms.Label();
this.labelspeed = new System.Windows.Forms.Label();
this.panelObject = new System.Windows.Forms.Panel();
this.labelAdditionalColor = new System.Windows.Forms.Label();
this.labelMainColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxParam.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxParam
//
this.groupBoxParam.Controls.Add(this.labelModifiedObject);
this.groupBoxParam.Controls.Add(this.labelSimpleObject);
this.groupBoxParam.Controls.Add(this.groupBoxColor);
this.groupBoxParam.Controls.Add(this.checkBox_Katki);
this.groupBoxParam.Controls.Add(this.checkBox_Kovsh);
this.groupBoxParam.Controls.Add(this.numericUpDownWeight);
this.groupBoxParam.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParam.Controls.Add(this.labelweight);
this.groupBoxParam.Controls.Add(this.labelspeed);
this.groupBoxParam.Location = new System.Drawing.Point(12, 12);
this.groupBoxParam.Name = "groupBoxParam";
this.groupBoxParam.Size = new System.Drawing.Size(562, 437);
this.groupBoxParam.TabIndex = 0;
this.groupBoxParam.TabStop = false;
this.groupBoxParam.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(373, 258);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(100, 23);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(217, 258);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(100, 23);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelWhite);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Location = new System.Drawing.Point(201, 54);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(292, 170);
this.groupBoxColor.TabIndex = 6;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(222, 102);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 50);
this.panelPurple.TabIndex = 7;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(156, 102);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(49, 50);
this.panelBlack.TabIndex = 6;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(87, 102);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(51, 50);
this.panelGray.TabIndex = 5;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(16, 102);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(53, 50);
this.panelWhite.TabIndex = 4;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(222, 36);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(50, 50);
this.panelYellow.TabIndex = 3;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(87, 36);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(51, 50);
this.panelGreen.TabIndex = 2;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(155, 36);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(50, 50);
this.panelBlue.TabIndex = 1;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(16, 37);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(51, 49);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBox_Katki
//
this.checkBox_Katki.AutoSize = true;
this.checkBox_Katki.Location = new System.Drawing.Point(0, 205);
this.checkBox_Katki.Name = "checkBox_Katki";
this.checkBox_Katki.Size = new System.Drawing.Size(114, 19);
this.checkBox_Katki.TabIndex = 5;
this.checkBox_Katki.Text = "Наличие катков";
this.checkBox_Katki.UseVisualStyleBackColor = true;
//
// checkBox_Kovsh
//
this.checkBox_Kovsh.AutoSize = true;
this.checkBox_Kovsh.Location = new System.Drawing.Point(0, 156);
this.checkBox_Kovsh.Name = "checkBox_Kovsh";
this.checkBox_Kovsh.Size = new System.Drawing.Size(114, 19);
this.checkBox_Kovsh.TabIndex = 4;
this.checkBox_Kovsh.Text = "Наличие ковша";
this.checkBox_Kovsh.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(74, 91);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(120, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(74, 55);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(120, 23);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelweight
//
this.labelweight.AutoSize = true;
this.labelweight.Location = new System.Drawing.Point(6, 95);
this.labelweight.Name = "labelweight";
this.labelweight.Size = new System.Drawing.Size(29, 15);
this.labelweight.TabIndex = 1;
this.labelweight.Text = "Вес:";
//
// labelspeed
//
this.labelspeed.AutoSize = true;
this.labelspeed.Location = new System.Drawing.Point(6, 57);
this.labelspeed.Name = "labelspeed";
this.labelspeed.Size = new System.Drawing.Size(62, 15);
this.labelspeed.TabIndex = 0;
this.labelspeed.Text = "Скорость:";
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelAdditionalColor);
this.panelObject.Controls.Add(this.labelMainColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(593, 22);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(279, 343);
this.panelObject.TabIndex = 1;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelAdditionalColor
//
this.labelAdditionalColor.AllowDrop = true;
this.labelAdditionalColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAdditionalColor.Location = new System.Drawing.Point(166, 38);
this.labelAdditionalColor.Name = "labelAdditionalColor";
this.labelAdditionalColor.Size = new System.Drawing.Size(100, 23);
this.labelAdditionalColor.TabIndex = 2;
this.labelAdditionalColor.Text = "Доп. цвет";
this.labelAdditionalColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelAdditionalColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelMainColor
//
this.labelMainColor.AllowDrop = true;
this.labelMainColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelMainColor.Location = new System.Drawing.Point(13, 38);
this.labelMainColor.Name = "labelMainColor";
this.labelMainColor.Size = new System.Drawing.Size(100, 23);
this.labelMainColor.TabIndex = 1;
this.labelMainColor.Text = "Цвет";
this.labelMainColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelMainColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(13, 68);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(253, 260);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(606, 382);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 23);
this.buttonOk.TabIndex = 2;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(784, 382);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormExcavatorConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxParam);
this.Name = "FormExcavatorConfig";
this.Text = "FormExcavatorConfig";
this.groupBoxParam.ResumeLayout(false);
this.groupBoxParam.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParam;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelweight;
private Label labelspeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColor;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelGreen;
private Panel panelBlue;
private Panel panelRed;
private CheckBox checkBox_Katki;
private CheckBox checkBox_Kovsh;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelMainColor;
private PictureBox pictureBoxObject;
private Button buttonOk;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.Excavators;
namespace ProjectExcavator
{
public partial class FormExcavatorConfig : Form
{
/// <summary>
/// Переменная-выбранного экскаватора
/// </summary>
DrawingExcavator? _excavator = null;
/// <summary>
/// Встроенный делегат
/// </summary>
private event Action<DrawingExcavator>? EventAddExcavator;
/// <summary>
/// Конструктор
/// </summary>
public FormExcavatorConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (sender, e) =>
{
Close();
};
}
/// <summary>
/// Отрисовать экскаватор
/// </summary>
private void DrawExcavator()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_excavator?.SetPosition(5, 5);
_excavator?.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,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = 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":
_excavator = new DrawingExcavator((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_excavator = new DrawingExcavatorKovsh((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBox_Kovsh.Checked, checkBox_Katki.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawExcavator();
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawingExcavator> ev)
{
if (EventAddExcavator == null)
{
EventAddExcavator = ev;
}
else
{
EventAddExcavator += ev;
}
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_excavator == null)
return;
((Label)sender).BackColor = (Color)e.Data.GetData(typeof(Color));
switch (((Label)sender).Name)
{
case "labelMainColor":
_excavator.bodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAdditionalColor":
if (!(_excavator is DrawingExcavatorKovsh))
return;
(_excavator as DrawingExcavatorKovsh).additionalColor((Color)e.Data.GetData(typeof(Color)));
break;
}
DrawExcavator();
}
/// <summary>
/// Добавление экскаватора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddExcavator?.Invoke(_excavator);
Close();
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в правый нижний угол экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectBorderRight <= FieldWidth &&
objParams.ObjectBorderRight + GetStep() >= FieldWidth &&
objParams.ObjectBorderDown <= FieldHeight &&
objParams.ObjectBorderDown + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectBorderRight - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectBorderDown - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

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

View File

@ -8,4 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectExcavator.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectExcavator.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap down {
get {
object obj = ResourceManager.GetObject("down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up {
get {
object obj = ResourceManager.GetObject("up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap влево {
get {
object obj = ResourceManager.GetObject("влево", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap право {
get {
object obj = ResourceManager.GetObject("право", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1015 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1015 B

View File

@ -0,0 +1,133 @@
using ProjectExcavator.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="excavator">Добавляемый экскаватор</param>
/// <returns></returns>
public bool Insert(T excavator)
{
return Insert(excavator, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="excavator">Добавляемый экскаватор</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T excavator, int position)
{
// TODO проверка позиции
if (position < 0 || position >= _maxCount)
{
throw new ExcavatorNotFoundException(position);
}
// TODO проверка, что есть место для вставки
if (_places.Count >= _maxCount)
{
throw new StorageOverflowException(_places.Count);
}
// TODO вставка по позиции
_places.Insert(position, excavator);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
// TODO проверка позиции
if (position < 0 || position >= _places.Count)
{
throw new ExcavatorNotFoundException(position);
}
// TODO удаление объекта из списка
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
// TODO проверка позиции
if (position < 0 || position >= _places.Count)
{
return null;
}
return _places[position];
}
set
{
// TODO проверка позиции
if (position < 0 || position >= _places.Count)
{
return;
}
// TODO проверка свободных мест в списке
if (_places.Count >= _maxCount)
{
return;
}
// TODO вставка в список по позиции
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetExcavators(int? maxExcavators = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxExcavators.HasValue && i == maxExcavators.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
public enum Status
{
NotInit, InProgress, Finish
}
}

View File

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

View File

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