Compare commits

...

4 Commits
main ... lab3

Author SHA1 Message Date
Илья
ba9a4d66ce Изменен метод добавления в начало набора 2023-10-10 17:42:35 +04:00
Илья
656f12f9a9 Готовая 3 лабораторная 2023-10-10 14:57:21 +04:00
Илья
fcf35359c7 Готовая 2 лабораторная 2023-09-26 16:06:43 +04:00
Илья
17c57e7c37 Готовая 1 лабораторная 2023-09-25 16:43:21 +04:00
30 changed files with 2091 additions and 75 deletions

@ -0,0 +1,141 @@
namespace ProjectMonorail.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;
}
}
}

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

@ -0,0 +1,99 @@
using ProjectMonorail.Entities;
namespace ProjectMonorail.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingExtendedMonorail : DrawingMonorail
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="magneticRail">Признак наличия магнитной рельсы</param>
/// <param name="extraCabin">Признак наличия дополнительной кабины</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingExtendedMonorail(int speed, double weight, Color mainColor, Color additionalColor, bool magneticRail,
bool extraCabin, int width, int height) : base(speed, weight, mainColor, width, height, 186, 92)
{
if (!magneticRail && !extraCabin)
{
_monorailWidth = 117;
_monorailHeight = 56;
}
if (!magneticRail && extraCabin)
{
_monorailWidth = 183;
_monorailHeight = 56;
}
if (EntityMonorail != null)
{
EntityMonorail = new EntityExtendedMonorail(speed, weight, mainColor,
additionalColor, magneticRail, extraCabin);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityMonorail is not EntityExtendedMonorail extendedMonorail)
{
return;
}
Pen mainPen = new Pen(Color.Black, 2);
Pen additionalPen = new(Color.Blue);
Brush additionalBrush = new SolidBrush(extendedMonorail.AdditionalColor);
Brush brBlue = new SolidBrush(Color.Blue);
Brush brBlack = new SolidBrush(Color.Black);
Brush brWhite = new SolidBrush(Color.White);
Brush brGray = new SolidBrush(Color.Gray);
base.DrawTransport(g);
//магнитная рельса
if (extendedMonorail.MagneticRail)
{
g.DrawRectangle(mainPen, _startPosX + 2, _startPosY + 58, 184, 18);
g.FillRectangle(brGray, _startPosX + 2, _startPosY + 58, 184, 18);
for (int i = 0; i < 4; i++)
{
g.DrawRectangle(mainPen, _startPosX + 35 + 35 * i, _startPosY + 77, 8, 15);
g.FillRectangle(brGray, _startPosX + 35 + 35 * i, _startPosY + 77, 8, 15);
}
}
//дополнительная кабина
if (extendedMonorail.ExtraCabin)
{
//корпус дополнительной кабины
g.FillRectangle(additionalBrush, _startPosX + 118, _startPosY + 15, 65, 31);
g.DrawRectangle(mainPen, _startPosX + 118, _startPosY + 15, 65, 31);
g.DrawLine(additionalPen, _startPosX + 118, _startPosY + 31, _startPosX + 183, _startPosY + 31);
//дверь дополнительной кабины
g.FillRectangle(brBlue, _startPosX + 146, _startPosY + 21, 7, 20);
g.DrawRectangle(mainPen, _startPosX + 146, _startPosY + 21, 7, 20);
//окна дополнительной кабины
g.FillRectangle(brBlue, _startPosX + 130, _startPosY + 18, 6, 9);
g.DrawRectangle(mainPen, _startPosX + 130, _startPosY + 18, 6, 9);
g.FillRectangle(brBlue, _startPosX + 169, _startPosY + 18, 6, 9);
g.DrawRectangle(mainPen, _startPosX + 169, _startPosY + 18, 6, 9);
//колеса и тележка дополнительной кабины
g.FillRectangle(brBlack, _startPosX + 126, _startPosY + 47, 15, 6);
g.DrawRectangle(mainPen, _startPosX + 126, _startPosY + 47, 15, 6);
g.FillRectangle(brBlack, _startPosX + 159, _startPosY + 47, 15, 6);
g.DrawRectangle(mainPen, _startPosX + 159, _startPosY + 47, 15, 6);
g.FillEllipse(brWhite, _startPosX + 128, _startPosY + 47, 10, 9);
g.DrawEllipse(mainPen, _startPosX + 128, _startPosY + 47, 10, 9);
g.FillEllipse(brWhite, _startPosX + 161, _startPosY + 47, 10, 9);
g.DrawEllipse(mainPen, _startPosX + 161, _startPosY + 47, 10, 9);
}
}
}
}

@ -0,0 +1,243 @@
using ProjectMonorail.Entities;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingMonorail
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityMonorail? EntityMonorail { 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 int _monorailWidth = 117;
/// <summary>
/// Высота прорисовки монорельса
/// </summary>
protected int _monorailHeight = 56;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _monorailWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _monorailHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingMonorail
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectMonorail(this);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingMonorail(int speed, double weight, Color mainColor, int width, int height)
{
if (width < _monorailWidth || height < _monorailHeight) { return; }
_pictureWidth = width;
_pictureHeight = height;
EntityMonorail = new EntityMonorail(speed, weight, mainColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="monorailWidth">Ширина прорисовки монорельса</param>
/// <param name="monorailHeight">Высота прорисовки монорельса</param>
protected DrawingMonorail(int speed, double weight, Color mainColor, int width,
int height, int monorailWidth, int monorailHeight)
{
if (width < monorailWidth || height < monorailHeight) { return; }
_pictureWidth = width;
_pictureHeight = height;
_monorailWidth = monorailWidth;
_monorailHeight = monorailHeight;
EntityMonorail = new EntityMonorail(speed, weight, mainColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x < 0 || x + _monorailWidth > _pictureWidth) { x = 0; }
if (y < 0 || y + _monorailHeight > _pictureHeight) { y = 0; }
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityMonorail == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityMonorail.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityMonorail.Step > 0,
//вправо
DirectionType.Right => _startPosX + _monorailWidth + EntityMonorail.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _monorailHeight + EntityMonorail.Step < _pictureHeight,
_ => false
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityMonorail == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityMonorail.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityMonorail.Step;
break;
//вправо
case DirectionType.Right:
_startPosX += (int)EntityMonorail.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityMonorail.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityMonorail == null)
{
return;
}
Pen mainPen = new Pen(Color.Black, 2);
Pen additionalPen = new(Color.Blue);
Brush mainBrush = new SolidBrush(EntityMonorail.MainColor);
Brush brBlue = new SolidBrush(Color.Blue);
Brush brBlack = new SolidBrush(Color.Black);
Brush brWhite = new SolidBrush(Color.White);
Brush brGray = new SolidBrush(Color.Gray);
//надстройка
g.FillRectangle(mainBrush, _startPosX + 55, _startPosY, 25, 15);
g.DrawRectangle(mainPen, _startPosX + 55, _startPosY, 25, 15);
//корпус локомотива
Point[] locoPoints = { new Point(_startPosX + 29, _startPosY + 15), new Point(_startPosX + 112, _startPosY + 15),
new Point(_startPosX + 112, _startPosY + 46), new Point(_startPosX + 25, _startPosY + 46), new Point(_startPosX + 25, _startPosY + 31) };
g.FillPolygon(mainBrush, locoPoints);
g.DrawPolygon(mainPen, locoPoints);
g.DrawLine(additionalPen, _startPosX + 25, _startPosY + 31, _startPosX + 112, _startPosY + 31);
//дверь локомотива
g.FillRectangle(brGray, _startPosX + 54, _startPosY + 21, 7, 20);
g.DrawRectangle(mainPen, _startPosX + 54, _startPosY + 21, 7, 20);
//окна локомотива
g.FillRectangle(brBlue, _startPosX + 32, _startPosY + 18, 6, 9);
g.DrawRectangle(mainPen, _startPosX + 32, _startPosY + 18, 6, 9);
g.FillRectangle(brBlue, _startPosX + 44, _startPosY + 18, 6, 9);
g.DrawRectangle(mainPen, _startPosX + 44, _startPosY + 18, 6, 9);
g.FillRectangle(brBlue, _startPosX + 103, _startPosY + 18, 6, 9);
g.DrawRectangle(mainPen, _startPosX + 103, _startPosY + 18, 6, 9);
//колеса и тележка локомотива
g.FillRectangle(brBlack, _startPosX + 23, _startPosY + 47, 33, 6);
g.DrawRectangle(mainPen, _startPosX + 23, _startPosY + 47, 33, 6);
g.FillRectangle(brBlack, _startPosX + 76, _startPosY + 47, 30, 6);
g.DrawRectangle(mainPen, _startPosX + 76, _startPosY + 47, 30, 6);
g.FillEllipse(brWhite, _startPosX + 25, _startPosY + 47, 10, 9);
g.DrawEllipse(mainPen, _startPosX + 25, _startPosY + 47, 10, 9);
g.FillEllipse(brWhite, _startPosX + 45, _startPosY + 47, 10, 9);
g.DrawEllipse(mainPen, _startPosX + 45, _startPosY + 47, 10, 9);
g.FillEllipse(brWhite, _startPosX + 75, _startPosY + 47, 10, 9);
g.DrawEllipse(mainPen, _startPosX + 75, _startPosY + 47, 10, 9);
g.FillEllipse(brWhite, _startPosX + 95, _startPosY + 47, 10, 9);
g.DrawEllipse(mainPen, _startPosX + 95, _startPosY + 47, 10, 9);
Point[] bogiePoints = { new Point(_startPosX + 26, _startPosY + 46), new Point(_startPosX + 24, _startPosY + 54),
new Point(_startPosX + 12, _startPosY + 54), new Point(_startPosX + 8, _startPosY + 51), new Point(_startPosX + 12, _startPosY + 48),
new Point(_startPosX + 18, _startPosY + 46) };
g.FillPolygon(brBlack, bogiePoints);
//соединение между кабинами
g.DrawRectangle(mainPen, _startPosX + 112, _startPosY + 18, 5, 28);
g.FillRectangle(brBlack, _startPosX + 112, _startPosY + 18, 5, 28);
}
}
}

@ -0,0 +1,38 @@
using ProjectMonorail.DrawingObjects;
namespace ProjectMonorail.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IMoveableObject для работы с объектом DrawingMonorail (паттерн Adapter)
/// </summary>
public class DrawingObjectMonorail : IMoveableObject
{
private readonly DrawingMonorail? _drawingMonorail = null;
public DrawingObjectMonorail(DrawingMonorail drawingMonorail)
{
_drawingMonorail = drawingMonorail;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingMonorail == null || _drawingMonorail.EntityMonorail == null)
{
return null;
}
return new ObjectParameters(_drawingMonorail.GetPosX, _drawingMonorail.GetPosY,
_drawingMonorail.GetWidth, _drawingMonorail.GetHeight);
}
}
public int GetStep => (int)(_drawingMonorail?.EntityMonorail?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingMonorail?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingMonorail?.MoveTransport(direction);
}
}

@ -0,0 +1,40 @@
namespace ProjectMonorail.Entities
{
/// <summary>
/// Класс-сущность "Расширенный монорельс"
/// </summary>
public class EntityExtendedMonorail : EntityMonorail
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия магнитной рельсы
/// </summary>
public bool MagneticRail { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительной кабины
/// </summary>
public bool ExtraCabin { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса расширенного монорельса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес монорельса</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="magneticRail">Признак наличия магнитной рельсы</param>
/// <param name="extraCabin">Признак наличия дополнительной кабины</param>
public EntityExtendedMonorail(int speed, double weight, Color mainColor, Color
additionalColor, bool magneticRail, bool extraCabin) : base(speed, weight, mainColor)
{
AdditionalColor = additionalColor;
MagneticRail = magneticRail;
ExtraCabin = extraCabin;
}
}
}

@ -0,0 +1,42 @@
namespace ProjectMonorail.Entities
{
/// <summary>
/// Класс-сущность "Монорельс"
/// </summary>
public class EntityMonorail
{
/// <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 => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес монорельса</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityMonorail(int speed, double weight, Color mainColor)
{
Speed = speed;
Weight = weight;
MainColor = mainColor;
}
}
}

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

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

@ -0,0 +1,193 @@
namespace ProjectMonorail
{
partial class FormMonorail
{
/// <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()
{
pictureBoxMonorail = new PictureBox();
buttonCreateExtendedMonorail = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
comboBoxStrategy = new ComboBox();
buttonCreateMonorail = new Button();
buttonStep = new Button();
buttonSelectMonorail = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit();
SuspendLayout();
//
// pictureBoxMonorail
//
pictureBoxMonorail.Dock = DockStyle.Fill;
pictureBoxMonorail.Location = new Point(0, 0);
pictureBoxMonorail.Name = "pictureBoxMonorail";
pictureBoxMonorail.Size = new Size(884, 461);
pictureBoxMonorail.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxMonorail.TabIndex = 0;
pictureBoxMonorail.TabStop = false;
//
// buttonCreateExtendedMonorail
//
buttonCreateExtendedMonorail.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateExtendedMonorail.Location = new Point(12, 403);
buttonCreateExtendedMonorail.Name = "buttonCreateExtendedMonorail";
buttonCreateExtendedMonorail.Size = new Size(140, 39);
buttonCreateExtendedMonorail.TabIndex = 1;
buttonCreateExtendedMonorail.Text = "Create extended monorail";
buttonCreateExtendedMonorail.UseVisualStyleBackColor = true;
buttonCreateExtendedMonorail.Click += buttonCreateExtendedMonorail_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(770, 419);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(806, 419);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(842, 419);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(806, 383);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Form center", "Form border" });
comboBoxStrategy.Location = new Point(751, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 6;
//
// buttonCreateMonorail
//
buttonCreateMonorail.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateMonorail.Location = new Point(168, 403);
buttonCreateMonorail.Name = "buttonCreateMonorail";
buttonCreateMonorail.Size = new Size(140, 39);
buttonCreateMonorail.TabIndex = 7;
buttonCreateMonorail.Text = "Create monorail";
buttonCreateMonorail.UseVisualStyleBackColor = true;
buttonCreateMonorail.Click += buttonCreateMonorail_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(797, 50);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 28);
buttonStep.TabIndex = 8;
buttonStep.Text = "Step";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectMonorail
//
buttonSelectMonorail.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectMonorail.Location = new Point(324, 403);
buttonSelectMonorail.Name = "buttonSelectMonorail";
buttonSelectMonorail.Size = new Size(140, 39);
buttonSelectMonorail.TabIndex = 9;
buttonSelectMonorail.Text = "Select";
buttonSelectMonorail.UseVisualStyleBackColor = true;
buttonSelectMonorail.Click += buttonSelectMonorail_Click;
//
// FormMonorail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(buttonSelectMonorail);
Controls.Add(buttonStep);
Controls.Add(buttonCreateMonorail);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonCreateExtendedMonorail);
Controls.Add(pictureBoxMonorail);
Name = "FormMonorail";
StartPosition = FormStartPosition.CenterScreen;
Text = "Monorail";
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxMonorail;
private Button buttonCreateExtendedMonorail;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
private ComboBox comboBoxStrategy;
private Button buttonCreateMonorail;
private Button buttonStep;
private Button buttonSelectMonorail;
}
}

@ -0,0 +1,179 @@
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail
{
/// <summary>
/// Форма работы с объектом "Монорельс"
/// </summary>
public partial class FormMonorail : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingMonorail? _drawingMonorail;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Выбранный монорельс
/// </summary>
public DrawingMonorail? SelectedMonorail { get; private set; }
/// <summary>
/// Инициализация формы
/// </summary>
public FormMonorail()
{
InitializeComponent();
_strategy = null;
SelectedMonorail = null;
}
/// <summary>
/// Метод прорисовки транспорта
/// </summary>
private void Draw()
{
if (_drawingMonorail == null)
{
return;
}
Bitmap bmp = new(pictureBoxMonorail.Width, pictureBoxMonorail.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingMonorail.DrawTransport(gr);
pictureBoxMonorail.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать расширенный монорельс"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateExtendedMonorail_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;
}
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog additionalDialog = new();
if (additionalDialog.ShowDialog() == DialogResult.OK)
{
additionalColor = additionalDialog.Color;
}
_drawingMonorail = new DrawingExtendedMonorail(random.Next(200, 400), random.Next(1000, 3000), color, additionalColor,
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать монорельс"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateMonorail_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;
}
_drawingMonorail = new DrawingMonorail(random.Next(200, 400), random.Next(1000, 3000), color, pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Изменение положения монорельса
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingMonorail == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingMonorail.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingMonorail.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingMonorail.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingMonorail.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingMonorail == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new DrawingObjectMonorail(_drawingMonorail), pictureBoxMonorail.Width, pictureBoxMonorail.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 buttonSelectMonorail_Click(object sender, EventArgs e)
{
SelectedMonorail = _drawingMonorail;
DialogResult = DialogResult.OK;
}
}
}

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

@ -0,0 +1,149 @@
namespace ProjectMonorail
{
partial class FormMonorailCollection
{
/// <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()
{
panelTools = new Panel();
buttonRefreshCollection = new Button();
labelName = new Label();
maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveMonorail = new Button();
buttonAddMonorail = new Button();
pictureBoxCollection = new PictureBox();
panelTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// panelTools
//
panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Right;
panelTools.BorderStyle = BorderStyle.FixedSingle;
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(labelName);
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveMonorail);
panelTools.Controls.Add(buttonAddMonorail);
panelTools.Location = new Point(788, 10);
panelTools.Name = "panelTools";
panelTools.Size = new Size(186, 430);
panelTools.TabIndex = 0;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRefreshCollection.BackColor = SystemColors.Window;
buttonRefreshCollection.FlatAppearance.BorderColor = Color.Black;
buttonRefreshCollection.FlatStyle = FlatStyle.Flat;
buttonRefreshCollection.Location = new Point(18, 281);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(155, 34);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Refresh collection";
buttonRefreshCollection.UseVisualStyleBackColor = false;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// labelName
//
labelName.AutoSize = true;
labelName.Font = new Font("Segoe UI Semibold", 12F, FontStyle.Bold, GraphicsUnit.Point);
labelName.Location = new Point(17, -2);
labelName.Name = "labelName";
labelName.Size = new Size(48, 21);
labelName.TabIndex = 0;
labelName.Text = "Tools";
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.BorderStyle = BorderStyle.FixedSingle;
maskedTextBoxNumber.Location = new Point(17, 144);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(155, 23);
maskedTextBoxNumber.TabIndex = 2;
//
// buttonRemoveMonorail
//
buttonRemoveMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRemoveMonorail.BackColor = SystemColors.Window;
buttonRemoveMonorail.FlatAppearance.BorderColor = Color.Black;
buttonRemoveMonorail.FlatStyle = FlatStyle.Flat;
buttonRemoveMonorail.Location = new Point(18, 173);
buttonRemoveMonorail.Name = "buttonRemoveMonorail";
buttonRemoveMonorail.Size = new Size(155, 34);
buttonRemoveMonorail.TabIndex = 1;
buttonRemoveMonorail.Text = "Remove monorail";
buttonRemoveMonorail.UseVisualStyleBackColor = false;
buttonRemoveMonorail.Click += buttonRemoveMonorail_Click;
//
// buttonAddMonorail
//
buttonAddMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAddMonorail.BackColor = SystemColors.Window;
buttonAddMonorail.FlatAppearance.BorderColor = Color.Black;
buttonAddMonorail.FlatStyle = FlatStyle.Flat;
buttonAddMonorail.Location = new Point(18, 33);
buttonAddMonorail.Name = "buttonAddMonorail";
buttonAddMonorail.Size = new Size(155, 34);
buttonAddMonorail.TabIndex = 0;
buttonAddMonorail.Text = "Add monorail";
buttonAddMonorail.UseVisualStyleBackColor = false;
buttonAddMonorail.Click += buttonAddMonorail_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(5, 10);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(777, 430);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// FormMonorailCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(974, 439);
Controls.Add(pictureBoxCollection);
Controls.Add(panelTools);
Name = "FormMonorailCollection";
Text = "Monorail collection";
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelTools;
private Label labelName;
private Button buttonAddMonorail;
private Button buttonRemoveMonorail;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonRefreshCollection;
private PictureBox pictureBoxCollection;
}
}

@ -0,0 +1,83 @@
using ProjectMonorail.Generics;
using ProjectMonorail.MovementStrategy;
using ProjectMonorail.DrawingObjects;
namespace ProjectMonorail
{
/// <summary>
/// Форма для работы с набором объектов класса DrawingMonorail
/// </summary>
public partial class FormMonorailCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly MonorailsGenericCollection<DrawingMonorail, DrawingObjectMonorail> _monorails;
/// <summary>
/// Конструктор
/// </summary>
public FormMonorailCollection()
{
InitializeComponent();
_monorails = new MonorailsGenericCollection<DrawingMonorail, DrawingObjectMonorail>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddMonorail_Click(object sender, EventArgs e)
{
FormMonorail form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_monorails + form.SelectedMonorail != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _monorails.ShowMonorails();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveMonorail_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_monorails - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _monorails.ShowMonorails();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _monorails.ShowMonorails();
}
}
}

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

@ -0,0 +1,31 @@
namespace ProjectMonorail.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);
}
}

@ -0,0 +1,155 @@
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MonorailsGenericCollection<T, U>
where T : DrawingMonorail
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 193;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 102;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public MonorailsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(MonorailsGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(MonorailsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
return collect._collection.Remove(pos);
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowMonorails()
{
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)
{
T? obj;
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int diff = 1, currWidth = 0;
for (int i = 0; i < _collection.Count; i++)
{
currWidth++;
if (currWidth > width)
{
diff++;
currWidth = 1;
}
obj = _collection.Get(i);
if (obj != null)
{
obj.SetPosition(i % width * _placeSizeWidth + _placeSizeWidth / 40,
(height - diff) * _placeSizeHeight + _placeSizeHeight / 15);
obj.DrawTransport(g);
}
}
}
}
}

@ -0,0 +1,46 @@
namespace ProjectMonorail.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 <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX < 0)
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY < 0)
{
MoveDown();
}
}
}
}
}

@ -0,0 +1,54 @@
namespace ProjectMonorail.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();
}
}
}
}
}

@ -0,0 +1,61 @@
namespace ProjectMonorail.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;
}
}
}

@ -11,7 +11,7 @@ namespace ProjectMonorail
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
Application.Run(new FormMonorailCollection());
}
}
}

@ -8,4 +8,19 @@
<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>

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

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

Binary file not shown.

After

(image error) Size: 415 B

Binary file not shown.

After

(image error) Size: 411 B

Binary file not shown.

After

(image error) Size: 352 B

Binary file not shown.

After

(image error) Size: 412 B

@ -0,0 +1,98 @@
using System.Numerics;
namespace ProjectMonorail.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="monorail">Добавляемый монорельс</param>
/// <returns></returns>
public int Insert(T monorail)
{
return Insert(monorail, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="monorail">Добавляемый монорельс</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T monorail, int position)
{
int nullIndex = -1, i;
if (position < 0 || position >= Count)
return -1;
for (i = position; i < Count; i++)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
return -1;
for (i = nullIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = monorail;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count)
return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
}
}

@ -0,0 +1,14 @@
namespace ProjectMonorail.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}