Merge pull request 'PIbd-22 Puchkina A.A. LabWork_02' (#2) from LabWork_2 into LabWork_1

Reviewed-on: http://student.git.athene.tech/a.puchkina/PIbd-22_Puchkina_A.A_AirplaneWithRadar._BASE/pulls/2
This commit is contained in:
Анна Пучкина 2023-10-11 09:19:48 +04:00
commit 6592399f10
14 changed files with 736 additions and 87 deletions

View File

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

@ -35,6 +35,9 @@
buttonLeft = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonCreateAirplaneWithRadar = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
((System.ComponentModel.ISupportInitialize)pictureBoxAirplane).BeginInit();
SuspendLayout();
//
@ -107,11 +110,47 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonCreateAirplaneWithRadar
//
buttonCreateAirplaneWithRadar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirplaneWithRadar.Location = new Point(112, 411);
buttonCreateAirplaneWithRadar.Name = "buttonCreateAirplaneWithRadar";
buttonCreateAirplaneWithRadar.Size = new Size(198, 30);
buttonCreateAirplaneWithRadar.TabIndex = 6;
buttonCreateAirplaneWithRadar.Text = "Создать с дополнениями";
buttonCreateAirplaneWithRadar.UseVisualStyleBackColor = true;
buttonCreateAirplaneWithRadar.Click += buttonCreateAirplaneWithRadar_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(788, 34);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 7;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "в центр", "к гарнице" });
comboBoxStrategy.Location = new Point(731, 0);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 8;
//
// AirplaneWithRadarForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStep);
Controls.Add(buttonCreateAirplaneWithRadar);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
@ -134,5 +173,8 @@
private Button buttonLeft;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateAirplaneWithRadar;
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 AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy;
namespace AirplaneWithRadar
{
@ -19,6 +21,11 @@ namespace AirplaneWithRadar
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAirplane? _drawningAirplane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Инициализация формы
/// </summary>
@ -43,26 +50,42 @@ namespace AirplaneWithRadar
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать самолет"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirplane_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAirplane = new DrawningAirplane();
_drawningAirplane.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)), Convert.ToBoolean(random.Next(0, 2)), pictureBoxAirplane.Width, pictureBoxAirplane.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
_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)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBoxAirplane.Width, pictureBoxAirplane.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonCreateAirplaneWithRadar_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAirplane = new DrawningAirplaneWithRadar(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)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAirplane.Width, pictureBoxAirplane.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Изменение размеров формы
/// Изменение положения самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@ -90,5 +113,49 @@ namespace AirplaneWithRadar
}
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), pictureBoxAirplane.Width,
pictureBoxAirplane.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -121,7 +121,7 @@
<data name="buttonLeft.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOEBAMAAAALYOIIAAAABGdBTUEAALGPC/xhBQAAABJQTFRF5ubm
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvgAADr4B6kKxwAAAFy1JREFUeNrtnV2S6ka2RkFB
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvAAADrwBlbxySQAAFy1JREFUeNrtnV2S6ka2RkFB
v7ese98VCmkA6hwBlzsB4tjzn0qTPxLC5lBCKH++qsVDVy932yf5VmxD1lbmPnT+1R78C5RD4pBH4pBH
4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pDH6VWFvw6qInHII3HII3HII3HII3HII3HI
I3HII3HII3HII3HII3HII3HII3HII3EIY/hJ700WiUMeiUMeiUMeiUMeiUMeiUMeiUMeiUMeiUMeiUMe
@ -328,7 +328,7 @@
<data name="buttonDown.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOEBAMAAAALYOIIAAAABGdBTUEAALGPC/xhBQAAABJQTFRF5ubm
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvgAADr4B6kKxwAAAGBNJREFUeNrt3V9y+r7Vx3Fj
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvAAADrwBlbxySQAAGBNJREFUeNrt3V9y+r7Vx3Fj
NoARuTeacB9VYQGPM92A2f9eimTZSb5PSAD/05Hens7QTy/6i/WqjqFHkotwlbq7oosf1fWy3WWq7lo+
WvsW4+B8jRBCmDahglA6oYUQQgghhBBCCCGEEEIIIRwT+V0IIYQQQjg2KgilE1bqJV7C8FmH/zy2WH5c
i5gNI6rCkK4Qq5e6iHSsIIQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGE8K+oIJROaM/xEoaLfuGvka49

View File

@ -4,8 +4,10 @@ using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.Entities;
namespace AirplaneWithRadar
namespace AirplaneWithRadar.DrawningObjects
{/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
@ -14,7 +16,7 @@ namespace AirplaneWithRadar
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirplaneWithRadar? EntityAirplaneWithRadar{ get; private set; }
public EntityAirplane? EntityAirplane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -26,19 +28,19 @@ namespace AirplaneWithRadar
/// <summary>
/// /// Левая координата прорисовки самолета
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки самолета
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки самолета
/// </summary>
private readonly int _airplaneWidth = 200;
protected readonly int _airplaneWidth = 200;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _airplaneHeight = 85;
protected readonly int _airplaneHeight = 85;
/// <summary>
/// Инициализация свойств
/// </summary>
@ -46,24 +48,43 @@ namespace AirplaneWithRadar
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет фюзеляжа</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия доп.бака</param>
/// <param name="pin">Признак наличия штыря</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 radar, bool tank, bool pin, int width, int height)
public DrawningAirplane(int speed, double weight, Color bodyColor, Color
additionalColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{
return false;
return;
}
EntityAirplaneWithRadar = new EntityAirplaneWithRadar();
EntityAirplaneWithRadar.Init(speed, weight, bodyColor, additionalColor, radar, tank, pin);
return true;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor, additionalColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="airplaneWidth">Ширина прорисовки автомобиля</param>
/// <param name="airplaneHeight">Высота прорисовки автомобиля</param>
protected DrawningAirplane(int speed, double weight, Color bodyColor, Color additionalColor, int
width, int height, int airplaneWidth, int airplaneHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{
return;
}
EntityAirplane = new EntityAirplane(speed, weight, bodyColor, additionalColor);
}
/// <summary>
/// Установка позиции
@ -75,13 +96,55 @@ namespace AirplaneWithRadar
_startPosX = Math.Min(x, _pictureWidth - _airplaneWidth);
_startPosY = Math.Min(y, _pictureHeight - _airplaneHeight);
}
/// <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="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 + EntityAirplane.Step < _pictureWidth + _airplaneWidth,
//вниз
DirectionType.Down => _startPosY + EntityAirplane.Step < _pictureHeight + _airplaneHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityAirplaneWithRadar == null)
if (!CanMove(direction) || EntityAirplane == null)
{
return;
}
@ -89,30 +152,30 @@ namespace AirplaneWithRadar
{
//влево
case DirectionType.Left:
if (_startPosX - EntityAirplaneWithRadar.Step > 0)
if (_startPosX - EntityAirplane.Step > 0)
{
_startPosX -= (int)EntityAirplaneWithRadar.Step;
_startPosX -= (int)EntityAirplane.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityAirplaneWithRadar.Step > 0)
if (_startPosY - EntityAirplane.Step > 0)
{
_startPosY -= (int)EntityAirplaneWithRadar.Step;
}
_startPosY -= (int)EntityAirplane.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + EntityAirplaneWithRadar.Step + _airplaneWidth < _pictureWidth)
if (_startPosX + EntityAirplane.Step + _airplaneWidth < _pictureWidth)
{
_startPosX += (int)EntityAirplaneWithRadar.Step;
_startPosX += (int)EntityAirplane.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + EntityAirplaneWithRadar.Step + _airplaneHeight < _pictureHeight)
if (_startPosY + EntityAirplane.Step + _airplaneHeight < _pictureHeight)
{
_startPosY += (int)EntityAirplaneWithRadar.Step;
_startPosY += (int)EntityAirplane.Step;
}
break;
}
@ -121,32 +184,24 @@ namespace AirplaneWithRadar
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityAirplaneWithRadar == null)
if (EntityAirplane == null)
{
return;
}
Pen penBlack = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityAirplaneWithRadar.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityAirplaneWithRadar.BodyColor);
Brush additionalBrush = new SolidBrush(EntityAirplane.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityAirplane.BodyColor);
// радар
if (EntityAirplaneWithRadar.Radar)
{
g.FillEllipse(additionalBrush, _startPosX + 65, _startPosY + 25, 50, 10);
g.DrawEllipse(penBlack, _startPosX + 65, _startPosY + 25, 50, 10);
g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5);
g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5);
}
//фюзеляж
g.FillRectangle(bodyBrush, _startPosX + 4, _startPosY + 40, 150, 30);
g.DrawRectangle(penBlack, _startPosX + 4, _startPosY + 40, 150, 30);
//киль
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 4, _startPosY + 40), new Point(_startPosX + 4, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 40)});
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 4, _startPosY + 40), new Point(_startPosX + 4, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 40) });
g.DrawPolygon(penBlack, new Point[] { new Point(_startPosX + 4, _startPosY + 40), new Point(_startPosX + 4, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 40) });
//стабилизатор и крыло
Brush brSilver = new SolidBrush(Color.Silver);
g.FillEllipse(brSilver, _startPosX, _startPosY + 35, 55, 10);
@ -174,20 +229,6 @@ namespace AirplaneWithRadar
g.DrawLine(penBlue, new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 150, _startPosY + 55));
g.DrawLine(penBlack, new Point(_startPosX + 150, _startPosY + 72), new Point(_startPosX + 150, _startPosY + 55));
g.DrawLine(penBlack, new Point(_startPosX + 150, _startPosY + 72), new Point(_startPosX + 190, _startPosY + 55));
// Штырь
if (EntityAirplaneWithRadar.Pin)
{
g.DrawLine(penGray, new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 200, _startPosY + 55));
}
// бак
if (EntityAirplaneWithRadar.Tank)
{
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 65, 45, 15);
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) });
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) });
}
}
}
}

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.Entities;
namespace AirplaneWithRadar.DrawningObjects
{
public class DrawningAirplaneWithRadar : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет фюзеляжа</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия бака</param>
/// <param name="pin">Признак наличия штыря</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningAirplaneWithRadar(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool tank, bool pin, int width, int height) :
base(speed, weight, bodyColor, additionalColor, width, height)
{
if (EntityAirplane != null)
{
EntityAirplane = new EntityAirplaneWithRadar(speed, weight, bodyColor,
additionalColor, radar, tank, pin);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityAirplane is not EntityAirplaneWithRadar airplaneWithRadar)
{
return;
}
Pen penBlack = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityAirplane.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityAirplane.BodyColor);
Pen penGray = new Pen(Color.Gray);
// радар
if (airplaneWithRadar.Radar)
{
g.FillEllipse(additionalBrush, _startPosX + 65, _startPosY + 25, 50, 10);
g.DrawEllipse(penBlack, _startPosX + 65, _startPosY + 25, 50, 10);
g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5);
g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5);
}
base.DrawTransport(g);
// Штырь
if (airplaneWithRadar.Pin)
{
g.DrawLine(penGray, new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 200, _startPosY + 55));
}
// бак
if (airplaneWithRadar.Tank)
{
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 65, 45, 15);
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) });
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) });
}
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.DrawningObjects;
namespace AirplaneWithRadar.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar
/// </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

@ -4,9 +4,12 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
namespace AirplaneWithRadar.Entities
{
public class EntityAirplaneWithRadar
/// <summary>
/// Класс-сущность "Самолет"
/// </summary>
public class EntityAirplane
{
/// <summary>
/// Скорость
@ -25,18 +28,6 @@ namespace AirplaneWithRadar
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Признак (опция) наличия доп.бака
/// </summary>
public bool Tank { get; private set; }
/// <summary>
/// Признак (опция) наличия штыря
/// </summary>
public bool Pin { get; private set; }
/// <summary>
/// Шаг перемещения самолета
/// </summary>
public double Step => (double)Speed * 100 / Weight;
@ -47,19 +38,13 @@ namespace AirplaneWithRadar
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия доп.бака</param>
/// <param name="pin">Признак наличия штыря</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool tank, bool pin)
public EntityAirplane(int speed, double weight, Color bodyColor, Color
additionalColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Radar = radar;
Tank = tank;
Pin = pin;
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.Entities
{
/// <summary>
/// Класс-сущность "Самолет с радаром"
/// </summary>
public class EntityAirplaneWithRadar : EntityAirplane
{
/// <summary>
/// Признак (опция) наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Признак (опция) наличия доп.бака
/// </summary>
public bool Tank { get; private set; }
/// <summary>
/// Признак (опция) наличия штыря
/// </summary>
public bool Pin { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса самолета с радаром
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия доп.бака</param>
/// <param name="pin">Признак наличия штыря</param>
public EntityAirplaneWithRadar(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool tank, bool pin) : base (speed, weight, bodyColor, additionalColor)
{
Radar = radar;
Tank = tank;
Pin = pin;
}
}
}

View File

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

View File

@ -0,0 +1,57 @@
using AirplaneWithRadar.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.MovementStrategy
{
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,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}