Compare commits

...

4 Commits

15 changed files with 819 additions and 114 deletions

View File

@ -1,11 +1,15 @@

namespace ProjectAirbus;
namespace ProjectAirbus.Drawning;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -0,0 +1,69 @@
using ProjectAirbus.Entities;
namespace ProjectAirbus.Drawning;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirbus : DrawningBus
{
/// <summary>
/// Ширина прорисовки аэробуса
/// </summary>
private readonly int _drawningAirbusWidth = 133;
/// <summary>
/// Высота прорисовки аэробуса
/// </summary>
private readonly int _drawningAirbusHeight = 60;
/// <summary>
/// Конструтор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
/// <param name="additionalcolor">Дополнительный цвет</param>
/// <param name="compartment">Признак наличия дополнительного отсека для пассажиров</param>
/// <param name="engine">Признак наличия дополнительных двигателей</param>
public DrawningAirbus(int speed, double weight, Color bodycolor, Color additionalcolor, bool compartment, bool engine) : base(133, 60)
{
EntityBus = new EntityAirbus(speed, weight, bodycolor, additionalcolor, compartment, engine);
}
public override void DrawTransport(Graphics g)
{
if (EntityBus == null || EntityBus is not EntityAirbus airbus || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(airbus.AdditionalColor);
base.DrawTransport(g);
if (airbus.Engine)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 30, _startPosY.Value + 33, 13, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 33, 15, 5);
}
Brush brBlue = new SolidBrush(Color.LightBlue);
if (airbus.Compartment)
{
//g.FillEllipse(brBlue, _startPosX.Value + 37, _startPosY.Value + 13, 49, 15);
g.FillPolygon(brBlue, new Point[]
{
new Point(_startPosX.Value + 35, _startPosY.Value + 20), new Point(_startPosX.Value + 60, _startPosY.Value + 12),
new Point(_startPosX.Value + 80, _startPosY.Value + 12), new Point(_startPosX.Value + 95, _startPosY.Value + 20)});
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 20, _startPosX.Value + 60, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 12, _startPosX.Value + 80, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 80, _startPosY.Value + 12, _startPosX.Value + 95, _startPosY.Value + 20);
}
}
}

View File

@ -1,15 +1,18 @@

namespace ProjectAirbus;
using ProjectAirbus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirbus
namespace ProjectAirbus.Drawning;
public class DrawningBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirbus? EntityAirbus { get; private set; }
public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Ширина окна
@ -24,42 +27,82 @@ public class DrawningAirbus
/// <summary>
/// Левая координата прорисовки аэробуса
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки аэробуса
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки аэробуса
/// </summary>
private readonly int _drawningAirbusWidth = 133;
private readonly int _drawningBusWidth = 135;
/// <summary>
/// Высота прорисовки аэробуса
/// </summary>
private readonly int _drawningAirbusHeight = 60;
private readonly int _drawningBusHeight = 60;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
/// <param name="additionalcolor">Дополнительный цвет</param>
/// <param name="compartment">Признак наличия дополнительного отсека для пассажиров</param>
/// <param name="engine">Признак наличия дополнительных двигателей</param>
public void Init(int speed, double weight, Color bodycolor, Color additionalcolor, bool compartment, bool engine)
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBusWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningBusHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningBus()
{
EntityAirbus = new EntityAirbus();
EntityAirbus.Init(speed, weight, bodycolor, additionalcolor, compartment, engine);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
public DrawningBus(int speed, double weight, Color bodycolor) : this()
{
EntityBus = new EntityBus(speed, weight, bodycolor);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningBusWidth">Ширина прорисовки аэробуса</param>
/// <param name="drawningBusHeight">Высота прорисовки аэробуса</param>
protected DrawningBus(int drawningAirbusWidth, int drawningAirbusHeight) : this()
{
_drawningBusWidth = drawningAirbusWidth;
_drawningBusHeight = drawningAirbusHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -71,7 +114,7 @@ public class DrawningAirbus
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта,если она была уже установлена
if (width >= _drawningAirbusWidth || height >= _drawningAirbusHeight)
if (width >= _drawningBusWidth || height >= _drawningBusHeight)
{
_pictureWidth = width;
_pictureHeight = height;
@ -102,17 +145,17 @@ public class DrawningAirbus
{
x = 0;
}
else if (x > _pictureWidth - _drawningAirbusWidth)
else if (x > _pictureWidth - _drawningBusWidth)
{
x = _pictureWidth.Value - _drawningAirbusWidth;
x = _pictureWidth.Value - _drawningBusWidth;
}
if (y < 0)
{
y = 0;
}
else if (y > _pictureHeight - _drawningAirbusHeight)
else if (y > _pictureHeight - _drawningBusHeight)
{
y = _pictureHeight.Value - _drawningAirbusHeight;
y = _pictureHeight.Value - _drawningBusHeight;
}
_startPosX = x;
@ -125,7 +168,7 @@ public class DrawningAirbus
/// <returns></returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityAirbus == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -133,33 +176,33 @@ public class DrawningAirbus
{
// Влево
case DirectionType.Left:
if (_startPosX.Value - EntityAirbus.Step > 0)
if (_startPosX.Value - EntityBus.Step > 0)
{
_startPosX -= (int)EntityAirbus.Step;
_startPosX -= (int)EntityBus.Step;
}
return true;
//Вверх
case DirectionType.Up:
if (_startPosY.Value - EntityAirbus.Step > 0)
if (_startPosY.Value - EntityBus.Step > 0)
{
_startPosY -= (int)EntityAirbus.Step;
_startPosY -= (int)EntityBus.Step;
}
return true;
//Вправо
case DirectionType.Right:
{
if (_startPosX.Value + _drawningAirbusWidth + EntityAirbus.Step < _pictureWidth)
if (_startPosX.Value + _drawningBusWidth + EntityBus.Step < _pictureWidth)
{
_startPosX += (int)EntityAirbus.Step;
_startPosX += (int)EntityBus.Step;
}
}
return true;
//Вниз
case DirectionType.Down:
{
if (_startPosY.Value + _drawningAirbusHeight + EntityAirbus.Step < _pictureHeight)
if (_startPosY.Value + _drawningBusHeight + EntityBus.Step < _pictureHeight)
{
_startPosY += (int)EntityAirbus.Step;
_startPosY += (int)EntityBus.Step;
}
}
return true;
@ -171,23 +214,15 @@ public class DrawningAirbus
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityAirbus == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityBus == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyColorBrush = new SolidBrush(EntityAirbus.BodyColor);
Brush additionalBrush = new SolidBrush(EntityAirbus.AdditionalColor);
//Дополнительный отсек
Brush brBlue = new SolidBrush(Color.LightBlue);
if (EntityAirbus.Compartment)
{
g.FillEllipse(brBlue, _startPosX.Value + 37, _startPosY.Value + 13, 49, 15);
}
Brush bodyColorBrush = new SolidBrush(EntityBus.BodyColor);
//корпус
g.FillRectangle(bodyColorBrush, _startPosX.Value, _startPosY.Value + 20, 100, 20);
@ -208,7 +243,7 @@ public class DrawningAirbus
g.DrawLine(pen, _startPosX.Value, _startPosY.Value, _startPosX.Value + 20, _startPosY.Value + 20);
//заднее доп крыло
g.FillEllipse(darkBrush, _startPosX.Value - 7, _startPosY.Value + 15, 20, 5);
g.FillEllipse(darkBrush, _startPosX.Value, _startPosY.Value + 15, 20, 5);
//нос самолёта
g.DrawLine(pen, _startPosX.Value + 100, _startPosY.Value + 20, _startPosX.Value + 130, _startPosY.Value + 30);
@ -224,12 +259,5 @@ public class DrawningAirbus
g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 40, _startPosX.Value + 90, _startPosY.Value + 45);
g.FillEllipse(darkBrush, _startPosX.Value + 87, _startPosY.Value + 45, 6, 6);
// Двигатели
if (EntityAirbus.Engine)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 30, _startPosY.Value + 33, 13, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 33, 15, 5);
}
}
}

View File

@ -1,26 +1,10 @@

namespace ProjectAirbus;
namespace ProjectAirbus.Entities;
/// <summary>
/// Класс-сущность "Аэробус"
/// </summary>
public class EntityAirbus
public class EntityAirbus : EntityBus
{
/// <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>
@ -50,11 +34,8 @@ public class EntityAirbus
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="compartment">Признак наличия дополнительного отсека для пассажиров</param>
/// <param name="engine">Признак наличия дополнительных двигателей</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool compartment, bool engine)
public EntityAirbus(int speed, double weight, Color bodyColor, Color additionalColor, bool compartment, bool engine) : base (speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Compartment = compartment;
Engine = engine;

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirbus.Entities;
/// <summary>
/// Класс-сущность "Аэробус2"
/// </summary>
public class EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цывет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения аэробуса
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>m>
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -29,11 +29,14 @@
private void InitializeComponent()
{
buttonCreateAirbus = new Button();
ButtonLeft = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
pictureBoxAirbus = new PictureBox();
buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirbus).BeginInit();
SuspendLayout();
//
@ -42,23 +45,23 @@
buttonCreateAirbus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirbus.Location = new Point(12, 498);
buttonCreateAirbus.Name = "buttonCreateAirbus";
buttonCreateAirbus.Size = new Size(75, 23);
buttonCreateAirbus.Size = new Size(193, 23);
buttonCreateAirbus.TabIndex = 1;
buttonCreateAirbus.Text = "Создать";
buttonCreateAirbus.Text = "Создать аэробус";
buttonCreateAirbus.UseVisualStyleBackColor = true;
buttonCreateAirbus.Click += ButtonCreateAirbus_Click;
//
// ButtonLeft
// buttonLeft
//
ButtonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
ButtonLeft.BackgroundImage = Properties.Resources.free_icon_left_arrow_10696518;
ButtonLeft.BackgroundImageLayout = ImageLayout.Stretch;
ButtonLeft.Location = new Point(927, 491);
ButtonLeft.Name = "buttonLeft";
ButtonLeft.Size = new Size(35, 35);
ButtonLeft.TabIndex = 2;
ButtonLeft.UseVisualStyleBackColor = true;
ButtonLeft.Click += ButtonMove_Click;
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.free_icon_left_arrow_10696518;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(927, 491);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonDown
//
@ -105,15 +108,49 @@
pictureBoxAirbus.TabIndex = 6;
pictureBoxAirbus.TabStop = false;
//
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.Location = new Point(229, 498);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.Size = new Size(193, 23);
buttonCreateBus.TabIndex = 7;
buttonCreateBus.Text = "Создать базовый аэробус";
buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += ButtonCreateBus_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(927, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(117, 23);
comboBoxStrategy.TabIndex = 8;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(969, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 9;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormAirbus
//
AutoScaleMode = AutoScaleMode.None;
ClientSize = new Size(1059, 533);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus);
Controls.Add(buttonCreateAirbus);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(ButtonLeft);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxAirbus);
Name = "FormAirbus";
Text = "Аэробус";
@ -123,10 +160,13 @@
#endregion
private Button buttonCreateAirbus;
private Button ButtonLeft;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
private PictureBox pictureBoxAirbus;
private Button buttonCreateBus;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,8 @@

using ProjectAirbus.Drawning;
using ProjectAirbus.MovementStrategy;
using ProjectAirbus.MovementStrategyж;
namespace ProjectAirbus
{
/// <summary>
@ -9,14 +13,19 @@ namespace ProjectAirbus
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAirbus? _drawningAirbus;
private DrawningBus? _drawningBus;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormAirbus()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -24,7 +33,7 @@ namespace ProjectAirbus
/// </summary>
private void Draw()
{
if (_drawningAirbus == null)
if (_drawningBus == null)
{
return;
}
@ -32,28 +41,52 @@ namespace ProjectAirbus
Bitmap bmp = new(pictureBoxAirbus.Width,
pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAirbus.DrawTransport(gr);
_drawningBus.DrawTransport(gr);
pictureBoxAirbus.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningBus):
_drawningBus = new DrawningBus(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(DrawningAirbus):
_drawningBus = new DrawningAirbus(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;
}
_drawningBus.SetPictureSize(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawningBus.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 ButtonCreateAirbus_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAirbus = new DrawningAirbus();
_drawningAirbus.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)));
_drawningAirbus.SetPictureSize(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawningAirbus.SetPosition(random.Next(10, 100), random.Next(10, 100));
private void ButtonCreateAirbus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirbus));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать автобус"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateBus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBus));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
@ -62,7 +95,7 @@ namespace ProjectAirbus
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningAirbus == null)
if (_drawningBus == null)
{
return;
}
@ -72,19 +105,19 @@ namespace ProjectAirbus
{
case "buttonUp":
result =
_drawningAirbus.MoveTransport(DirectionType.Up);
_drawningBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningAirbus.MoveTransport(DirectionType.Down);
_drawningBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningAirbus.MoveTransport(DirectionType.Left);
_drawningBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningAirbus.MoveTransport(DirectionType.Right);
_drawningBus.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -92,5 +125,47 @@ namespace ProjectAirbus
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableBus(_drawningBus), pictureBoxAirbus.Width, pictureBoxAirbus.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,143 @@
using ProjectAirbus.MovementStrategyж;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirbus.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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