Compare commits

...

2 Commits

Author SHA1 Message Date
artemkudinov14
6b4cfb6026 Добавление стратегии 2024-04-03 00:57:03 +04:00
artemkudinov14
682b384961 Добавление родителей и ввод конструкторов 2024-04-02 23:39:55 +04:00
15 changed files with 818 additions and 122 deletions

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diesellocomotive.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Diesellocomotive.Entities;
namespace Diesellocomotive.Drawnings;
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningDiesellocomotive : DrawningLocomotive
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">труба</param>
/// <param name="fuelCompartment">отсек под топливо</param>
public DrawningDiesellocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool pipe, bool fuelCompartment) : base(95, 35)
{
EntityLocomotive = new EntityDiesellocomotive(speed, weight, bodyColor, additionalColor, pipe, fuelCompartment);
}
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive == null || EntityLocomotive is not EntityDiesellocomotive Diesellocomotive || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(Diesellocomotive.AdditionalColor);
//труба
if (Diesellocomotive.Pipe)
{
Point[] points_Pipe = {
new Point(_startPosX.Value + 75, _startPosY.Value),
new Point(_startPosX.Value + 75, _startPosY.Value - 4),
new Point(_startPosX.Value + 60, _startPosY.Value - 4),
new Point(_startPosX.Value + 60, _startPosY.Value),
};
g.FillPolygon(additionalBrush, points_Pipe);
g.DrawPolygon(pen, points_Pipe);
}
//отсек под топливо
if (Diesellocomotive.FuelCompartment)
{
Point[] points_Fuel_Compartment = {
new Point(_startPosX.Value + 85, _startPosY.Value + 2),
new Point(_startPosX.Value + 88, _startPosY.Value + 2),
new Point(_startPosX.Value + 88, _startPosY.Value + 28),
new Point(_startPosX.Value + 85, _startPosY.Value + 28),
};
g.FillPolygon(additionalBrush, points_Fuel_Compartment);
g.DrawPolygon(pen, points_Fuel_Compartment);
}
base.DrawTransport(g);
}
}

View File

@ -1,19 +1,18 @@
using System;
using Diesellocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace diesellocomotive;
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningDiesellocomotive
namespace Diesellocomotive.Drawnings;
public class DrawningLocomotive
{
/// <summary>
/// Класс-сущность (объект)
/// </summary>
public EntityDiesellocomotive? EntityDiesellocomotive { get; private set; }
public EntityLocomotive? EntityLocomotive { get; protected set; }
/// <summary>
/// Ширина окна
@ -28,39 +27,75 @@ public class DrawningDiesellocomotive
/// <summary>
/// Левая координата прорисовки тепловоза
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки те5пловоза
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки тепловоза (размер объекта)
/// </summary>
private readonly int _drawningDiesellocomotiveWidth = 95;
private readonly int _drawningDiesellocomotiveWidth = 80;
/// <summary>
/// Высота прорисовки тепловоза (размер объекта)
/// </summary>
private readonly int _drawingDiesellocomotiveHeight = 35;
private readonly int _drawingDiesellocomotiveHeight = 30;
/// <summary>
/// Инициализация свойства
/// Координата X объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">труба</param>
/// <param name="fuelCompartment">отсек под топливо</param>
public int? GetPosX => _startPosX;
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pipe, bool fuelCompartment)
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningDiesellocomotiveWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningDiesellocomotiveWidth;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningLocomotive()
{
EntityDiesellocomotive = new EntityDiesellocomotive();
EntityDiesellocomotive.Init(speed, weight, bodyColor, additionalColor, pipe, fuelCompartment);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningLocomotive(int speed, double weight, Color bodyColor) : this()
{
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningDiesellocomotiveWidth">Ширина прорисовки тепловоза (размер объекта)</param>
/// <param name="drawingDiesellocomotiveHeight">Высота прорисовки тепловоза (размер объекта)</param>
protected DrawningLocomotive(int drawningDiesellocomotiveWidth, int drawingDiesellocomotiveHeight) : this()
{
_drawningDiesellocomotiveWidth = drawningDiesellocomotiveWidth;
_pictureHeight = drawingDiesellocomotiveHeight;
}
@ -144,7 +179,7 @@ public class DrawningDiesellocomotive
/// <returns>true - перемещение выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityDiesellocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -152,33 +187,33 @@ public class DrawningDiesellocomotive
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityDiesellocomotive.Step > 0)
if (_startPosX.Value - EntityLocomotive.Step > 0)
{
_startPosX -= (int)EntityDiesellocomotive.Step;
_startPosX -= (int)EntityLocomotive.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityDiesellocomotive.Step > 0)
if (_startPosY.Value - EntityLocomotive.Step > 0)
{
_startPosY -= (int)EntityDiesellocomotive.Step;
_startPosY -= (int)EntityLocomotive.Step;
}
return true;
// вправо
case DirectionType.Right:
// TODO прописать логику сдвига в право
if (_startPosX.Value + EntityDiesellocomotive.Step + _drawningDiesellocomotiveWidth < _pictureWidth)
if (_startPosX.Value + EntityLocomotive.Step + _drawningDiesellocomotiveWidth < _pictureWidth)
{
_startPosX += (int)EntityDiesellocomotive.Step;
_startPosX += (int)EntityLocomotive.Step;
}
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY.Value + EntityDiesellocomotive.Step + _drawingDiesellocomotiveHeight < _pictureHeight)
if (_startPosY.Value + EntityLocomotive.Step + _drawingDiesellocomotiveHeight < _pictureHeight)
{
_startPosY += (int)EntityDiesellocomotive.Step;
_startPosY += (int)EntityLocomotive.Step;
}
return true;
default:
@ -192,54 +227,18 @@ public class DrawningDiesellocomotive
/// </summary>
/// <param name="g"></param>
///
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityDiesellocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityDiesellocomotive.AdditionalColor);
//труба
if (EntityDiesellocomotive.Pipe)
{
Point[] points_Pipe = {
new Point(_startPosX.Value + 75, _startPosY.Value),
new Point(_startPosX.Value + 75, _startPosY.Value - 4),
new Point(_startPosX.Value + 60, _startPosY.Value - 4),
new Point(_startPosX.Value + 60, _startPosY.Value),
};
g.FillPolygon(additionalBrush, points_Pipe);
g.DrawPolygon(pen, points_Pipe);
}
//отсек под топливо
if (EntityDiesellocomotive.FuelCompartment)
{
Point[] points_Fuel_Compartment = {
new Point(_startPosX.Value + 85, _startPosY.Value + 2),
new Point(_startPosX.Value + 88, _startPosY.Value + 2),
new Point(_startPosX.Value + 88, _startPosY.Value + 28),
new Point(_startPosX.Value + 85, _startPosY.Value + 28),
};
g.FillPolygon(additionalBrush, points_Fuel_Compartment);
g.DrawPolygon(pen, points_Fuel_Compartment);
}
//границы
Brush br = new SolidBrush(EntityDiesellocomotive.BodyColor);
Brush br = new SolidBrush(EntityLocomotive.BodyColor);
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 15, 80, 15);
Point[] points1 = {
new Point(_startPosX.Value + 15, _startPosY.Value),
@ -344,4 +343,4 @@ public class DrawningDiesellocomotive
}
}
}

View File

@ -4,24 +4,13 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace diesellocomotive;
namespace Diesellocomotive.Entities;
/// <summary>
/// Класс-сущность "Тепловоз"
/// </summary>
public class EntityDiesellocomotive
public class EntityDiesellocomotive : EntityLocomotive
{
/// <summary>
/// скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// дополнительный цвет
/// </summary>
@ -35,10 +24,7 @@ public class EntityDiesellocomotive
/// </summary>
public bool FuelCompartment { get; private set; }
/// <summary>
/// шаг
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса тепловоза
/// </summary>
@ -48,7 +34,7 @@ public class EntityDiesellocomotive
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">признак наличие трубы</param>
/// <param name="fuelCompartment">признак отсек под топливо</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pipe, bool fuelCompartment)
public EntityDiesellocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool pipe, bool fuelCompartment) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diesellocomotive.Entities;
/// <summary>
/// Класс-сущность "Тепловоз"
/// </summary>
public class EntityLocomotive
{
/// <summary>
/// скорость
/// </summary>
public int Speed { get; set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; set; }
/// <summary>
/// основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// шаг
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityLocomotive(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -34,6 +34,9 @@
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonCreateLocomotive = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox1Diesellocomotive).BeginInit();
SuspendLayout();
//
@ -54,9 +57,9 @@
buttonCreateDiesellocomotive.Location = new Point(14, 362);
buttonCreateDiesellocomotive.Margin = new Padding(3, 4, 3, 4);
buttonCreateDiesellocomotive.Name = "buttonCreateDiesellocomotive";
buttonCreateDiesellocomotive.Size = new Size(86, 31);
buttonCreateDiesellocomotive.Size = new Size(221, 31);
buttonCreateDiesellocomotive.TabIndex = 1;
buttonCreateDiesellocomotive.Text = "Создать";
buttonCreateDiesellocomotive.Text = "Создать Тепловоз с трубой";
buttonCreateDiesellocomotive.UseVisualStyleBackColor = true;
buttonCreateDiesellocomotive.Click += buttonCreateDiesellocomotive_Click;
//
@ -112,11 +115,48 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonCreateLocomotive
//
buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateLocomotive.Location = new Point(241, 362);
buttonCreateLocomotive.Margin = new Padding(3, 4, 3, 4);
buttonCreateLocomotive.Name = "buttonCreateLocomotive";
buttonCreateLocomotive.Size = new Size(221, 31);
buttonCreateLocomotive.TabIndex = 6;
buttonCreateLocomotive.Text = "Создать Тепловоз ";
buttonCreateLocomotive.UseVisualStyleBackColor = true;
buttonCreateLocomotive.Click += buttonCreateLocomotive_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(709, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(766, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormDiesellocomotive
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(872, 408);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateLocomotive);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
@ -139,5 +179,8 @@
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private Button buttonCreateLocomotive;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,5 @@
using diesellocomotive;
using Diesellocomotive.Drawnings;
using Diesellocomotive.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -18,27 +19,33 @@ public partial class FormDiesellocomotive : Form
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningDiesellocomotive? _drawningDiesellocomotive;
private DrawningLocomotive? _drawningLocomotive;
/// <summary>
///
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// конструктор формы
/// </summary>
public FormDiesellocomotive()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки машины
/// </summary>
private void Draw()
{
if (_drawningDiesellocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
Bitmap bmp = new(pictureBox1Diesellocomotive.Width, pictureBox1Diesellocomotive.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningDiesellocomotive.DrawTransport(gr);
_drawningLocomotive.DrawTransport(gr);
pictureBox1Diesellocomotive.Image = bmp;
}
@ -49,28 +56,52 @@ public partial class FormDiesellocomotive : Form
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningLocomotive):
_drawningLocomotive = new DrawningLocomotive(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningDiesellocomotive):
_drawningLocomotive = new DrawningDiesellocomotive(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningLocomotive.SetPictureSize(pictureBox1Diesellocomotive.Width, pictureBox1Diesellocomotive.Height);
_drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать Тепловоз с трубой"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateDiesellocomotive_Click(object sender, EventArgs e)
{
Random random = new();
_drawningDiesellocomotive = new DrawningDiesellocomotive();
_drawningDiesellocomotive.Init(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningDiesellocomotive.SetPictureSize(pictureBox1Diesellocomotive.Width, pictureBox1Diesellocomotive.Height);
_drawningDiesellocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
private void buttonCreateDiesellocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningDiesellocomotive));
Bitmap bmp = new(pictureBox1Diesellocomotive.Width, pictureBox1Diesellocomotive.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningDiesellocomotive.DrawTransport(gr);
pictureBox1Diesellocomotive.Image = bmp;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать тепловоз"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
@ -79,7 +110,7 @@ public partial class FormDiesellocomotive : Form
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningDiesellocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
@ -89,16 +120,16 @@ public partial class FormDiesellocomotive : Form
switch (name)
{
case "buttonUp":
result = _drawningDiesellocomotive.MoveTransport(DirectionType.Up);
result = _drawningLocomotive.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningDiesellocomotive.MoveTransport(DirectionType.Down);
result = _drawningLocomotive.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningDiesellocomotive.MoveTransport(DirectionType.Left);
result = _drawningLocomotive.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningDiesellocomotive.MoveTransport(DirectionType.Right);
result = _drawningLocomotive.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -112,4 +143,47 @@ public partial class FormDiesellocomotive : Form
{
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningLocomotive == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBox1Diesellocomotive.Width, pictureBox1Diesellocomotive.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diesellocomotive.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 ||
objParams.RightBorder + GetStep() >= FieldWidth ||
objParams.TopBorder - GetStep() <= 0
|| objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
//реализация в правый нижний угол
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

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

View File

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

View File

@ -4,17 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace diesellocomotive;
namespace Diesellocomotive.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
@ -27,5 +27,4 @@ public enum DirectionType
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diesellocomotive.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина объекта</param>
/// <param name="height">Высота объекта</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

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