Лабораторная работа №2

This commit is contained in:
qkrlnt 2024-03-27 01:29:09 +04:00
parent 42aa45de02
commit b869ca4747
16 changed files with 821 additions and 161 deletions

View File

@ -1,21 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное
/// </summary>
Unknown = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>

View File

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectMonorail.Entities;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingMonorail : DrawingTrain
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="wheels">Количество колёс</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rail">Признак наличия магнитного рельса</param>
/// <param name="secondCarriage">Признак наличия второго вагона</param>
public DrawingMonorail(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) : base(40, 150)
{
EntityTrain = new EntityMonorail(speed, (int)weight, wheels, mainColor, additionalColor, rail, secondCarriage);
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityTrain == null || EntityTrain is not EntityMonorail monoRail || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
base.DrawTransport(g);
Brush additionalBrush = new SolidBrush(monoRail.AdditionalColor);
Pen pen = new(Color.Black);
Brush brBlue = new SolidBrush(Color.LightBlue);
Brush brWhite = new SolidBrush(Color.White);
Brush brBlack = new SolidBrush(Color.Black);
//магнитная рельса
if (monoRail.Rail)
{
if (monoRail.SecondСarriage)
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 150, 3);
}
else
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3);
}
}
//Второй вагон
if (monoRail.SecondСarriage)
{
//кузов
g.DrawRectangle(pen, _startPosX.Value + 95, _startPosY.Value, 55, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 96, _startPosY.Value + 1, 54, 29);
//сцепка
g.FillRectangle(brBlack, _startPosX.Value + 85, _startPosY.Value + 5, 10, 23);
//Окно
g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 35, 10);
g.FillRectangle(brBlue, _startPosX.Value + 106, _startPosY.Value + 6, 34, 9);
//Дверь
g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 10, 23);
g.FillRectangle(brWhite, _startPosX.Value + 106, _startPosY.Value + 16, 9, 12);
//Колёса
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 130, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 140, _startPosY.Value + 30, 10, 10);
}
switch (monoRail.Wheels)
{
case 3:
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
break;
case 4:
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10);
break;
}
}
}

View File

@ -1,20 +1,21 @@
using System;
using ProjectMonorail.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary>
public class DrawingMonorail
public class DrawingTrain
{
/// <summary>
/// Класс-сущность "монорельс"
/// </summary>
public EntityMonorail? EntityMonorail { get; private set; }
public EntityTrain? EntityTrain { get; protected set; }
/// <summary>
/// Высота окна
@ -29,12 +30,12 @@ public class DrawingMonorail
/// <summary>
/// Левая координата прорисовки монорельса
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки монорельса
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Высота прорисовки монорельса
@ -44,35 +45,68 @@ public class DrawingMonorail
/// <summary>
/// Ширина прорисовки монорельса
/// </summary>
private readonly int _drawingMonorailWidth = 100;
private readonly int _drawingMonorailWidth = 95;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="wheels">Количество колёс</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rail">Признак наличия магнитного рельса</param>
/// <param name="secondCarriage">Признак наличия второго вагона</param>
public void Init(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage)
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawingMonorailWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingMonorailHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawingTrain()
{
EntityMonorail = new EntityMonorail();
EntityMonorail.Init(speed, weight, wheels, mainColor, additionalColor, rail, secondCarriage);
_pictureHeight = null;
_pictureWidth = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
public DrawingTrain(int speed, double weight, Color mainColor) : this()
{
EntityTrain = new EntityTrain(speed, weight, mainColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawingMonorailHeight">Высота</param>
/// <param name="drawingMonorailWidth">Ширина</param>
protected DrawingTrain(int drawingMonorailHeight, int drawingMonorailWidth) : this()
{
_drawingMonorailHeight = drawingMonorailHeight;
_drawingMonorailWidth = drawingMonorailWidth;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns></returns>
public bool SetPictureSize(int width, int height)
public bool SetPictureSize(int width, int height)
{
//TODO!
if (_drawingMonorailWidth <= width && _drawingMonorailHeight <= height)
@ -133,50 +167,39 @@ public class DrawingMonorail
/// <returns>true - перемещение выполнено; false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityMonorail == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//Перемещение влево
case DirectionType.Left:
if (_startPosX.Value - EntityMonorail.Step > 0)
if (_startPosX.Value - EntityTrain.Step > 0)
{
_startPosX -= (int)EntityMonorail.Step;
_startPosX -= (int)EntityTrain.Step;
}
return true;
//Перемещение вправо
case DirectionType.Right:
if (EntityMonorail.SecondСarriage)
if (_startPosX.Value + _drawingMonorailWidth + EntityTrain.Step < _pictureWidth)
{
if (_startPosX.Value + 180 + EntityMonorail.Step < _pictureWidth)
{
_startPosX += (int)EntityMonorail.Step;
}
return true;
_startPosX += (int)EntityTrain.Step;
}
else
{
if (_startPosX.Value + _drawingMonorailWidth + EntityMonorail.Step < _pictureWidth)
{
_startPosX += (int)EntityMonorail.Step;
}
return true;
}
//Перемещение вверх
case DirectionType.Up:
if (_startPosY.Value - EntityMonorail.Step > 0)
if (_startPosY.Value - EntityTrain.Step > 0)
{
_startPosY -= (int)EntityMonorail.Step;
_startPosY -= (int)EntityTrain.Step;
}
return true;
//Перемещение вниз
case DirectionType.Down:
if (_startPosY.Value + _drawingMonorailHeight + EntityMonorail.Step < _pictureHeight)
if (_startPosY.Value + _drawingMonorailHeight + EntityTrain.Step < _pictureHeight)
{
_startPosY += (int)EntityMonorail.Step;
_startPosY += (int)EntityTrain.Step;
}
return true;
default: return false;
@ -187,16 +210,15 @@ public class DrawingMonorail
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityMonorail == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush mainBrush = new SolidBrush(EntityMonorail.MainColor);
Brush additionalBrush = new SolidBrush(EntityMonorail.AdditionalColor);
Brush mainBrush = new SolidBrush(EntityTrain.MainColor);
Brush brBlue = new SolidBrush(Color.LightBlue);
Brush brWhite = new SolidBrush(Color.White);
Brush brBlack = new SolidBrush(Color.Black);
@ -269,38 +291,6 @@ public class DrawingMonorail
g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 7, 10, 21);
g.FillRectangle(brWhite, _startPosX.Value + 41, _startPosY.Value + 8, 9, 20);
//магнитная рельса
if (EntityMonorail.Rail)
{
if (EntityMonorail.SecondСarriage)
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 180, 3);
}
else
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 40, 90, 3);
}
}
//Второй вагон
if (EntityMonorail.SecondСarriage)
{
g.DrawRectangle(pen, _startPosX.Value + 95, _startPosY.Value, 80, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 96, _startPosY.Value + 1, 79, 29);
g.FillRectangle(brBlack, _startPosX.Value + 85, _startPosY.Value + 5, 10, 23);
//Окно
g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 60, 10);
g.FillRectangle(brBlue, _startPosX.Value + 106, _startPosY.Value + 6, 59, 9);
//Дверь
g.DrawRectangle(pen, _startPosX.Value + 105, _startPosY.Value + 5, 10, 23);
g.FillRectangle(brWhite, _startPosX.Value + 106, _startPosY.Value + 16, 9, 12);
//Колёса
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 115, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 145, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 160, _startPosY.Value + 30, 10, 10);
}
//колёса
//1, 4 колесо
g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 30, 10, 10);
@ -308,19 +298,5 @@ public class DrawingMonorail
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 65, _startPosY.Value + 30, 10, 10);
switch (EntityMonorail.Wheels)
{
case 3:
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
break;
case 4:
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 30, _startPosY.Value + 30, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 50, _startPosY.Value + 30, 10, 10);
break;
}
}
}

View File

@ -4,33 +4,18 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail;
namespace ProjectMonorail.Entities;
/// <summary>
/// Класс-сущность "Монорельс"
/// </summary>
public class EntityMonorail
public class EntityMonorail : EntityTrain
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Количество колёс
/// </summary>
public int Wheels { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color MainColor { get; private set; }
/// <summary>
/// Дополнительный цвет
/// </summary>
@ -39,7 +24,7 @@ public class EntityMonorail
/// <summary>
/// Признак наличия магнитного рельса
/// </summary>
public bool Rail { get; private set; }
public bool Rail { get; private set; }
/// <summary>
/// Признак наличия второго вагона
@ -47,26 +32,15 @@ public class EntityMonorail
public bool SecondСarriage { get; private set; }
/// <summary>
/// Шаг передвижения
/// Конструктор
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса монорельса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="wheels">Количество колёс</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rail">Признак наличия магнитного рельса</param>
/// <param name="secondCarriage">Признак наличия второго вагона</param>
public void Init(int speed, double weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage)
public EntityMonorail(int speed, int weight, int wheels, Color mainColor, Color additionalColor, bool rail, bool secondCarriage) : base(speed, weight, mainColor)
{
Speed = speed;
Weight = weight;
Wheels = wheels;
MainColor = mainColor;
AdditionalColor = additionalColor;
Rail = rail;
SecondСarriage = secondCarriage;

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Entities;
/// <summary>
/// Класс-сущность "Поезд"
/// </summary>
public class EntityTrain
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color MainColor { get; private set; }
/// <summary>
/// Шаг передвижения
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
public EntityTrain(int speed, double weight, Color mainColor)
{
Speed = speed;
Weight = weight;
MainColor = mainColor;
}
}

View File

@ -34,6 +34,9 @@
buttonLeft = new Button();
buttonUp = new Button();
CreateMonorailButton = new Button();
CreateTrainButton = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit();
SuspendLayout();
//
@ -41,8 +44,9 @@
//
pictureBoxMonorail.Dock = DockStyle.Fill;
pictureBoxMonorail.Location = new Point(0, 0);
pictureBoxMonorail.Margin = new Padding(3, 4, 3, 4);
pictureBoxMonorail.Name = "pictureBoxMonorail";
pictureBoxMonorail.Size = new Size(1200, 647);
pictureBoxMonorail.Size = new Size(1142, 596);
pictureBoxMonorail.TabIndex = 5;
pictureBoxMonorail.TabStop = false;
//
@ -50,7 +54,8 @@
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.icons8_стрелка_50вниз;
buttonDown.Location = new Point(1082, 585);
buttonDown.Location = new Point(1024, 530);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(50, 50);
buttonDown.TabIndex = 10;
@ -61,7 +66,8 @@
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.icons8_стрелка_50__1_;
buttonRight.Location = new Point(1138, 585);
buttonRight.Location = new Point(1080, 530);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(50, 50);
buttonRight.TabIndex = 9;
@ -72,7 +78,8 @@
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.icons8_стрелка_50влево;
buttonLeft.Location = new Point(1026, 585);
buttonLeft.Location = new Point(968, 530);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(50, 50);
buttonLeft.TabIndex = 8;
@ -83,7 +90,8 @@
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.icons8_стрелка_50вверх;
buttonUp.Location = new Point(1082, 529);
buttonUp.Location = new Point(1024, 472);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(50, 50);
buttonUp.TabIndex = 7;
@ -93,25 +101,64 @@
// CreateMonorailButton
//
CreateMonorailButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
CreateMonorailButton.Location = new Point(12, 606);
CreateMonorailButton.Location = new Point(14, 541);
CreateMonorailButton.Margin = new Padding(3, 4, 3, 4);
CreateMonorailButton.Name = "CreateMonorailButton";
CreateMonorailButton.Size = new Size(76, 29);
CreateMonorailButton.Size = new Size(167, 39);
CreateMonorailButton.TabIndex = 6;
CreateMonorailButton.Text = "Создать";
CreateMonorailButton.Text = "Создать монорельс";
CreateMonorailButton.UseVisualStyleBackColor = true;
CreateMonorailButton.Click += CreateButton_Click;
//
// CreateTrainButton
//
CreateTrainButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
CreateTrainButton.Location = new Point(205, 541);
CreateTrainButton.Margin = new Padding(3, 4, 3, 4);
CreateTrainButton.Name = "CreateTrainButton";
CreateTrainButton.Size = new Size(167, 39);
CreateTrainButton.TabIndex = 11;
CreateTrainButton.Text = "Создать поезд";
CreateTrainButton.UseVisualStyleBackColor = true;
CreateTrainButton.Click += CreateTrainButton_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(979, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 12;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(1036, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 13;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormMonorail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1200, 647);
ClientSize = new Size(1142, 596);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(CreateTrainButton);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(CreateMonorailButton);
Controls.Add(pictureBoxMonorail);
Margin = new Padding(3, 4, 3, 4);
Name = "FormMonorail";
Text = "FormMonorail";
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).EndInit();
@ -126,5 +173,8 @@
private Button buttonLeft;
private Button buttonUp;
private Button CreateMonorailButton;
private Button CreateTrainButton;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -7,6 +7,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectMonorail.Drawings;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail
{
@ -18,7 +20,12 @@ namespace ProjectMonorail
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingMonorail? _drawingMonorail;
private DrawingTrain? _drawingTrain;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
@ -26,6 +33,7 @@ namespace ProjectMonorail
public FormMonorail()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -33,40 +41,65 @@ namespace ProjectMonorail
/// </summary>
private void Draw()
{
if (_drawingMonorail == null)
if (_drawingTrain == null)
{
return;
}
Bitmap bmp = new(pictureBoxMonorail.Width, pictureBoxMonorail.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingMonorail.DrawTransport(gr);
_drawingTrain.DrawTransport(gr);
pictureBoxMonorail.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawingTrain):
_drawingTrain = new DrawingTrain(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(DrawingMonorail):
_drawingTrain = new DrawingMonorail(random.Next(100, 300), random.Next(1000, 3000), random.Next(2, 5),
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;
}
_drawingTrain.SetPictureSize(pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawingTrain.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 CreateButton_Click(object sender, EventArgs e)
{
Random random = new();
_drawingMonorail = new DrawingMonorail();
_drawingMonorail.Init(random.Next(100, 300), random.Next(1000, 3000), random.Next(2, 5),
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)));
_drawingMonorail.SetPictureSize(pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100));
CreateObject(nameof(DrawingMonorail));
}
Draw();
/// <summary>
/// Обработка нажатия кнопки "Создать поезд"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CreateTrainButton_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingTrain));
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingMonorail == null)
if (_drawingTrain == null)
{
return;
}
@ -76,16 +109,16 @@ namespace ProjectMonorail
switch (name)
{
case "buttonUp":
result = _drawingMonorail.MoveTransport(DirectionType.Up);
result = _drawingTrain.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawingMonorail.MoveTransport(DirectionType.Down);
result = _drawingTrain.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawingMonorail.MoveTransport(DirectionType.Left);
result = _drawingTrain.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawingMonorail.MoveTransport(DirectionType.Right);
result = _drawingTrain.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -93,5 +126,43 @@ namespace ProjectMonorail
Draw();
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingTrain == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTrain(_drawingTrain), pictureBoxMonorail.Width, pictureBoxMonorail.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,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMovableObjects? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
/// <returns></returns>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="movableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMovableObjects movableObject, int width, int height)
{
if (movableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = movableObject;
FieldHeight = height;
FieldWidth = width;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Шаг влево
/// </summary>
/// <returns></returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Шаг вверх
/// </summary>
/// <returns></returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Шаг вправо
/// </summary>
/// <returns></returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Шаг вниз
/// </summary>
/// <returns></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 IsTargetDestination();
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 ProjectMonorail.MovementStrategy;
public interface IMovableObjects
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в заданном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
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())
{
MoveRight();
}
int diffy = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffy) > GetStep())
{
MoveDown();
}
}
}

View File

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

View File

@ -0,0 +1,63 @@
using ProjectMonorail.Drawings;
namespace ProjectMonorail.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawingTrain
/// </summary>
public class MoveableTrain : IMovableObjects
{
/// <summary>
/// Поле-объект класса DrawingTrain или его наследника
/// </summary>
private readonly DrawingTrain? _train = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="train">Объект класса DrawingTrain</param>
public MoveableTrain(DrawingTrain train)
{
_train = train;
}
public ObjectParameters? GetObjectPosition
{
get
{
if(_train == null || _train.EntityTrain == null || !_train.GetPosX.HasValue || !_train.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_train.GetPosX.Value, _train.GetPosY.Value, _train.GetWidth, _train.GetHeight);
}
}
public int GetStep => (int)(_train?.EntityTrain?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_train == null || _train.EntityTrain == null)
{
return false;
}
return _train.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.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
_ => DirectionType.Unknown,
};
}
}

View File

@ -0,0 +1,27 @@
namespace ProjectMonorail.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4,
}

View File

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TobBorder => _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="height">Высота</param>
/// <param name="width">Ширина</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_height = height;
_width = width;
}
}

View File

@ -0,0 +1,22 @@
namespace ProjectMonorail.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@ -1,5 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>