PIbd-12_Bugrov_D.A._Simple LabWork03 #2

Closed
BoiledMilk wants to merge 8 commits from LabWork02 into LabWork01
15 changed files with 839 additions and 173 deletions

View File

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

View File

@ -0,0 +1,74 @@

using ProjectElectricLocomotive.Entities;
namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта - сущности
/// </summary>
public class DrawningElectricLocomotive : DrawningLocomotive
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="electricHorns"></param>
/// <param name="batteryPlacement"></param>
public DrawningElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) : base(83,45)
{
EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement);
}
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
//Создание перьев и кистей для прорисовки электровоза
Brush blackBrush = new SolidBrush(Color.Black);
Pen penSolid = new(electricLocomotive.AdditionalColor, 2);
Pen penSolidYellow = new(Color.Yellow, 0.5f);
Brush additionalBrush = new SolidBrush(electricLocomotive.AdditionalColor);
//Прорисовка дополнительного элемента (рогов)
if (electricLocomotive.ElectricHorns)
{
//Инициализация опорных точек для прорисовки "рогов"
Point pointHorns1 = new Point(_startPosX.Value + 13, _startPosY.Value + 5);
Point pointHorns2 = new Point(_startPosX.Value + 16, _startPosY.Value + 2);
Point pointHorns3 = new Point(_startPosX.Value + 11, _startPosY.Value);
//Прорисовка "рогов" электровоза
g.DrawLine(penSolid, pointHorns1, pointHorns2);
g.DrawLine(penSolid, pointHorns2, pointHorns3);
}
//Прорисовка дополнительного элемента (места под батарею)
if (electricLocomotive.BatteryPlacement)
{
//Инициализация опорных точек для прорисовки молнии на хранилище батарей
Point pointLightning1 = new Point(_startPosX.Value + 39, _startPosY.Value + 37);
Point pointLightning2 = new Point(_startPosX.Value + 37, _startPosY.Value + 39);
Point pointLightning3 = new Point(_startPosX.Value + 39, _startPosY.Value + 40);
Point pointLightning4 = new Point(_startPosX.Value + 37, _startPosY.Value + 41);
//Прорисовка "хранилища батарей" электровоза
g.FillRectangle(additionalBrush, _startPosX.Value + 36, _startPosY.Value + 37, 8, 4.5f);
g.DrawLine(penSolidYellow, pointLightning1, pointLightning2);
g.DrawLine(penSolidYellow, pointLightning2, pointLightning3);
g.DrawLine(penSolidYellow, pointLightning3, pointLightning4);
}
_startPosY += 5;
base.DrawTransport(g);
_startPosY -= 5;
}
}

View File

@ -1,15 +1,18 @@

namespace ProjectElectricLocomotive;
using ProjectElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта - сущности
/// </summary>
public class DrawningElectricLocomotive
namespace ProjectElectricLocomotive.Drawnings;
public class DrawningLocomotive
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityElectricLocomotive? EntityElectricLocomotive { get; private set; }
public EntityLocomotive? EntityLocomotive { get; protected set; }
/// <summary>
/// Ширина окна
@ -22,47 +25,79 @@ public class DrawningElectricLocomotive
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки электровоза
/// Левая координата прорисовки локомотива
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки электровоза
/// Верхняя координата прорисовки локомотива
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки электровоза
/// Ширина прорисовки локомотива
/// </summary>
private readonly int _drawningElectricLocomotiveWidth = 83;
private readonly int _drawningLocomotiveWidth = 83;
/// <summary>
/// Высота прорисовки электровоза
/// Высота прорисовки локомотива
/// </summary>
private readonly int _drawningElectricLocomotiveHeight = 45;
private readonly int _drawningLocomotiveHeight = 40;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="bodyKit"></param>
/// <param name="electricHorns"></param>
/// <param name="batteryPlacement"></param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement)
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningLocomotiveWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningLocomotiveHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningLocomotive()
{
EntityElectricLocomotive = new EntityElectricLocomotive();
EntityElectricLocomotive.Init(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public DrawningLocomotive(int speed, double weight, Color bodyColor) : this()
{
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningLocomotiveWidth">Ширина прорисовки локомотива</param>
/// <param name="drawningLocomotiveHeight">Высота прорисовки локомотива</param>
protected DrawningLocomotive(int drawningLocomotiveWidth, int drawningLocomotiveHeight) : this()
{
_drawningLocomotiveWidth = drawningLocomotiveWidth;
_drawningLocomotiveHeight = drawningLocomotiveHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -71,19 +106,19 @@ public class DrawningElectricLocomotive
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if(_drawningElectricLocomotiveHeight > height || _drawningElectricLocomotiveWidth > width)
if (_drawningLocomotiveHeight > height || _drawningLocomotiveWidth > width)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
if (_startPosY.HasValue && _startPosY + _drawningElectricLocomotiveHeight < _pictureHeight )
if (_startPosY.HasValue && _startPosY + _drawningLocomotiveHeight < _pictureHeight)
{
_startPosY = _pictureHeight - _drawningElectricLocomotiveHeight;
_startPosY = _pictureHeight - _drawningLocomotiveHeight;
}
if (_startPosX.HasValue && _startPosX + _drawningElectricLocomotiveWidth < _pictureWidth )
if (_startPosX.HasValue && _startPosX + _drawningLocomotiveWidth < _pictureWidth)
{
_startPosX = _pictureWidth - _drawningElectricLocomotiveWidth;
_startPosX = _pictureWidth - _drawningLocomotiveWidth;
}
return true;
}
@ -95,23 +130,21 @@ public class DrawningElectricLocomotive
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if(!_pictureHeight.HasValue || !_pictureWidth.HasValue) {
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if ( _drawningElectricLocomotiveHeight + y > _pictureHeight)
if (_drawningLocomotiveHeight + y > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningElectricLocomotiveHeight;
_startPosY = _pictureHeight - _drawningLocomotiveHeight;
}
if ( _drawningElectricLocomotiveWidth + x > _pictureWidth)
if (_drawningLocomotiveWidth + x > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningElectricLocomotiveWidth;
_startPosX = _pictureWidth - _drawningLocomotiveWidth;
}
if (x < 0)
{
@ -133,39 +166,39 @@ public class DrawningElectricLocomotive
/// <returns>true - перемещение выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if(EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch(direction)
switch (direction)
{
//влево
case DirectionType.Left:
if(_startPosX.Value - EntityElectricLocomotive.Step > 0)
if (_startPosX.Value - EntityLocomotive.Step > 0)
{
_startPosX -= (int)EntityElectricLocomotive.Step;
_startPosX -= (int)EntityLocomotive.Step;
}
return true;
//вверх
case DirectionType.Up:
if(_startPosY.Value - EntityElectricLocomotive.Step > 0)
if (_startPosY.Value - EntityLocomotive.Step > 0)
{
_startPosY -= (int)EntityElectricLocomotive.Step;
}
_startPosY -= (int)EntityLocomotive.Step;
}
return true;
//вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningElectricLocomotiveWidth + EntityElectricLocomotive.Step < _pictureWidth)
if (_startPosX.Value + _drawningLocomotiveWidth + EntityLocomotive.Step < _pictureWidth)
{
_startPosX += (int)EntityElectricLocomotive.Step;
_startPosX += (int)EntityLocomotive.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawningElectricLocomotiveHeight + EntityElectricLocomotive.Step < _pictureHeight)
if (_startPosY.Value + _drawningLocomotiveHeight + EntityLocomotive.Step < _pictureHeight)
{
_startPosY += (int)EntityElectricLocomotive.Step;
_startPosY += (int)EntityLocomotive.Step;
}
return true;
default:
@ -177,9 +210,9 @@ public class DrawningElectricLocomotive
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
@ -189,34 +222,34 @@ public class DrawningElectricLocomotive
Pen penSolid = new(Color.Black, 2);
Pen penSolidYellow = new(Color.Yellow, 0.5f);
Pen windowPen = new(Color.DeepSkyBlue);
Brush additionalBrush = new SolidBrush(EntityElectricLocomotive.AdditionalColor);
Brush blackBrush = new SolidBrush(Color.Black);
Brush whiteBrush = new SolidBrush(Color.White);
Brush additionalBrush = new SolidBrush(EntityLocomotive.BodyColor);
//Инициализация опорных точек для прорисовки корпуса
Point pointStart = new Point(_startPosX.Value + 75, _startPosY.Value + 20);
Point point1 = new Point(_startPosX.Value + 75, _startPosY.Value + 5);
Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value + 5);
Point pointFinish = new Point(_startPosX.Value + 5, _startPosY.Value + 20);
Point pointStart = new Point(_startPosX.Value + 75, _startPosY.Value + 15);
Point point1 = new Point(_startPosX.Value + 75, _startPosY.Value);
Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value);
Point pointFinish = new Point(_startPosX.Value + 5, _startPosY.Value + 15);
//Инициализация опорных точек для прорисовки первой "юбки"
Point point3 = new Point(_startPosX.Value + 7, _startPosY.Value + 37);
Point point4 = new Point(_startPosX.Value + 0, _startPosY.Value + 37 +6 );
Point point5 = new Point(_startPosX.Value + 7, _startPosY.Value + 37 + 6 );
Point point3 = new Point(_startPosX.Value + 7, _startPosY.Value + 32);
Point point4 = new Point(_startPosX.Value, _startPosY.Value + 32 + 6);
Point point5 = new Point(_startPosX.Value + 7, _startPosY.Value + 32 + 6);
//Инициализация опорных точек для прорисовки второй "юбки"
Point point6 = new Point(_startPosX.Value + 69, _startPosY.Value + 37);
Point point7 = new Point(_startPosX.Value + 75 + 7, _startPosY.Value + 37 + 6);
Point point8 = new Point(_startPosX.Value + 69, _startPosY.Value + 37 + 6);
Point point6 = new Point(_startPosX.Value + 69, _startPosY.Value + 32);
Point point7 = new Point(_startPosX.Value + 75 + 7, _startPosY.Value + 32 + 6);
Point point8 = new Point(_startPosX.Value + 69, _startPosY.Value + 32 + 6);
//Совокупность точек полигона уголка первой "юбки"
Point[] firstTrianglePoints =
{
point3,
point4,
point5,
};
//Совокупность точек полигона уголка второй "юбки"
Point[] secondTrianglePoints =
@ -233,77 +266,49 @@ public class DrawningElectricLocomotive
g.FillPolygon(blackBrush, secondTrianglePoints);
//Прорисовка корпуса
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 20, 70, 17);
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 15, 70, 17);
g.DrawLine(pen, point3, point4);
g.DrawLine(pen, pointStart, point1);
g.DrawLine(pen, point1, point2);
g.DrawLine(pen, point2, pointFinish);
Brush brWhite = new SolidBrush(Color.White);
g.DrawRectangle(windowPen, _startPosX.Value + 24.3f, _startPosY.Value + 9, 8, 8);
g.DrawRectangle(windowPen, _startPosX.Value + 24.3f, _startPosY.Value + 4, 8, 8);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 14, 8, 12);
g.FillRectangle(brWhite, _startPosX.Value + 36, _startPosY.Value + 16, 7, 10);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 9, 8, 12);
g.FillRectangle(brWhite, _startPosX.Value + 36, _startPosY.Value + 11, 7, 10);
//Прорисовка передней и задней "юбки"
g.FillRectangle(blackBrush, _startPosX.Value + 7, _startPosY.Value + 37, 25, 5.3f);
g.FillRectangle(blackBrush, _startPosX.Value + 47, _startPosY.Value + 37, 22, 5.3f);
g.FillRectangle(blackBrush, _startPosX.Value + 7, _startPosY.Value + 32, 25, 5.3f);
g.FillRectangle(blackBrush, _startPosX.Value + 47, _startPosY.Value + 32, 22, 5.3f);
//Прорисовка двух передних колёс
g.FillEllipse(whiteBrush, _startPosX.Value + 6.3f, _startPosY.Value + 37, 10, 10);
g.DrawEllipse(penSolid, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8);
g.DrawEllipse(penSolid, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8);
g.FillEllipse(whiteBrush, _startPosX.Value + 6.3f, _startPosY.Value + 32, 10, 10);
g.DrawEllipse(penSolid, _startPosX.Value + 9, _startPosY.Value + 32, 8, 8);
g.DrawEllipse(penSolid, _startPosX.Value + 24, _startPosY.Value + 32, 8, 8);
//Прорисовка двух задних колёс
g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 38, _startPosY.Value + 37, 10, 10);
g.DrawEllipse(penSolid, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8);
g.DrawEllipse(penSolid, _startPosX.Value+ 25 + 37, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 37, 8, 8);
g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 38, _startPosY.Value + 32, 10, 10);
g.DrawEllipse(penSolid, _startPosX.Value + 25 + 26, _startPosY.Value + 32, 8, 8);
g.DrawEllipse(penSolid, _startPosX.Value + 25 + 37, _startPosY.Value + 32, 8, 8);
//Прорисовка заднего "шлюза"
g.FillRectangle(blackBrush, _startPosX.Value + 75, _startPosY.Value + 9, 5.7f, 27.4f);
g.FillRectangle(blackBrush, _startPosX.Value + 75, _startPosY.Value + 4, 5.7f, 27.4f);
//Прорисовка первого и третьего окна
g.DrawRectangle(windowPen, _startPosX.Value + 12, _startPosY.Value + 9, 8, 8);
g.DrawRectangle(windowPen, _startPosX.Value + 63, _startPosY.Value + 9, 8, 8);
g.DrawRectangle(windowPen, _startPosX.Value + 12, _startPosY.Value + 4, 8, 8);
g.DrawRectangle(windowPen, _startPosX.Value + 63, _startPosY.Value + 4, 8, 8);
//Опциональная прорисовка цвета передних колёс
g.FillEllipse(additionalBrush, _startPosX.Value + 9, _startPosY.Value + 32, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 24, _startPosY.Value + 32, 8, 8);
if (EntityElectricLocomotive.ElectricHorns)
{
//Инициализация опорных точек для прорисовки "рогов"
Point pointHorns1 = new Point(_startPosX.Value + 13, _startPosY.Value + 5);
Point pointHorns2 = new Point(_startPosX.Value + 16, _startPosY.Value + 2);
Point pointHorns3 = new Point(_startPosX.Value + 11, _startPosY.Value);
//Прорисовка "рогов" электровоза
g.DrawLine(penSolid, pointHorns1, pointHorns2);
g.DrawLine(penSolid, pointHorns2, pointHorns3);
}
if(EntityElectricLocomotive.BatteryPlacement)
{
//Инициализация опорных точек для прорисовки молнии на хранилище батарей
Point pointLightning1 = new Point(_startPosX.Value + 39, _startPosY.Value + 37);
Point pointLightning2 = new Point(_startPosX.Value + 37, _startPosY.Value + 39);
Point pointLightning3 = new Point(_startPosX.Value + 39, _startPosY.Value + 40);
Point pointLightning4 = new Point(_startPosX.Value + 37, _startPosY.Value + 41);
//Прорисовка "хранилища батарей" электровоза
g.FillRectangle(blackBrush, _startPosX.Value + 36, _startPosY.Value + 37, 8, 4.5f);
g.DrawLine(penSolidYellow, pointLightning1, pointLightning2);
g.DrawLine(penSolidYellow, pointLightning2, pointLightning3);
g.DrawLine(penSolidYellow, pointLightning3, pointLightning4);
}
//Опциональная прорисовка цвета задних колёс
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 32, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 32, 8, 8);
}
}

View File

@ -1,26 +1,11 @@

namespace ProjectElectricLocomotive;
namespace ProjectElectricLocomotive.Entities;
/// <summary>
/// Класс-сущность "Тепловоз"
/// Класс-сущность "Электровоз"
/// </summary>
public class EntityElectricLocomotive
public class EntityElectricLocomotive : EntityLocomotive
{
/// <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>
@ -36,11 +21,6 @@ public class EntityElectricLocomotive
/// </summary>
public bool BatteryPlacement { get; private set; }
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса тепловоза
/// </summary>
@ -50,15 +30,10 @@ public class EntityElectricLocomotive
/// <param name="additionalcolor"></param>
/// <param name="electrichorns"></param>
/// <param name="batteryplacement"></param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement)
public EntityElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
ElectricHorns = electricHorns;
BatteryPlacement = batteryPlacement;
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Entities;
/// <summary>
/// Класс-сущность "Локомотив"
/// </summary>
public class EntityLocomotive
{
/// <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 => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public EntityLocomotive(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -34,6 +34,9 @@
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonCreateLocomotive = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit();
SuspendLayout();
//
@ -49,11 +52,11 @@
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 430);
buttonCreate.Location = new Point(12, 436);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(104, 37);
buttonCreate.Size = new Size(150, 31);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать электровоз";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
@ -109,11 +112,45 @@
buttonUp.UseVisualStyleBackColor = false;
buttonUp.Click += ButtonMove_Click;
//
// buttonCreateLocomotive
//
buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateLocomotive.Location = new Point(187, 436);
buttonCreateLocomotive.Name = "buttonCreateLocomotive";
buttonCreateLocomotive.Size = new Size(150, 31);
buttonCreateLocomotive.TabIndex = 6;
buttonCreateLocomotive.Text = "Создать локомотив";
buttonCreateLocomotive.UseVisualStyleBackColor = true;
buttonCreateLocomotive.Click += buttonCreateLocomotive_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(733, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(764, 72);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(90, 33);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormElectricLocomotive
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(866, 479);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateLocomotive);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
@ -134,5 +171,8 @@
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
private Button buttonCreateLocomotive;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,6 @@
using System;
using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -12,11 +14,20 @@ namespace ProjectElectricLocomotive;
public partial class FormElectricLocomotive : Form
{
private DrawningElectricLocomotive? _drawningElectricLocomotive;
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningLocomotive? _drawningLocomotive;
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormElectricLocomotive()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -24,34 +35,61 @@ public partial class FormElectricLocomotive : Form
/// </summary>
private void Draw()
{
if (_drawningElectricLocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
Bitmap bmp = new(pictureBoxElectricLocomotive.Width,
pictureBoxElectricLocomotive.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningElectricLocomotive.DrawTransport(gr);
_drawningLocomotive.DrawTransport(gr);
pictureBoxElectricLocomotive.Image = bmp;
}
private void ButtonCreate_Click(object sender, EventArgs e)
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type"></param>
private void CreateObject(string type)
{
Random random = new();
_drawningElectricLocomotive = new DrawningElectricLocomotive();
_drawningElectricLocomotive.Init(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningElectricLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningElectricLocomotive.SetPosition(random.Next(0,pictureBoxElectricLocomotive.Width), random.Next(0,pictureBoxElectricLocomotive.Height));
Bitmap bmp = new(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningElectricLocomotive.DrawTransport(gr);
pictureBoxElectricLocomotive.Image = bmp;
switch (type)
{
case nameof(DrawningLocomotive):
_drawningLocomotive = new DrawningLocomotive(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningElectricLocomotive):
_drawningLocomotive = new DrawningElectricLocomotive(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать электровоз"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningElectricLocomotive));
/// <summary>
/// Обработка нажатия кнопки "Создать локомотив"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
@ -59,7 +97,7 @@ public partial class FormElectricLocomotive : Form
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningElectricLocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
@ -69,19 +107,19 @@ public partial class FormElectricLocomotive : Form
{
case "buttonUp":
result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Up);
_drawningLocomotive.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Down);
_drawningLocomotive.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Left);
_drawningLocomotive.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Right);
_drawningLocomotive.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -89,6 +127,38 @@ public partial class FormElectricLocomotive : Form
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningLocomotive == null) return;
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null) return;
_strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
}
if (_strategy == null) return;
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

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

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public interface IMoveableObject
{
/// <summary>
/// Получение координат объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>True - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,69 @@
using ProjectElectricLocomotive.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject c использованием DrawningLocomotive
/// </summary>
public class MoveableLocomotive : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningLocomotive или его наследника
/// </summary>
private readonly DrawningLocomotive? _locomotive = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="locomotive">Объект класса DrawningLocomotive</param>
public MoveableLocomotive(DrawningLocomotive locomotive)
{
_locomotive = locomotive;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_locomotive == null || _locomotive.EntityLocomotive == null || !_locomotive.GetPosX.HasValue || !_locomotive.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_locomotive.GetPosX.Value, _locomotive.GetPosY.Value, _locomotive.GetWidth, _locomotive.GetHeight);
}
}
public int GetStep => (int)(_locomotive?.EntityLocomotive?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_locomotive == null || _locomotive.EntityLocomotive == null)
{
return false;
}
return _locomotive.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0) MoveLeft();
else MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0) MoveUp();
else MoveDown();
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0) MoveLeft();
else MoveRight();
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0) MoveUp();
else MoveDown();
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вверх
/// </summary>
Down = 2,
/// <summary>
/// Вверх
/// </summary>
Left = 3,
/// <summary>
/// Вверх
/// </summary>
Right = 4,
}

View File

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

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