Готовая 2 лабораторная

This commit is contained in:
Даниил Путинцев 2023-10-06 21:35:14 +04:00
parent 6d70beffa4
commit 852c7c8a50
14 changed files with 743 additions and 128 deletions

View File

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

View File

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

View File

@ -3,60 +3,96 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using RoadTrain.Entities;
namespace RoadTrain namespace RoadTrain.DrawningObjects
{ {
public class DrawningRoadTrain public class DrawningRoadTrain
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityRoadTrain? EntityRoadTrain { get; private set; } public EntityRoadTrain? EntityRoadTrain { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
private int _pictureWidth; protected int _pictureWidth;
/// <summary> /// <summary>
/// Высота окна /// Высота окна
/// </summary> /// </summary>
private int _pictureHeight; protected int _pictureHeight;
/// <summary> /// <summary>
/// Левая координата прорисовки автомобиля /// Левая координата прорисовки автомобиля
/// </summary> /// </summary>
private int _startPosX; protected int _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки автомобиля /// Верхняя кооридната прорисовки автомобиля
/// </summary> /// </summary>
private int _startPosY; protected int _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки автомобиля /// Ширина прорисовки автомобиля
/// </summary> /// </summary>
private readonly int _trainWidth = 70; protected readonly int _trainWidth = 70;
/// <summary> /// <summary>
/// Высота прорисовки автомобиля /// Высота прорисовки автомобиля
/// </summary> /// </summary>
private readonly int _trainHeight = 30; protected readonly int _trainHeight = 30;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _trainWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _trainHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityRoadTrain == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityRoadTrain.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityRoadTrain.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityRoadTrain.Step + _trainWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityRoadTrain.Step + _trainHeight < _pictureHeight
};
}
/// <summary> /// <summary>
/// Инициализация свойств /// Инициализация свойств
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param> /// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="WaterContainer">Признак наличия контейнера для воды</param>
/// <param name="SweepingBrush">Признак наличия щетки</param>
/// <param name="width">Ширина картинки</param> /// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param> /// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns> /// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(EntityRoadTrain entityRoadTrain, int width, int height) public DrawningRoadTrain(int speed, double weight, Color bodyColor, int width, int height)
{ {
if (width < _trainWidth) { return false; } if (width < _trainWidth) { return; }
if (height < _trainHeight) { return false; } if (height < _trainHeight) { return; }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
EntityRoadTrain = entityRoadTrain; EntityRoadTrain = new EntityRoadTrain(speed, weight, bodyColor);
return true;
} }
/// <summary> /// <summary>
/// Установка позиции /// Установка позиции
@ -78,39 +114,28 @@ namespace RoadTrain
/// <param name="direction">Направление</param> /// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction) public void MoveTransport(DirectionType direction)
{ {
if (EntityRoadTrain == null) if (!CanMove(direction) || EntityRoadTrain == null)
{ {
return; return;
} }
switch (direction) switch (direction)
{ {
//влево //влево
case DirectionType.Left: case DirectionType.Left:
if (_startPosX - EntityRoadTrain.Step > 0)
{
_startPosX -= (int)EntityRoadTrain.Step; _startPosX -= (int)EntityRoadTrain.Step;
}
break; break;
//вверх //вверх
case DirectionType.Up: case DirectionType.Up:
if (_startPosY - EntityRoadTrain.Step > 0)
{
_startPosY -= (int)EntityRoadTrain.Step; _startPosY -= (int)EntityRoadTrain.Step;
}
break; break;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX + EntityRoadTrain.Step + _trainWidth < _pictureWidth)
{
_startPosX += (int)EntityRoadTrain.Step; _startPosX += (int)EntityRoadTrain.Step;
}
break; break;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY + EntityRoadTrain.Step + _trainHeight < _pictureHeight)
{
_startPosY += (int)EntityRoadTrain.Step; _startPosY += (int)EntityRoadTrain.Step;
}
break; break;
} }
} }
@ -118,28 +143,14 @@ namespace RoadTrain
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityRoadTrain == null) if (EntityRoadTrain == null)
{ {
return; return;
} }
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityRoadTrain.AdditionalColor);
//Контейнер с водой
if (EntityRoadTrain.WaterContainer)
{
g.DrawEllipse(pen, _startPosX + 30, _startPosY, 10, 20);
g.FillEllipse(additionalBrush, _startPosX + 30, _startPosY, 10, 20);
}
if (EntityRoadTrain.SweepingBrush)
{
g.DrawLine(pen, _startPosX + 30, _startPosY + 10, _startPosX + 20, _startPosY + 10);
g.DrawLine(pen, _startPosX + 20, _startPosY + 10, _startPosX + 10, _startPosY + 30);
g.DrawLine(pen, _startPosX + 17, _startPosY + 30, _startPosX + 3, _startPosY + 30);
}
Brush br = new SolidBrush(EntityRoadTrain.BodyColor); Brush br = new SolidBrush(EntityRoadTrain.BodyColor);
Pen pen = new(Color.Black);
g.DrawLine(pen, _startPosX + 20, _startPosY + 20, _startPosX + 70, _startPosY + 20); g.DrawLine(pen, _startPosX + 20, _startPosY + 20, _startPosX + 70, _startPosY + 20);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 20, 10, 10); g.DrawEllipse(pen, _startPosX + 20, _startPosY + 20, 10, 10);
g.DrawEllipse(pen, _startPosX + 30, _startPosY + 20, 10, 10); g.DrawEllipse(pen, _startPosX + 30, _startPosY + 20, 10, 10);

View File

@ -0,0 +1,56 @@
using RoadTrain.Entities;
using System.Drawing;
namespace RoadTrain.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTrain : DrawningRoadTrain
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="waterContainer">Признак наличия обвеса</param>
/// <param name="sweepingBrush">Признак наличия антикрыла</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningTrain(int speed, double weight, Color bodyColor, Color
additionalColor, bool waterContainer, bool sweepingBrush, int width, int height) :base(speed, weight, bodyColor, 70, 30)
{
if (EntityRoadTrain != null)
{
EntityRoadTrain = new EntityTrain(speed, weight, bodyColor,
additionalColor, waterContainer, sweepingBrush);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityRoadTrain is not EntityTrain train)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(train.AdditionalColor);
//Контейнер с водой
if (train.WaterContainer)
{
g.DrawEllipse(pen, _startPosX + 30, _startPosY, 10, 20);
g.FillEllipse(additionalBrush, _startPosX + 30, _startPosY, 10, 20);
}
base.DrawTransport(g);
if (train.SweepingBrush)
{
g.DrawLine(pen, _startPosX + 30, _startPosY + 10, _startPosX + 20, _startPosY + 10);
g.DrawLine(pen, _startPosX + 20, _startPosY + 10, _startPosX + 10, _startPosY + 30);
g.DrawLine(pen, _startPosX + 17, _startPosY + 30, _startPosX + 3, _startPosY + 30);
}
}
}
}

View File

@ -4,37 +4,25 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace RoadTrain namespace RoadTrain.Entities
{ {
public class EntityRoadTrain public class EntityRoadTrain
{ {
/// <summary> /// <summary>
/// Скорость /// Скорость
/// </summary> /// </summary>
public int Speed { get; private set; } public int Speed { get; protected set; }
/// <summary> /// <summary>
/// Вес /// Вес
/// </summary> /// </summary>
public double Weight { get; private set; } public double Weight { get; protected set; }
/// <summary> /// <summary>
/// Основной цвет /// Основной цвет
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; protected set; }
/// <summary> /// <summary>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия контейнера с водой
/// </summary>
public bool WaterContainer { get; private set; }
/// <summary>
/// Признак (опция) наличия щетки
/// </summary>
public bool SweepingBrush { get; private set; }
/// <summary>
/// Шаг перемещения поезда
/// </summary>
public double Step => (double)Speed * 100 / Weight; public double Step => (double)Speed * 100 / Weight;
/// <summary> /// <summary>
/// Инициализация полей объекта-класса поезда /// Инициализация полей объекта-класса поезда
@ -42,19 +30,12 @@ namespace RoadTrain
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="waterContainer">Признак наличия контейнера с водой</param> public EntityRoadTrain(int speed, double weight, Color bodyColor)
/// <param name="sweepingBrush">Признак наличия щетки</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool waterContainer, bool sweepingBrush)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
AdditionalColor = additionalColor; }
WaterContainer = waterContainer;
SweepingBrush = sweepingBrush;
}
} }
} }

45
RoadTrain/EntityTrain.cs Normal file
View File

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

View File

@ -34,18 +34,18 @@
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonCreate = new Button(); buttonCreate = new Button();
button1 = new Button();
comboBoxStrategy = new ComboBox();
ButtonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxRoadTrain // pictureBoxRoadTrain
// //
pictureBoxRoadTrain.BackgroundImageLayout = ImageLayout.Zoom;
pictureBoxRoadTrain.Dock = DockStyle.Fill;
pictureBoxRoadTrain.Location = new Point(0, 0); pictureBoxRoadTrain.Location = new Point(0, 0);
pictureBoxRoadTrain.Name = "pictureBoxRoadTrain"; pictureBoxRoadTrain.Name = "pictureBoxRoadTrain";
pictureBoxRoadTrain.Size = new Size(685, 362); pictureBoxRoadTrain.Size = new Size(685, 361);
pictureBoxRoadTrain.SizeMode = PictureBoxSizeMode.AutoSize; pictureBoxRoadTrain.TabIndex = 10;
pictureBoxRoadTrain.TabIndex = 0;
pictureBoxRoadTrain.TabStop = false; pictureBoxRoadTrain.TabStop = false;
// //
// buttonLeft // buttonLeft
@ -53,7 +53,7 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.left; buttonLeft.BackgroundImage = Properties.Resources.left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(539, 268); buttonLeft.Location = new Point(533, 269);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30); buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
@ -65,7 +65,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.up; buttonUp.BackgroundImage = Properties.Resources.up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom; buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(583, 222); buttonUp.Location = new Point(577, 223);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30); buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 3; buttonUp.TabIndex = 3;
@ -77,7 +77,7 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right; buttonRight.BackgroundImage = Properties.Resources.right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom; buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(626, 268); buttonRight.Location = new Point(620, 269);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30); buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 4; buttonRight.TabIndex = 4;
@ -89,7 +89,7 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.down; buttonDown.BackgroundImage = Properties.Resources.down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom; buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(583, 314); buttonDown.Location = new Point(577, 315);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30); buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 5; buttonDown.TabIndex = 5;
@ -99,19 +99,52 @@
// buttonCreate // buttonCreate
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(92, 265); buttonCreate.Location = new Point(82, 236);
buttonCreate.Name = "buttonCreate"; buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23); buttonCreate.Size = new Size(107, 38);
buttonCreate.TabIndex = 6; buttonCreate.TabIndex = 6;
buttonCreate.Text = "создать"; buttonCreate.Text = "создать грузовик";
buttonCreate.UseVisualStyleBackColor = true; buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click; buttonCreate.Click += buttonCreate_Click;
// //
// button1
//
button1.Location = new Point(82, 289);
button1.Name = "button1";
button1.Size = new Size(107, 55);
button1.TabIndex = 7;
button1.Text = "создать очистительную машину";
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Центр формы", "Граница формы" });
comboBoxStrategy.Location = new Point(552, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 8;
//
// ButtonStep
//
ButtonStep.Location = new Point(581, 50);
ButtonStep.Name = "ButtonStep";
ButtonStep.Size = new Size(75, 23);
ButtonStep.TabIndex = 9;
ButtonStep.Text = "Шаг";
ButtonStep.UseVisualStyleBackColor = true;
ButtonStep.Click += ButtonStep_Click_1;
//
// FormRoadTrain // FormRoadTrain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(685, 362); ClientSize = new Size(679, 363);
Controls.Add(ButtonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(button1);
Controls.Add(buttonCreate); Controls.Add(buttonCreate);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
@ -122,7 +155,6 @@
Text = "FormRoadTrain"; Text = "FormRoadTrain";
((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -134,5 +166,8 @@
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private Button buttonCreate; private Button buttonCreate;
private Button button1;
private ComboBox comboBoxStrategy;
private Button ButtonStep;
} }
} }

View File

@ -1,3 +1,7 @@
using RoadTrain.MovementStrategy;
using RoadTrain.DrawningObjects;
namespace RoadTrain namespace RoadTrain
{ {
public partial class FormRoadTrain : Form public partial class FormRoadTrain : Form
@ -6,6 +10,8 @@ namespace RoadTrain
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà /// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary> /// </summary>
private DrawningRoadTrain? _drawningRoadTrain; private DrawningRoadTrain? _drawningRoadTrain;
private AbstractStrategy? _abstractStrategy;
/// <summary> /// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû /// Èíèöèàëèçàöèÿ ôîðìû
/// </summary> /// </summary>
@ -67,25 +73,67 @@ namespace RoadTrain
private void buttonCreate_Click(object sender, EventArgs e) private void buttonCreate_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawningRoadTrain = new DrawningRoadTrain(); _drawningRoadTrain = new DrawningRoadTrain(random.Next(100, 300), random.Next(1000, 3000),
EntityRoadTrain entityRoadTrain = new EntityRoadTrain(); Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
entityRoadTrain.Init(random.Next(100, 300), random.Next(0, 256)),
random.Next(1000, 3000), pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void button1_Click(object sender, EventArgs e)
{
Random random = new();
_drawningRoadTrain = new DrawningTrain(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2))); Convert.ToBoolean(random.Next(0, 2)),
pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.Init(entityRoadTrain, pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.SetPosition(random.Next(10, 100), _drawningRoadTrain.SetPosition(random.Next(10, 100),
random.Next(10, 100)); random.Next(10, 100));
Draw(); Draw();
} }
private void ButtonStep_Click_1(object sender, EventArgs e)
{
if (_drawningRoadTrain == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectTrain(_drawningRoadTrain), pictureBoxRoadTrain.Width,
pictureBoxRoadTrain.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
} }
} }

View File

@ -1,4 +1,64 @@
<root> <?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: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:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">

View File

@ -0,0 +1,32 @@

using RoadTrain.MovementStrategy;
using RoadTrain;
namespace RoadTrain.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);
}
}

55
RoadTrain/MoveToBorder.cs Normal file
View File

@ -0,0 +1,55 @@
using RoadTrain.MovementStrategy;
namespace RoadTrain.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)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

55
RoadTrain/MoveToCenter.cs Normal file
View File

@ -0,0 +1,55 @@
using RoadTrain.MovementStrategy;
namespace RoadTrain.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoadTrain.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;
}
}
}

12
RoadTrain/Status.cs Normal file
View File

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