Compare commits

..

30 Commits
main ... Laba8

Author SHA1 Message Date
Kirill
8f30dca90b TractorGeneriStorage ready 2023-12-27 09:23:17 +04:00
Kirill
a0a018477f Начало 2023-12-27 08:38:38 +04:00
Kirill
55bb9dd042 Конец 7ой лабы2 2023-12-26 21:33:04 +04:00
Kirill
fec308c18b Конец 7ой лабы 2023-12-26 20:40:57 +04:00
Kirill
a8ae769f5c serilog меня убивает, помогите 2023-12-26 16:23:38 +04:00
Kirill
e1baef291c Закончил работу с логгером 2023-12-25 23:41:28 +04:00
Kirill
5ca50283c7 коммит2 2023-12-25 22:24:52 +04:00
Kirill
baa9a24290 коммит1 2023-12-25 22:22:47 +04:00
Kirill
47cf7a6743 коммит 2023-12-25 22:08:53 +04:00
Kirill
39e4865cc7 переделал StreamWriter и StreamReader 2023-12-25 21:36:16 +04:00
Kirill
e785755a98 Конец шестой 2023-12-21 19:29:49 +04:00
Kirill
7dfb6b2606 Создал 2 класса 2023-12-08 08:35:28 +04:00
Kirill
de6a249739 Забыл закомититть 2023-12-06 21:31:30 +04:00
Kirill
4cac5d627c Почти все 2023-11-24 08:49:27 +04:00
Kirill
a46f9d9063 П 2023-11-23 13:14:13 +04:00
Kirill
9164ec396f Создание формы 2023-11-22 20:32:24 +04:00
KirillFirsof
caaf1bf162 Конец четвертой лабы 2023-11-10 08:32:07 +04:00
KirillFirsof
c06691432d коммит 2023-11-09 21:54:25 +04:00
KirillFirsof
988e9bf8d6 работа с формой 2023-11-09 21:34:06 +04:00
KirillFirsof
b3a5559303 Создание классов 2023-11-09 21:01:58 +04:00
KirillFirsof
bd7a35bdf7 Теперь точно все 2023-11-09 19:09:59 +04:00
KirillFirsof
6cb1d0eeea Вроде все 2023-11-09 16:30:36 +04:00
KirillFirsof
d3b2e3a0ec Чутка вроде осталось 2023-11-09 15:06:11 +04:00
KirillFirsof
a666cfd261 Создание классов 2023-11-09 14:31:52 +04:00
KirillFirsof
07e6b5fba6 Коммит 2023-10-28 22:37:28 +04:00
KirillFirsof
679f01efec Закончено 2023-10-27 08:58:51 +04:00
KirillFirsof
c8f9dead9c Надеюсь все 2023-10-27 08:24:37 +04:00
KirillFirsof
b6e2b79297 СМЭРТЬ 2023-10-26 14:35:36 +04:00
KirillFirsof
0d0d57578e Доработка формы 2023-10-12 21:25:26 +04:00
KirillFirsof
8c7e0c3e99 Создание классов и формы 2023-10-12 21:23:15 +04:00
42 changed files with 3308 additions and 35 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32602.215
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RPP_FirstLaba_Tractor", "RPP_FirstLaba_Tractor\RPP_FirstLaba_Tractor.csproj", "{EF413F48-FFBF-4510-BA11-FAEBE7C0142A}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectTractor", "RPP_FirstLaba_Tractor\ProjectTractor.csproj", "{EF413F48-FFBF-4510-BA11-FAEBE7C0142A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
namespace ProjectTractor.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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor
{
public enum DirectionType
{
/// <summary>
/// /// Вверх
/// /// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
using ProjectTractor.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectTractor.Generics
{
internal class DrawiningTractorEqutables : IEqualityComparer<DrawningTractor?>
{
public bool Equals(DrawningTractor? x, DrawningTractor? y)
{
if (x == null || x.EntityTractor == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTractor == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTractor.Speed != y.EntityTractor.Speed)
{
return false;
}
if (x.EntityTractor.Weight != y.EntityTractor.Weight)
{
return false;
}
if (x.EntityTractor.BodyColor != y.EntityTractor.BodyColor)
{
return false;
}
if (x is DrawningBulldoser && y is DrawningBulldoser)
{
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTractor obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.Entities;
namespace ProjectTractor.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningBulldoser : DrawningTractor
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="wheelsOrnament">Признак наличия орнамента на колесах</param>
/// <param name="blade">Признак наличия отвала</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningBulldoser(int speed, double weight, Color bodyColor, Color
additionalColor, bool wheelsOrnament, bool blade, int width, int height) :
base(speed, weight, bodyColor, width, height, 110, 60)
{
if (EntityTractor != null)
{
EntityTractor = new EntityBulldoser(speed, weight, bodyColor,
additionalColor, wheelsOrnament, blade);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityTractor is not EntityBulldoser bulldoser)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(bulldoser.AdditionalColor);
base.DrawTransport(g);
// орнамент на колесах
if (bulldoser.WheelsOrnament)
{
g.FillEllipse(additionalBrush, _startPosX + 2, _startPosY + 47, 11, 11);
g.FillEllipse(additionalBrush, _startPosX + 67, _startPosY + 47, 11, 11);
g.FillEllipse(additionalBrush, _startPosX + 37, _startPosY + 57, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 22, _startPosY + 57, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 52, _startPosY + 57, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 27, _startPosY + 42, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 47, _startPosY + 42, 6, 6);
g.DrawLine(pen, _startPosX + 7, _startPosY + 47, _startPosX + 7, _startPosY + 58);
g.DrawLine(pen, _startPosX + 2, _startPosY + 53, _startPosX + 13, _startPosY + 53);
g.DrawLine(pen, _startPosX + 73, _startPosY + 47, _startPosX + 73, _startPosY + 58);
g.DrawLine(pen, _startPosX + 67, _startPosY + 53, _startPosX + 78, _startPosY + 53);
g.DrawLine(pen, _startPosX + 40, _startPosY + 57, _startPosX + 40, _startPosY + 62);
g.DrawLine(pen, _startPosX + 37, _startPosY + 60, _startPosX + 43, _startPosY + 60);
g.DrawLine(pen, _startPosX + 25, _startPosY + 57, _startPosX + 25, _startPosY + 62);
g.DrawLine(pen, _startPosX + 22, _startPosY + 60, _startPosX + 28, _startPosY + 60);
g.DrawLine(pen, _startPosX + 55, _startPosY + 57, _startPosX + 55, _startPosY + 62);
g.DrawLine(pen, _startPosX + 52, _startPosY + 60, _startPosX + 58, _startPosY + 60);
g.DrawLine(pen, _startPosX + 30, _startPosY + 42, _startPosX + 30, _startPosY + 48);
g.DrawLine(pen, _startPosX + 27, _startPosY + 45, _startPosX + 33, _startPosY + 45);
g.DrawLine(pen, _startPosX + 50, _startPosY + 42, _startPosX + 50, _startPosY + 48);
g.DrawLine(pen, _startPosX + 47, _startPosY + 45, _startPosX + 53, _startPosY + 45);
}
// отвал
if (bulldoser.Blade)
{
g.FillRectangle(additionalBrush, _startPosX + 82, _startPosY + 30, 10, 40);
g.FillRectangle(additionalBrush, _startPosX + 82, _startPosY + 60, 40, 10);
for (int i = 0; i < 15; i++)
{
g.FillRectangle(additionalBrush, _startPosX + 82, _startPosY + 60 - i * 2, 40 - i * 2, 10);
}
g.FillRectangle(additionalBrush, _startPosX + 50, _startPosY + 25, 10, 10);
for (int i = 0; i < 16; i++)
{
g.FillRectangle(additionalBrush, _startPosX + 50 + i * 2, _startPosY + 25 + i, 10, 10);
}
}
}
public void ChangeAdditionalColor(Color color)
{
((EntityBulldoser)EntityTractor).setAdditionalColor(color);
}
}
}

View File

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

View File

@ -0,0 +1,250 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.Entities;
using ProjectTractor.MovementStrategy;
namespace ProjectTractor.DrawningObjects {
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTractor {
/// <summary>
/// Класс-сущность
/// </summary>
public EntityTractor? EntityTractor { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
protected readonly int _tractorWidth = 75;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
protected readonly int _tractorHeight = 60;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningTractor(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width <= _tractorWidth || height <= _tractorHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
EntityTractor = new EntityTractor(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="tractorWidth">Ширина прорисовки автомобиля</param>
/// <param name="tractorHeight">Высота прорисовки автомобиля</param>
protected DrawningTractor(int speed, double weight, Color bodyColor, int
width, int height, int tractorWidth, int tractorHeight)
{
if (width <= _tractorWidth || height <= _tractorHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
_tractorWidth = tractorWidth;
_tractorHeight = tractorHeight;
EntityTractor = new EntityTractor(speed, weight, bodyColor);
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningTractor
/// </summary>
public IMoveableObject GetMoveableObject => new
DrawningObjectTractor(this);
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _tractorWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _tractorHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанномнаправлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityTractor == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityTractor.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityTractor.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityTractor.Step + _tractorWidth < _pictureWidth,
// вниз
DirectionType.Down => _startPosY + EntityTractor.Step + _tractorHeight < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityTractor == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityTractor.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityTractor.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityTractor.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityTractor.Step;
break;
}
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (EntityTractor == null)
return;
_startPosX = x;
_startPosY = y;
if (x + _tractorWidth >= _pictureWidth || y + _tractorHeight >= _pictureHeight)
{
_startPosX = 1;
_startPosY = (_tractorHeight + _tractorHeight) / 2;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityTractor == null)
{
return;
}
Pen pen = new(Color.Black);
Brush brGray = new SolidBrush(Color.Gray);
Brush brBlack = new SolidBrush(Color.Black);
Brush additionalBrush = new
SolidBrush(EntityTractor.BodyColor);
//Гусеницы
g.FillEllipse(brGray, _startPosX, _startPosY + 41, 25, 25);
g.FillEllipse(brGray, _startPosX + 55, _startPosY + 41, 25, 25);
g.FillRectangle(brGray, _startPosX + 13, _startPosY + 41, 54, 25);
//колеса
g.FillEllipse(brBlack, _startPosX, _startPosY + 45, 15, 15);
g.FillEllipse(brBlack, _startPosX + 65, _startPosY + 45, 15, 15);
g.FillEllipse(brBlack, _startPosX + 35, _startPosY + 55, 10, 10);
g.FillEllipse(brBlack, _startPosX + 20, _startPosY + 55, 10, 10);
g.FillEllipse(brBlack, _startPosX + 50, _startPosY + 55, 10, 10);
g.FillEllipse(brBlack, _startPosX + 25, _startPosY + 40, 10, 10);
g.FillEllipse(brBlack, _startPosX + 45, _startPosY + 40, 10, 10);
//кузов
g.FillRectangle(additionalBrush, _startPosX, _startPosY + 20, 80, 20);
g.FillRectangle(additionalBrush, _startPosX + 60, _startPosY, 10, 20);
g.FillRectangle(additionalBrush, _startPosX, _startPosY, 40, 20);
//Окно
Brush brBlue = new SolidBrush(Color.Blue);
g.FillRectangle(brBlue, _startPosX + 10, _startPosY + 3, 25, 15);
//Колеса
g.FillEllipse(additionalBrush, _startPosX + 2, _startPosY + 47, 11, 11);
g.FillEllipse(additionalBrush, _startPosX + 67, _startPosY + 47, 11, 11);
g.FillEllipse(additionalBrush, _startPosX + 37, _startPosY + 57, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 22, _startPosY + 57, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 52, _startPosY + 57, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 27, _startPosY + 42, 6, 6);
g.FillEllipse(additionalBrush, _startPosX + 47, _startPosY + 42, 6, 6);
//границы трактора
g.DrawRectangle(pen, _startPosX, _startPosY + 20, 80, 20);
g.DrawRectangle(pen, _startPosX + 60, _startPosY, 10, 20);
g.DrawRectangle(pen, _startPosX, _startPosY, 40, 20);
}
public void ChangeColor(Color color)
{
if (EntityTractor == null)
{
return;
}
EntityTractor.setBodyColor(color);
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.Entities
{
/// <summary>
/// Класс-сущность "Спортивный автомобиль"
/// </summary>
public class EntityBulldoser : EntityTractor
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия обвеса
/// </summary>
public bool WheelsOrnament { get; private set; }
/// <summary>
/// Признак (опция) наличия антикрыла
/// </summary>
public bool Blade { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="wheelsOrnament">Признак наличия обвеса</param>
/// <param name="blade">Признак наличия отвала</param>
public EntityBulldoser(int speed, double weight, Color bodyColor, Color
additionalColor, bool wheelsOrnament, bool blade) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
WheelsOrnament = wheelsOrnament;
Blade = blade;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

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

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.Entities;
namespace ProjectTractor.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityTractor
/// </summary>
public static class ExtentionDrawningTractor
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningTractor? CreateDrawningTractor(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningTractor(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningBulldoser(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="drawingTractor">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTractor drawningTractor,
char separatorForObject)
{
var tractor = drawningTractor.EntityTractor;
if (tractor == null)
{
return string.Empty;
}
var str = $"{tractor.Speed}{separatorForObject}{tractor.Weight}{separatorForObject}{tractor.BodyColor.Name}";
if (tractor is not EntityBulldoser bulldoser)
{
return str;
}
str = $"{str}{separatorForObject}{bulldoser.AdditionalColor.Name}{separatorForObject}{bulldoser.WheelsOrnament}{separatorForObject}{bulldoser.Blade}";
return str;
}
}
}

View File

@ -1,9 +1,377 @@
namespace RPP_FirstLaba_Tractor
using ProjectTractor.MovementStrategy;
using ProjectTractor.DrawningObjects;
namespace ProjectTractor
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Ñïîðòèâíûé àâòîìîáèëü"
/// </summary>
public partial class FormTractor : Form
{
private PictureBox pictureBoxTractor;
private Button buttonCreateTractor;
private Button buttonTop;
private Button buttonLeft;
private Button buttonDown;
private Button buttonCreateBulldoserTractor;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button buttonRight;
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningTractor? _drawningTractor;
private Button ButtonSelectTractor;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Âûáðàííûé àâòîìîáèëü
/// </summary>
public DrawningTractor? SelectedTractor { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormTractor()
{
InitializeComponent();
_strategy = null;
SelectedTractor = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû
/// </summary>
private void Draw()
{
if (_drawningTractor == null)
{
return;
}
Bitmap bmp = new(pictureBoxTractor.Width,
pictureBoxTractor.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningTractor.DrawTransport(gr);
pictureBoxTractor.Image = bmp;
}
/// <summary>
/// Èçìåíåíèå ðàçìåðîâ ôîðìû
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningTractor == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningTractor.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningTractor.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningTractor.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningTractor.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Ñîçäàíèå ïðîñòîãî àâòîìîáèëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_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;
}
_drawningTractor = new DrawningTractor(random.Next(100, 300),
random.Next(1000, 3000), color,
pictureBoxTractor.Width, pictureBoxTractor.Height);
_drawningTractor.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Øàã ñòðàòåãèè ïåðåìåùåíèÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStartegyStep_Click(object sender, EventArgs e)
{
if (_drawningTractor == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawningTractor.GetMoveableObject,
pictureBoxTractor.Width, pictureBoxTractor.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
/// <summary>
/// Âûáîð àâòîìîáèëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectTractor_Click(object sender, EventArgs e)
{
SelectedTractor = _drawningTractor;
DialogResult = DialogResult.OK;
}
private void InitializeComponent()
{
this.pictureBoxTractor = new System.Windows.Forms.PictureBox();
this.buttonCreateTractor = new System.Windows.Forms.Button();
this.buttonTop = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateBulldoserTractor = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.ButtonSelectTractor = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxTractor)).BeginInit();
this.SuspendLayout();
//
// pictureBoxTractor
//
this.pictureBoxTractor.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxTractor.Location = new System.Drawing.Point(0, 0);
this.pictureBoxTractor.Name = "pictureBoxTractor";
this.pictureBoxTractor.Size = new System.Drawing.Size(882, 453);
this.pictureBoxTractor.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxTractor.TabIndex = 0;
this.pictureBoxTractor.TabStop = false;
//
// buttonCreateTractor
//
this.buttonCreateTractor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateTractor.Location = new System.Drawing.Point(12, 403);
this.buttonCreateTractor.Name = "buttonCreateTractor";
this.buttonCreateTractor.Size = new System.Drawing.Size(246, 29);
this.buttonCreateTractor.TabIndex = 1;
this.buttonCreateTractor.Text = "Ñîçäàòü òðàêòîð";
this.buttonCreateTractor.UseVisualStyleBackColor = true;
this.buttonCreateTractor.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// buttonTop
//
this.buttonTop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonTop.BackgroundImage = global::ProjectTractor.Properties.Resources.arrowUp;
this.buttonTop.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonTop.Location = new System.Drawing.Point(804, 375);
this.buttonTop.Name = "buttonTop";
this.buttonTop.Size = new System.Drawing.Size(30, 30);
this.buttonTop.TabIndex = 2;
this.buttonTop.UseVisualStyleBackColor = true;
this.buttonTop.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::ProjectTractor.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(768, 411);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 3;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.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::ProjectTractor.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(804, 411);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 4;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.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::ProjectTractor.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(840, 411);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 5;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonCreateBulldoserTractor
//
this.buttonCreateBulldoserTractor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateBulldoserTractor.Location = new System.Drawing.Point(264, 403);
this.buttonCreateBulldoserTractor.Name = "buttonCreateBulldoserTractor";
this.buttonCreateBulldoserTractor.Size = new System.Drawing.Size(199, 29);
this.buttonCreateBulldoserTractor.TabIndex = 6;
this.buttonCreateBulldoserTractor.Text = "Ñîçäàòü áóëüäîçåð";
this.buttonCreateBulldoserTractor.UseVisualStyleBackColor = true;
this.buttonCreateBulldoserTractor.Click += new System.EventHandler(this.buttonCreateBulldoserTractor_Click);
//
// buttonStep
//
this.buttonStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonStep.Location = new System.Drawing.Point(776, 46);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(94, 29);
this.buttonStep.TabIndex = 7;
this.buttonStep.Text = "Øàã";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"Öåíòð ",
"Ïðàâûé íèæíèé"});
this.comboBoxStrategy.Location = new System.Drawing.Point(719, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(151, 28);
this.comboBoxStrategy.TabIndex = 8;
//
// ButtonSelectTractor
//
this.ButtonSelectTractor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ButtonSelectTractor.Location = new System.Drawing.Point(469, 403);
this.ButtonSelectTractor.Name = "ButtonSelectTractor";
this.ButtonSelectTractor.Size = new System.Drawing.Size(199, 29);
this.ButtonSelectTractor.TabIndex = 9;
this.ButtonSelectTractor.Text = "Âûáðàòü òðàêòîð";
this.ButtonSelectTractor.UseVisualStyleBackColor = true;
this.ButtonSelectTractor.Click += new System.EventHandler(this.ButtonSelectTractor_Click);
//
// FormTractor
//
this.ClientSize = new System.Drawing.Size(882, 453);
this.Controls.Add(this.ButtonSelectTractor);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.buttonCreateBulldoserTractor);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonTop);
this.Controls.Add(this.buttonCreateTractor);
this.Controls.Add(this.pictureBoxTractor);
this.Name = "FormTractor";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxTractor)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void buttonCreateBulldoserTractor_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 dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDopColor.Color;
}
_drawningTractor = new DrawningBulldoser(random.Next(100, 300),
random.Next(1000, 3000),
color,
dopColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxTractor.Width,
pictureBoxTractor.Height);
_drawningTractor.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningTractor == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new
DrawningObjectTractor(_drawningTractor), pictureBoxTractor.Width,
pictureBoxTractor.Height);
comboBoxStrategy.Enabled = false;
}
if (_strategy == null)
{
return;
}
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,514 @@
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 Microsoft.Extensions.Logging;
using ProjectTractor.DrawningObjects;
using ProjectTractor.Generics;
using ProjectTractor.MovementStrategy;
using ProjectTractor.Exceptions;
using System.Xml.Linq;
using System.Linq.Expressions;
using Serilog;
namespace ProjectTractor
{
public partial class FormTractorCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
///
private readonly TractorsGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormTractorCollection()
{
InitializeComponent();
_storage = new TractorsGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <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);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStorages_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTractors();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ??
string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTractor_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormTractorConfig form = new();
form.Show();
Action<DrawningTractor>? tractorDelegate = new((m) =>
{
bool isAdditionSuccessful = (obj + m);
if (isAdditionSuccessful)
{
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowTractors();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
});
form.AddEvent(tractorDelegate);
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTractor_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
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.ShowTractors();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
catch (TractorNotFoundException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <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.ShowTractors();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripMenuItemSave_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripMenuItemload_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information("Загрузка прошла успешно:");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void InitializeComponent()
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBox = new System.Windows.Forms.GroupBox();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.ButtonDelObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.ButtonAddObject = new System.Windows.Forms.Button();
this.textBoxStorageName = new System.Windows.Forms.MaskedTextBox();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveTractor = new System.Windows.Forms.Button();
this.ButtonAddTractor = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.file = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItemSave = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemload = 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.groupBox.SuspendLayout();
this.groupBox1.SuspendLayout();
this.file.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Dock = System.Windows.Forms.DockStyle.Left;
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(643, 532);
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
//
// groupBox
//
this.groupBox.Controls.Add(this.ButtonSortByColor);
this.groupBox.Controls.Add(this.ButtonSortByType);
this.groupBox.Controls.Add(this.groupBox1);
this.groupBox.Controls.Add(this.ButtonRefreshCollection);
this.groupBox.Controls.Add(this.ButtonRemoveTractor);
this.groupBox.Controls.Add(this.ButtonAddTractor);
this.groupBox.Controls.Add(this.maskedTextBoxNumber);
this.groupBox.Controls.Add(this.file);
this.groupBox.Location = new System.Drawing.Point(649, 12);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(255, 524);
this.groupBox.TabIndex = 2;
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
//
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(28, 326);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(203, 29);
this.ButtonSortByColor.TabIndex = 12;
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, 289);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(203, 29);
this.ButtonSortByType.TabIndex = 11;
this.ButtonSortByType.Text = "Сортировка по типу";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.ButtonDelObject);
this.groupBox1.Controls.Add(this.listBoxStorages);
this.groupBox1.Controls.Add(this.ButtonAddObject);
this.groupBox1.Controls.Add(this.textBoxStorageName);
this.groupBox1.Location = new System.Drawing.Point(16, 54);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(224, 229);
this.groupBox1.TabIndex = 9;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Наборы";
//
// ButtonDelObject
//
this.ButtonDelObject.Location = new System.Drawing.Point(12, 184);
this.ButtonDelObject.Name = "ButtonDelObject";
this.ButtonDelObject.Size = new System.Drawing.Size(203, 35);
this.ButtonDelObject.TabIndex = 3;
this.ButtonDelObject.Text = "Удалить набор";
this.ButtonDelObject.UseVisualStyleBackColor = true;
this.ButtonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 20;
this.listBoxStorages.Location = new System.Drawing.Point(12, 94);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(203, 84);
this.listBoxStorages.TabIndex = 2;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxStorages_SelectedIndexChanged);
//
// ButtonAddObject
//
this.ButtonAddObject.Location = new System.Drawing.Point(12, 59);
this.ButtonAddObject.Name = "ButtonAddObject";
this.ButtonAddObject.Size = new System.Drawing.Size(203, 29);
this.ButtonAddObject.TabIndex = 1;
this.ButtonAddObject.Text = "Добавить набор";
this.ButtonAddObject.UseVisualStyleBackColor = true;
this.ButtonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(12, 26);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(203, 27);
this.textBoxStorageName.TabIndex = 0;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(28, 473);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(203, 35);
this.ButtonRefreshCollection.TabIndex = 8;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// ButtonRemoveTractor
//
this.ButtonRemoveTractor.Location = new System.Drawing.Point(28, 434);
this.ButtonRemoveTractor.Name = "ButtonRemoveTractor";
this.ButtonRemoveTractor.Size = new System.Drawing.Size(203, 33);
this.ButtonRemoveTractor.TabIndex = 7;
this.ButtonRemoveTractor.Text = "Удалить трактор";
this.ButtonRemoveTractor.UseVisualStyleBackColor = true;
this.ButtonRemoveTractor.Click += new System.EventHandler(this.ButtonRemoveTractor_Click);
//
// ButtonAddTractor
//
this.ButtonAddTractor.Location = new System.Drawing.Point(28, 361);
this.ButtonAddTractor.Name = "ButtonAddTractor";
this.ButtonAddTractor.Size = new System.Drawing.Size(203, 34);
this.ButtonAddTractor.TabIndex = 6;
this.ButtonAddTractor.Text = "Добавить трактор";
this.ButtonAddTractor.UseVisualStyleBackColor = true;
this.ButtonAddTractor.Click += new System.EventHandler(this.ButtonAddTractor_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 401);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(203, 27);
this.maskedTextBoxNumber.TabIndex = 5;
//
// file
//
this.file.ImageScalingSize = new System.Drawing.Size(20, 20);
this.file.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemSave,
this.toolStripMenuItemload});
this.file.Location = new System.Drawing.Point(3, 23);
this.file.Name = "file";
this.file.Size = new System.Drawing.Size(249, 28);
this.file.TabIndex = 10;
this.file.Text = "файл";
//
// toolStripMenuItemSave
//
this.toolStripMenuItemSave.Name = "toolStripMenuItemSave";
this.toolStripMenuItemSave.Size = new System.Drawing.Size(97, 24);
this.toolStripMenuItemSave.Text = "Сохранить";
this.toolStripMenuItemSave.Click += new System.EventHandler(this.toolStripMenuItemSave_Click);
//
// toolStripMenuItemload
//
this.toolStripMenuItemload.Name = "toolStripMenuItemload";
this.toolStripMenuItemload.Size = new System.Drawing.Size(83, 24);
this.toolStripMenuItemload.Text = "Загрузка";
this.toolStripMenuItemload.Click += new System.EventHandler(this.toolStripMenuItemload_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormTractorCollection
//
this.ClientSize = new System.Drawing.Size(916, 532);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.pictureBoxCollection);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MinimizeBox = false;
this.Name = "FormTractorCollection";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Набор тракторов";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.groupBox.ResumeLayout(false);
this.groupBox.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.file.ResumeLayout(false);
this.file.PerformLayout();
this.ResumeLayout(false);
}
private GroupBox groupBox;
private Button ButtonRefreshCollection;
private Button ButtonRemoveTractor;
private Button ButtonAddTractor;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBox1;
private Button ButtonDelObject;
private ListBox listBoxStorages;
private Button ButtonAddObject;
private MaskedTextBox textBoxStorageName;
private MenuStrip file;
private ToolStripMenuItem toolStripMenuItemSave;
private ToolStripMenuItem toolStripMenuItemload;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
private PictureBox pictureBoxCollection;
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByColor());
private void CompareTractors(IComparer<DrawningTractor?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTractors();
}
}
}

View File

@ -0,0 +1,72 @@
<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>
<metadata name="file.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>94, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -0,0 +1,410 @@
namespace ProjectTractor
{
partial class FormTractorConfig
{
/// <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.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurpule = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGrey = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxBlade = new System.Windows.Forms.CheckBox();
this.checkBoxWheelsOrnament = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.labelColor = new System.Windows.Forms.Label();
this.labelAdditionalColor = new System.Windows.Forms.Label();
this.panelObject = new System.Windows.Forms.Panel();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxBlade);
this.groupBoxConfig.Controls.Add(this.checkBoxWheelsOrnament);
this.groupBoxConfig.Controls.Add(this.label2);
this.groupBoxConfig.Controls.Add(this.label1);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 0);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(585, 256);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(449, 171);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(114, 42);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(369, 171);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(74, 42);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurpule);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelGrey);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(369, 28);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(194, 120);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPurpule
//
this.panelPurpule.AllowDrop = true;
this.panelPurpule.BackColor = System.Drawing.Color.Purple;
this.panelPurpule.Location = new System.Drawing.Point(144, 69);
this.panelPurpule.Name = "panelPurpule";
this.panelPurpule.Size = new System.Drawing.Size(40, 40);
this.panelPurpule.TabIndex = 1;
this.panelPurpule.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelPurpule.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.AllowDrop = true;
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(98, 69);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 1;
this.panelBlack.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelGrey
//
this.panelGrey.AllowDrop = true;
this.panelGrey.BackColor = System.Drawing.Color.Silver;
this.panelGrey.Location = new System.Drawing.Point(52, 69);
this.panelGrey.Name = "panelGrey";
this.panelGrey.Size = new System.Drawing.Size(40, 40);
this.panelGrey.TabIndex = 1;
this.panelGrey.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelGrey.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.AllowDrop = true;
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(145, 23);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 1;
this.panelYellow.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.AllowDrop = true;
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(98, 23);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 1;
this.panelBlue.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.AllowDrop = true;
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(6, 69);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 1;
this.panelWhite.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.AllowDrop = true;
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(52, 23);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 0;
this.panelGreen.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelRed
//
this.panelRed.AllowDrop = true;
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(6, 23);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 0;
this.panelRed.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// checkBoxBlade
//
this.checkBoxBlade.AutoSize = true;
this.checkBoxBlade.Location = new System.Drawing.Point(32, 154);
this.checkBoxBlade.Name = "checkBoxBlade";
this.checkBoxBlade.Size = new System.Drawing.Size(205, 24);
this.checkBoxBlade.TabIndex = 5;
this.checkBoxBlade.Text = "Признак наличия отвала";
this.checkBoxBlade.UseVisualStyleBackColor = true;
//
// checkBoxWheelsOrnament
//
this.checkBoxWheelsOrnament.AutoSize = true;
this.checkBoxWheelsOrnament.Location = new System.Drawing.Point(32, 189);
this.checkBoxWheelsOrnament.Name = "checkBoxWheelsOrnament";
this.checkBoxWheelsOrnament.Size = new System.Drawing.Size(305, 24);
this.checkBoxWheelsOrnament.TabIndex = 4;
this.checkBoxWheelsOrnament.Text = "Признак наличия орнамета на колесах";
this.checkBoxWheelsOrnament.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(32, 82);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(33, 20);
this.label2.TabIndex = 3;
this.label2.Text = "Вес";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(32, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(73, 20);
this.label1.TabIndex = 2;
this.label1.Text = "Скорость";
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(132, 80);
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(109, 27);
this.numericUpDownWeight.TabIndex = 1;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(132, 26);
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(109, 27);
this.numericUpDownSpeed.TabIndex = 0;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(631, 227);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(94, 29);
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(746, 227);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(3, 50);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(259, 150);
this.pictureBoxObject.TabIndex = 2;
this.pictureBoxObject.TabStop = false;
//
// labelColor
//
this.labelColor.AllowDrop = true;
this.labelColor.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.labelColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelColor.Location = new System.Drawing.Point(2, 15);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(119, 32);
this.labelColor.TabIndex = 3;
this.labelColor.Text = "Цвет";
this.labelColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelColor_DragDrop);
this.labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// labelAdditionalColor
//
this.labelAdditionalColor.AllowDrop = true;
this.labelAdditionalColor.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.labelAdditionalColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAdditionalColor.Location = new System.Drawing.Point(142, 15);
this.labelAdditionalColor.Name = "labelAdditionalColor";
this.labelAdditionalColor.Size = new System.Drawing.Size(120, 32);
this.labelAdditionalColor.TabIndex = 4;
this.labelAdditionalColor.Text = "Доп. цвет";
this.labelAdditionalColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAdditionalColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelAdditionalColor_DragDrop);
this.labelAdditionalColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelObject.Controls.Add(this.labelAdditionalColor);
this.panelObject.Controls.Add(this.labelColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(603, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(267, 208);
this.panelObject.TabIndex = 4;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.panelObject_DragEnter);
//
// FormTractorConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(882, 271);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormTractorConfig";
this.Text = "FormTractorConfig";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private GroupBox groupBoxColors;
private Panel panelRed;
private Panel panelGreen;
private CheckBox checkBoxBlade;
private CheckBox checkBoxWheelsOrnament;
private Label label2;
private Label label1;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Panel panelPurpule;
private Panel panelBlack;
private Panel panelGrey;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelWhite;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Button buttonOk;
private Button buttonCancel;
private PictureBox pictureBoxObject;
private Label labelColor;
private Label labelAdditionalColor;
private Panel panelObject;
}
}

View File

@ -0,0 +1,180 @@
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 ProjectTractor.DrawningObjects;
using ProjectTractor.Entities;
namespace ProjectTractor;
public partial class FormTractorConfig : Form
{
/// <summary>
/// Переменная-выбранный трактор
/// </summary>
DrawningTractor? _tractor = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningTractor>? EventAddTractor;
/// <summary>
/// Конструктор
/// </summary>
//
public FormTractorConfig()
{
InitializeComponent();
panelBlack.MouseDown += panelColor_MouseDown;
panelPurpule.MouseDown += panelColor_MouseDown;
panelGrey.MouseDown += panelColor_MouseDown;
panelGreen.MouseDown += panelColor_MouseDown;
panelRed.MouseDown += panelColor_MouseDown;
panelWhite.MouseDown += panelColor_MouseDown;
panelYellow.MouseDown += panelColor_MouseDown;
panelBlue.MouseDown += panelColor_MouseDown;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать трактор
/// </summary>
private void DrawTractor()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_tractor?.SetPosition(5, 5);
_tractor?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningTractor> ev)
{
if (EventAddTractor == null)
{
EventAddTractor = ev;
}
else
{
EventAddTractor += ev;
}
}
/// <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":
_tractor = new DrawningTractor((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_tractor = new DrawningBulldoser((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxWheelsOrnament.Checked,
checkBoxBlade.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
labelColor.BackColor = Color.Empty;
labelAdditionalColor.BackColor = Color.Empty;
DrawTractor();
}
/// <summary>
/// Смена цвета
/// </summary>
private void panelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_tractor == null)
{
return;
}
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_tractor.ChangeColor(labelColor.BackColor);
DrawTractor();
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if ((_tractor == null) || (_tractor is DrawningBulldoser == false))
{
return;
}
labelAdditionalColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawningBulldoser)_tractor).ChangeAdditionalColor(labelAdditionalColor.BackColor);
DrawTractor();
}
/// <summary>
/// Добавление трактора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
if (_tractor == null)
return;
EventAddTractor?.Invoke(_tractor);
Close();
}
}

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,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.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,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth
&& objParams.RightBorder + GetStep() >= FieldWidth
&& objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - (FieldWidth - 1);
if (Math.Abs(diffX) > GetStep())
{
if (diffX < 0)
{
MoveRight();
}
}
var diffY = objParams.DownBorder - (FieldHeight - 1);
if (Math.Abs(diffY) > GetStep())
{
if (diffY < 0)
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.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,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
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>
/// <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,4 +1,10 @@
namespace RPP_FirstLaba_Tractor
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectTractor
{
internal static class Program
{
@ -8,10 +14,24 @@ namespace RPP_FirstLaba_Tractor
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTractor());
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appSettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormTractorCollection());
}
}
}

View File

@ -0,0 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="https://appsemble.app/api.json" /></VisualStudio></ProjectExtensions>
</Project>

View File

@ -8,7 +8,7 @@
// </auto-generated>
//------------------------------------------------------------------------------
namespace RPP_FirstLaba_Tractor.Properties {
namespace ProjectTractor.Properties {
using System;
@ -39,7 +39,7 @@ namespace RPP_FirstLaba_Tractor.Properties {
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RPP_FirstLaba_Tractor.Properties.Resources", typeof(Resources).Assembly);
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectTractor.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;

View File

@ -59,6 +59,7 @@
: 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">

View File

@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<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>

View File

@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.Exceptions;
namespace ProjectTractor.Generics
{
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) =>
_places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="tractor">Добавляемый трактор</param>
/// <returns></returns>
public bool Insert(T tractor, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(tractor, 0, equal);
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="tractor">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public void Insert(T tractor, int position, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
throw new Exception("Неверная позиция для вставки");
if (equal != null)
{
if (_places.Contains(tractor, equal))
throw new ArgumentException(nameof(tractor));
}
_places.Insert(position, tractor);
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public void Remove(int position)
{
if (!(position >= 0 && position < Count))
throw new TractorNotFoundException(position);
_places.RemoveAt(position);
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (!(position >= 0 && position <= Count))
return null;
return _places[position];
}
set
{
if (!(position >= 0 && position <= Count))
return;
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetTractors(int? maxTractors = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTractors.HasValue && i == maxTractors.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectTractor.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,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
namespace ProjectTractor.Generics
{
internal class TractorCompareByColor : IComparer<DrawningTractor?>
{
public int Compare(DrawningTractor? x, DrawningTractor? y)
{
if (x == null || x.EntityTractor == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityTractor == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityTractor.BodyColor.Name != y.EntityTractor.BodyColor.Name)
{
return x.EntityTractor.BodyColor.Name.CompareTo(y.EntityTractor.BodyColor.Name);
}
var speedCompare = x.EntityTractor.Speed.CompareTo(y.EntityTractor.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityTractor.Weight.CompareTo(y.EntityTractor.Weight);
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTractor.Generics
{
internal class TractorsCollectionInfo : IEquatable<TractorsCollectionInfo?>
{
public string Name { get; private set; }
public string Description { get; private set; }
public TractorsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(TractorsCollectionInfo? other)
{
if (other == null || other.Name == null)
throw new ArgumentNullException(nameof(other));
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
using ProjectTractor.MovementStrategy;
namespace ProjectTractor.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningTractor
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class TractorsGenericCollection<T, U>
where T : DrawningTractor
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTractors => _collection.GetTractors();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <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 TractorsGenericCollection(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="comparer"></param>
public void Sort(IComparer<T?> comparer) =>
_collection.SortSet(comparer);
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator +(TractorsGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(TractorsGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return true;
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCars => _collection.GetTractors();
/// <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 ShowTractors()
{
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 / 2, 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 i = 0;
foreach (var tractor in _collection.GetTractors())
{
if (tractor != null)
{
int countRows = _pictureWidth / _placeSizeWidth;
tractor.SetPosition(_pictureWidth - _placeSizeWidth * 2 - (i % countRows * _placeSizeWidth) + 210, _pictureHeight - i / countRows * _placeSizeHeight - 160);
tractor.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTractor.DrawningObjects;
using ProjectTractor.MovementStrategy;
using ProjectTractor.Generics;
namespace ProjectTractor
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class TractorsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<TractorsCollectionInfo, TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>> _tractorStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<TractorsCollectionInfo> Keys => _tractorStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public TractorsGenericStorage(int pictureWidth, int pictureHeight)
{
_tractorStorages = new Dictionary<TractorsCollectionInfo,
TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_tractorStorages.Add(new TractorsCollectionInfo(name, string.Empty),
new TractorsGenericCollection<DrawningTractor,
DrawningObjectTractor>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_tractorStorages.ContainsKey(new TractorsCollectionInfo(name, string.Empty)))
return;
_tractorStorages.Remove(new TractorsCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>?this[string ind]
{
get
{
TractorsCollectionInfo indObj = new TractorsCollectionInfo(ind, string.Empty);
if (_tractorStorages.ContainsKey(indObj))
return _tractorStorages[indObj];
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<TractorsCollectionInfo, TractorsGenericCollection<DrawningTractor, DrawningObjectTractor>> record in _tractorStorages)
{
StringBuilder records = new();
foreach (DrawningTractor? elem in record.Value.GetTractors)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter streamWriter = new(filename))
{
streamWriter.WriteLine($"TractorStorage{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
using (StreamReader streamReader = new(filename))
{
string str = streamReader.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("PlaneStorage"))
{
throw new IOException("Неверный формат данных");
}
_tractorStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = streamReader.ReadLine();
continue;
}
TractorsGenericCollection<DrawningTractor, DrawningObjectTractor> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningTractor? tractor = elem?.CreateDrawningTractor(_separatorForObject, _pictureWidth, _pictureHeight);
if (tractor != null)
{
if (!(collection + tractor))
{
throw new ArgumentNullException("Ошибка добавления в коллекцию");
}
}
}
_tractorStorages.Add(new TractorsCollectionInfo(record[0], string.Empty), collection);
str = streamReader.ReadLine();
} while (str != null);
}
return true;
}
}
}

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": "DoubleDeckerBus"
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -0,0 +1,4 @@
TractorStorage
первый|100:100:Yellow:Red:True:True;100:100:Green;
второй|100:100:Purple:Red:True:False;100:100:Yellow:Blue:False:True;

View File

@ -0,0 +1,3 @@
TractorStorage
gg|100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:White;100:100:Green:Purple:True:True;100:100:Yellow;100:100:White;