Compare commits

..

8 Commits
main ... lab08

43 changed files with 3519 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,65 @@
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.Entities;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Generics
{
internal class DrawningExcavatorEqutables : IEqualityComparer<DrawingExcavator?>
{
public bool Equals(DrawingExcavator? x, DrawingExcavator? y)
{
if (x == null || x.EntityExcavator == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityExcavator == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityExcavator.Speed != y.EntityExcavator.Speed)
{
return false;
}
if (x.EntityExcavator.Weight != y.EntityExcavator.Weight)
{
return false;
}
if (x.EntityExcavator.BodyColor != y.EntityExcavator.BodyColor)
{
return false;
}
if (x is DrawingExcavatorKovsh && y is DrawingExcavatorKovsh)
{
// TODO доделать логику сравнения дополнительных параметров
EntityExcavatorKovsh _excavatorX = (EntityExcavatorKovsh)x.EntityExcavator;
EntityExcavatorKovsh _excavatorY = (EntityExcavatorKovsh)y.EntityExcavator;
if (_excavatorX.Kovsh != _excavatorY.Kovsh)
{
return false;
}
if (_excavatorX.Katki != _excavatorY.Katki)
{
return false;
}
if (_excavatorX.AdditionalColor != _excavatorY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingExcavator obj)
{
return obj.GetHashCode();
}
}
}

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,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Generics
{
internal class ExcavatorCollectionInfo : IEquatable<ExcavatorCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public ExcavatorCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(ExcavatorCollectionInfo? other)
{
if (this.Name == other?.Name)
{
return true;
}
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,51 @@
using ProjectExcavator.DrawingObjects;
using ProjectExcavator.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Generics
{
internal class ExcavatorCompareByColor : IComparer<DrawingExcavator?>
{
public int Compare(DrawingExcavator? x, DrawingExcavator? y)
{
if (x == null || x.EntityExcavator == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityExcavator == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityExcavator.BodyColor.Name != y.EntityExcavator.BodyColor.Name)
{
return x.EntityExcavator.BodyColor.Name.CompareTo(y.EntityExcavator.BodyColor.Name);
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
if (x.GetType().Name == y.GetType().Name && x is DrawingExcavatorKovsh)
{
EntityExcavatorKovsh _exX = (EntityExcavatorKovsh)x.EntityExcavator;
EntityExcavatorKovsh _exY = (EntityExcavatorKovsh)y.EntityExcavator;
if (_exX.AdditionalColor.Name != _exY.AdditionalColor.Name)
{
return _exX.AdditionalColor.Name.CompareTo(_exY.AdditionalColor.Name);
}
}
var speedCompare = x.EntityExcavator.Speed.CompareTo(y.EntityExcavator.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityExcavator.Weight.CompareTo(y.EntityExcavator.Weight);
}
}
}

View File

@ -0,0 +1,35 @@
using ProjectExcavator.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.Generics
{
internal class ExcavatorCompareByType : IComparer<DrawingExcavator?>
{
public int Compare(DrawingExcavator? x, DrawingExcavator? y)
{
if (x == null || x.EntityExcavator == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityExcavator == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityExcavator.Speed.CompareTo(y.EntityExcavator.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityExcavator.Weight.CompareTo(y.EntityExcavator.Weight);
}
}
}

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,155 @@
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
{
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <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 (bool)collect?._collection.Insert(obj, new DrawningExcavatorEqutables());
}
/// <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,193 @@
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<ExcavatorCollectionInfo, ExcavatorGenericCollection<DrawingExcavator,
DrawingObjectExcavator>> _excavatorStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<ExcavatorCollectionInfo> 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<ExcavatorCollectionInfo,
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_excavatorStorages.ContainsKey(new ExcavatorCollectionInfo(name, string.Empty)))
{
ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator> newSet = new ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>(_pictureWidth, _pictureHeight);
_excavatorStorages.Add(new ExcavatorCollectionInfo(name, string.Empty), newSet);
}
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
{
if (_excavatorStorages.ContainsKey(new ExcavatorCollectionInfo(name, string.Empty)))
{
_excavatorStorages.Remove(new ExcavatorCollectionInfo(name, string.Empty));
}
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ExcavatorGenericCollection<DrawingExcavator, DrawingObjectExcavator>? this[string ind]
{
get
{
ExcavatorCollectionInfo indOb = new ExcavatorCollectionInfo(ind, string.Empty);
if (_excavatorStorages.ContainsKey(indOb))
{
return _excavatorStorages[indOb];
}
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<ExcavatorCollectionInfo,
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(new ExcavatorCollectionInfo(namestorage, string.Empty), 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,269 @@
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()
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.buttonAddEx = new System.Windows.Forms.Button();
this.buttonRemoveEx = new System.Windows.Forms.Button();
this.buttonRefreshCollection = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.buttonDelObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.buttonAddObject = new System.Windows.Forms.Button();
this.FilemenuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.FilemenuStrip.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 24);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(909, 437);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(35, 339);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(100, 23);
this.maskedTextBoxNumber.TabIndex = 1;
//
// buttonAddEx
//
this.buttonAddEx.Location = new System.Drawing.Point(13, 310);
this.buttonAddEx.Name = "buttonAddEx";
this.buttonAddEx.Size = new System.Drawing.Size(150, 23);
this.buttonAddEx.TabIndex = 2;
this.buttonAddEx.Text = "Добавить экскаватор";
this.buttonAddEx.UseVisualStyleBackColor = true;
this.buttonAddEx.Click += new System.EventHandler(this.ButtonAddEx_Click);
//
// buttonRemoveEx
//
this.buttonRemoveEx.Location = new System.Drawing.Point(13, 368);
this.buttonRemoveEx.Name = "buttonRemoveEx";
this.buttonRemoveEx.Size = new System.Drawing.Size(150, 23);
this.buttonRemoveEx.TabIndex = 3;
this.buttonRemoveEx.Text = "Удалить экскаватор";
this.buttonRemoveEx.UseVisualStyleBackColor = true;
this.buttonRemoveEx.Click += new System.EventHandler(this.ButtonRemoveEx_Click);
//
// buttonRefreshCollection
//
this.buttonRefreshCollection.Location = new System.Drawing.Point(13, 432);
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(148, 23);
this.buttonRefreshCollection.TabIndex = 4;
this.buttonRefreshCollection.Text = "Обновить коллекцию";
this.buttonRefreshCollection.UseVisualStyleBackColor = true;
this.buttonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.ButtonSortByColor);
this.groupBox1.Controls.Add(this.ButtonSortByType);
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.buttonAddEx);
this.groupBox1.Controls.Add(this.buttonRefreshCollection);
this.groupBox1.Controls.Add(this.maskedTextBoxNumber);
this.groupBox1.Controls.Add(this.buttonRemoveEx);
this.groupBox1.Location = new System.Drawing.Point(741, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(168, 461);
this.groupBox1.TabIndex = 5;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(28, 277);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(122, 23);
this.ButtonSortByColor.TabIndex = 7;
this.ButtonSortByColor.Text = "Сортировка(цвет)";
this.ButtonSortByColor.UseVisualStyleBackColor = true;
this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// ButtonSortByType
//
this.ButtonSortByType.Location = new System.Drawing.Point(28, 248);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(122, 23);
this.ButtonSortByType.TabIndex = 6;
this.ButtonSortByType.Text = "Сортировка(тип)";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.textBoxStorageName);
this.groupBox2.Controls.Add(this.buttonDelObject);
this.groupBox2.Controls.Add(this.listBoxStorages);
this.groupBox2.Controls.Add(this.buttonAddObject);
this.groupBox2.Location = new System.Drawing.Point(13, 28);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(143, 214);
this.groupBox2.TabIndex = 5;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Наборы";
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(15, 30);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(122, 23);
this.textBoxStorageName.TabIndex = 6;
//
// buttonDelObject
//
this.buttonDelObject.Location = new System.Drawing.Point(15, 185);
this.buttonDelObject.Name = "buttonDelObject";
this.buttonDelObject.Size = new System.Drawing.Size(122, 23);
this.buttonDelObject.TabIndex = 8;
this.buttonDelObject.Text = "Удалить набор";
this.buttonDelObject.UseVisualStyleBackColor = true;
this.buttonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(15, 88);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(122, 79);
this.listBoxStorages.TabIndex = 6;
//
// buttonAddObject
//
this.buttonAddObject.Location = new System.Drawing.Point(15, 59);
this.buttonAddObject.Name = "buttonAddObject";
this.buttonAddObject.Size = new System.Drawing.Size(122, 23);
this.buttonAddObject.TabIndex = 7;
this.buttonAddObject.Text = "Добавить набор";
this.buttonAddObject.UseVisualStyleBackColor = true;
this.buttonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// FilemenuStrip
//
this.FilemenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.FilemenuStrip.Location = new System.Drawing.Point(0, 0);
this.FilemenuStrip.Name = "FilemenuStrip";
this.FilemenuStrip.Size = new System.Drawing.Size(909, 24);
this.FilemenuStrip.TabIndex = 6;
this.FilemenuStrip.Text = "menuStrip1";
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
this.SaveToolStripMenuItem.Text = "Сохранить";
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
this.LoadToolStripMenuItem.Text = "Загрузить";
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog";
this.openFileDialog.Filter = "\"txt file|*.txt|Все файлы|*.*\".";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "\"txt file|*.txt|Все файлы|*.*\".";
//
// FormExcavatorCollection
//
this.ClientSize = new System.Drawing.Size(909, 461);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.FilemenuStrip);
this.MainMenuStrip = this.FilemenuStrip;
this.Name = "FormExcavatorCollection";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.FilemenuStrip.ResumeLayout(false);
this.FilemenuStrip.PerformLayout();
this.ResumeLayout(false);
this.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;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -0,0 +1,287 @@
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].Name);
}
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;
}
}
/// <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}");
}
catch (ArgumentException ex)
{
_logger.LogWarning($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
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}");
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareExcavators(new ExcavatorCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareExcavators(new ExcavatorCompareByColor());
private void CompareExcavators(IComparer<DrawingExcavator?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowExcavator();
}
}
}

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,138 @@
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);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="excavator">Добавляемый экскаватор</param>
/// <returns></returns>
public bool Insert(T excavator, IEqualityComparer<T?>? equal = null)
{
return Insert(excavator, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="excavator">Добавляемый экскаватор</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T excavator, int position, IEqualityComparer<T?>? equal = null)
{
// TODO проверка позиции
if (position < 0 || position >= _maxCount)
{
throw new ExcavatorNotFoundException(position);
}
// TODO проверка, что есть место для вставки
if (_places.Count >= _maxCount)
{
throw new StorageOverflowException(_places.Count);
}
if (equal != null && _places.Contains(excavator, equal))
{
throw new ArgumentException("Добавляемый объект присутствует в коллекции");
}
// TODO вставка по позиции
_places.Insert(0, 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"
}
}
}