This commit is contained in:
Anna 2023-11-30 14:13:38 +04:00
parent ed306e312a
commit f89951adef
14 changed files with 809 additions and 146 deletions

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Airbus_Base
{
internal enum DirectionType
public enum DirectionType
{
/// <summary>
/// Вверх

View File

@ -0,0 +1,77 @@
using Airbus_Base.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirbus : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalEngine">Признак наличия двигателей</param>
/// <param name="additionalPassengerCompartment">Признак наличия отсека для пассажиров</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningAirbus(int speed, double weight, Color bodyColor, Color
additionalColor, bool additionalEngine, bool additionalPassengerCompartment, int width, int height) :
base(speed, weight, bodyColor, width, height, 159, 103)
{
if (EntityAirplane != null)
{
EntityAirplane = new EntityAirbus(speed, weight, bodyColor,
additionalColor, additionalEngine, additionalPassengerCompartment);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityAirplane is not EntityAirbus airBus)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(airBus.AdditionalColor);
//Дополнительные двигатели
if (airBus.AdditionalEngine)
{
Point[] enginedraw = { new Point(_startPosX + 55, _startPosY + 30),
new Point(_startPosX + 69, _startPosY + 25), new Point(_startPosX + 55, _startPosY + 20)};
g.FillPolygon(additionalBrush, enginedraw);
Point[] enginedraw1 = { new Point(_startPosX + 55, _startPosY + 75),
new Point(_startPosX + 70, _startPosY + 70), new Point(_startPosX + 55, _startPosY + 65)};
g.FillPolygon(additionalBrush, enginedraw1);
}
base.DrawTransport(g);
//Дополнительный отсек для пассажиров
if (airBus.AdditionalPassengerCompartment)
{
Point[] points = { new Point(_startPosX + 90, _startPosY + 30),
new Point(_startPosX + 100, _startPosY + 15), new Point(_startPosX + 130, _startPosY + 15),
new Point(_startPosX + 140, _startPosY + 30) };
g.FillPolygon(additionalBrush, points);
g.DrawLine(pen, _startPosX + 90, _startPosY + 30, _startPosX + 100, _startPosY + 15);
g.DrawLine(pen, _startPosX + 100, _startPosY + 15, _startPosX + 130, _startPosY + 15);
g.DrawLine(pen, _startPosX + 130, _startPosY + 15, _startPosX + 140, _startPosY + 30);
}
}
}
}

View File

@ -1,17 +1,21 @@
using System;
using Airbus_Base.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base
namespace Airbus_Base.DrawningObjects
{
internal class DrawningAirbus
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirplane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirbus? EntityAirbus { get; private set; }
public EntityAirplane? EntityAirplane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -21,47 +25,83 @@ namespace Airbus_Base
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки аэробуса
/// Левая координата прорисовки самолёта
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки аэробуса
/// Верхняя кооридната прорисовки самолёта
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки аэробуса
/// Ширина прорисовки самолёта
/// </summary>
private readonly int _airbusWidth = 159;
protected readonly int _airplaneWidth = 159;
/// <summary>
/// Высота прорисовки аэробуса
/// Высота прорисовки самолёта
/// </summary>
private readonly int _airbusHeight = 103;
protected readonly int _airplaneHeight = 103;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _airplaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _airplaneHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalEngine">Признак наличия дополнительных двигателей</param>
/// <param name="additionalPassengerCompartment">Признак наличия дополнительного отсека для пассажиров</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool additionalEngine, bool additionalPassengerCompartment, int width, int height)
public DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width > _airbusWidth & height > _airbusHeight)
if (width < _airplaneHeight || height < _airplaneWidth)
{
_pictureWidth = width;
_pictureHeight = height;
EntityAirbus = new EntityAirbus();
EntityAirbus.Init(speed, weight, bodyColor, additionalColor,
additionalEngine, additionalPassengerCompartment);
return true;
return;
}
else return false;
_pictureWidth = width;
_pictureHeight = height;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="airWidth">Ширина прорисовки cамолёта</param>
/// <param name="airHeight">Высота прорисовки cамолёта</param>
protected DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height, int airWidth, int airHeight)
{
if (width < _airplaneHeight || height < _airplaneWidth)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airWidth;
_airplaneHeight = airHeight;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
@ -69,22 +109,51 @@ namespace Airbus_Base
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (_startPosY + _airbusHeight < _pictureHeight)
_startPosY = y;
else
_startPosY = _pictureHeight - _airbusHeight;
if (_startPosX + _airbusWidth < _pictureWidth)
_startPosX = x;
else
_startPosX = _pictureWidth - _airbusWidth;
if (x < 0 || x + _airplaneWidth > _pictureWidth)
{
x = Math.Max(0, _pictureWidth - _airplaneWidth);
}
if (y < 0 || y + _airplaneHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _airplaneHeight);
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityAirplane == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityAirplane.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityAirplane.Step > 0,
//вправо
DirectionType.Right => _startPosX + _airplaneWidth + EntityAirplane.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _airplaneHeight + EntityAirplane.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityAirbus == null)
if (!CanMove(direction) || EntityAirplane == null)
{
return;
}
@ -92,52 +161,37 @@ namespace Airbus_Base
{
//влево
case DirectionType.Left:
if (_startPosX - EntityAirbus.Step > 0)
{
_startPosX -= (int)EntityAirbus.Step;
}
else _startPosX = 0;
_startPosX -= (int)EntityAirplane.Step;
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityAirbus.Step > 0)
{
_startPosY -= (int)EntityAirbus.Step;
}
else _startPosY = 0;
_startPosY -= (int)EntityAirplane.Step;
break;
// вправо
case DirectionType.Right:
if (_startPosX + _airbusWidth + EntityAirbus.Step < _pictureWidth)
{
_startPosX += (int)EntityAirbus.Step;
}
else _startPosX = _pictureWidth - _airbusWidth;
_startPosX += (int)EntityAirplane.Step;
break;
//вниз
case DirectionType.Down:
if (_startPosY + _airbusHeight + EntityAirbus.Step < _pictureHeight)
{
_startPosY += (int)EntityAirbus.Step;
}
else _startPosY = _pictureHeight - _airbusHeight;
_startPosY += (int)EntityAirplane.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityAirbus == null)
if (EntityAirplane == null)
{
return;
}
Pen pen = new(Color.Black);
Brush brBlack = new SolidBrush(Color.Black);
Brush bodybrush = new SolidBrush(EntityAirbus.BodyColor);
Brush brAdd = new SolidBrush(EntityAirbus.AdditionalColor);
Brush bodybrush = new SolidBrush(EntityAirplane.BodyColor);
//передняя часть
Point[] k = { new Point(_startPosX + 140, _startPosY + 30),
new Point(_startPosX + 160, _startPosY + 56), new Point(_startPosX + 140, _startPosY + 81)};
@ -170,27 +224,6 @@ namespace Airbus_Base
g.DrawLine(pen, _startPosX + 65, _startPosY + 60, _startPosX + 45, _startPosY + 100);
g.DrawLine(pen, _startPosX + 45, _startPosY + 100, _startPosX + 100, _startPosY + 60);
g.FillEllipse(brBlack, _startPosX + 16, _startPosY + 27, 30, 6);
//Дополнительные двигатели
if (EntityAirbus.AdditionalEngine)
{
Point[] enginedraw = { new Point(_startPosX + 55, _startPosY + 30),
new Point(_startPosX + 69, _startPosY + 25), new Point(_startPosX + 55, _startPosY + 20)};
g.FillPolygon(brAdd, enginedraw);
Point[] enginedraw1 = { new Point(_startPosX + 55, _startPosY + 75),
new Point(_startPosX + 70, _startPosY + 70), new Point(_startPosX + 55, _startPosY + 65)};
g.FillPolygon(brAdd, enginedraw1);
}
//Дополнительный отсек для пассажиров
if (EntityAirbus.AdditionalPassengerCompartment)
{
Point[] points = { new Point(_startPosX + 90, _startPosY + 30),
new Point(_startPosX + 100, _startPosY + 15), new Point(_startPosX + 130, _startPosY + 15),
new Point(_startPosX + 140, _startPosY + 30) };
g.FillPolygon(brAdd, points);
g.DrawLine(pen, _startPosX + 90, _startPosY + 30, _startPosX + 100, _startPosY + 15);
g.DrawLine(pen, _startPosX + 100, _startPosY + 15, _startPosX + 130, _startPosY + 15);
g.DrawLine(pen, _startPosX + 130, _startPosY + 15, _startPosX + 140, _startPosY + 30);
}
}
}
}

View File

@ -4,53 +4,36 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base
namespace Airbus_Base.Entities
{
internal class EntityAirbus
/// <summary>
/// Класс-сущность "Аэробус"
/// </summary>
public class EntityAirbus : EntityAirplane
{
/// <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 Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных двигателей
/// Признак (опция) наличия двигателей
/// </summary>
public bool AdditionalEngine { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительного отсека для пассажиров
/// Признак (опция) наличия отсека для пассажиров
/// </summary>
public bool AdditionalPassengerCompartment { get; private set; }
/// <summary>
/// Шаг перемещения аэробуса
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса аэробуса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес аэробуса</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalEngine">Признак наличия дополнительных двигателей</param>
/// <param name="additionalPassengerCompartment">Признак наличия дополнительного отсека для пассажиров</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool additionalEngine, bool additionalPassengerCompartment)
/// <param name="additionalEngine">Признак наличия двигателей</param>
/// <param name="additionalPassengerCompartment">Признак наличия отсека для пассажиров</param>
public EntityAirbus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalEngine, bool additionalPassengerCompartment) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
AdditionalEngine = additionalEngine;
AdditionalPassengerCompartment = additionalPassengerCompartment;

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Entities
{
/// <summary>
/// Класс-сущность "Самолёт"
/// </summary>
public class EntityAirplane
{
/// <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 => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолёта</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityAirplane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -29,11 +29,14 @@
private void InitializeComponent()
{
this.pictureBoxAirbus = new System.Windows.Forms.PictureBox();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonCreateAirplane = new System.Windows.Forms.Button();
this.buttonCreateAirbus = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).BeginInit();
this.SuspendLayout();
//
@ -48,17 +51,25 @@
this.pictureBoxAirbus.TabIndex = 0;
this.pictureBoxAirbus.TabStop = false;
//
// buttonCreate
// buttonCreateAirplane
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(14, 406);
this.buttonCreate.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(86, 31);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
this.buttonCreateAirplane.Location = new System.Drawing.Point(12, 393);
this.buttonCreateAirplane.Name = "buttonCreateAirplane";
this.buttonCreateAirplane.Size = new System.Drawing.Size(75, 52);
this.buttonCreateAirplane.TabIndex = 6;
this.buttonCreateAirplane.Text = "Создать самолёт";
this.buttonCreateAirplane.UseVisualStyleBackColor = true;
this.buttonCreateAirplane.Click += new System.EventHandler(this.buttonCreateAirplane_Click);
//
// buttonCreateAirbus
//
this.buttonCreateAirbus.Location = new System.Drawing.Point(115, 393);
this.buttonCreateAirbus.Name = "buttonCreateAirbus";
this.buttonCreateAirbus.Size = new System.Drawing.Size(75, 52);
this.buttonCreateAirbus.TabIndex = 7;
this.buttonCreateAirbus.Text = "Создать аэробус";
this.buttonCreateAirbus.UseVisualStyleBackColor = true;
this.buttonCreateAirbus.Click += new System.EventHandler(this.buttonCreateAirbus_Click);
//
// buttonLeft
//
@ -112,6 +123,28 @@
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(797, 51);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(75, 29);
this.buttonStep.TabIndex = 8;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"К центру",
"К краю"});
this.comboBoxStrategy.Location = new System.Drawing.Point(753, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 28);
this.comboBoxStrategy.TabIndex = 9;
//
// FormAirbus
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -121,7 +154,10 @@
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonCreateAirbus);
this.Controls.Add(this.buttonCreateAirplane);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.pictureBoxAirbus);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormAirbus";
@ -135,10 +171,13 @@
#endregion
private PictureBox pictureBoxAirbus;
private Button buttonCreate;
private Button buttonCreateAirplane;
private Button buttonCreateAirbus;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonStep;
private ComboBox comboBoxStrategy;
}
}

View File

@ -7,6 +7,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Airbus_Base.DrawningObjects;
using Airbus_Base.MovementStrategy;
namespace Airbus_Base
{
@ -18,10 +20,11 @@ namespace Airbus_Base
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAirbus? _drawningAirbus;
private DrawningAirplane? _drawningAirplane;
/// <summary>
/// Инициализация формы
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
public FormAirbus()
{
InitializeComponent();
@ -31,38 +34,45 @@ namespace Airbus_Base
/// </summary>
private void Draw()
{
if (_drawningAirbus == null)
if (_drawningAirplane == null)
{
return;
}
Bitmap bmp = new(pictureBoxAirbus.Width,
pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAirbus.DrawTransport(gr);
_drawningAirplane.DrawTransport(gr);
pictureBoxAirbus.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать самолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
private void buttonCreateAirplane_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)),
_drawningAirplane = new DrawningAirplane(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать aэробус"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirbus_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAirplane = 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)),
pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawningAirbus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
@ -72,7 +82,7 @@ namespace Airbus_Base
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningAirbus == null)
if (_drawningAirplane == null)
{
return;
}
@ -80,20 +90,61 @@ namespace Airbus_Base
switch (name)
{
case "buttonUp":
_drawningAirbus.MoveTransport(DirectionType.Up);
_drawningAirplane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningAirbus.MoveTransport(DirectionType.Down);
_drawningAirplane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningAirbus.MoveTransport(DirectionType.Left);
_drawningAirplane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningAirbus.MoveTransport(DirectionType.Right);
_drawningAirplane.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningAirplane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectAirplane(_drawningAirplane), pictureBoxAirbus.Width,
pictureBoxAirbus.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Airbus_Base.MovementStrategy;
namespace Airbus_Base.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,43 @@
using Airbus_Base.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningAirplane (паттерн Adapter)
/// </summary>
public class DrawningObjectAirplane : IMoveableObject
{
private readonly DrawningAirplane? _drawningAirplane = null;
public DrawningObjectAirplane(DrawningAirplane drawningAirplane)
{
_drawningAirplane = drawningAirplane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningAirplane == null || _drawningAirplane.EntityAirplane == null)
{
return null;
}
return new ObjectParameters(_drawningAirplane.GetPosX,
_drawningAirplane.GetPosY, _drawningAirplane.GetWidth, _drawningAirplane.GetHeight);
}
}
public int GetStep => (int)(_drawningAirplane?.EntityAirplane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningAirplane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningAirplane?.MoveTransport(direction);
}
}

View File

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

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.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.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}